Code reference¶
analyze (Generic fitting wrapper)¶
-
qpsphere.
analyze
()¶ alias of
qpsphere.cnvnc.analyze()
cnvnc (Convenience methods)¶
-
qpsphere.cnvnc.
analyze
(qpi, r0, method='edge', model='projection', edgekw={}, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False)[source]¶ Determine refractive index and radius of a spherical object
Parameters: - qpi (qpimage.QPImage) – Quantitative phase image data
- r0 (float) – Approximate radius of the sphere [m]
- method (str) – The method used to determine the refractive index can either be “edge” (determine the radius from the edge detected in the phase image) or “image” (perform a 2D phase image fit).
- model (str) – The light-scattering model used by method. If method is “edge”, only “projection” is allowed. If method is “image”, model can be one of “mie”, “projection”, “rytov”, or “rytov-sc”.
- edgekw (dict) – Keyword arguments for tuning the edge detection algorithm,
see
qpsphere.edgefit.contour_canny()
. - imagekw (dict) – Keyword arguments for tuning the image fitting algorithm,
see
qpsphere.imagefit.alg.match_phase()
- ret_center (bool) – If True, return the center coordinate of the sphere.
- ret_pha_offset (bool) – If True, return the phase image background offset.
- ret_qpi (bool) – If True, return the modeled data as a
qpimage.QPImage
.
Returns: - n (float) – Computed refractive index
- r (float) – Computed radius [m]
- c (tuple of floats) – Only returned if ret_center is True; Center position of the sphere [px]
- pha_offset (float) – Only returned if ret_pha_offset is True; Phase image background offset
- qpi_sim (qpimage.QPImage) – Only returned if ret_qpi is True; Modeled data
Notes
If method is “image”, then the “edge” method is used as a first step to estimate initial parameters for radius, refractive index, and position of the sphere using edgekw. If this behavior is not desired, please make use of the method
qpsphere.imagefit.analyze()
.
-
qpsphere.cnvnc.
bg_phase_mask_from_sim
(sim, radial_clearance=1.1)[source]¶ Return the background phase mask of a qpsphere simulation
Parameters: - sim (qpimage.QPImage) – Quantitative phase data simulated with qpsphere; The simulation keyword arguments “sim center”, “sim radius”, and “pixel size” must be present in sim.meta.
- radial_clearance (float) – Multiplicator to the fitted radius of the sphere; modifies
the size of the mask; set to “1” to use the radius determined
by
qpsphere.analyze()
. The circular area containing the phase object is set to False in the output mask image.
Returns: mask – The mask is True for background regions and False for object regions.
Return type: boolean 2d np.ndarray
-
qpsphere.cnvnc.
bg_phase_mask_for_qpi
(qpi, r0, method='edge', model='projection', edgekw={}, imagekw={}, radial_clearance=1.1)[source]¶ Determine the background phase mask for a spherical phase object
The position and radius of the phase object are determined with
analyze()
, to which the corresponding keyword arguments are passed. A binary mask is created from the simulation results viabg_phase_mask_from_sim()
.Parameters: - qpi (qpimage.QPImage) – Quantitative phase image data
- r0 (float) – Approximate radius of the sphere [m]
- method (str) – The method used to determine the refractive index can either be “edge” (determine the radius from the edge detected in the phase image) or “image” (perform a 2D phase image fit).
- model (str) – The light-scattering model used by method. If method is “edge”, only “projection” is allowed. If method is “image”, model can be one of “mie”, “projection”, “rytov”, or “rytov-sc”.
- edgekw (dict) – Keyword arguments for tuning the edge detection algorithm,
see
qpsphere.edgefit.contour_canny()
. - imagekw (dict) – Keyword arguments for tuning the image fitting algorithm,
see
qpsphere.imagefit.alg.match_phase()
- radial_clearance (float) – Multiplicator to the fitted radius of the sphere; modifies
the size of the mask; set to “1” to use the radius determined
by
qpsphere.analyze()
. The circular area containing the phase object is set to False in the output mask image.
Returns: mask – The mask is True for background regions and False for object regions.
Return type: boolean 2d np.ndarray
edgefit (Contour-based fitting)¶
Canny edge detection approach for QPI analysis of spheres
-
qpsphere.edgefit.
analyze
(qpi, r0, edgekw={}, ret_center=False, ret_edge=False)[source]¶ Determine refractive index and radius using Canny edge detection
Compute the refractive index of a spherical phase object by detection of an edge in the phase image, a subsequent circle fit to the edge, and finally a weighted average over the phase image assuming a parabolic phase profile.
Parameters: - qpi (QPImage) – Quantitative phase image information
- r0 (float) – Approximate radius of the sphere [m]
- edgekw (dict) – Additional keyword arguments for
contour_canny()
- ret_center (bool) – Return the center coordinate of the sphere
Returns: - n (float) – Computed refractive index
- r (float) – Computed radius [m]
- center (tuple of floats) – Center position of the sphere [px], only returned if ret_center is True
-
qpsphere.edgefit.
average_sphere
(image, center, radius, weighted=True, ret_crop=False)[source]¶ Compute the weighted average phase from a phase image of a sphere
Parameters: - image (2d ndarray) – Quantitative phase image of a sphere
- center (tuble (x,y)) – Center of the sphere in image in ndarray coordinates
- radius (float) – Radius of the sphere in pixels
- weighted (bool) – If True, return average phase density weighted with the height profile obtained from the radius, otherwise return simple average phase density. Weighting gives data points at the center of the sphere more weight than those points at the boundary of the sphere, avoiding edge artifacts.
- ret_crop (bool) – Return the cropped image.
Returns: - average (float) – The average phase value of the sphere from which the refractive index can be computed
- cropped_image (2d ndarray) – Returned if ret_crop is True
-
qpsphere.edgefit.
circle_fit
(edge, ret_dev=False)[source]¶ Fit a circle to a boolean edge image
Parameters: - edge (2d boolean ndarray) – Edge image
- ret_dev (bool) – Return the average deviation of the distance from contour to center of the fitted circle.
Returns: - center (tuple of (float, float)) – Coordinates of the circle center
- radius (float) – Radius of the circle [px]
- rdev – Only returned if ret_dev is True Average deviation of the radius from the circle
-
qpsphere.edgefit.
circle_radii
(params, xedge, yedge)[source]¶ Compute the distance to the center from cartesian coordinates
This method is used for fitting a circle to a set of contour points.
Parameters: - params (lmfit.Parameters) –
Must contain the keys:
- ”cx”: origin of x coordinate [px]
- ”cy”: origin of y coordinate [px]
- xedge (1D np.ndarray) – Edge coordinates x [px]
- yedge (1D np.ndarray) – Edge coordinates y [px]
Returns: radii – Radii corresponding to edge coordinates relative to origin
Return type: 1D np.ndarray
- params (lmfit.Parameters) –
-
qpsphere.edgefit.
circle_residual
(params, xedge, yedge)[source]¶ Residuals for circle fitting
Parameters: - params (lmfit.Parameters) –
Must contain the keys:
- ”cx”: origin of x coordinate [px]
- ”cy”: origin of y coordinate [px]
- xedge (1D np.ndarray) – Edge coordinates x [px]
- yedge (1D np.ndarray) – Edge coordinates y [px]
Returns: rad_dev – Deviation of radii from average radius
Return type: 1D np.ndarray
- params (lmfit.Parameters) –
-
qpsphere.edgefit.
contour_canny
(image, radius, mult_coarse=0.4, mult_fine=0.1, clip_rmin=0.9, clip_rmax=1.1, maxiter=20, verbose=True)[source]¶ Heuristic Canny edge detection for circular objects
Two Canny-based edge detections with different filter sizes are performed to find the outmost contour of an object in a phase image while keeping artifacts at a minimum.
Parameters: - image (2d ndarray) – Image containing an approximately spherically symmetric object
- radius (float) – The approximate object radius in pixels (required for filtering)
- mult_coarse (float) – The coarse edge detection has a filter size of
sigma = mult_coarse * radius
- mult_fine (float) – The fine edge detection has a filter size of
sigma = mult_fine * radius
- clip_rmin (float) – Removes edge points that are closer than clip_rmin times the average radial edge position from the center of the image.
- clip_rmax (float) – Removes edge points that are further than clip_rmin times the average radial edge position from the center of the image.
- maxiter (int) – Maximum number iterations for coarse edge detection, see Notes
- verbose (bool) – If set to True, issues EdgeDetectionWarning where applicable
Returns: edge – The detected edge positions of the object.
Return type: 2d boolean ndarray
Notes
If no edge is found using the filter size defined by mult_coarse, then the coarse filter size is reduced by a factor of 2 until an edge is found or until maxiter is reached.
The edge found using the filter size defined by mult_fine is heuristically filtered (parts at the center and at the edge of the image are removed). This heuristic filtering assumes that the circular object is centered in the image.
See also
skimage.feature.canny()
- Canny edge detection algorithm used
imagefit (2D phase image fitting)¶
-
qpsphere.imagefit.
analyze
(qpi, model, n0, r0, c0=None, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False)[source]¶ Fit refractive index and radius to a phase image of a sphere
Parameters: - qpi (QPImage) – Quantitative phase image information
- model (str) – Name of the light-scattering model
(see
qpsphere.models.available
) - n0 (float) – Approximate refractive index of the sphere
- r0 (float) – Approximate radius of the sphere [m]
- c0 (tuple of (float, float)) – Approximate center position in ndarray index coordinates [px]; if set to None (default), the center of the image is used.
- imagekw (dict) – Additional keyword arguments to
qpsphere.imagefit.alg.match_phase()
. - ret_center (bool) – Return the center coordinate of the sphere
- ret_pha_offset (bool) – If True, return the phase image background offset.
- ret_qpi (bool) – If True, return the modeled data as a
qpimage.QPImage
.
Returns: - n (float) – Computed refractive index
- r (float) – Computed radius [m]
- c (tuple of floats) – Only returned if ret_center is True Center position of the sphere [px]
- pha_offset (float) – Only returned if ret_pha_offset is True Phase image background offset
- qpi_sim (qpimage.QPImage) – Only returned if ret_qpi is True Modeled data
imagefit.alg (Algorithms)¶
-
qpsphere.imagefit.alg.
match_phase
(qpi, model, n0, r0, c0=None, pha_offset=0, fix_pha_offset=False, nrel=0.1, rrel=0.05, crel=0.05, stop_dn=0.0005, stop_dr=0.001, stop_dc=1, min_iter=3, max_iter=100, ret_center=False, ret_pha_offset=False, ret_qpi=False, ret_num_iter=False, ret_interim=False, verbose=0, verbose_h5path='./match_phase_error.h5')[source]¶ Fit a scattering model to a quantitative phase image
Parameters: - qpi (qpimage.QPImage) – QPI data to fit (e.g. experimental data)
- model (str) – Name of the light-scattering model
(see
qpsphere.models.available
) - n0 (float) – Initial refractive index of the sphere
- r0 (float) – Initial radius of the sphere [m]
- c0 (tuple of (float, float)) – Initial center position of the sphere in ndarray index coordinates [px]; if set to None (default), the center of the image is used.
- pha_offset (float) – Initial phase offset [rad]
- fix_pha_offset (bool) –
If True, do not fit the phase offset pha_offset. The phase offset is determined from the mean of all pixels whose absolute phase is
- below 1% of the modeled phase and
- within a 5px or 20% border (depending on which is larger) around the phase image.
- nrel (float) – Determines the border of the interpolation range for the refractive index: [n-(n-nmed)*nrel, n+(n-nmed)*nrel] with nmed=qpi[“medium_index”] and, initially, n=n0.
- rrel (float) – Determines the border of the interpolation range for the radius: [r*(1-rrel), r*(1+rrel)] with, initially, r=r0.
- crel (float) – Determines the border of the interpolation range for the center position: [cxy - dc, cxy + dc] with the center position (along x or y) cxy, and the interval radius dc defined by dc=max(lambda, crel * r0) with the vacuum wavelength lambda=qpi[“wavelenght”].
- stop_dn (float) – Stopping criterion for refractive index
- stop_dr (float) – Stopping criterion for radius
- stop_dc (float) – Stopping criterion for lateral offsets
- min_iter (int) – Minimum number of fitting iterations to perform
- max_iter (int) – Maximum number of fitting iterations to perform
- ret_center (bool) – If True, return the fitted center coordinates
- ret_pha_offset (bool) – If True, return the fitted phase offset
- ret_qpi (bool) – If True, return the final fit as a data set
- ret_num_iter (bool) – If True, return the number of iterations
- ret_interim (bool) – If True, return intermediate parameters of each iteration
- verbose (int) – Higher values increase verbosity
- verbose_h5path (str) – Path to hdf5 output file, created when verbosity >= 2
Returns: - n (float) – Fitted refractive index
- r (float) – Fitted radius [m]
- c (tuple of (float, float)) – Only returned if ret_center is True Center position of the sphere in ndarray index coordinates [px]
- pha_offset (float) – Only returned if ret_pha_offset is True Fitted phase offset [rad]
- qpi (qpimage.QPImage) – Only returned if ret_qpi is True Simulation using model with the final fit parameters
- num_iter (int) – Only returned if ret_num_iter is True Number of iterations performed; negative number is returned when iteration fails
- interim (list) – Only returned if ret_interim is True Intermediate fitting parameters
-
qpsphere.imagefit.alg.
sq_phase_diff
(pha_a, pha_b)[source]¶ Compute sum of squares error between two arrays
Parameters: pha_b (pha_a,) – Phase data to compare Returns: sumsq – Sum of squares of differences Return type: float
-
qpsphere.imagefit.alg.
export_phase_error_hdf5
(h5path, identifier, index, phase, mphase, model, n0, r0, spi_params)[source]¶ Export the phase error to an hdf5 file
Parameters: - h5path (str or pathlib.Path) – path to hdf5 output file
- identifier (str) – unique identifier of the input phase (e.g. qpimage.QPImage[“identifier”])
- index (int) – iteration index
- phase (2d real-valued np.ndarray) – phase image
- mphase (2d real-valued np.ndarray) – reference phase image
- model (str) – sphere model name
- n0 (float) – initial object index
- r0 (float) – initial object radius [m]
- spi_params (dict) – parameter dictionary of
SpherePhaseInterpolator()
imagefit.interp (Image interpolation logic)¶
-
class
qpsphere.imagefit.interp.
SpherePhaseInterpolator
(model, model_kwargs, pha_offset=0, nrel=0.1, rrel=0.05, verbose=0)[source]¶ Interpolation in-between modeled phase images
Parameters: - model (str) – Name of the light-scattering model
(see
qpsphere.models.available
) - model_kwargs (dict) –
Keyword arguments for the sphere model; must contain:
- radius: float
- Radius of the sphere [m]
- sphere_index: float
- Refractive index of the object
- medium_index: float
- Refractive index of the surrounding medium
- wavelength: float
- Vacuum wavelength of the imaging light [m]
- pixel_size: float
- Pixel size [m]
- grid_size: tuple of floats
- Resulting image size in x and y [px]
- center: tuple of floats
- Center position in image coordinates [px]
- pha_offset (float) – Phase offset added to the interpolation result
- nrel (float) – Determines the border of the interpolation range for the refractive index: [n-(n-nmed)*nrel, n+(n-nmed)*nrel] with n=model_kwargs[“sphere_index”] and nmed=model_kwargs[“medium_index”]
- rrel (float) – Determines the border of the interpolation range for the radius: [r*(1-rrel), r*(1+rrel)] with r=model_kwargs[“radius”]
- verbose (int) – Increases verbosity.
-
model
= None¶ scattering model
-
sphere_method
= None¶ scattering model function
-
model_kwargs
= None¶ scattering model keyword arguments
-
radius
= None¶ current sphere radius [m]
-
sphere_index
= None¶ current sphere index
-
pha_offset
= None¶ current background phase offset
-
posx_offset
= None¶ current pixel offset in x
-
posy_offset
= None¶ current pixel offset in y
-
dn
= None¶ half of current search interval size for refractive index
-
dr
= None¶ half of current search interval size for radius [m]
-
params
¶ Current interpolation parameter dictionary
-
range_n
¶ Current interpolation range of refractive index
-
range_r
¶ Current interpolation range of radius
-
compute_qpi
()[source]¶ Compute model data with current parameters
Returns: qpi – Modeled phase data Return type: qpimage.QPImage Notes
The model image might deviate from the fitted image because of interpolation during the fitting process.
-
get_phase
(nintp=None, rintp=None, delta_offset_x=0, delta_offset_y=0)[source]¶ Interpolate from the border fields to new coordinates
Parameters: Returns: phase_intp – Interpolated phase at the given parameters
Return type: 2D real-valued np.ndarray
Notes
Not all combinations are poosible, e.g.
- One of nintp or rintp must be None
- The current interpolation range must include the values for rintp and nintp
- model (str) – Name of the light-scattering model
(see
models (Scattering models)¶
-
qpsphere.models.
available
= ['mie', 'mie-avg', 'projection', 'rytov', 'rytov-sc']¶ available light-scattering models
-
qpsphere.models.
simulate
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, grid_size=(80, 80), model='projection', pixel_size=None, center=None)[source]¶ Simulate scattering at a sphere
Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the object
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- grid_size (tuple of ints or int) – Resulting image size in x and y [px]
- model (str) – Sphere model to use (see
available
) - pixel_size (float or None) – Pixel size [m]; if set to None the pixel size is chosen such that the radius fits at least three to four times into the grid.
- center (tuple of floats or None) – Center position in image coordinates [px]; if set to None, the center of the image (grid_size - 1)/2 is used.
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.
mie
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, pixel_size=1e-07, grid_size=(80, 80), center=(39.5, 39.5), focus=0, arp=True)[source]¶ Mie-simulated field behind a dielectric sphere
Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the sphere
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- pixel_size (float) – Pixel size [m]
- grid_size (tuple of floats) – Resulting image size in x and y [px]
- center (tuple of floats) – Center position in image coordinates [px]
- focus (float) –
New in version 0.5.0.
Axial focus position [m] measured from the center of the sphere in the direction of light propagation.
- arp (bool) – Use arbitrary precision (ARPREC) in BHFIELD computations
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.
mie_avg
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, pixel_size=1e-07, grid_size=(80, 80), center=(39.5, 39.5), interpolate=3, focus=0, arp=True)[source]¶ Mie-simulated non-polarized field behind a dielectric sphere
Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the sphere
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- pixel_size (float) – Pixel size [m]
- grid_size (tuple of floats) – Resulting image size in x and y [px]
- center (tuple of floats) – Center position in image coordinates [px]
- interpolate (int) – Compute the radial field with sampling that is by a factor of interpolate higher than the required data and interpolate the 2D field from there.
- focus (float) –
New in version 0.5.0.
Axial focus position [m] measured from the center of the sphere in the direction of light propagation.
- arp (bool) – Use arbitrary precision (ARPREC) in BHFIELD computations
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.
projection
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, pixel_size=1e-07, grid_size=(80, 80), center=(39.5, 39.5))[source]¶ Optical path difference projection of a dielectric sphere
Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the sphere
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- pixel_size (float) – Pixel size [m]
- grid_size (tuple of floats) – Resulting image size in x and y [px]
- center (tuple of floats) – Center position in image coordinates [px]
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.
rytov
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, pixel_size=5e-07, grid_size=(80, 80), center=(39.5, 39.5), focus=0, radius_sampling=42)[source]¶ Field behind a dielectric sphere in the Rytov approximation
Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the sphere
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- pixel_size (float) – Pixel size [m]
- grid_size (tuple of floats) – Resulting image size in x and y [px]
- center (tuple of floats) – Center position in image coordinates [px]
- focus (float) –
New in version 0.5.0.
Axial focus position [m] measured from the center of the sphere in the direction of light propagation.
- radius_sampling (int) – Number of pixels used to sample the sphere radius when computing the Rytov field. The default value of 42 pixels is a reasonable number for single-cell analysis.
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.
rytov_sc
(radius=5e-06, sphere_index=1.339, medium_index=1.333, wavelength=5.5e-07, pixel_size=1e-07, grid_size=(80, 80), center=(39.5, 39.5), radius_sampling=42)[source]¶ Field behind a dielectric sphere, systematically corrected Rytov
This method implements a correction of
qpsphere.models.rytov()
, where the radius \(r_\text{Ryt}\) and the sphere_index \(n_\text{Ryt}\) are corrected using the approach described in [Mueller2018] (eqns. 3,4, and 5).\[ \begin{align}\begin{aligned}n_\text{Ryt-SC} &= n_\text{Ryt} + n_\text{med} \cdot \left( a_n x^2 + b_n x + c_n \right)\\r_\text{Ryt-SC} &= r_\text{Ryt} \cdot \left( a_r x^2 +b_r x + c_r \right)\\&\text{with} x = \frac{n_\text{Ryt}}{n_\text{med}} - 1\end{aligned}\end{align} \]The correction factors are given in
qpsphere.models.mod_rytov_sc.RSC_PARAMS
.Parameters: - radius (float) – Radius of the sphere [m]
- sphere_index (float) – Refractive index of the sphere
- medium_index (float) – Refractive index of the surrounding medium
- wavelength (float) – Vacuum wavelength of the imaging light [m]
- pixel_size (float) – Pixel size [m]
- grid_size (tuple of floats) – Resulting image size in x and y [px]
- center (tuple of floats) – Center position in image coordinates [px]
- radius_sampling (int) – Number of pixels used to sample the sphere radius when computing the Rytov field. The default value of 42 pixels is a reasonable number for single-cell analysis.
Returns: qpi – Quantitative phase data set
Return type:
-
qpsphere.models.mod_rytov_sc.
RSC_PARAMS
= {42: {'na': 1.936, 'nb': -0.012, 'ra': -2.431, 'rb': -0.753, 'rc': 1.001}}¶ correction parameters (see
correct_rytov_output()
)
util (Helper methods)¶
-
qpsphere.util.
CACHE_PATH
= PosixPath('/home/docs/.cache/python-qpsphere')¶ User’s cache directory
-
qpsphere.util.
RESCR_PATH
= PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/qpsphere/checkouts/0.5.7/qpsphere/resources')¶ Qpsphere package resources directory.
-
qpsphere.util.
download_binaries
(package_dir=False)[source]¶ Download all binaries for the current platform
Parameters: package_dir (bool) – If set to True, the binaries will be downloaded to the resources directory of the qpsphere package instead of to the users application data directory. Note that this might require administrative rights if qpsphere is installed in a system directory. Returns: paths – List of paths to binaries. This will always return binaries in the resources directory of the qpsphere package (if binaries are present there), in disregard of the parameter package_dir. Return type: list of pathlib.Path