### Configure Instrument Parameters for Feature Object Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Instantiates a Feature object with a Lorenz-Mie model and configures instrument-specific parameters such as wavelength, magnification, and medium refractive index. These constants are crucial for accurate analysis and may vary between hardware setups. ```python feature = Feature(model=LMHologram(double_precision=False)) # Instrument configuration ins = feature.model.instrument ins.wavelength = 0.447 # [um] ins.magnification = 0.048 # [um/pixel] ins.n_m = 1.34 ``` -------------------------------- ### Import Libraries for Hologram Analysis Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Imports necessary libraries for plotting, numerical operations, image processing, and Pylorenzmie analysis. Ensure these are installed before running. ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import cv2 from pylorenzmie.analysis import Feature from pylorenzmie.theory import LMHologram from pylorenzmie.utilities import coordinates ``` -------------------------------- ### Import Libraries for Video Post-processing Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Video_analysis.ipynb Imports essential libraries for video analysis and prediction post-processing, including Pylorenzmie and CNNLorenzMie components. Ensure these libraries are installed in your environment. ```python import os import numpy as np import cv2, json import matplotlib.pyplot as plt from time import time import pandas as pd from pylorenzmie.analysis import Frame, Video from CNNLorenzMie.Localizer import Localizer from CNNLorenzMie.Estimator import Estimator from CNNLorenzMie.crop_feature import crop_feature from CNNLorenzMie.filters import no_edges, nodoubles from CNNLorenzMie.experiments.normalize_image import normalize_video from CNNLorenzMie.experiments.running_normal import running_normalize ``` -------------------------------- ### Initialize and inspect a Particle object Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Demonstrates the creation of a base Particle object and printing its default location and scattering properties. ```python from pylorenzmie.theory import Particle p = Particle() print(p.r_p) print(p.ab()) ``` -------------------------------- ### Instantiate Frame Object with Configuration Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/FrameAnalysis.ipynb Initializes the Frame object with specific optical and instrumental parameters for hologram analysis. Ensure these constants match your hardware implementation. ```python configuration = dict(wavelength = 0.447, # [um] magnification = 0.048, # [um/pixel] n_m = 1.34, distribution = 'radial', percentpix = 0.2, pupil=640.) frame = Frame(**configuration) ``` -------------------------------- ### Create and set an Instrument object Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Demonstrates creating an Instrument object with specific optical parameters and assigning it to the hologram simulation. The hologram is then regenerated and displayed with the new instrument settings. ```python from pylorenzmie.theory import Instrument #create an instrument object ins = Instrument(wavelength = 0.447, magnification=0.048, n_m = 1.34) print(ins) #set the model's instrument h.instrument = ins plt.imshow(h.hologram().reshape(shape), cmap='gray') plt.show() ``` -------------------------------- ### Initialize fitting parameters and instrument model Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Sets up initial guesses for fitting parameters (a_p, n_p, r_p) and initializes an Instrument object with physical properties like wavelength and magnification. Requires Instrument and LMHologram from Pylorenzmie. ```python # Initialize guesses for fitting and Instrument shape = cropped_norm.shape guesses = {'a_p': .92, #um 'n_p': 1.41, 'r_p': [shape[0] // 2, shape[1] // 2, 200.]} #pixels instrument = Instrument.Instrument(wavelength=.447, #pixels magnification=.048, #microns/pixel n_m=1.340, dark_count=13, background=1.) ``` -------------------------------- ### Initialize and inspect a Sphere object Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Shows how to create a Sphere object, a subclass of Particle, and access its size and refractive index properties. It also demonstrates calculating the first few Mie scattering coefficients. ```python from pylorenzmie.theory import Sphere s = Sphere() print(s.a_p) print(s.n_p, s.k_p) print(s.ab(n_m = 1.34, wavelength=0.447)[:4]) ``` -------------------------------- ### Initialize Plotting Environment Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Sets up the plotting environment for interactive use with matplotlib and pylab. Configures the default figure size. ```python import matplotlib.pyplot as plt %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] = (12, 8) ``` -------------------------------- ### Perform and Report Initial Optimization Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Executes the default optimization process and then reports the results and displays the visualization. This is the standard workflow for fitting. ```python result = feature.optimize() report(result) present(feature) ``` -------------------------------- ### Initialize LMHologram Kernel Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/MultiSphere.ipynb Initialize the LMHologram kernel with specified shape and coordinates. The kernel incorporates the instrument and particle properties for light scattering. ```python shape = [480, 640] coords = coordinates(shape) kernel = LMHologram(coordinates=coords) ``` -------------------------------- ### Import Detection and Localization Libraries Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Imports modules for circle transform detection, HDF5 video handling, localization, and trackpy for particle tracking. ```python # For circle transform detection import pylorenzmie.detection.circletransform as ct import pylorenzmie.detection.h5video as h5 import pylorenzmie.detection.localize as localize import trackpy as tp ``` -------------------------------- ### Configure Instrument and Estimate Particle Properties Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Configure an instrument, load a hologram, and estimate particle properties. The estimates include position, size, and refractive index. This snippet also shows how to process multiple holograms at once. ```python from pylorenzmie.core import Instrument, Estimator import cv2 # Configure instrument for estimation instrument = Instrument() instrument.wavelength = 0.447 instrument.magnification = 0.048 instrument.n_m = 1.34 # Create estimator estimator = Estimator(instrument=instrument) # Load cropped hologram hologram = cv2.imread('crop.png', cv2.IMREAD_GRAYSCALE).astype(float) hologram /= 100. # Normalize # Estimate particle properties estimates = estimator.estimate(hologram) print(f"Estimated z_p: {estimates.z_p:.1f} pixels") print(f"Estimated a_p: {estimates.a_p:.3f} um") print(f"Estimated n_p: {estimates.n_p:.4f}") # Estimates are centered on the image by default print(f"x_p: {estimates.x_p}, y_p: {estimates.y_p}") # Process multiple holograms at once holograms = [hologram1, hologram2, hologram3] all_estimates = estimator.estimate(holograms) # Returns list of Series ``` -------------------------------- ### Prepare experimental data for fitting Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Loads experimental image data, normalizes it, and sets it as the 'data' attribute of a Feature object. A hologram model is created and assigned to the Feature object for comparison. ```python from pylorenzmie.theory import Feature import cv2 f = Feature() #experimental data img = cv2.imread('test_image_crop_201.png')[:,:,0] data = img.reshape(img.size)/100. f.data = data #our best guess h.particle.a_p = 1.1 h.particle.n_p = 1.55 h.particle.z_p = 165 f.model = h # Plot experimental image vs initial guesses guess = f.model.hologram().reshape(shape) feature = f.data.reshape(shape) plt.imshow(np.hstack([feature, guess]), cmap='gray') ``` -------------------------------- ### Initialize Feature fitter and set data Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Initializes the Feature fitter with a specified model (LMHologram) and assigns the instrument, coordinates, and experimental data (cropped image). Requires Feature and Instrument from Pylorenzmie. ```python # Initialize fitter fitter = Feature(model=LMHologram(**guesses)) fitter.model.instrument = instrument fitter.model.coordinates = Instrument.coordinates(shape) fitter.data = (cropped_norm).reshape(cropped_norm.size) ``` -------------------------------- ### Set Initial Estimates for Particle Properties Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Provides initial estimates for the sphere's radius, refractive index, and 3D position. Random offsets are added to these estimates to challenge the fitting process. The initial particle properties are then printed. ```python # Initial estimates for particle properties p = feature.particle p.r_p = [img.shape[0]//2, img.shape[1]//2, 330.] p.a_p = 1.1 p.n_p = 1.4 # add errors to parameters p.r_p += np.random.normal(0., 1, 3) p.z_p += np.random.normal(0., 30, 1) p.a_p += np.random.normal(0., 0.1, 1) p.n_p += np.random.normal(0., 0.04, 1) print(p) fig, ax = plt.subplots(figsize=(5,5)) ax.imshow(feature.hologram(), cmap='gray') ax.axis('off') ax.set_title('Initial Estimate'); ``` -------------------------------- ### Compare initial guess hologram with experimental image Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Generates a hologram based on the initial guesses and displays it side-by-side with the experimental (cropped) image. Helps visualize the quality of the initial fit. ```python # Plot initial guesses vs. experimental image guess = fitter.model.hologram().reshape(shape) feature = fitter.data.reshape(shape) plt.imshow(np.hstack([feature, guess]), cmap='gray') ``` -------------------------------- ### Initialize and Normalize Video Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Video_analysis.ipynb Initializes a Video object with the specified path and then normalizes the video data. If the video has already been normalized, the normalized frames can be loaded using the set_frames() method. ```python path = './tutorials/sample_vid.avi' video = Video(path=path) video.normalize() #video.set_frames() ``` -------------------------------- ### Report Optimization Results Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Formats and prints the fitted parameters from the optimization. Includes particle position, radius, refractive index, and fit quality metrics like reduced chi-squared. ```python def report(result): def value(val, err, dec=2): fmt = '{' + ':.{}f'.format(dec) + '}' return (fmt + ' +-' + fmt).format(val, err) res = ['x_p = ' + value(result.x_p, result.dx_p) + ' [pixels]', 'y_p = ' + value(result.y_p, result.dy_p) + ' [pixels]', 'z_p = ' + value(result.z_p, result.dz_p) + ' [pixels]', 'a_p = ' + value(result.a_p, result.da_p, 3) + ' [um]', 'n_p = ' + value(result.n_p, result.dn_p, 4)] print('npixels = {}'.format(result.npix)) print(*res, sep='\n') print('chisq = {:.2f}'.format(result.redchi)) ``` -------------------------------- ### Import Libraries for Hologram Computation Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/MultiSphere.ipynb Import necessary libraries from cupy, pylorenzmie, and matplotlib for hologram computation. ```python #import cupy from pylorenzmie.theory import ( Sphere, LMHologram ) from pylorenzmie.utilities import coordinates import matplotlib.pyplot as plt ``` -------------------------------- ### Load YOLO Localizer Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Video_analysis.ipynb Initialize the YOLO localizer for feature identification in frames. Specify the model type ('holo') and weights. ```python print('loading Localizer...') loc = Localizer('holo', weights='_100k') ``` -------------------------------- ### Configure Instrument Parameters Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Model the holographic microscope system using the Instrument class, setting optical parameters like wavelength, magnification, NA, and medium properties. Wavenumber can be computed in various units. ```python from pylorenzmie.theory import Instrument # Create and configure the instrument model instrument = Instrument() instrument.wavelength = 0.447 # Vacuum wavelength [micrometers] instrument.magnification = 0.048 # Magnification [um/pixel] instrument.numerical_aperture = 1.45 # Objective lens NA instrument.n_m = 1.340 # Refractive index of medium instrument.noise = 0.05 # Estimated camera noise (5%) instrument.darkcount = 0.0 # Camera dark count ``` -------------------------------- ### Set Video Trajectories (Commented Out) Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Video_analysis.ipynb This is a commented-out section that would typically be used to set trajectories for the video. It is not currently active. ```python #video.set_trajectories() #display(video.trajectories) ``` -------------------------------- ### Initialize CNNLorenzMie Localizer Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Initializes the Localizer object from the CNNLorenzMie library. This object is used for feature detection using a deep convolutional neural network. ```python # Initialize Localizer localizer = Localizer() ``` -------------------------------- ### Read and Convert Images for Normalization Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Reads a raw image and a background image using OpenCV, then converts them to grayscale. This is the first step in image normalization. ```python # Read raw image and background image fn = "sample.png" fn_bg = "background.png" image = cv2.imread(fn) background = cv2.imread(fn_bg) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) background = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY) ``` -------------------------------- ### Create and Simulate Dimer Hologram Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Sets up a Dimer object representing two touching spheres, configures instrument properties, and computes the resulting hologram using the LorenzMie model. ```python import numpy as np from pylorenzmie.theory import Dimer, Instrument, LorenzMie # Create a dimer (pair of touching spheres) instrument = Instrument() instrument.magnification = 0.048 instrument.wavelength = 0.447 instrument.n_m = 1.340 dimer = Dimer(magnification=instrument.magnification) dimer.a_p = 0.5 # Radius of each sphere [micrometers] dimer.n_p = 1.42 # Refractive index of each sphere dimer.r_p = [150., 150., 250.] # Center position of dimer dimer.theta = np.pi/4 # Polar angle of dimer axis [radians] dimer.phi = np.pi/4 # Azimuthal angle of dimer axis [radians] # Compute hologram of the dimer shape = (301, 301) coordinates = LorenzMie.meshgrid(shape) model = LorenzMie(coordinates=coordinates, particle=dimer, instrument=instrument) hologram = model.hologram().reshape(shape) # Access individual spheres in the dimer print(f"Number of particles: {len(dimer)}") # 2 sphere1 = dimer[0] sphere2 = dimer[1] print(f"Sphere 1 position: {sphere1.r_p}") print(f"Sphere 2 position: {sphere2.r_p}") ``` -------------------------------- ### Create and Simulate Cluster Hologram Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Constructs a Cluster object with multiple spheres, sets its position, and computes the collective hologram using the LorenzMie model with specified instrument parameters. ```python from pylorenzmie.theory import Cluster, Sphere, Instrument, LorenzMie # Create a cluster of three spheres sphere1 = Sphere(a_p=0.5, n_p=1.45, x_p=0, y_p=0, z_p=0) sphere2 = Sphere(a_p=0.75, n_p=1.42, x_p=20, y_p=0, z_p=0) sphere3 = Sphere(a_p=0.6, n_p=1.50, x_p=10, y_p=17, z_p=0) cluster = Cluster(particles=[sphere1, sphere2, sphere3]) cluster.r_p = [150., 150., 200.] # Set cluster center position # Iterate over particles in the cluster for i, particle in enumerate(cluster): print(f"Particle {i}: radius={particle.a_p}, n_p={particle.n_p}") # Access particles by index print(f"Second particle radius: {cluster[1].a_p}") # Compute hologram of the cluster instrument = Instrument() instrument.magnification = 0.048 instrument.wavelength = 0.447 instrument.n_m = 1.340 shape = (301, 301) coordinates = LorenzMie.meshgrid(shape) model = LorenzMie(coordinates=coordinates, particle=cluster, instrument=instrument) hologram = model.hologram().reshape(shape) ``` -------------------------------- ### Import Standard Python Libraries Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Imports common libraries used for numerical operations, scientific computing, data manipulation, and file system interaction. ```python # The Usual Suspects. import numpy as np import scipy as sp import pandas as pd import os import cv2 ``` -------------------------------- ### Analyze and Fit Feature Hologram Data Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Loads hologram image data, configures a Feature object with instrument and particle properties, sets up optimization parameters, and runs the fitting process to estimate particle characteristics. ```python import cv2 import numpy as np from pylorenzmie.analysis import Feature from pylorenzmie.theory import LorenzMie # Load a cropped hologram image data = cv2.imread('hologram.png', cv2.IMREAD_GRAYSCALE).astype(float) data /= 100. # Normalize by background intensity # Create feature with data and coordinates feature = Feature() feature.data = data feature.coordinates = LorenzMie.meshgrid(data.shape) # Configure instrument properties instrument = feature.model.instrument instrument.wavelength = 0.447 instrument.magnification = 0.048 instrument.n_m = 1.34 # Set initial estimates for particle properties particle = feature.model.particle particle.r_p = [data.shape[0]//2, data.shape[1]//2, 330.] # Center position particle.a_p = 1.1 # Initial radius estimate [um] particle.n_p = 1.4 # Initial refractive index estimate # Configure optimizer (specify which parameters to fit) feature.optimizer.variables = ['x_p', 'y_p', 'z_p', 'a_p', 'n_p'] # Configure mask to use subset of pixels (speeds up fitting) feature.mask.fraction = 0.25 # Use 25% of pixels # Run optimization result = feature.optimize() print(f"Optimized position: ({particle.x_p:.1f}, {particle.y_p:.1f}, {particle.z_p:.1f})") print(f"Optimized radius: {particle.a_p:.3f} um") print(f"Optimized refractive index: {particle.n_p:.4f}") # Generate model hologram and compute residuals model_hologram = feature.hologram() residuals = feature.residuals() # data - model ``` -------------------------------- ### Import pylorenzmie for Hologram Analysis Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Imports specific modules from the pylorenzmie library for hologram generation, fitting, and instrument simulation. ```python # Hologram generation and fitting imports from pylorenzmie.theory import LorenzMie, Instrument from pylorenzmie.analysis import Feature ``` -------------------------------- ### Import Libraries for Hologram Analysis Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/FrameAnalysis.ipynb Imports necessary libraries for data visualization, display, image manipulation, numerical operations, and the Frame object from pylorenzmie. Uncomment the cupy import to enable GPU acceleration. ```python import matplotlib.pyplot as plt from IPython.display import display from matplotlib.patches import Rectangle import numpy as np import cv2 # import cupy # Uncomment to use GPU acceleration from pylorenzmie.analysis import Frame import pandas as pd pd.set_option('display.max_columns', None) pd.set_option('display.precision', 3) ``` -------------------------------- ### Compute Hologram with LorenzMie Class Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Use the LorenzMie class to compute synthetic holograms by combining instrument and particle models. Requires setting up coordinates, instrument parameters, and particle properties. ```python import numpy as np from pylorenzmie.theory import LorenzMie, Sphere, Instrument # Create coordinate grid for a 201x201 pixel image shape = (201, 201) coordinates = LorenzMie.meshgrid(shape) # Configure the microscope instrument instrument = Instrument() instrument.wavelength = 0.447 # Vacuum wavelength [micrometers] instrument.magnification = 0.048 # System magnification [um/pixel] instrument.numerical_aperture = 1.45 # Objective lens NA instrument.n_m = 1.340 # Refractive index of medium (water) # Create a spherical particle particle = Sphere() particle.r_p = [100, 100, 200] # Position [x, y, z] in pixels particle.a_p = 0.75 # Radius [micrometers] particle.n_p = 1.45 # Refractive index of particle # Create Lorenz-Mie model and compute hologram model = LorenzMie(coordinates=coordinates, particle=particle, instrument=instrument) # Generate synthetic hologram hologram = model.hologram() image = hologram.reshape(shape) # Reshape to 2D image # Access the scattered electric field (complex-valued) field = model.field() # Shape: (3, npts) for Ex, Ey, Ez components # Access/modify model properties as a dictionary print(model.properties) # {'x_p': 100, 'y_p': 100, 'z_p': 200, 'a_p': 0.75, 'n_p': 1.45, 'k_p': 0.0, # 'n_m': 1.34, 'wavelength': 0.447, 'magnification': 0.048, ...} ``` -------------------------------- ### Import CNNLorenzMie for Detection Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Imports the Localizer and nodoubles filter from the CNNLorenzMie package for advanced particle detection. ```python # For CNNLorenzMie detection from CNNLorenzMie.Localizer import Localizer from CNNLorenzMie.filters.nodoubles import nodoubles ``` -------------------------------- ### Optimize experimental data using least-squares fitting Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Performs a non-linear least-squares fit of the experimental data to the hologram model using the Feature object's optimize() method. The fitting results, including variable values and statistics, are reported. ```python from lmfit import report_fit result = f.optimize() report_fit(result) ``` -------------------------------- ### Perform and Report Optimized Fit with Custom Settings Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Applies custom settings to the optimizer, specifically changing the method to 'trf' and the loss function to 'cauchy', before performing the optimization and reporting results. ```python feature.optimizer.settings['method'] = 'trf' feature.optimizer.settings['loss'] = 'cauchy' result = feature.optimize() report(result) present(feature) ``` -------------------------------- ### Prepare residual and fitted image for plotting Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Calculates the residual image (difference between experimental data and the fitted model) and reshapes the fitted hologram for visualization. Requires the optimization result. ```python # Prepare residuals and fitted image for plotting residual = result.residual.reshape(shape) fit = fitter.model.hologram().reshape(shape) ``` -------------------------------- ### Display cropped image, fitted image, and residuals Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Compares the original cropped image, the fitted image, and the residuals side-by-side. The residuals are scaled by the noise level and offset for better visualization. ```python # Plot cropped image vs fitted image vs residuals noise = fitter.noise mega_image = np.hstack([cropped_norm, fit, residual*fitter.noise+1.0]) fig, ax = plt.subplots(figsize=(12, 36)) ax.imshow(mega_image, cmap='gray', interpolation=None) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Imports common libraries for plotting, numerical operations, and system path manipulation. ```python %matplotlib inline ``` ```python import json import numpy as np import matplotlib.pyplot as plt import os ``` ```python import sys sys.path.append('/Users/laurenaltman/Desktop/summer_research/machine_learning') ``` -------------------------------- ### Configure Sub-sampling Mask for Fitting Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Sets the percentage of pixels to use for fitting and specifies a radial distribution for sub-sampling. This reduces computational cost without sacrificing accuracy. The selected pixels and their corresponding coordinates are visualized. ```python feature.mask.percentpix = 0.2 feature.mask.distribution = 'radial' fig, (axa, axb) = plt.subplots(ncols=2, figsize=(8, 4), sharex=True, sharey = True, constrained_layout=True) axa.imshow(feature.mask.selected.reshape(img.shape)) index = feature.mask.selected coords = feature.coordinates[:, index] axb.scatter(coords[0,:], coords[1,:], c=feature.data.flatten()[index], cmap='gray') ``` -------------------------------- ### Generate a hologram with a Sphere particle Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Creates a hologram image using the LorenzMie simulation with a defined Sphere particle and default instrument settings. The resulting hologram is displayed. ```python from pylorenzmie.theory import LorenzMie from pylorenzmie.utilities import coordinates shape = [201, 201] h = LorenzMie(coordinates=coordinates(shape)) s.r_p = [100,100,300] h.particle = s plt.imshow(h.hologram().reshape(shape), cmap='gray') plt.show() print(h.instrument) ``` -------------------------------- ### Load and Prepare Hologram Image Data Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Loads a hologram image using OpenCV, converts it to grayscale, normalizes it by its mean value, and assigns it to the Feature object's data. A standard coordinate system is also provided using the coordinates() helper function. ```python # Read example image img = cv2.imread('tutorials/crop.png', 0).astype(float) # The normalized image constitutes the data for the Feature() feature.data = img / np.mean(img) # Specify the coordinates for the pixels in the image data feature.coordinates = coordinates(img.shape) fig, ax = plt.subplots(figsize=(5,5)) ax.imshow(img, cmap='gray') ax.axis('off'); ``` -------------------------------- ### Plot bounding boxes on image Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Plots initial bounding boxes for detected features onto an image. Requires matplotlib and Rectangle from matplotlib.patches. ```python fig, ax = plt.subplots() ax.imshow(norm, cmap='gray') for feature in features: x, y, w, h = feature test_rect = Rectangle(xy=(x - w/2, y - h/2), width=w, height=h, fill=False, linewidth=3, edgecolor='r') ax.add_patch(test_rect) ``` -------------------------------- ### Compute Hologram Performance Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/MultiSphere.ipynb Measure the performance of the hologram computation using %timeit. This helps in understanding the execution time for generating the hologram. ```python %timeit a = kernel.hologram() ``` -------------------------------- ### Visualize Optimization Fit Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Fitting.ipynb Generates a plot comparing the original data, the fitted hologram, and the residuals. Uses matplotlib for visualization. ```python def present(feature): fig, axes = plt.subplots(ncols=3, figsize=(10, 4), constrained_layout=True) vmin = np.min(feature.data) * 0.9 vmax = np.max(feature.data) * 1.1 style = dict(vmin=vmin, vmax=vmax, cmap='gray') images = [feature.data, feature.hologram(), feature.residuals()+1] labels = ['Data', 'Fit', 'Residuals'] for ax, image, label in zip(axes, images, labels): ax.imshow(image, **style) ax.axis('off') ax.set_title(label) ``` -------------------------------- ### Define and Position Multiple Spheres Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/MultiSphere.ipynb Create a list of Sphere objects and assign distinct positions to each sphere within the scene. This defines the particles that will scatter light. ```python p = [Sphere() for _ in range(5)] p[0].r_p = [100,240,100] p[1].r_p = [200,240,150] p[2].r_p = [300,240,200] p[3].r_p = [400,240,250] p[4].r_p = [500,240,300] kernel.particle = p ``` -------------------------------- ### Detect Features using OAT and Trackpy Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Applies the OAT method and trackpy.locate to detect features in the normalized image. Specific parameters for trackpy.locate are provided for optimization. ```python # First find features using orientational alignment transform (OAT). trackpy_params = {'diameter': 51, 'minmass': 25.} features, circle_transform = detect(norm, trackpy_params=trackpy_params) ``` -------------------------------- ### Optimize Lorenz-Mie Model Fit Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Use the Optimizer class to perform nonlinear least-squares fitting of a Lorenz-Mie model to hologram data. It wraps scipy's least_squares and provides uncertainty estimates. Configure optimization settings like method, loss function, and tolerances. ```python import numpy as np from pylorenzmie.analysis import Optimizer from pylorenzmie.theory import LorenzMie # Create synthetic data with noise shape = (201, 201) model = LorenzMie() model.coordinates = model.meshgrid(shape) model.particle.a_p = 0.75 model.particle.n_p = 1.42 model.particle.r_p = [100., 100., 225.] noise = model.instrument.noise * np.random.normal(size=shape) data = model.hologram() + noise.flatten() # Create optimizer with fixed and variable parameters fixed = ['wavelength', 'magnification', 'numerical_aperture', 'n_m', 'k_p'] optimizer = Optimizer(model=model, fixed=fixed) optimizer.data = data # Configure optimization settings optimizer.settings['method'] = 'trf' # Trust Region Reflective optimizer.settings['loss'] = 'cauchy' # Robust loss function optimizer.settings['ftol'] = 1e-3 # Cost function tolerance optimizer.settings['max_nfev'] = 2000 # Max function evaluations # Alternatively, use the robust property for quick configuration optimizer.robust = True # Sets method='trf' and loss='cauchy' # Run optimization result = optimizer.optimize() # Access results as pandas Series print(f"x_p = {result.x_p:.2f} +/- {result.dx_p:.2f} pixels") print(f"y_p = {result.y_p:.2f} +/- {result.dy_p:.2f} pixels") print(f"z_p = {result.z_p:.2f} +/- {result.dz_p:.2f} pixels") print(f"a_p = {result.a_p:.3f} +/- {result.da_p:.3f} um") print(f"n_p = {result.n_p:.4f} +/- {result.dn_p:.4f}") print(f"Reduced chi-squared: {result.redchi:.2f}") # Get formatted report print(optimizer.report()) # Access metadata (fixed parameters and settings) metadata = optimizer.metadata ``` -------------------------------- ### Predict features using CNNLorenzMie localizer Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Uses a CNNLorenzMie localizer to predict features in an image. The input image is inflated and scaled to have a mean of approximately 100. Requires the 'inflate' function and a 'localizer' object. ```python # We will repeat the same procedure with CNNLorenzMie localizer.threshold = .4 feats = localizer.predict([inflate(norm)*100]) #NOTE: Localizer expects images with a mean ~100. ``` -------------------------------- ### Detect and Localize Holographic Features Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Use the Localizer class to detect ring-like patterns in holographic images using the circle transform algorithm. It returns bounding boxes for detected features. Configure diameter and number of fringes for detection. ```python import cv2 from pylorenzmie.analysis import Localizer # Load a holographic microscopy image image = cv2.imread('hologram_frame.png', cv2.IMREAD_GRAYSCALE).astype(float) image /= 100. # Normalize by background # Create localizer with default parameters localizer = Localizer() localizer.diameter = 31 # Typical feature size [pixels] localizer.nfringes = 20 # Number of fringes for bounding box # Detect features in the image features = localizer.localize(image) # Results are returned as pandas DataFrame print(f"Detected {len(features)} features") for idx, row in features.iterrows(): print(f"Feature {idx}: center=({row.x_p:.1f}, {row.y_p:.1f}), bbox={row.bbox}") # Crop individual features from the image for bbox in features.bbox: cropped = localizer.crop(image, bbox) # Process each cropped feature... # Process multiple images at once (returns list of DataFrames) images = [image1, image2, image3] all_features = localizer.localize(images) ``` -------------------------------- ### TensorFlow Backend Warnings Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb These are informational warnings related to the TensorFlow backend and NumPy dtype compatibility, typically seen during library initialization. ```text Output: Using TensorFlow backend. /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /home/michael/.virtualenvs/base/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) ``` -------------------------------- ### Reanalyze Data with Robust Estimation Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/FrameAnalysis.ipynb Configure a Frame with robust estimation enabled and analyze image data. This method is less sensitive to outliers. Ensure necessary libraries like cv2 and numpy are imported. ```python configuration = dict(wavelength = 0.447, # [um] magnification = 0.048, # [um/pixel] n_m = 1.34, distribution = 'radial', percentpix = 0.2, robust = True ) robust_frame = Frame(**configuration) data = cv2.imread('tutorials/image0010.png', 0).astype(float) data /= np.median(data) robust_frame.analyze(data) report(robust_frame) ``` -------------------------------- ### Optimize feature fitting Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Performs the optimization process to fit the experimental data to the model. Prints the optimization result, which includes parameters and fit quality metrics. ```python # Fit result = fitter.optimize() print(result) ``` -------------------------------- ### Generate and Apply Random Pixel Masks Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Use the Mask class to generate random pixel masks for subsampling data during optimization, which speeds up fitting. You can also exclude specific pixels from being selected. ```python import numpy as np from pylorenzmie.analysis import Mask # Create a mask for a 201x201 image mask = Mask() mask.shape = (201, 201) mask.fraction = 0.25 # Use 25% of pixels # Get the boolean mask array m = mask() # or mask.mask print(f"Actual fraction: {np.sum(m) / m.size:.2%}") # Apply mask to data data = np.random.random((201, 201)) masked_data = data[m] # Extract selected pixels # Exclude specific pixels (e.g., saturated pixels) saturated = data > 0.99 mask.exclude = saturated # These pixels will never be selected mask.update() # Regenerate mask with exclusions # Regenerate mask with new random selection mask.update() ``` -------------------------------- ### Plot Experimental Data vs Optimized Hologram Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Displays experimental data alongside an optimized hologram. Requires numpy and matplotlib. The output is a matplotlib AxesImage object. ```python guess = hfit.hologram().reshape(shape) feature = f.data.reshape(shape) plt.imshow(np.hstack([feature, guess])), cmap='gray') ``` -------------------------------- ### Compute Wavenumber in Different Units Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Calculates and prints the wavenumber in different units (scaled, in medium, in vacuum). Accesses instrument properties as a dictionary. ```python k_medium_scaled = instrument.wavenumber() # Default: in medium, scaled [rad/pixel] k_medium = instrument.wavenumber(scaled=False) # In medium [rad/um] k_vacuum = instrument.wavenumber(in_medium=False, scaled=False) # In vacuum [rad/um] print(f"Wavenumber (scaled): {k_medium_scaled:.4f} rad/pixel") print(f"Wavenumber (medium): {k_medium:.4f} rad/um") print(f"Wavenumber (vacuum): {k_vacuum:.4f} rad/um") # Access instrument properties as dictionary print(instrument.properties) # {'n_m': 1.34, 'wavelength': 0.447, 'magnification': 0.048, 'numerical_aperture': 1.45} ``` -------------------------------- ### Configure Sphere Particle Properties Source: https://context7.com/davidgrier/pylorenzmie/llms.txt Define a spherical particle's properties such as radius, refractive index, and position using the Sphere class. Mie scattering coefficients can be computed for given medium conditions. ```python from pylorenzmie.theory import Sphere # Create a sphere with specified properties sphere = Sphere() sphere.a_p = 0.75 # Radius [micrometers] sphere.n_p = 1.50 # Refractive index sphere.k_p = 0.0 # Absorption coefficient (0 = transparent) sphere.r_p = [100, 100, 250] # Position [x, y, z] in pixels # Alternative: set position via individual coordinates sphere.x_p = 100.0 # x position [pixels] sphere.y_p = 100.0 # y position [pixels] sphere.z_p = 250.0 # z position (above focal plane) [pixels] # Access diameter property (derived from radius) print(f"Diameter: {sphere.d_p} micrometers") # Diameter: 1.5 micrometers # Compute Mie scattering coefficients for given medium conditions n_m = 1.339 # Refractive index of medium wavelength = 0.447 # Vacuum wavelength [micrometers] ab = sphere.ab(n_m, wavelength) # Returns complex array of Mie coefficients print(f"Number of multipole terms: {ab.shape[0]}") # Export sphere properties as dictionary props = sphere.properties # {'x_p': 100.0, 'y_p': 100.0, 'z_p': 250.0, 'a_p': 0.75, 'n_p': 1.5, 'k_p': 0.0} ``` -------------------------------- ### Load and Normalize Hologram Data Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/FrameAnalysis.ipynb Reads a hologram image file using OpenCV, converts it to a floating-point array, and normalizes the intensity values. Assumes the background intensity is 100 in the source image. ```python data = cv2.imread('tutorials/PS_silica.png', 0).astype(float) / 100 ``` -------------------------------- ### Load and Predict Image Features Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/Video_analysis.ipynb This function loads an image from a frame, predicts bounding boxes for features, crops the features, and adds them back to the frame. It's used for processing individual frames in a video. ```python def predict_load(frame): frame.load() #### Read image from frame's path preds = loc.predict([frame.image])#### Detect bboxes bboxes = [x['bbox'] for x in preds[0]] features = crop_feature(img_list = [frame.image], xy_preds = preds) frame.add(features = features, bboxes = bboxes) ``` -------------------------------- ### Analyze Hologram and Report Results Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/FrameAnalysis.ipynb Performs the Lorenz-Mie analysis on the normalized hologram data using the Frame object and then calls the report function to display the results visually and tabularly. ```python frame.analyze(data) report(frame) ``` -------------------------------- ### Retrieve the fitted hologram model Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/Theory.ipynb Assigns the hologram model, after optimization, to a new variable 'hfit'. This allows access to the model with the fitted parameters. ```python hfit = f.model ``` -------------------------------- ### Plot results with refined bounding boxes Source: https://github.com/davidgrier/pylorenzmie/blob/master/docs/tutorials/SingleFrame.ipynb Plots the image with the refined bounding boxes for each detected feature. Requires matplotlib and Rectangle. ```python # Plot results fig, ax = plt.subplots() ax.imshow(norm, cmap='gray') for feature in features: x, y, w, h = feature test_rect = Rectangle(xy=(x - w/2, y - h/2), width=w, height=h, fill=False, linewidth=3, edgecolor='r') ax.add_patch(test_rect) ```