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.cli_analyze_sphere(path=None, ret_data=False)[source]

Perform sphere analysis

drymass.cli.cli_convert(path=None, ret_data=False)[source]

Convert input data to QPSeries data

drymass.cli.cli_extract_roi(path=None, ret_data=False)[source]

Extract regions of interest

drymass.cli.parse_bg_value(bg, reldir)[source]

Determine the background to use from the configuration key

drymass.cli.strpar(cfg, section, key)[source]

String representation of a section/key combination

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
remove_section(section)[source]

Remove a section from the configuration file

set_value(section, key, value)[source]

Set a configuration key value

Parameters:
  • section (str) – the configuration section
  • key (str) – the configuration key in section
  • value – the configuration key value

Notes

Valid section and key names are defined in definitions.py

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)

drymass.cli.dialog.input_setting[source]

Ask the user for a configuration key

drymass.cli.dialog.main(path=None, req_meta=[])[source]

Main user dialog with optional “meta” kwargs required

drymass.cli.dialog.parse[source]

Obtain the input data set path by parsing the command line

drymass.cli.dialog.transfer_meta_data(path_in, path_out)[source]

Read input meta data and write it to the configuration file

drymass.cli.dialog.print_info[source]

Print input and output paths

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.fbool(value)[source]

Boolean value from string or number

drymass.cli.parse_funcs.fintlist(alist)[source]

List of integers from string or list of strings/integers

drymass.cli.parse_funcs.float01(flt)[source]

Float value between 0 and 1

drymass.cli.parse_funcs.float_or_str(flt_or_str)[source]

Float value from string or number

drymass.cli.parse_funcs.floattuple_or_one(fti)[source]

Tuple of two floats or ±1 from a string or a number

drymass.cli.parse_funcs.int_or_path(intpath)[source]

Integer or string from a string or a number

drymass.cli.parse_funcs.lcstr(astr)[source]

Convert a string to lower-case

drymass.cli.parse_funcs.strlist(alist)[source]

List of strings, comma- or space-separated

drymass.cli.parse_funcs.tupletupleint(items)[source]

A tuple containing x- and y- slice tuples from a string or tuple

cli.plot

DryMass plotting functionalities.

drymass.cli.plot.add_cbar(ax, mapper, fmt='%.2f', units='', loc='right', size='5%', labelloc=None, extend='neither')[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, cbformat=None, **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]

drymass.cli.plot.plot_qpi_phase(qpi, rois=None, path=None, labels_excluded=[])[source]

Plot phase data

drymass.cli.plot.plot_qpi_sphere(qpi_real, qpi_sim, path=None, simtype='simulation')[source]

Plot QPI sphere analysis data

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

exception drymass.anasphere.EdgeDetectionFailedWarning[source]
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:
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 interest phi_tot, the pixel area deltaA, the refractive index of the medium n_med (stored in qpi.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:

float

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:

float

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:

bool

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 1) 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 index bg_data - 1 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

drymass.converter.h5series2tif(h5in, tifout)[source]

Convert a qpimage.QPSeries file to a phase/amplitude TIFF file

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, ignore_data=None, 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]
  • ignore_data (list of str) – Identifiers for sensor images or ROIs to be excluded from further analysis. These will be labeled in the output tiff file and not written to the output qpseries file.
  • 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.
drymass.extractroi.is_ignored_roi(roi, ignore_data)[source]

Determine whether a specific ROI should be ignored

Parameters:
  • roi (drymass.roi.ROI) – ROI instance
  • ignore_data (list of str) – List of strings of the form “image_index” or “image_index.roi_index” that identify ROIs that should be ignored. For instance [“1.0”, “2.1”, “3”].

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:

  1. Search phase objects in qpi.raw_pha with a background correction computed from the gaussian-filtered image
  2. If no objects were found and qpi.bg_pha is nonzero, search objects in qpi.pha.
  3. 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:
  • path (str) – path to the file
  • blocksize (int) – block size read from the file
Returns:

hex – The first six characters of the hash

Return type:

str

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
drymass.util.obj2bytes(obj)[source]

String representation of an object for hashing

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(roi_slice=(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	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))

exception drymass.roi.ROIManagerWarning[source]

Used for unexpected keyword arguments.