### .NET Integration Example (C#) Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/toupcam/toupcam/docs.md Example demonstrating how to use the Toupcam .NET wrapper class for the Snap function. ```APIDOC # .NET and C# and VB.NET Toupcam supports .NET development environments (C# and VB.NET) through P/Invoke calls into toupcam.dll. The `toupcam.cs` file in the 'inc' directory provides a thin wrapper class `ToupTek.ToupCam`. ## Example: Snap Method (C#) This example shows the C# wrapper for the `Toupcam_Snap` native function. ### C# Code Snippet ```csharp [DllImport("toupcam.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern int Toupcam_Snap(SafeHToupCamHandle h, uint nResolutionIndex); public bool Snap(uint nResolutionIndex) { if (_handle == null || _handle.IsInvalid || _handle.IsClosed) return false; return (Toupcam_Snap(_handle, nResolutionIndex) >= 0); } ``` ### Description The `Snap` method in the C# wrapper class calls the native `Toupcam_Snap` function. It takes a resolution index as input and returns `true` if the snap operation is successful, `false` otherwise. The native function's return value (HRESULT) is checked to determine success (>= 0). ### Parameters - **nResolutionIndex** (uint) - The index of the desired resolution for the snapshot. ``` -------------------------------- ### Install and Test Hardware Component Source: https://github.com/berkeleylab/foundry_scope/blob/master/utils/testing_hw_pip_setup.txt Install the component via pip and execute the test application. ```bash (test_env) $ cd ScopeFoundryHW/picam (test_env) $ pip install . (test_env) $ python -m ScopeFoundryHW.picam.picam_test_app (test_env) $ conda deactivate ``` -------------------------------- ### Table Widget Creation Example (PyQt5, ScopeFoundry) Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html An example demonstrating how to create a table widget using PyQt5 and ScopeFoundry's ArrayLQ_QTableModel for displaying hierarchical data, such as recipe steps. ```python self.table_widget = QtWidgets.QWidget() self.table_widget_layout = QtWidgets.QHBoxLayout() self.table_widget.setLayout(self.table_widget_layout) self.table_label = QtWidgets.QLabel('Table Label') self.table_widget.layout().addWidget(self.table_label) self.table = QtWidgets.QTableView() # Optional height constraint. self.table.setMaximumHeight(65) names = ['List', 'of', 'column', 'labels'] self.tableModel = ArrayLQ_QTableModel(self.displayed_array, col_names=names) self.table.setModel(self.tableModel) self.table_widget.layout().addWidget(self.table) # Add widget to enclosing outer widget self.containing_widget.layout().addWidget(self.table_widget) ``` -------------------------------- ### Table Creation Example - PyQt5 and ScopeFoundry Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Demonstrates how to create a table widget using PyQt5 and ScopeFoundry's ArrayLQ_QTableModel. This example illustrates setting up a QTableView with custom data and column labels, and integrating it into a larger widget structure. ```python self.table_widget = QtWidgets.QWidget() self.table_widget_layout = QtWidgets.QHBoxLayout() self.table_widget.setLayout(self.table_widget_layout) self.table_label = QtWidgets.QLabel('Table Label') self.table_widget.layout().addWidget(self.table_label) self.table = QtWidgets.QTableView() ## Optional height constraint. self.table.setMaximumHeight(65) names = ['List', 'of', 'column', 'labels'] self.tableModel = ArrayLQ_QTableModel(self.displayed_array, col_names=names) self.table.setModel(self.tableModel) self.table_widget.layout().addWidget(self.table) ### Add widget to enclosing outer widget self.containing_widget.layout().addWidget(self.table_widget) Note that `ArrayLQ_QTableModel` is a ScopeFoundry function containing PyQt5 code. For simplicity, it has been included in ScopeFoundry’s core framework under ndarray_interactive. ``` -------------------------------- ### Example Output: Initial Data Points Source: https://github.com/berkeleylab/foundry_scope/blob/master/mi_cryo_micro/20211011_Calibration/20200825_calibration_autodetected.ipynb Example output showing the initial data points collected during spectral analysis, including calibration line, center wavelength, and peak pixel index. ```text [[23, [[435.84, 437.99700000000001, 475]]], [41, [[546.08, 545.99699999999996, 510]]], [77, [[763.51, 761.99599999999998, 535]]]] ``` -------------------------------- ### Install ScopeFoundry and Dependencies Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundry/docs/source/index.md This snippet shows the commands to install ScopeFoundry and its necessary dependencies using Anaconda and pip. It ensures that the required Python packages like numpy, pyqt, qtpy, and h5py are installed before installing ScopeFoundry itself. ```bash conda install numpy pyqt qtpy h5py pyqtgraph pip install ScopeFoundry ``` -------------------------------- ### Test installation in a clean environment Source: https://github.com/berkeleylab/foundry_scope/blob/master/utils/how_to_package_for_pypi.txt Commands to set up a fresh conda environment and install the package from the generated tar.gz file. ```bash conda env remove -n test_env conda create -n test_env python=3.10 conda activate test_env pip uninstall ScopeFoundry mkdir ~/test cp dist/ScopeFoundry-x.x.x.tar.gz ~/test cd ~/test tar zxvf ScopeFoundry-x.x.x.tar.gz cd ScopeFoundry-x.x.x python setup.py build python setup.py install #conda install ``` -------------------------------- ### Example Output of Fit Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/mi_cryo_micro/20211011_Calibration/20200825_calibration_autodetected.ipynb Provides an example of the output generated after fitting the grating model, showing the optimized parameters. ```text ########################### COPY FOLLOWING ############################# [378515625.00000012, -0.00012499522803565571, -0.54341936279130221, 512.0, 0, 833.3333333333334, 26000.0, 3.7523793626684174e-07] ``` -------------------------------- ### Launch Daisy Application (Bash) Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/LX32/install/readme.linux.txt Starts the Daisy application in the background from a shell where LD_LIBRARY_PATH has been set. This command assumes Daisy is installed in '/home/me/daisy'. ```bash /home/me/daisy/daisy & ``` -------------------------------- ### Install ScopeFoundry via pip Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundry/README.md Installs the ScopeFoundry package directly from the GitHub repository using pip. This method assumes all system-level dependencies are already satisfied. ```bash pip install git+git://github.com/ScopeFoundry/ScopeFoundry.git ``` -------------------------------- ### Install ZWO ASI Dependencies Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/zwo_camera/README.md Installs the required Python library and system-level USB drivers. Ensure libusb is installed via Homebrew on macOS to enable hardware communication. ```bash pip install zwoasi brew install libusb ``` -------------------------------- ### Install Adaptive Package Source: https://github.com/berkeleylab/foundry_scope/blob/master/supra_cl/gpcam_setup.txt Installs the 'adaptive' Python package using pip. This is a dependency for GPCAM. ```bash pip install adaptive ``` -------------------------------- ### Clone and Install GPCAM Repository Source: https://github.com/berkeleylab/foundry_scope/blob/master/supra_cl/gpcam_setup.txt Clones the GPCAM repository from Bitbucket, checks out a specific branch, and installs it locally using pip. Ensure you are in the desired directory before cloning. ```bash cd c:\users\lab\documents\ git clone https://esbarnard@bitbucket.org/MarcusMichaelNoack/gpcam.git cd gpcam git checkout -b origin/v4ei0 pip install . ``` -------------------------------- ### Create and Configure Test Environment Source: https://github.com/berkeleylab/foundry_scope/blob/master/utils/testing_hw_pip_setup.txt Initialize a conda environment and install necessary dependencies for ScopeFoundry. ```bash (base) $ conda create -n test_env python=3.7 (base) $ conda activate test_env (test_env) $ conda install numpy pyqt qtpy h5py pyqtgraph (test_env) $ pip install ScopeFoundry ``` -------------------------------- ### Begin Camera Acquisition Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/flircam/flir_ctypes_test.ipynb Starts the image acquisition process on the camera. This function should be called after the camera is initialized and configured. The return value indicates the success or failure of starting the acquisition. ```Python err = lib.spinCameraBeginAcquisition(hCamera) print(err) ``` -------------------------------- ### Install ScopeFoundry via Conda Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundry/README.md Creates a dedicated Conda environment for ScopeFoundry and installs the required scientific Python libraries. This ensures dependency isolation for laboratory experiment control. ```bash conda create -n scopefoundry python=3.10 source activate scopefoundry conda install numpy pyqt qtpy h5py pyqtgraph pip install git+git://github.com/ScopeFoundry/ScopeFoundry.git ``` -------------------------------- ### Define Equipment Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/ir_microscope/20190603_Calibration/190117_calibration_autodetected.ipynb Sets physical constants for the optical setup. ```python x_pixel = 25e3 #nm pixel_width f = 300e6 offset_adjust = 0 ``` -------------------------------- ### Install Elgato StreamDeck HW for ScopeFoundry Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/elgato_streamdeck/doc/website_hw.md This command installs the Elgato StreamDeck hardware integration package for ScopeFoundry using pip. It fetches the latest version directly from the GitHub repository. ```bash pip install git+https://github.com/ScopeFoundry/HW_elgato_streamdeck.git ``` -------------------------------- ### Get Zhinst Module File Path Source: https://github.com/berkeleylab/foundry_scope/blob/master/TDTR/zhinst_tdtr_test.ipynb Prints the file path of the zhinst module. This can be helpful for debugging or verifying the installation location. ```python zhinst.__file__ ``` -------------------------------- ### Read Multiple Registers Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/dps3005_powersupply/dps3005 power supply modbus communication.ipynb Reads a block of registers from the Modbus instrument. This function is useful for retrieving multiple data points efficiently. The example reads 16 registers starting from address 0. ```python instrument.read_registers(0, 16) ``` -------------------------------- ### NI MFC Setup Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.NI_MFC.html Initializes the NI MFC hardware, defining I/O port addresses, establishing logged quantities, creating buffers, and setting full-scale and limit values. ```APIDOC ## POST /api/ni_mfc/setup ### Description Initializes the NI MFC hardware. This includes defining I/O port addresses, establishing logged quantities, creating buffers for MFC flow data, relating pin numbers to labels, and defining full-scale (fs) and limit (lim) values. ### Method POST ### Endpoint /api/ni_mfc/setup ### Parameters #### Request Body - **mfc_config** (object) - Optional - Configuration details for the MFCs. - **mfc1_fs** (float) - Full scale flow rate for MFC 1. - **mfc1_lim** (float) - Limit flow rate for MFC 1. - **mfc2_fs** (float) - Full scale flow rate for MFC 2. - **mfc2_lim** (float) - Limit flow rate for MFC 2. ### Request Example { "mfc_config": { "mfc1_fs": 100.0, "mfc1_lim": 90.0, "mfc2_fs": 50.0, "mfc2_lim": 45.0 } } ### Response #### Success Response (200) - **status** (string) - Indicates the success of the setup operation. #### Response Example { "status": "setup complete" } ``` -------------------------------- ### Get and Set Shutter Speed with Camera Control API Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/canon_ccapi/ccapi_tests.ipynb This example shows how to retrieve the current shutter speed (TV) settings and then update it to a new value. It first fetches the current settings and then sends a PUT request to change the shutter speed. ```python resp = requests.get('http://192.168.1.2:8080/ccapi/ver100/shooting/settings/tv') print(resp.json()) resp = requests.put('http://192.168.1.2:8080/ccapi/ver100/shooting/settings/tv', json={"value":'1/1000'}) resp.json() ``` -------------------------------- ### Get New Points Using Gaussian Process Optimization Source: https://github.com/berkeleylab/foundry_scope/blob/master/ALDbot/notebooks/GP_Code_Function.ipynb This function performs Bayesian optimization to suggest new experimental points. It requires a dataframe of existing data, variable definitions, parameter constraints, and optional pre-trained hyperparameters to guide the acquisition process. ```python Get_New_Points_With_GP(df, variables_names, parameter_space_limits, num_new_points, num_RMSE_trials) # With pre-trained hyperparameters prev_trained_GP_hps = np.array([1.39619317e+01, 1.48966989e+00, 1.48011105e+00, 1.49600234e+00, 9.51587788e-02, 7.72750480e-01, 1.43566368e+00, 1.46241551e+00, 1.32932834e+00, 1.30299791e+02, 1.64642410e+02]) Get_New_Points_With_GP(df, variables_names, parameter_space_limits, num_new_points, num_RMSE_trials, prev_trained_GP_hps) ``` -------------------------------- ### Setup System - ALD Recipe Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Initializes the system for a new recipe run. This function prepares all necessary components and configurations before the main process begins. ```python def setup(self): pass ``` -------------------------------- ### Setup Hardware Widget Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a widget to organize and display subpanels for Plasma, Temperature, Pressures, and Flow readouts, providing a structured view of hardware status. ```python def setup_hardware_widget(self): """Creates Hardware widget which contains the Plasma and Temperature readout subpanels and the Pressures and Flow subpanel. This enclosing widget was created solely for the purpose of organizing subpanel arrangement in UI.""" pass ``` -------------------------------- ### Setup and Show Console Widget (Python) Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundry/tests/embedded_app_in_jupyter_notebook.ipynb Sets up and displays the console widget for the application. This allows for interactive command execution within the application's context. ```python app = BaseApp([]) app.setup_console_widget().show() app.console_widget.raise_() ``` -------------------------------- ### Serial Communication Output Example Source: https://github.com/berkeleylab/foundry_scope/blob/master/SiC_Furnace/optris_pyrometer_test.ipynb Example output from serial communication, showing byte sequences and read data. ```text b'' b'' ``` ```text 00 00 00 00 00 00 00 00 00 00 01 17 0C .. 00 00 00 00 00 00 00 00 00 00 52 00 52 0F ..........R.R. 09 90 . ``` -------------------------------- ### StreamDeck Test App Tutorial in Python Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/elgato_streamdeck/doc/website_hw.md A Python tutorial demonstrating the setup of a ScopeFoundry application that integrates with an Elgato StreamDeck. It shows how to initialize the hardware, set key images, and connect key presses to application settings or custom functions like brightness adjustment. ```python from ScopeFoundry import BaseMicroscopeApp from ScopeFoundryHW.elgato_streamdeck.elgato_streamdeck_hw import ElgatoStreamDeckHW import numpy as np class StreamDeckTestApp(BaseMicroscopeApp): name = 'streamdeck_testapp' def setup(self): hw = self.add_hardware(ElgatoStreamDeckHW(self)) key_image_format = hw.deck.key_image_format() width, height = (key_image_format['width'], key_image_format['height']) depth = key_image_format['depth'] grid_x, grid_y = np.mgrid[0:1:width*1j, 0:1:height*1j] img = np.ones((height, width, depth), dtype=int) print(img.shape) img[:,:,0] = 255 hw.deck.set_key_image(0, img.flat) hw.connect_key_to_lq_toggle(1, hw.settings.debug_mode, text="Toggle") hw.connect_key_to_lq_momentary(2, hw.settings.debug_mode, text="Momentary") def inc_brightness(): hw.settings['brightness'] += 5 hw.add_key_press_listener(3, inc_brightness) hw.set_key_image(3, hw.img_icon("plus", text='brightness')) def dec_brightness(): hw.settings['brightness'] -= 5 hw.add_key_press_listener(4, dec_brightness) hw.set_key_image(4, hw.img_icon("minus", text='brightness')) hw.set_key_image(6, hw.img_icon("arrow-circle-left", text="icon test") ) hw.set_key_image(5, hw.img_icon("arrow-circle-right", text=" MOOSE", bgcolor='yellow' )) ``` -------------------------------- ### Acquire Device Sample Source: https://github.com/berkeleylab/foundry_scope/blob/master/TDTR/zhinst_tdtr_test.ipynb Executes a sample acquisition from the DAQ server. ```python daq.getSample() ``` -------------------------------- ### Initialize and Terminate Canon EDSDK Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/canon_edsdk/canon-edsdk-test.ipynb Demonstrates how to load the EDSDK DLL, initialize the SDK environment, and properly terminate the session to release resources. ```python import ctypes from ctypes import byref, c_void_p dll = ctypes.WinDLL("EDSDK_64/Dll/EDSDK.dll") dll.EdsInitializeSDK() # ... perform operations ... dll.EdsTerminateSDK() ``` -------------------------------- ### Install Core Python Packages Source: https://github.com/berkeleylab/foundry_scope/blob/master/supra_cl/gpcam_setup.txt Installs essential scientific Python packages using conda. Ensure you are in the activated 'gpcam' environment. ```bash conda install wheel numpy scipy matplotlib numba ``` -------------------------------- ### Instantiate and Use SQWrap Class Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ADS/Untitled.ipynb Demonstrates how to create an instance of the SQWrap class and establish a connection to the SQLite database. This is typically the first step before performing any database operations. ```python sq = SQWrap() sq.connect() ``` -------------------------------- ### Initialize Spinnaker System Instance (Python) Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/flircam/flir_ctypes_test.ipynb Obtains an instance of the Spinnaker system. This is a fundamental step to interact with the camera system, requiring a pointer to store the system instance. The result indicates success or failure. ```python hSystem = ctypes.c_void_p() err = lib.spinSystemGetInstance(ctypes.byref(hSystem)) hSystem ``` -------------------------------- ### Get SD Card Contents Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/canon_ccapi/ccapi_tests.ipynb Use this endpoint to retrieve a list of files on the SD card. Requires a GET request to the specified URL. ```python resp = requests.get('http://192.168.1.2:8080/ccapi/ver100/contents/sd/100CANON') resp.json() ``` -------------------------------- ### Hardware Widget Setup Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a hardware widget that organizes subpanels for Plasma, Temperature, Pressures, and Flow readouts. ```APIDOC ## setup_hardware_widget ### Description Creates Hardware widget which contains the Plasma and Temperature readout subpanels and the Pressures and Flow subpanel. This enclosing widget was created solely for the purpose of organizing subpanel arrangement in UI. ### Method N/A (This is a setup function) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Retrieve Shooting Settings via GET Request Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/canon_ccapi/ccapi_tests.ipynb Fetches the current shooting settings of the camera using a GET request. The response is returned as JSON. ```python resp = requests.get('http://192.168.1.2:8080/ccapi/ver100/shooting/settings') ``` ```python resp.json() ``` ```text Result: {'shootingmodedial': {'value': 'm'}, 'av': {'value': '', 'ability': []}, 'tv': {'value': '1/2000', 'ability': ['bulb', '30"', '25"', '20"', '15"', '13"', '10"', '8"', '6"', '5"', '4"', '3"2', '2"5', '2"', '1"6', '1"3', '1"', '0"8', '0"6', '0"5', '0"4', '0"3', '1/4', '1/5', '1/6', '1/8', '1/10', '1/13', '1/15', '1/20', '1/25', '1/30', '1/40', '1/50', '1/60', '1/80', '1/100', '1/125', '1/160', '1/200', '1/250', '1/320', '1/400', '1/500', '1/640', '1/800', '1/1000', '1/1250', '1/1600', '1/2000', '1/2500', '1/3200', '1/4000', '1/5000', '1/6400', '1/8000', '1/10000', '1/12800', '1/16000']}, 'iso': {'value': '100', 'ability': ['auto', '100', '125', '160', '200', '250', '320', '400', '500', '640', '800', '1000', '1250', '1600', '2000', '2500', '3200', '4000', '5000', '6400', '8000', '10000', '12800', '16000', '20000', '25600']}, 'exposure': {'value': '', 'ability': []}, 'wb': {'value': 'colortemp', 'ability': ['auto', 'awbwhite', 'daylight', 'shade', 'cloudy', 'tungsten', 'whitefluorescent', 'flash', 'custom', 'colortemp']}, 'colortemperature': {'value': 6000, 'ability': {'min': 2500, 'max': 10000, 'step': 100}}, 'afoperation': {'value': 'manual'}, 'afmethod': {'value': 'face+tracking', 'ability': ['face+tracking', 'spot', '1point', 'zone']}, 'stillimagequality': {'value': {'raw': 'raw', 'jpeg': 'none'}, 'ability': {'raw': ['none', 'raw', 'craw'], 'jpeg': ['none', 'large_fine', 'large_normal', 'medium_fine', 'medium_normal', 'small1_fine', 'small1_normal', 'small2']}}, 'stillimageaspectratio': {'value': '3:2', 'ability': ['3:2', '4:3', '16:9', '1:1']}, 'flash': {'value': '', 'ability': []}, 'metering': {'value': 'evaluative', 'ability': ['evaluative', 'partial', 'spot', 'center_weighted_average']}, 'drive': {'value': 'single', 'ability': ['single', 'self_10sec', 'self_2sec']}, 'aeb': {'value': '', 'ability': []}, 'wbshift': {'value': {'ba': 0, 'mg': 0}, 'ability': {'ba': {'min': -9, 'max': 9, 'step': 1}, 'mg': {'min': -9, 'max': 9, 'step': 1}}}, 'wbbracket': {'value': '0', 'ability': ['0', 'ba1', 'ba2', 'ba3', 'mg1', 'mg2', 'mg3']}, 'colorspace': {'value': 'srgb', 'ability': ['srgb', 'adobe_rgb']}, 'picturestyle': {'value': 'auto', 'ability': ['auto', 'standard', 'portrait', 'landscape', 'finedetail', 'neutral', 'faithful', 'monochrome', 'userdef1', 'userdef2', 'userdef3']}, 'picturestyle_auto': {'value': {'sharpness_strength': 4, 'sharpness_fineness': 2, 'sharpness_threshold': 4, 'contrast': 0, 'saturation': 0, 'colortone': 0}, } ``` -------------------------------- ### Start and Stop Video Capture Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/zwo_camera/Untitled.ipynb Provides functions to start and stop continuous video streaming from the camera. This is useful for live viewing or high-frame-rate applications. ```python camera.start_video_capture() # ... video capture in progress ... camera.stop_video_capture() ``` -------------------------------- ### Initialize Calibration Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/mi_cryo_micro/20201213_Calibration/20200825_calibration_autodetected (spec calibration).ipynb Sets up grating constants and defines the calibration wavelength list for the spectrometer. ```python d_grating = 1e6/1200 #nm/groove px_offsets_data = [800] #center of chip in pixels n0 = np.mean(px_offsets_data) ###################################### INPUTS HERE ########## fname = '2021.10.11 Spectrometer Calibratio new gratings/211011_151340_1200 grat 532 laser_andor_spec_calib.h5' calibration_lines_wls = [ #404.66, #435.84, #546.08, 532 #579.07, #696.54, #738.40, #750.39, #763.51, #772.40, #794.82, #800.62, ] calibration_lines_wls = sorted(calibration_lines_wls) ``` -------------------------------- ### Initialize and Render Text with BitmapFont Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/elgato_streamdeck/Untitled.ipynb Demonstrates how to initialize a BitmapFont object with a pixel-setting function and render text onto a NumPy array. ```python import bitmapfont import numpy as np import matplotlib.pyplot as plt A = np.zeros((72,72)) def px_func(i,j): A[j,i] = 1 bf = bitmapfont.BitmapFont(72,72, px_func) bf.init() bf.text("Shutter",5,5) plt.imshow(A) ``` -------------------------------- ### Install ScopeFoundry Environment and Data Browser Source: https://github.com/berkeleylab/foundry_scope/blob/master/FoundryDataBrowser/README.md This snippet outlines the steps to set up a Python 3.5 environment using Anaconda for the Foundry Data Browser. It includes creating a virtual environment, activating it, and installing necessary dependencies like numpy, pyqt, qtpy, h5py, pyqtgraph, and the ScopeFoundry package itself from GitHub. Finally, it shows how to run the data browser. ```bash $ conda create -n scopefoundry python=3.5 $ source activate scopefoundry (scopefoundry) $ conda install numpy pyqt qtpy h5py (scopefoundry) $ pip install pyqtgraph (scopefoundry) $ pip install git+git://github.com/ScopeFoundry/ScopeFoundry.git (scopefoundry) $ python foundry_data_browser.py ``` -------------------------------- ### Setup Conditions Widget Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a widget displaying LED indicators and push buttons to show the status of desired conditions within the ALD recipe process. ```python def setup_display_controls(self): """Creates a dockArea widget containing other parameters to be set by the end user, including the length of plot time history and temperature data export path.""" pass ``` -------------------------------- ### Device Initialization Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/lambda_zup/zup_test.ipynb Establishes a connection to the ZUP power supply via the specified serial port. ```APIDOC ## Initialization ### Description Initializes the LambdaZup object to communicate with the hardware. ### Parameters - **port** (string) - Required - The serial port (e.g., 'COM5'). - **address** (int) - Required - The device address. - **always_send_address** (boolean) - Optional - Whether to prepend address to commands. - **debug** (boolean) - Optional - Enable debug logging. ### Request Example ```python zup = lambda_zup.LambdaZup(port="COM5", address=0x01, always_send_address=True, debug=True) ``` ``` -------------------------------- ### Control Device ID - C++ Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/Documentation/doc/ecc_8h_source.html Sets or gets the device ID. Requires a device handle, a pointer to an integer for the ID, and a boolean flag to indicate set or get operation. ```C++ Int32 ECC_controlDeviceId( Int32 deviceHandle, Int32* id, Bln32 set); ``` -------------------------------- ### Initialize Grating Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/ir_microscope/20190117_Calibration/190117_calibration_autodetected.ipynb Sets up initial parameters for grating calibration, including groove density, central wavelengths, and calibration line wavelengths. ```python fname = 'grating_3_data/190116_144255_calibration_sweep.h5' d_grating = 1e6/300 #nm /groove wl_center_data = [468.5, 469] n0 = np.mean(wl_center_data) calibration_lines_wls = [912.288, 965.770, 1013.975, 1128.71, 1529.582] calibration_lines_wls = sorted(calibration_lines_wls) ``` -------------------------------- ### Setup Operations Widget Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a widget with push buttons that allow the end user to initiate specific subroutines within the ALD recipe process. ```python def setup_operations_widget(self): """Creates operations widget which is meant to provide end user with push buttons which initiate specific subroutines of the ALD recipe process.""" pass ``` -------------------------------- ### ALD_App Initialization and Module Loading Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.html Demonstrates how to initialize the ALD_App and load the essential ALD_Recipe and ALD_Display modules in the correct order for proper application functionality. ```APIDOC ## ALD_App Initialization and Module Loading ### Description This section shows the core logic for initializing the ALD application and loading its primary measurement modules, ALD_Recipe and ALD_Display. It emphasizes the critical dependency and loading order required for these modules. ### Method N/A (Code Snippet) ### Endpoint N/A (Code Snippet) ### Parameters N/A ### Request Example ```python from ScopeFoundry.base_app import BaseMicroscopeApp class ALD_App(BaseMicroscopeApp): from ScopeFoundryHW.ALD.ALD_recipes.ALD_recipe import ALD_Recipe self.recipe_measure = self.add_measurement(ALD_Recipe(self)) from ScopeFoundryHW.ALD.ALD_recipes.ALD_display import ALD_Display self.display_measure = self.add_measurement(ALD_Display(self)).start() self.recipe_measure.load_display_module() if __name__ == '__main__': import sys app = ALD_App(sys.argv) sys.exit(app.exec_()) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Initialize ZWO ASI Camera SDK Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/zwo_camera/Untitled.ipynb Initializes the ZWO ASI camera SDK. This is a prerequisite for using any other camera functions. It requires the path to the SDK library. ```python import zwoasi as asi asi.init("ASI_linux_mac_SDK_V1.22/lib/mac/libASICamera2.dylib") ``` -------------------------------- ### Fetch Image Content via GET Request Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/canon_ccapi/ccapi_tests.ipynb Retrieves image content using a GET request to the specified URL. The 'kind' parameter is set to 'main'. The response status is indicated. ```python resp = requests.get('http://192.168.1.2:8080/ccapi/ver100/contents/sd/100CANON/IMG_0004.CR3', params={'kind':'main'}) ``` ```text Result: ``` -------------------------------- ### Control Amplitude - C Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/Documentation/doc/ecc_8h_source.html Sets or gets the amplitude for a specific axis on a device. It requires the device handle, axis number, and a pointer to an integer for the amplitude value. The 'set' parameter indicates whether to set or get the value. ```c Int32 ECC_controlAmplitude(Int32 deviceHandle, Int32 axis, Int32* amplitude, Bln32 set); ``` -------------------------------- ### Initialize MKS_600_Hardware Component Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.MKS_600.html Demonstrates the initialization of the MKS_600_Hardware class, which inherits from ScopeFoundry's HardwareComponent. This class manages the connection and control logic for the MKS 600 hardware. ```python from ALD.MKS_600.mks_600_hw import MKS_600_Hardware # Initialize the hardware component mks_hw = MKS_600_Hardware(app=app, debug=False, name='mks_600_hw') # Connect to the hardware mks_hw.connect() ``` -------------------------------- ### Start Pull Mode with Callback Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/toupcam/toupcam/docs.html Starts pull mode and calls a user-defined callback function when events occur. This function is called from an internal thread, so be mindful of multithreading issues. Do not call Toupcam_Stop or Toupcam_Close within this callback. ```c typedef void (__stdcall* PTOUPCAM_EVENT_CALLBACK)(unsigned nEvent, void* pCallbackCtx); HRESULT hr = Toupcam_StartPullModeWithCallback(h, pEventCallback, pCallbackContext); ``` -------------------------------- ### Initialize Camera and Retrieve Serial Number Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/andor3/Untitled.ipynb Demonstrates how to initialize the Andor SDK3 interface, connect to the first available camera, and print its serial number. ```python from pyAndorSDK3 import AndorSDK3 sdk3 = AndorSDK3() cam = sdk3.GetCamera(0) print(cam.SerialNumber) ``` -------------------------------- ### Start Pull Mode with Window Messages Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/toupcam/toupcam/docs.html Starts pull mode and posts events as Windows messages to a specified window. This function is Windows-specific. Ensure multithreading safety; do not call Toupcam_Stop or Toupcam_Close within the event callback. ```c typedef void (__stdcall* PTOUPCAM_EVENT_CALLBACK)(unsigned nEvent, void* pCallbackCtx); HRESULT hr = Toupcam_StartPullModeWithWndMsg(h, hWnd, nMsg, pEventCallback, pCallbackContext); ``` -------------------------------- ### Setup Pressures Subpanel Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a subpanel for displaying pressure sensor measurements and allows users to set target values for pressure controllers. ```python def setup_pressures_subpanel(self): """Creates pressures subpanel which display pressure sensor measurements. Subpanel includes measurement value fields and input fields which allow for user defined setpoints to be sent to pressure controllers.""" pass """Creates UI elements related to ALD pressure controllers, establishes signals and slots, as well as connections between UI elements and their associated _LoggedQuantities_. """ pass ``` -------------------------------- ### Control Target Range - C++ Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/Documentation/doc/ecc_8h_source.html Sets or gets the target range for a specified axis on a device. Requires a device handle, axis identifier, and a pointer to an integer for the range value. A boolean flag determines if the operation is a set or get. ```C++ Int32 ECC_controlTargetRange( Int32 deviceHandle, Int32 axis, Int32* range, Bln32 set); ``` -------------------------------- ### Initialize Calibration Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/mi_cryo_micro/20201213_Calibration/20200825_calibration_autodetected.ipynb Sets up the grating constant, pixel offsets, and the list of calibration wavelengths for the HDF5 file processing. ```python d_grating = 1e6/1200 #nm/groove px_offsets_data = [800] #center of chip in pixels n0 = np.mean(px_offsets_data) ###################################### INPUTS HERE ########## fname = 'grating_3_data/210805_170706_andor_spec_calib.h5' calibration_lines_wls = [ #404.66, #435.84, #546.08, 532 #579.07, #696.54, #738.40, #750.39, #763.51, #772.40, #794.82, #800.62, ] calibration_lines_wls = sorted(calibration_lines_wls) ``` -------------------------------- ### Configure Device Parameters Source: https://github.com/berkeleylab/foundry_scope/blob/master/TDTR/zi_test.ipynb Demonstrates how to set and get device parameters such as current gain and time constants using the daq session object. ```python daq.setInt('/dev1021/zctrls/0/tamp/1/currentgain', 1000) daq.setDouble("/dev1021/demods/0/timeconstant", 1.0) daq.getDouble("/dev1021/demods/0/timeconstant") ``` -------------------------------- ### ECC_controlDeviceId Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/LX32/userlib/doc/ecc_8h_source.html Sets or gets the device ID for a device. ```APIDOC ## ECC_controlDeviceId ### Description Sets or gets the device ID for a device. ### Method POST/GET (Assumed, depends on 'set' parameter) ### Endpoint `/bitbucket_berkeleylab/foundry_scope/ECC_controlDeviceId` ### Parameters #### Path Parameters None #### Query Parameters - **deviceHandle** (Int32) - Required - Handle to the device. - **id** (Int32*) - Required/Optional - Pointer to an integer for setting/getting the device ID. Required if 'set' is true. - **set** (Bln32) - Required - Boolean indicating whether to set (true) or get (false) the device ID. #### Request Body None ### Request Example ```json { "deviceHandle": 1, "id": 12345, "set": true } ``` ### Response #### Success Response (200) - **id** (Int32*) - Pointer to an integer where the device ID will be stored if 'set' is false. - **status** (Int32) - Indicates the success or failure of the operation. #### Response Example ```json { "id": "", "status": 0 } ``` ``` -------------------------------- ### Initialize ALD Application with ScopeFoundry Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.html Demonstrates the instantiation of the ALD_App class, which inherits from BaseMicroscopeApp. It highlights the mandatory loading sequence where the ALD_Recipe module must be initialized before the ALD_Display module to ensure proper inter-module dependency resolution. ```python from ScopeFoundry.base_app import BaseMicroscopeApp class ALD_App(BaseMicroscopeApp): from ScopeFoundryHW.ALD.ALD_recipes.ALD_recipe import ALD_Recipe self.recipe_measure = self.add_measurement(ALD_Recipe(self)) from ScopeFoundryHW.ALD.ALD_recipes.ALD_display import ALD_Display self.display_measure = self.add_measurement(ALD_Display(self)).start() self.recipe_measure.load_display_module() if __name__ == '__main__': import sys app = ALD_App(sys.argv) sys.exit(app.exec_()) ``` -------------------------------- ### Get Camera Handle Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/flircam/flir_ctypes_test.ipynb Retrieves a handle to a specific camera from the camera list. It initializes a void pointer for the camera handle and calls the library function to get the handle for the camera at index 0. The output displays the error code and the camera handle. ```Python #spinCamera hCamera = NULL; hCamera = c_void_p() err = lib.spinCameraListGet(hCameraList, 0, byref(hCamera)) print(err, hCamera) ``` -------------------------------- ### Setup Recipe Control Widget Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a widget for managing ALD recipe settings, including UI elements, signals, slots, and connections to associated data quantities. ```python def setup_recipe_control_widget(self): """Creates recipe control widget, UI elements related to ALD recipe settings, establishes signals and slots, as well as connections between UI elements and their associated _LoggedQuantities_""" pass ``` -------------------------------- ### Toupcam_put_LEDState Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/toupcam/toupcam/docs.html Controls the status of LED lights installed on the camera. ```APIDOC ## Toupcam_put_LEDState ### Description Controls the status of one or more LED lights installed on the camera. ### Parameters - **h** (HToupCam) - Required - Camera instance handle - **iLed** (unsigned short) - Required - Index of LED light - **iState** (unsigned short) - Required - LED status: 1 (Ever bright), 2 (Flashing), other (Off) - **iPeriod** (unsigned short) - Required - Flashing Period (>= 500ms) ### Response - **Return Value** (HRESULT) - Success or failure status ``` -------------------------------- ### GET /status Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/picomotor/Untitled1.ipynb Retrieves the current status of the Picomotor driver. ```APIDOC ## GET /status ### Description Queries the device status byte to determine the current state of the motor, including movement status. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **status** (int) - The status byte integer representing the driver state. #### Response Example { "status": 1 } ``` -------------------------------- ### Recipe Control Widget Setup Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_recipes.html Creates a recipe control widget for ALD recipe settings and includes a table for subroutine and main recipe data. ```APIDOC ## setup_recipe_control_widget ### Description Creates recipe control widget, UI elements related to ALD recipe settings, establishes signals and slots, as well as connections between UI elements and their associated _LoggedQuantities_ The table widget consists of a hierarchy of PyQt5 classes. The structure of the table widget assumes the following form: * `QWidget` * `QTableView` * `QTableModel` More specific to the case of the subroutine table: * `QWidget` (`subroutine_table_widget`) * `QTableView` (`subroutine_table`) * `QTableModel` (`subtableModel`) And in the case of the main recipe table: * `QWidget` (`table_widget`) * `QTableView` (`pulse_table`) * `QTableModel` (`tableModel`) See `ALD.ALD_recipes.ALD_display.setup_recipe_control_widget()` for details. ### Method N/A (This is a setup function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python self.table_widget = QtWidgets.QWidget() self.table_widget_layout = QtWidgets.QHBoxLayout() self.table_widget.setLayout(self.table_widget_layout) self.table_label = QtWidgets.QLabel('Table Label') self.table_widget.layout().addWidget(self.table_label) self.table = QtWidgets.QTableView() ## Optional height constraint. self.table.setMaximumHeight(65) names = ['List', 'of', 'column', 'labels'] self.tableModel = ArrayLQ_QTableModel(self.displayed_array, col_names=names) self.table.setModel(self.tableModel) self.table_widget.layout().addWidget(self.table) ### Add widget to enclosing outer widget self.containing_widget.layout().addWidget(self.table_widget) ``` ### Response N/A ``` -------------------------------- ### Get Firmware Version Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/Documentation/doc/ecc_8h.html Retrieves the firmware version of the device. ```APIDOC ## ECC_getFirmwareVersion ### Description Retrieves the version of actual firmware. ### Method GET ### Endpoint /api/devices/{deviceHandle}/firmwareVersion ### Parameters #### Path Parameters - **deviceHandle** (Int32) - Required - Handle of device ### Response #### Success Response (200) - **version** (Int32) - Version number. ``` -------------------------------- ### Plotting Data with Matplotlib Source: https://github.com/berkeleylab/foundry_scope/blob/master/TDTR/tdtd_h5_reader.ipynb Example of plotting data using matplotlib. ```python plt.plot(M['t'], -M['x']/M['y']) ``` -------------------------------- ### Resolution Management Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/toupcam/toupcam/docs.html Functions to get and set camera resolution settings. ```APIDOC ## Toupcam_put_Size / Toupcam_get_Size / Toupcam_put_eSize / Toupcam_get_eSize ### Description Sets or retrieves the current camera resolution using either width/height or a resolution index. ### Parameters - **h** (HToupCam) - Required - Instance handle - **nResolutionIndex** (ULONG) - Required - Resolution index - **nWidth** (LONG) - Required - Width - **nHeight** (LONG) - Required - Height ### Response - **HRESULT** (type) - Success or failure status ``` -------------------------------- ### Import Dependencies for Spectral Analysis Source: https://github.com/berkeleylab/foundry_scope/blob/master/ir_microscope/20190603_Calibration/190117_calibration_autodetected.ipynb Initializes the environment with necessary libraries for data handling, plotting, and peak detection. ```python from __future__ import division import numpy as np import matplotlib.pyplot as plt from pprint import pprint import numpy as np import h5py import peakutils from peakutils.plot import plot as pplot %matplotlib inline ``` -------------------------------- ### Get Position Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/Win64/doc/ecc_8h_source.html Retrieves the current position of a specified axis on a device. ```APIDOC ## GET /api/devices/{deviceHandle}/axes/{axis}/position ### Description Retrieves the current position of a specified axis on a device. ### Method GET ### Endpoint /api/devices/{deviceHandle}/axes/{axis}/position ### Parameters #### Path Parameters - **deviceHandle** (Int32) - Required - The handle of the device. - **axis** (Int32) - Required - The axis identifier. ### Response #### Success Response (200) - **position** (Int32) - Description: The current position value. #### Response Example ```json { "position": 750 } ``` ``` -------------------------------- ### Setup MFC Hardware Configuration Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.NI_MFC.html Initializes the MFC hardware by defining I/O port addresses, establishing logged quantities, creating data buffers, and mapping pin numbers to labels. It also sets the full scale and limit values for MFCs. ```python setup() ``` -------------------------------- ### ECC_controlAQuadBOutResolution Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/attocube_ecc100/attocube_ecc100/ECC100_Library/LX64/userlib/doc/ecc_8h_source.html Gets or sets the AQuadB output resolution for a specific axis. ```APIDOC ## ECC_controlAQuadBOutResolution ### Description Configures the resolution for the AQuadB output of a specific axis. ### Method FUNCTION ### Endpoint ECC_controlAQuadBOutResolution(Int32 deviceHandle, Int32 axis, Int32* resolution, Bln32 set) ### Parameters #### Path Parameters - **deviceHandle** (Int32) - Required - The handle of the target device. - **axis** (Int32) - Required - The axis index to control. - **resolution** (Int32*) - Required - Pointer to the resolution value. - **set** (Bln32) - Required - Flag to determine if setting (true) or getting (false) the value. ### Response #### Success Response (0) - **Return** (Int32) - Returns 0 on success. ``` -------------------------------- ### Instantiate and Get Camera Properties Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/zwo_camera/Untitled.ipynb Creates a camera object using its index and retrieves its properties. This includes details like maximum resolution, color information, pixel size, and whether it has a cooler or USB3 support. ```python cam = asi.Camera(0) properties = cam.get_camera_property() print(properties) ``` -------------------------------- ### GET /relay/status Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/ALD/doc/build/html/ALD.ALD_relay.html Polls the hardware to retrieve the current state of all relays. ```APIDOC ## GET /relay/poll ### Description Asks the Arduino to report on current relay states. ### Method GET ### Endpoint /relay/poll ### Response #### Success Response (200) - **relay_array** (array) - List of current states for all relay channels. #### Response Example { "relay_array": [1, 0, 0, 1] } ``` -------------------------------- ### Initialize and Acquire Image Data with FlirCamInterface Source: https://github.com/berkeleylab/foundry_scope/blob/master/ScopeFoundryHW/flircam/flircam_interface_test.ipynb This snippet demonstrates the lifecycle of a Flir camera session, including initialization, starting data acquisition, capturing a single frame as an image array, and safely releasing system resources. ```python from flircam_interface import FlirCamInterface try: cam = FlirCamInterface(debug=False) cam.start_acquisition() cam.print_device_info() test_data = cam.get_image(save_jpg=True) except Exception as ex: print('error') cam.stop_acquisition() cam.release_camera() cam.release_system() ```