Code reference¶
Command-line interface¶
The usage of the command line interface is described in detail here. It consists of these main methods:
-
drymass.cli.
FILE_SENSOR_WITH_ROI_IMAGE
= 'sensor_roi_images.tif'¶ Matplotlib images of sensor data with labeled ROI (TIFF)
-
drymass.cli.
FILE_SPHERE_ANALYSIS_IMAGE
= 'sphere_{}_{}_images.tif'¶ Matplotlib images of sphere analysis (TIFF)
-
drymass.cli.
parse_bg_value
(bg, reldir)[source]¶ Determine the background to use from the configuration key
cli.config¶
-
drymass.cli.config.
FILE_CONFIG
= 'drymass.cfg'¶ DryMass configuration file name
-
class
drymass.cli.config.
ConfigFile
(path)[source]¶ DryMass configuration file management
Manage configuration file of an experimental data set with restrictions imposed by
drymass.cli.definitions.config
.Parameters: path (str) – path to the configuration file
cli.definitions¶
-
drymass.cli.definitions.
config
¶ The keys and subkeys of the definition dictionary are defined and described in the configuration file section.
cli.dialog¶
The dialog submodule contains methods for user-interaction.
-
drymass.cli.dialog.
OUTPUT_SUFFIX
= '_dm'¶ DryMass analysis output suffix (appended to data path)
cli.parse_funcs¶
These methods are used to parse the values set in the Configuration file and convert them to the correct type.
-
drymass.cli.parse_funcs.
fintlist
(alist)[source]¶ List of integers from string or list of strings/integers
cli.plot¶
DryMass plotting functionalities.
-
drymass.cli.plot.
add_cbar
(ax, mapper, cbformat='%.2f', label='', loc='right', size='5%', labelloc=None)[source]¶ Add a colorbar to a plot
-
drymass.cli.plot.
plot_image
(data, ax=None, imtype='phase', cbar=True, px_um=None, ret_cbar=False, **kwargs)[source]¶ Plot an image
Parameters: - data (2d np.ndarray) – Input image
- ax (matplotlib.Axes) – Axis to plot to
- imtype (str) – One of [“intensity”, “phase”, “phase_error”, “refractive index”].
- cbar (bool) – Whether to add a colorbar.
- px_um (float) – Pixel size [µm]
- ret_cbar (bool) – Whether to return the colorbar.
- kwargs (dict) – Keyword arguments to plt.imshow.
Returns: Axis and colorbar.
Return type: ax [, cbar]
Data analysis¶
anasphere¶
-
drymass.anasphere.
FILE_SPHERE_DATA
= 'sphere_{}_{}_data.h5'¶ Output sphere analysis qpimage.QPSeries data
-
drymass.anasphere.
FILE_SPHERE_STAT
= 'sphere_{}_{}_statistics.txt'¶ Output sphere analysis statistics
-
drymass.anasphere.
analyze_sphere
(h5roi, dir_out, r0=1e-05, method='edge', model='projection', edgekw={}, imagekw={}, alpha=0.18, rad_fact=1.2, ret_changed=False)[source]¶ Perform sphere analysis
Parameters: - h5series (str) – Path of qpimage.QPSeries hdf5 file
- dir_out (str) – Path to output directory
- r0 (float) – Initial radius
- method (str) – Either “edge” or “image”; see [sphere] Sphere-based image analysis for more information.
- model (str) – Propagation model to use; see [sphere] Sphere-based image analysis for more information.
- edgekw (dict) – Keyword arguments to
qpsphere.edgefit.contour_canny()
- imagekw (dict) – Keyword arguments to
qpsphere.imagefit.alg.match_phase()
- alpha (float) – Refraction increment [mL/g]
- rad_fact (float) – Radial inclusion factor for dry mass computation
- ret_changed (bool) – Return boolean indicating whether the sphere data on disk was created/updated (True) or whether previously created ROI data was used (False).
-
drymass.anasphere.
absolute_dry_mass_sphere
(qpi, radius, center, alpha=0.18, rad_fact=1.2)[source]¶ Compute absolute dry mass of a spherical phase object
The absolute dry mass is computed with
m_abs = m_rel + m_sup m_rel = lambda / (2*PI*alpha) * phi_tot * deltaA m_sup = 4*PI / (3*alpha) * radius^3 (n_med - n_PBS)
with the vacuum wavelength
lambda
, the total phase retardation in the area of interestphi_tot
, the pixel areadeltaA
, the refractive index of the medium n_med (stored inqpi.meta
), and the refractive index of phosphate buffered saline (PBS)n_PBS=1.335
.This is the absolute dry mass, because it takes into account the offset caused by the suppressed density in the phase data.
Parameters: - qpi (qpimage.QPImage) – QPI data
- center (tuble (x,y)) – Center of the sphere [px]
- radius (float) – Radius of the sphere [m]
- wavelength (float) – The wavelength of the light [m]
- alpha (float) – Refraction increment [mL/g]
- rad_fact (float) – Inclusion factor that scales radius to increase the area used for phase summation; if the backgound phase exhibits a noise phase signal, positive and negative contributions cancel out and rad_fact does not have an effect above a certain critical value.
Returns: dry_mass – The absolute dry mass of the sphere [g]
Return type:
-
drymass.anasphere.
relative_dry_mass
(qpi, radius, center, alpha=0.18, rad_fact=1.2)[source]¶ Compute relative dry mass of a circular area in QPI
The dry mass is computed with
m_rel = lambda / (2*PI*alpha) * phi_tot * deltaA
with the vacuum wavelength lambda, the total phase retardation in the area of interest phi_tot, and the pixel area deltaA.
This is the relative dry mass, because it is computed relative to the surrounding medium (phi_tot) and not relative to water.
Parameters: - qpi (qpimage.QPImage) – QPI data
- center (tuble (x,y)) – Center of the area of interest [px]
- radius (float) – Radius of the area of interest [m]
- wavelength (float) – The wavelength of the light [m]
- alpha (float) – Refraction increment [mL/g]
- rad_fact (float) – Inclusion factor that scales radius to increase the area used for phase summation; if the backgound phase exhibits a noise phase signal, positive and negative contributions cancel out and rad_fact does not have an effect above a certain critical value.
Returns: dry_mass – The relative dry mass of the object [g]
Return type:
-
drymass.anasphere.
mode_for_sphere_analysis
(h5in, h5out, cfgid)[source]¶ Determine the mode for the QPSeries file for subsequent analysis
Sometimes an analysis is interrupted and the output files are still intact. This method determines whether it is possible to continue the analysis where left off or not.
Parameters: - h5in (pathlib.Path) – The input QPSeries file
- h5out (pathlib.Path) – The output QPSeries file
- cfgid (str) – The configuration hash of the sphere analysis which is part of the output QPSeries analysis
Returns: create – Whether the output QPSeries file is ok. This is dependent on the following scenarios:
- True: There is no output QPSeries file, it is corrupt,
- or at least one of the qpimage identifiers is not present in the input QPSeries.
- False: Some of the input QPSeries identifiers are
- present in the output QPSeries.
Return type:
converter¶
-
drymass.converter.
FILE_SENSOR_DATA_H5
= 'sensor_data.h5'¶ Output qpimage.QPSeries sensor data
-
drymass.converter.
FILE_SENSOR_DATA_TIF
= 'sensor_data.tif'¶ Output phase/amplitude TIFF sensor data
-
drymass.converter.
convert
(path_in, dir_out, meta_data={}, holo_kw={}, bg_data_amp=None, bg_data_pha=None, write_tif=False, ret_dataset=False, ret_changed=False)[source]¶ Convert experimental data to qpimage.QPSeries on disk
Parameters: bg_data_pha (bg_data_amp,) – The background data for phase and amplitude. One of
- None: No background data
- int: Image index (starting at 0) of the input data set to use as background data
- str, pathlib.Path: Path to a separate file that is used for background correction, relative to the directory in which path_in is located (path_in.parent).
-
drymass.converter.
get_background
(bg_data, dataset, which='phase')[source]¶ Obtain the background data for a dataset
Parameters: - bg_data (None, int, str, or pathlib.Path) –
Represents the background data:
- None: no background data
- int: image with this index in dataset is used for background correction
- str, pathlib.Path: An external file will be used for background correction.
- dataset (qpformat.dataset.SeriesData) – The dataset for which the background data is collected. No background correction is performed! dataset is needed for integer bg_data and for path-based bg_data (because of meta data and hologram kwargs).
Returns: bg – The background data.
Return type: 2d np.ndarray
- bg_data (None, int, str, or pathlib.Path) –
extractroi¶
-
drymass.extractroi.
BG_DEFAULT_KW
= {'border_perc': 5, 'border_px': 5, 'fit_offset': 'mean', 'fit_profile': 'tilt'}¶ Default background correction keyword arguments
-
drymass.extractroi.
FILE_ROI_DATA_H5
= 'roi_data.h5'¶ Output ROI qpimage.QPSeries data
-
drymass.extractroi.
FILE_ROI_DATA_TIF
= 'roi_data.tif'¶ Output phase/amplitude TIFF data
-
drymass.extractroi.
FILE_SLICES
= 'roi_slices.txt'¶ Output slice locations
-
drymass.extractroi.
extract_roi
(h5series, dir_out, size_m, size_var=0.5, max_ecc=0.7, dist_border=10, pad_border=40, exclude_overlap=30.0, bg_amp_kw={'border_perc': 5, 'border_px': 5, 'fit_offset': 'mean', 'fit_profile': 'tilt'}, bg_amp_bin=nan, bg_amp_mask_radial_clearance=nan, bg_pha_kw={'border_perc': 5, 'border_px': 5, 'fit_offset': 'mean', 'fit_profile': 'tilt'}, bg_pha_bin=nan, bg_pha_mask_radial_clearance=nan, bg_sphere_edge_kw={}, search_enabled=True, ret_roimgr=False, ret_changed=False)[source]¶ Extract ROIs from a qpimage.QPSeries hdf5 file
Parameters: - h5series (str) – Path of qpimage.QPSeries hdf5 file
- dir_out (str) – Path to output directory
- size_m (float) – Approximate diameter of the specimen [m]
- size_var (float) – Allowed variation relative to specimen size
- max_ecc (float) – Allowed maximal eccentricity of the specimen
- dist_border (int) – Minimum distance of objects to image border [px]
- pad_border (int) – Padding of object regions [px]
- exclude_overlap (float) – Allowed distance between two objects [px]
- bg_amp_kw (dict or None) – Amplitude image background correction keyword arguments
(see
qpimage.QPImage.compute_bg()
), defaults to BG_DEFAULT_KW, set to None to disable correction - bg_amp_bin (float or str) – The amplitude binary threshold value or the method for binary
threshold determination; see
skimage.filters
threshold_* methods - bg_amp_mask_radial_clearance (float) – If not NaN, use
qpsphere.cnvnc.bg_phase_mask_for_qpi()
to compute a mask image and use it for amplitude background correction. - bg_pha_kw (dict or None) – Phase image background correction keyword arguments
(see
qpimage.QPImage.compute_bg()
), defaults to BG_DEFAULT_KW, set to None to disable correction - bg_pha_bin (float or str) – The phase binary threshold value or the method for binary
threshold determination; see
skimage.filters
threshold_* methods - bg_pha_mask_radial_clearance (float) – If not NaN, use
qpsphere.cnvnc.bg_phase_mask_for_qpi()
to compute a mask image and use it for phase background correction. - search_enabled (bool) – If True, perform automated search for ROIs using the parameters above. If False, extract the ROIs from FILE_SLICES and only perform background correction using the bg_* parameters.
- ret_roimgr (bool) – Return the ROIManager instance of the found ROIs
- ret_changed (bool) – Return boolean indicating whether the ROI data on disk was created/updated (True) or whether previously created ROI data was used (False).
Notes
The output hdf5 file dir_out/FILE_ROI_DATA_H5 is a
qpimage.QPSeries
file with the keyword “identifier” consisting of two hashes: one from the relevant arguments to this method and one from the file dir_out/FILE_SLICES. This is to ensure that user-manipulated data is taken into account when deciding whether the ROIs should be re-computed after an initial run.
-
drymass.extractroi.
image2mask
(image, value_or_method)[source]¶ Convert an image to a binary mask
Parameters: - image (2d np.ndarray) – Input image
- value_or_method (float or str) – Either a threshold value or a string naming a
filter method in
skimage.filters
.
Helper classes and methods¶
search¶
-
drymass.search.
approx_bg
(data, filter_size=None)[source]¶ Approximate the image background with Gaussian convolution
Parameters: - data (2d ndarray) – Data from which to compute the background
- size (float) –
Approximate size of the objects on the background. The size of the Gaussian is heuristically determined with
\[\sigma = 5 \cdot \texttt{size}\]
Returns: Return type: Approximate background of data.
-
drymass.search.
search_objects_base
(image, size=110, size_var=0.5, max_ecc=0.7, dist_border=10, verbose=False)[source]¶ Search objects in images
The wrapper
search_phase_objects()
implements a more robust (heuristic) way of finding objects.Parameters: - image (2d ndarray) – Input image
- size (float) – Approximate diameter of phase objects in pixels
- size_var (float) – Allowed variation in size (relative to size) for the detected objects
- max_ecc (float in interval [0,1)) –
Maximal eccentricity of the objects. The eccentricity of a circle is zero. For an ellipse it is defined as
\[\varepsilon=\sqrt{\frac{a^2-b^2}{a^2}} = \sqrt{1-\left(\frac{b}{a}\right)^2} = f/a.\] - dist_border (float) – Minimum distance of detected regions to the borders of the image in pixels
- verbose (bool) – If True, print information about ignored regions
Returns: rois – Found regions
Return type: list of regionprops
See also
skimage.filters.threshold_otsu()
- threshold for finding objects
skimage.segmentation.clear_border()
- remove regions at the border
skimage.morphology.label()
- identify regions in binary images
-
drymass.search.
search_phase_objects
(qpi, size_m, size_var=0.5, max_ecc=0.7, dist_border=10, pad_border=40, exclude_overlap=30.0, verbose=False)[source]¶ Search phase objects in quantitative phase images
Parameters: - qpi (qpimage.QPImage) – Quantitative phase data
- size_m (float) – Expected size of the phase objects
- size_var (float) – Allowed variation in size (relative to size) for the detected objects
- max_ecc (float in interval [0,1)) –
Maximal eccentricity of the objects. The eccentricity of a circle is zero. For an ellipse it is defined as
\[\varepsilon=\sqrt{\frac{a^2-b^2}{a^2}} = \sqrt{1-\left(\frac{b}{a}\right)^2} = f/a.\] - dist_border (int) – Minimum distance of detected regions to the borders of the image in pixels
- pad_border (int) – Pad the regions of all objects
- exclude_overlap (float) – Allowed distance in pixels between two detected regions (without pad_border)
- verbose (bool) – If True, print information about ignored regions
Returns: slices
Return type: list of slice
Notes
Description of the heuristic search algorithm:
- Search phase objects in qpi.raw_pha with a background correction computed from the gaussian-filtered image
- If no objects were found and qpi.bg_pha is nonzero, search objects in qpi.pha.
- Search objects in qpi.bg_pha and remove any overlaps with the previously obtained regions.
See also
search_objects_base()
- underlying search algorithm
approx_bg()
- gaussian-filtered background estimation
util¶
Utility methods
-
drymass.util.
hash_file
(path, blocksize=65536)[source]¶ Compute sha256 hex-hash of a file
Parameters: Returns: hex – The first six characters of the hash
Return type:
-
drymass.util.
hash_object
(obj)[source]¶ Compute sha256 hex-hash of a Python object
Objects in dicts/lists/tuples are joined together before hashing using
obj2bytes()
in this module.Returns: hex – The first six characters of the hash Return type: str
roi¶
The ROIManager
class is used to manage and save/load ROI positions.
In [1]: from drymass.roi import ROIManager
In [2]: rmg = ROIManager(identifier="example")
In [3]: rmg.add(roislice=(slice(10, 100), slice(50, 140)),
...: image_index=2,
...: roi_index=0,
...: identifier="example_subroi_2.0")
...:
In [4]: rmg.get_from_image_index(2)
Out[4]: [['example_subroi_2.0', (slice(10, 100, None), slice(50, 140, None))]]
Saving and loading can be done with:
In [5]: rmg.save("output_rois.txt")
In [6]: rmg2 = ROIManager(identifier="ex")
In [7]: rmg2.load("output_rois.txt")
And the content of “output_rois.txt” is:
example_subroi_2.0 2 0 (slice(10, 100, None), slice(50, 140, None))