### Configure Camera and Laser Source: https://synpivimage.readthedocs.io/en/latest/getting_started/OutOfPlane.html Setup the camera and laser parameters for the simulation. ```python cam = synpivimage.Camera( nx=256, ny=256, bit_depth=16, qe=1, sensitivity=1, baseline_noise=50, dark_noise=10, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=4, # px seed=100 ) laser = synpivimage.Laser( width=1, shape_factor=2 ) ``` -------------------------------- ### Initialize camera for noise testing Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Setup camera with specific dimensions and noise parameters. ```python cam = synpivimage.Camera( nx=128, ny=128, bit_depth=16, qe=1, sensitivity=1, baseline_noise=0, dark_noise=0, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=2, seed=10 ) ``` -------------------------------- ### Saving the image and setup Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Use the Imwriter context manager to save the generated image along with camera and laser settings. ```python with synpivimage.Imwriter(case_name='single_img', image_dir='.', suffix='.tif', overwrite=True, camera=cam, laser=laser) as iw: iw.write(0, img, particles=part) ``` -------------------------------- ### Initialize Camera and Laser Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Sets up the camera and laser parameters for image acquisition. Adjust these based on your experimental setup. ```python cam = synpivimage.Camera( nx=256, ny=256, bit_depth=16, qe=1, sensitivity=1, baseline_noise=50, dark_noise=10, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=4 # px ) laser = synpivimage.Laser( width=0.25, shape_factor=2 ) ``` -------------------------------- ### Configuring camera and laser components Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Initialize the camera and laser objects with specific parameters for the synthetic PIV setup. ```python cam = synpivimage.Camera( nx=16, ny=16, bit_depth=16, qe=1, sensitivity=1, baseline_noise=50, dark_noise=10, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=2, seed=100 ) laser = synpivimage.Laser( width=0.25, shape_factor=2 ) ``` -------------------------------- ### Virtual PIV Setup - Particles Class Source: https://synpivimage.readthedocs.io/en/latest/api.html Documentation for the Particles class used in Virtual PIV setup. ```APIDOC ## synpivimage.particles.Particles ### Description Particle class for Virtual PIV setup. ### Parameters - **x** (type) - Required - Description - **y** (type) - Required - Description - **z** (type) - Required - Description - **size** (type) - Required - Description ``` -------------------------------- ### Configure camera and particle parameters Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Setup for particles and camera objects to simulate particle image distribution. ```python one_particle = synpivimage.Particles( x=4, y=4, z=0, size=2 # this is NOT the image particle size! ) laser = synpivimage.Laser(shape_factor=10**3, width=1) cam = synpivimage.Camera( nx=8, ny=8, bit_depth=16, qe=1, sensitivity=1, baseline_noise=0, dark_noise=0, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=2, seed=10 ) ``` -------------------------------- ### Virtual PIV Setup - Laser Class Source: https://synpivimage.readthedocs.io/en/latest/api.html Documentation for the Laser class used in Virtual PIV setup. ```APIDOC ## synpivimage.laser.Laser ### Description Laser class for Virtual PIV setup. ### Parameters - **shape_factor** (type) - Required - Description - **width** (type) - Required - Description ### Methods - **save_jsonld**(filename) Save the component to JSON. - **load_jsonld**(filename) Load the Laser from a JSON-LD file. ``` -------------------------------- ### Virtual PIV Setup - Camera Class Source: https://synpivimage.readthedocs.io/en/latest/api.html Documentation for the Camera class used in Virtual PIV setup. ```APIDOC ## synpivimage.camera.Camera ### Description Camera Model class for Virtual PIV setup. ### Parameters - **nx** (type) - Required - Description - **ny** (type) - Required - Description - **seed** (type) - Optional - Description ### Methods - **save_jsonld**(filename) Save the component to JSON. - **load_jsonld**(filename) Load the camera from a JSON-LD file. ``` -------------------------------- ### GET /load_jsonld Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/laser.html Loads laser component objects from a JSON-LD file. ```APIDOC ## GET /load_jsonld ### Description Loads laser objects from a JSON-LD file. Note that this may return a list of objects if multiple lasers are defined in the file. ### Method GET ### Parameters #### Query Parameters - **filename** (Union[str, pathlib.Path]) - Required - The path or filename to load the component from. ### Response #### Success Response (200) - **lasers** (List[Laser]) - A list of loaded laser objects. ``` -------------------------------- ### Virtual PIV Setup API Source: https://synpivimage.readthedocs.io/en/latest/_sources/api.rst API endpoints and classes for configuring virtual PIV components including cameras, lasers, and particles. ```APIDOC ## synpivimage.camera.Camera ### Description Represents the camera configuration for the virtual PIV setup. ### Methods - **save_jsonld()**: Serializes the camera configuration to a JSON-LD format. - **load_jsonld()**: Loads a camera configuration from a JSON-LD file. ## synpivimage.laser.Laser ### Description Represents the laser configuration for the virtual PIV setup. ### Methods - **save_jsonld()**: Serializes the laser configuration to a JSON-LD format. - **load_jsonld()**: Loads a laser configuration from a JSON-LD file. ## synpivimage.particles.Particles ### Description Represents the particle configuration for the virtual PIV setup. ``` -------------------------------- ### Load and Plot Image from HDF5 Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/SingleImage.ipynb Use the `h5tbx` library to open an HDF5 file, load the 'img_A' dataset, and plot it using a grayscale colormap. Ensure the 'h5tbx' library is installed and the 'single_img.hdf' file exists. ```python with h5tbx.File('single_img.hdf') as h5: imgAloaded = h5.images.img_A[()] imgAloaded.plot(cmap='gray') ``` -------------------------------- ### Initialize synpivimage environment Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Basic imports required to use the synpivimage library. ```python import matplotlib.pyplot as plt import numpy as np import synpivimage ``` -------------------------------- ### Configure Camera and Particle Settings Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Initializes the camera and particle objects with specific parameters for simulation. ```python cam = synpivimage.Camera( nx=8, ny=8, bit_depth=16, qe=1, sensitivity=1, baseline_noise=10, dark_noise=0, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=2, seed=50 ) one_particles = synpivimage.Particles( x=4, y=4, z=0, size=2 ) ``` -------------------------------- ### GET /particles/info Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/particles.html Retrieves summary statistics and status information about the current particle set. ```APIDOC ## GET /particles/info ### Description Prints and returns diagnostic information including total count, active particles, and out-of-plane losses. ### Method GET ### Response #### Success Response (200) - **n_particles** (int) - Total count of simulated particles - **n_active** (int) - Number of illuminated particles in FOV - **n_out_of_plane** (int) - Number of particles outside the measurement plane ``` -------------------------------- ### Initialize Camera and Laser Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/DoubleImage.ipynb Configure the camera sensor and laser sheet parameters. ```python cam = synpivimage.Camera( nx=256, ny=256, bit_depth=16, qe=1, sensitivity=1, baseline_noise=50, dark_noise=10, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=4 # px ) laser = synpivimage.Laser( width=0.25, shape_factor=2 ) ``` -------------------------------- ### Initialize particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Create a set of particles for illumination testing. ```python many_particles = synpivimage.Particles( x=np.ones_like(z), y=np.ones_like(z), z=z, size=np.ones_like(z) ) ``` -------------------------------- ### Get Image Histogram Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/OutOfPlane.ipynb Calculates and returns the histogram of an image. The histogram represents the distribution of pixel intensities. ```python from synpivimage.synpivimage import Synpivimage img = Synpivimage.load_image("/path/to/your/image.png") histogram = img.get_histogram() print(histogram) ``` -------------------------------- ### Configure camera Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Set up camera parameters for image acquisition simulation. ```python cam = synpivimage.Camera( nx=16, ny=16, bit_depth=16, qe=1, sensitivity=1, baseline_noise=0, dark_noise=0, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=1.0 ) ``` -------------------------------- ### Create Camera and Laser components Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/IO.ipynb Instantiate camera and laser objects with specific physical parameters. ```python cam = synpivimage.Camera( nx=128, ny=128, bit_depth=16, qe=1, sensitivity=1, baseline_noise=0, dark_noise=0, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=1.0 ) gauss_laser = synpivimage.Laser( width=1.4, shape_factor=2 ) ``` -------------------------------- ### Initialize Laser and Camera Parameters Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/Laser.ipynb Set up the laser and camera configurations for particle image velocimetry simulations. Ensure all necessary parameters like width, shape factor, resolution, bit depth, and noise levels are correctly defined. ```python laser = synpivimage.Laser( width=1.0, shape_factor=1 ) cam = synpivimage.Camera( nx=16, ny=16, bit_depth=16, qe=1, sensitivity=1, baseline_noise=200, dark_noise=100, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=1.0 ) ``` -------------------------------- ### Get Dictionary Representation Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/particles.html Returns a dictionary representation of the particle data, including coordinates, size, flag, and intensity-related properties. ```python def dict(self) -> Dict: """Returns a dictionary representation of the particle data""" return {'x': self.x, 'y': self.y, 'z': self.z, 'size': self.size, 'flag': self.flag, 'source_intensity': self.source_intensity, 'max_image_photons': self.max_image_photons, 'image_electrons': self.image_electrons, 'image_quantized_electrons': self.image_quantized_electrons} ``` -------------------------------- ### Instantiate new laser from loaded parameters Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/IO.ipynb Create a new synpivimage Laser object using the parameters extracted from the ontology model. ```python loaded_gauss_laser = synpivimage.Laser( width=lst, shape_factor=lsf ) loaded_gauss_laser ``` -------------------------------- ### Initialize Particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/OutOfPlane.html Create a set of particles with random spatial distributions. ```python n = 2000 particles = synpivimage.Particles( x=np.random.uniform(-3, cam.nx+2, n), y=np.random.uniform(-4, cam.ny+2, n), z=np.random.uniform(-2, 2, n), size=np.ones(n)*3, ) ``` -------------------------------- ### Define a Single Particle Object Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Initializes a `Particles` object to represent a single particle with its position and size. This is a setup step for subsequent image analysis. ```python one_particle = synpivimage.Particles( x=[8, ], y=[8, ], z=[0, ], size=[2, ] ) ``` -------------------------------- ### Load Laser and Camera Data from JSON-LD Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Load laser and camera configuration from JSON-LD files. Ensure the files exist at the specified paths. ```python loaded_laser = synpivimage.Laser.load_jsonld('single_img/laser.json') loaded_camera = synpivimage.Camera.load_jsonld('single_img/camera.json') ``` -------------------------------- ### Get Integer Peak Coordinates from Correlation Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Finds the coordinates of the highest peak in a correlation map. This function is used to determine the most likely displacement vector. ```python def get_integer_peak(corr): """Computes the cross-correlation of two images using the Fourier method.""" corr = np.asarray(corr) ind = corr.ravel().argmax(-1) peaks = np.array(np.unravel_index(ind, corr.shape[-2:])) peaks = np.vstack((peaks[0], peaks[1])).T index_list = [(i, v[0], v[1]) for i, v in enumerate(peaks)] # peaks_max = np.nanmax(corr, axis=(-2, -1)) # np.array(index_list), np.array(peaks_max) iy, ix = index_list[0][2], index_list[0][1] return iy, ix ``` -------------------------------- ### Instantiate Laser Component Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Instantiate a Laser component using the extracted parameters. This assumes the 'params' dictionary is correctly populated. ```python synpivimage.Laser(**params) ``` -------------------------------- ### Method: Camera.load_jsonld Source: https://synpivimage.readthedocs.io/en/latest/_sources/generated/synpivimage.camera.Camera.load_jsonld.rst Documentation for the load_jsonld method used to initialize camera parameters from a JSON-LD file. ```APIDOC ## Camera.load_jsonld ### Description Loads camera configuration data from a JSON-LD formatted source into the Camera instance. ### Method Method call ### Endpoint synpivimage.camera.Camera.load_jsonld ``` -------------------------------- ### Import synpivimage Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/IO.ipynb Initial import required to access the library functionality. ```python import synpivimage ``` -------------------------------- ### Configure and visualize noise (μ=50, σ=10) Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Set baseline and dark noise parameters and visualize the resulting image. ```python cam.baseline_noise = 50 cam.dark_noise = 10 img, _ = synpivimage.take_image(particles=no_particles, camera=cam, laser=laser, particle_peak_count=1000) plt.imshow(img) plt.title(f"$\\mu$= {cam.baseline_noise}, $\\sigma$={cam.dark_noise}") ``` -------------------------------- ### Initialize Particle Data Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/particles.html Initializes particle data with random uniform distributions for x, y, and z coordinates. If limits are not provided, it uses the min/max of existing data. ```python self._x = np.random.uniform(*self._xlim, N) if self._ylim is None: self._y = np.random.uniform(min(self.y), max(self.y), N) else: self._y = np.random.uniform(*self._ylim, N) if self._ylim is None: self._z = np.random.uniform(min(self.z), max(self.z), N) else: self._z = np.random.uniform(*self._zlim, N) return self ``` -------------------------------- ### Calculate Initial Particle Density (ppp) Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Calculates and prints the particles per pixel (ppp) for both acquired images (imgA and imgB) using the current particle distribution and camera size. ```python partA.get_ppp(cam.size), partB.get_ppp(cam.size) ``` ```python (0.0014801025390625, 0.001495361328125) ``` -------------------------------- ### Method: Laser.load_jsonld Source: https://synpivimage.readthedocs.io/en/latest/_sources/generated/synpivimage.laser.Laser.load_jsonld.rst Documentation for the load_jsonld method used to import JSON-LD formatted data into the Laser class instance. ```APIDOC ## Laser.load_jsonld ### Description Loads JSON-LD data into the Laser object instance. ### Method Method call ### Endpoint synpivimage.laser.Laser.load_jsonld ``` -------------------------------- ### Import Dependencies Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/DoubleImage.ipynb Initial imports required for the synpivimage workflow. ```python import numpy as np import synpivimage ``` -------------------------------- ### Configure and visualize noise (μ=0, σ=10) Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Update noise parameters and visualize the resulting image. ```python cam.baseline_noise = 0 cam.dark_noise = 10 ``` ```python img, _ = synpivimage.take_image(particles=no_particles, camera=cam, laser=laser, particle_peak_count=1000) plt.imshow(img) plt.title(f"$\\mu$= {cam.baseline_noise}, $\\sigma$={cam.dark_noise}") ``` -------------------------------- ### Configure and visualize noise (μ=10, σ=0) Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Update noise parameters and visualize the resulting image. ```python cam.baseline_noise = 10 cam.dark_noise = 0 ``` ```python img, _ = synpivimage.take_image(particles=no_particles, camera=cam, laser=laser, particle_peak_count=1000) plt.imshow(img) plt.title(f"$\\mu$= {cam.baseline_noise}, $\\sigma$={cam.dark_noise}") ``` -------------------------------- ### Camera Class Initialization Source: https://synpivimage.readthedocs.io/en/latest/generated/synpivimage.camera.Camera.html Initializes a Camera model by parsing and validating input data. Raises ValidationError if data is invalid. ```APIDOC ## Camera.__init__() ### Description Create a new model by parsing and validating input data from keyword arguments. Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. self is explicitly positional-only to allow self as a field name. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (*) - Description: Input data for model creation. - Required: Yes ### Request Example ```json { "nx": 1024, "ny": 1024, "bit_depth": 16, "qe": 0.8, "sensitivity": 1.0, "baseline_noise": 0.1, "dark_noise": 0.01, "shot_noise": 0.05, "fill_ratio_x": 0.9, "fill_ratio_y": 0.9, "particle_image_diameter": 5, "seed": 42 } ``` ### Response #### Success Response (200) - **Camera Model Instance**: A new instance of the Camera model. #### Response Example ```json { "nx": 1024, "ny": 1024, "bit_depth": 16, "qe": 0.8, "sensitivity": 1.0, "baseline_noise": 0.1, "dark_noise": 0.01, "shot_noise": 0.05, "fill_ratio_x": 0.9, "fill_ratio_y": 0.9, "particle_image_diameter": 5, "seed": 42 } ``` ``` -------------------------------- ### Load and Display Image Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/OutOfPlane.ipynb Loads an image from a file path and displays it. Ensure the image file exists at the specified path. ```python from synpivimage.synpivimage import Synpivimage img = Synpivimage.load_image("/path/to/your/image.png") img.show() ``` -------------------------------- ### Import matplotlib Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Import plotting library for visualization. ```python import matplotlib.pyplot as plt ``` -------------------------------- ### Laser Class Initialization Source: https://synpivimage.readthedocs.io/en/latest/generated/synpivimage.laser.Laser.html Initializes the Laser class with specified parameters. The class is used to illuminate particles. ```APIDOC ## Laser Class ### Description This class will be used to illuminate the particles. The Gaussian distribution is found for shape_factor=1, not =2 as in the literature. width is the width of the laser, where the intensity drops to 0.67. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (*) - **shape_factor** (*) - **width** (*) ### Request Example ```json { "shape_factor": 1.0, "width": 10.0 } ``` ### Response #### Success Response (200) - **Laser object**: An instance of the Laser class. #### Response Example ```json { "shape_factor": 1.0, "width": 10.0 } ``` ``` -------------------------------- ### Method: save_jsonld Source: https://synpivimage.readthedocs.io/en/latest/_sources/generated/synpivimage.laser.Laser.save_jsonld.rst Exports the current laser configuration to a JSON-LD file. ```APIDOC ## save_jsonld ### Description Saves the laser configuration data associated with the Laser instance into a JSON-LD formatted file. ### Method Internal Method (Python) ### Endpoint synpivimage.laser.Laser.save_jsonld ``` -------------------------------- ### Take First Image and Displace Particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Acquires the first image (imgA) with the initial particle distribution and then displaces these particles by a specified amount (dx, dy) to prepare for the second image acquisition. ```python imgA, partA = synpivimage.take_image(laser, cam, particles, particle_peak_count=1000) displaced_particles = partA.displace(dx=2.1, dy=3.4) ``` -------------------------------- ### POST /save_jsonld Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/laser.html Saves the current laser component configuration to a specified file in JSON-LD format. ```APIDOC ## POST /save_jsonld ### Description Saves the component data to a JSON-LD file. ### Method POST ### Parameters #### Request Body - **filename** (Union[str, pathlib.Path]) - Required - The path or filename where the component data will be saved. ### Response #### Success Response (200) - **path** (pathlib.Path) - The path to the saved file. ``` -------------------------------- ### Import synpivimage dependencies Source: https://synpivimage.readthedocs.io/en/latest/getting_started/OutOfPlane.html Initial imports required for numerical operations, plotting, and the synpivimage library. ```python import numpy as np import matplotlib.pyplot as plt import synpivimage ``` -------------------------------- ### Load components from JSON-LD Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/IO.ipynb Import necessary ontology classes to reconstruct objects from JSON-LD files. ```python from pivmetalib.pivmeta import LaserModel from ontolutils.namespacelib import PIVMETA ``` -------------------------------- ### Save components to JSON-LD Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/IO.ipynb Persist camera and laser configurations to JSON-LD files. ```python cam_filename = cam.save_jsonld('cam.json') gauss_laser_filename = gauss_laser.save_jsonld('laser.json') ``` -------------------------------- ### Particles Class Documentation Source: https://synpivimage.readthedocs.io/en/latest/_sources/generated/synpivimage.particles.Particles.rst Detailed documentation for the Particles class, including its constructor, methods, and attributes. ```APIDOC ## Particles Class ### Description Represents and manages a collection of particles, providing methods for initialization, manipulation, generation, and data handling. ### Methods #### `__init__` Initializes a new instance of the Particles class. #### `copy()` Creates a copy of the current Particles object. #### `dict()` Returns a dictionary representation of the Particles object. #### `displace(dx, dy, dz)` Displaces particles by the specified amounts in x, y, and z directions. #### `generate()` Generates particles based on internal configurations. #### `generate_uniform()` Generates particles with a uniform distribution. #### `get_ppp()` Retrieves particles per pixel information. #### `info()` Returns general information about the particle collection. #### `load_jsonld(filepath)` Loads particle data from a JSON-LD file. #### `model_dump()` Returns a dictionary representation of the model (similar to `dict`). #### `regenerate()` Regenerates particles, potentially updating their properties. #### `reset()` Resets the particles to their initial state. #### `save_json(filepath)` Saves the particle data to a JSON file. #### `save_jsonld(filepath)` Saves the particle data to a JSON-LD file. ### Attributes #### `active` (bool) Indicates if the particle is active. #### `disabled` (bool) Indicates if the particle is disabled. #### `flag` (int) A flag associated with the particle. #### `image_electrons` (float) Number of electrons in the particle's image. #### `image_quantized_electrons` (float) Quantized number of electrons in the particle's image. #### `in_fov` (bool) Indicates if the particle is within the field of view. #### `in_fov_and_out_of_plane` (bool) Indicates if the particle is within the field of view and out of plane. #### `inactive` (bool) Indicates if the particle is inactive. #### `irrad_photons` (float) Number of irradiated photons. #### `max_image_photons` (float) Maximum number of photons in the particle's image. #### `n_active` (int) Number of active particles. #### `n_out_of_plane_loss` (int) Number of out-of-plane losses. #### `n_particles` (int) Total number of particles. #### `out_of_plane` (bool) Indicates if the particle is out of plane. #### `size` (float) The size of the particle. #### `source_density_number` (float) Number density of the particle source. #### `source_intensity` (float) Intensity of the particle source. #### `x` (float) X-coordinate of the particle. #### `y` (float) Y-coordinate of the particle. #### `z` (float) Z-coordinate of the particle. ``` -------------------------------- ### Handle IndexError in Query Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html This traceback indicates that the list 'query_dict[0]['hasParameter']' was empty, meaning no parameters were found for the 'pivmeta:LaserModel' in the specified JSON-LD file. Ensure the file contains the expected data. ```python --------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[15], line 7 1 query_dict = ontolutils.dquery( 2 'pivmeta:LaserModel', 3 'single_img/laser.json', 4 context={'pivmeta': 'https://matthiasprobst.github.io/pivmeta#'} 5 ) ----> 7 for p in query_dict[0]['hasParameter']: 8 print(f"{p['label']:14s}: {p['hasNumericalValue']} (std name: {p['hasStandardName']})") IndexError: list index out of range ``` -------------------------------- ### Initialize Particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Creates an initial set of particles with random positions, sizes, and zero z-coordinates. Particles are seeded outside the camera's field of view to allow for movement into it. ```python n = 100 particles = synpivimage.Particles( x=np.random.uniform(-3, cam.nx-1, n), y=np.random.uniform(-4, cam.ny-1, n), z=np.zeros(n), size=np.ones(n)*2, ) ``` -------------------------------- ### Define laser profiles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Create Gaussian and top-hat laser sheet profiles with a specified width. ```python z = np.linspace(-2, 2, 10000) gauss_laser = synpivimage.Laser( width=1, shape_factor=1 ) tophat_laser = synpivimage.Laser( width=1, shape_factor=10 ) ``` -------------------------------- ### Generate Initial Particles Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/DoubleImage.ipynb Create a set of particles with random positions, including some outside the field of view. ```python n = 100 particles = synpivimage.Particles( x=np.random.uniform(-3, cam.nx-1, n), y=np.random.uniform(-4, cam.ny-1, n), z=np.zeros(n), size=np.ones(n)*2, ) ``` -------------------------------- ### Save and Load Camera Configuration Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/camera.html Methods for saving the current camera configuration to a JSON-LD file and loading configurations from a file. ```APIDOC ## POST /api/camera/save ### Description Saves the current camera configuration to a specified JSON-LD file. ### Method POST ### Endpoint /api/camera/save ### Parameters #### Request Body - **filename** (string) - Required - The path to the file where the camera configuration will be saved. ### Response #### Success Response (200) - **filename** (string) - The path to the saved JSON-LD file. ## GET /api/camera/load ### Description Loads camera configurations from a specified JSON-LD file. Returns a list of camera objects. ### Method GET ### Endpoint /api/camera/load ### Parameters #### Query Parameters - **filename** (string) - Required - The path to the JSON-LD file to load. ### Response #### Success Response (200) - **cameras** (list) - A list of camera objects loaded from the file. #### Response Example ```json { "cameras": [ { "@context": { "@import": "https://raw.githubusercontent.com/matthiasprobst/pivmeta/main/pivmeta_context.jsonld" }, "@type": "pivmeta:VirtualCamera", "hasParameter": [ { "label": "bit_depth", "value": 12, "unit": "http://qudt.org/vocab/unit/BIT", "qkind": "http://qudt.org/schema/qudt/InformationEntropy", "standard_name": "sensor_bit_depth", "description": "The bit depth of the sensor." } ], "shot_noise": "true" } ] } ``` ``` -------------------------------- ### Capture Image Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/camera.html The take_image method simulates the full image acquisition process, including particle modeling and noise application. ```python def take_image(self, particles: Particles) -> Tuple[np.ndarray, int]: """capture and quantize the image. .. note:: The definition of the image particle diameter is the diameter of the particle image in pixels, where the normalized gaussian is equal to $e^{-2}$, which is a full width of $4 \sigma$. Returns image and number of saturated pixels. """ # active = particles.active active = particles.in_fov irrad_photons, particles.max_image_photons[active] = model_image_particles( particles[active], nx=self.nx, ny=self.ny, sigmax=self.particle_image_diameter / 4, sigmay=self.particle_image_diameter / 4, fill_ratio_x=self.fill_ratio_x, fill_ratio_y=self.fill_ratio_y ) electrons = self._capture(irrad_photons) particles.image_electrons[active] = self._capture(particles.max_image_photons[active]) particles.image_quantized_electrons[active] = self._quantize(particles.image_electrons[active])[0] return self._quantize(electrons) ``` -------------------------------- ### GaussShapeLaser Initialization Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/laser.html Initializes a Gaussian laser with a specified width. This class inherits from Laser and sets the shape_factor to 1. ```python class GaussShapeLaser(Laser): """Gaussian laser""" def __init__(self, width: float): super().__init__(shape_factor=1, width=width) ``` -------------------------------- ### Simulate noise influence Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Configure laser and camera with noise to observe impact on effective laser width. ```python laser = synpivimage.Laser( width=1.0, shape_factor=1 ) cam = synpivimage.Camera( nx=16, ny=16, bit_depth=16, qe=1, sensitivity=1, baseline_noise=200, dark_noise=100, shot_noise=False, fill_ratio_x=1.0, fill_ratio_y=1.0, particle_image_diameter=1.0 ) many_particles.reset() imgOne, partOne = synpivimage.take_image(laser, cam, many_particles, particle_peak_count=1000) plt.scatter(partOne.z[partOne.active], partOne.max_image_photons[partOne.active], color='g', label='active') plt.scatter(partOne.z[~partOne.active], partOne.max_image_photons[~partOne.active], color='k', label='inactive') ``` -------------------------------- ### Import Ontolutils Library Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Import the ontolutils library for querying JSON-LD files. ```python import ontolutils ``` -------------------------------- ### Write Data to HDF5 Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Initializes an HDF5Writer to store image and particle data, followed by a dump of the file structure. ```python import h5rdmtoolbox as h5tbx ``` ```python with synpivimage.HDF5Writer(filename='single_img.hdf', n_images=1, camera=cam, laser=laser, overwrite=True) as h5: h5.writeA(0, img, particles=part) h5.writeA(0, img, particles=part) h5tbx.dump('single_img.hdf') ``` -------------------------------- ### Initialize Particles and Define FFT Cross-Correlation Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/Laser.ipynb Sets up a particle object and defines functions for computing cross-correlation via FFT, finding integer peaks, and performing 3-point Gaussian sub-pixel interpolation. ```python one_particle = synpivimage.Particles( x=[8, ], y=[8, ], z=[0, ], size=[2, ] ) from scipy.fft import rfft2, irfft2, fftshift def compute_fft_xcorr(imgA, imgB): """Computes the cross-correlation of two images using the Fourier method.""" f2a = np.conj(rfft2(imgA)) f2b = rfft2(imgB) return fftshift(irfft2(f2a * f2b).real, axes=(-2, -1)) def get_integer_peak(corr): corr = np.asarray(corr) ind = corr.ravel().argmax(-1) peaks = np.array(np.unravel_index(ind, corr.shape[-2:])) peaks = np.vstack((peaks[0], peaks[1])).T index_list = [(i, v[0], v[1]) for i, v in enumerate(peaks)] # peaks_max = np.nanmax(corr, axis=(-2, -1)) # np.array(index_list), np.array(peaks_max) iy, ix = index_list[0][2], index_list[0][1] return iy, ix def gauss3pt(arr): """assuming highest peak is at the center of the array""" assert arr.shape == (3, 3), f'Wrong shape {arr.shape}' cl = arr[1, 0] cc = arr[1, 1] cr = arr[1, 2] cu = arr[2, 1] cd = arr[0, 1] nom1 = np.log(cl) - np.log(cr) den1 = 2 * np.log(cl) - 4 * np.log(cc) + 2 * np.log(cr) nom2 = np.log(cd) - np.log(cu) den2 = 2 * np.log(cd) - 4 * np.log(cc) + 2 * np.log(cu) subp_peak_position = ( 1 + np.divide(nom2, den2, out=np.zeros(1), where=(den2 != 0.0))[0], 1 + np.divide(nom1, den1, out=np.zeros(1), where=(den1 != 0.0))[0] ) return subp_peak_position N = 10 ``` -------------------------------- ### Generate Particles by Density Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/DoubleImage.ipynb Automatically calculate the required number of particles to achieve a target ppp value. ```python particles01 = synpivimage.Particles.generate(ppp=0.1, dx_max=[0, 2.1], dy_max=[0, 3.4], dz_max=[0, 0], camera=cam, laser=laser) particles01.get_ppp(cam.size) ``` -------------------------------- ### Constructor: Particles.__init__ Source: https://synpivimage.readthedocs.io/en/latest/generated/synpivimage.particles.Particles.html Initializes a new instance of the Particles class with spatial and intensity parameters. ```APIDOC ## __init__ ### Description Initializes the Particles object with coordinates, size, and intensity properties. ### Parameters #### Request Body - **x** (np.ndarray) - Required - x-coordinate of the particles on the sensor in pixels - **y** (np.ndarray) - Required - y-coordinate of the particles on the sensor in pixels - **z** (np.ndarray) - Required - z-coordinate of the particles on the sensor in arbitrary units - **size** (np.ndarray) - Required - Particle size in pixels - **source_intensity** (np.ndarray) - Optional - Source intensity of the particles - **max_image_photons** (np.ndarray) - Optional - Maximum number of photons on the sensor - **image_electrons** (np.ndarray) - Optional - Number of electrons on the sensor - **image_quantized_electrons** (np.ndarray) - Optional - Number of quantized electrons on the sensor - **flag** (np.ndarray) - Optional - Status flag of the particle ``` -------------------------------- ### Illuminate particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Apply laser profiles to the particle set. ```python gauss_iluminated_particles = gauss_laser.illuminate(many_particles) tophat_iluminated_particles = tophat_laser.illuminate(many_particles) ``` -------------------------------- ### Visualize noise-free image Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Camera.html Capture and display an image with baseline and dark noise set to zero. ```python img, _ = synpivimage.take_image(particles=no_particles, camera=cam, laser=laser, particle_peak_count=1000) plt.imshow(img) plt.title(f"$\\mu$= {cam.baseline_noise}, $\\sigma$={cam.dark_noise}") ``` -------------------------------- ### POST /particles/generate Source: https://synpivimage.readthedocs.io/en/latest/_modules/synpivimage/particles.html Generates a new set of particles based on specified density, displacement limits, and hardware models. ```APIDOC ## POST /particles/generate ### Description Generates particles based on a certain ppp (particles per pixel). The camera and laser models are used to determine the sensor size and laser width. ### Method POST ### Parameters #### Request Body - **ppp** (float) - Required - Particles per pixel - **dx_max** (float) - Required - Maximum displacement in x-direction - **dy_max** (float) - Required - Maximum displacement in y-direction - **dz_max** (float) - Required - Maximum displacement in z-direction - **size** (float) - Required - Particle size - **camera** (Camera) - Required - Camera model - **laser** (Laser) - Required - Laser model ``` -------------------------------- ### Query Laser Parameters from JSON-LD Source: https://synpivimage.readthedocs.io/en/latest/getting_started/SingleImage.html Query laser parameters from a JSON-LD file using ontolutils. The context dictionary maps prefixes to URIs. This code iterates through the 'hasParameter' list, which might be empty, leading to an IndexError if not handled. ```python query_dict = ontolutils.dquery( 'pivmeta:LaserModel', 'single_img/laser.json', context={'pivmeta': 'https://matthiasprobst.github.io/pivmeta#'} ) for p in query_dict[0]['hasParameter']: print(f"{p['label']:14s}: {p['hasNumericalValue']} (std name: {p['hasStandardName']})") ``` -------------------------------- ### Import necessary libraries Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Imports the numpy and synpivimage libraries for numerical operations and image processing. ```python import numpy as np import synpivimage ``` -------------------------------- ### Laser.save_jsonld() Source: https://synpivimage.readthedocs.io/en/latest/generated/synpivimage.laser.Laser.save_jsonld.html Saves the component to a JSON file. ```APIDOC ## POST /websites/synpivimage_readthedocs_io_en/Laser/save_jsonld ### Description Saves the component to JSON. ### Method POST ### Endpoint /websites/synpivimage_readthedocs_io_en/Laser/save_jsonld ### Parameters #### Path Parameters - **_filename_** (Union[str, pathlib.Path]) - Required - The filename to save the component to ### Request Body This endpoint does not explicitly define a request body in the provided text. However, it is implied that the component data to be saved is associated with the instance of the Laser class. ### Response #### Success Response (200) - **filename** (pathlib.Path) - The filename the component was saved to #### Response Example { "filename": "path/to/saved/component.json" } ``` -------------------------------- ### Calculate ppp for Generated Particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Calculates and prints the particles per pixel (ppp) for both images after using particles generated with a target ppp. This verifies the effectiveness of the particle generation method. ```python partA.get_ppp(cam.size), partB.get_ppp(cam.size) ``` -------------------------------- ### Capture image Source: https://synpivimage.readthedocs.io/en/latest/getting_started/Laser.html Simulate image acquisition with the defined laser and camera. ```python imgOne, partOne = synpivimage.take_image(gauss_laser, cam, many_particles, particle_peak_count=1000) ``` -------------------------------- ### Take Images with Generated Particles Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Acquires two images (imgA and imgB) using particles generated with a specific ppp value. The particles are then displaced between the image acquisitions. ```python imgA, partA = synpivimage.take_image(laser, cam, particles01, # we passed out new object here! particle_peak_count=1000) displaced_particles = partA.displace(dx=2.1, dy=3.4) imgB, partB = synpivimage.take_image(laser, cam, displaced_particles, particle_peak_count=1000) ``` -------------------------------- ### Import HDF5 Toolbox Source: https://synpivimage.readthedocs.io/en/latest/_sources/getting_started/SingleImage.ipynb Imports the h5rdmtoolbox for HDF5 file operations. ```python import h5rdmtoolbox as h5tbx ``` -------------------------------- ### Camera Methods Source: https://synpivimage.readthedocs.io/en/latest/generated/synpivimage.camera.Camera.html Provides details on various methods available for the Camera class, including data manipulation, serialization, and image capture. ```APIDOC ## Camera Class Methods ### Description This section outlines the available methods for interacting with the Camera model, including data handling, serialization, and image capture. ### Methods - **construct**([_fields_set]) - Description: Creates a new instance of the Model class with validated data. - **copy**(*[, include, exclude, update, deep]) - Description: Returns a copy of the model. - **dict**(*[, include, exclude, by_alias, ...]) - Description: Serializes the model to a dictionary. - **from_orm**(obj) - Description: Creates a model instance from an ORM object. - **json**(*[, include, exclude, by_alias, ...]) - Description: Serializes the model to a JSON string. - **load_jsonld**(filename) - Description: Load the camera from a JSON-LD file. - **model_construct**([_fields_set]) - Description: Creates a new instance of the Model class with validated data. - **model_copy**(*[, update, deep]) - Description: Returns a copy of the model with optional updates. - **model_dump**(*[, mode, include, exclude, ...]) - Description: Dumps the model to a dictionary-like structure. - **model_dump_json**(*[, indent, include, ...]) - Description: Dumps the model to a JSON string. - **model_dump_jsonld**() - Description: Returns the model as a JSON-LD string. - **model_json_schema**([by_alias, ref_template, ...]) - Description: Generates a JSON schema for the model class. - **model_parametrized_name**(params) - Description: Computes the class name for parametrizations of generic classes. - **model_post_init**(_BaseModel__context) - Description: Override this method to perform additional initialization after __init__ and model_construct. - **model_rebuild**(*[, force, raise_errors, ...]) - Description: Tries to rebuild the pydantic-core schema for the model. - **model_validate**(obj, *[, strict, ...]) - Description: Validates a pydantic model instance. - **model_validate_json**(json_data, *[, strict, ...]) - Description: Validates a JSON string against the Pydantic model. - **model_validate_strings**(obj, *[, strict, context]) - Description: Validates the given object with string data against the Pydantic model. - **parse_file**(path, *[, content_type, ...]) - Description: Parses data from a file. - **parse_obj**(obj) - Description: Parses data from an object. - **parse_raw**(b, *[, content_type, encoding, ...]) - Description: Parses raw data. - **save_json**(filename) - Description: Saves the component to a JSON file. - **save_jsonld**(filename) - Description: Saves the component to a JSON-LD file. - **schema**([by_alias, ref_template]) - Description: Generates a JSON schema for the model. - **schema_json**(*[, by_alias, ref_template]) - Description: Generates a JSON schema for the model as a JSON string. - **take_image**(particles) - Description: Captures and quantizes the image. - Parameters: - **particles** (*): Description of the particles parameter. - **update_forward_refs**(**localns) - Description: Updates forward references. - **validate**(value) - Description: Validates a given value. ``` -------------------------------- ### Import Matplotlib for Plotting Source: https://synpivimage.readthedocs.io/en/latest/getting_started/DoubleImage.html Imports the matplotlib.pyplot library for visualizing the acquired images. ```python import matplotlib.pyplot as plt ```