mrbles package¶
Submodules¶
mrbles.core module¶
Core Classes and Functions¶
This file stores the core classes and functions for the MRBLEs Analysis module.
-
class
mrbles.core.Classify(target, sigma=1e-05, train=False, **kwargs)[source]¶ Bases:
future.types.newobject.newobjectClassification of beads by Gaussian Mixture Model.
Parameters: - target (list, NumPy array) – List of target ratios.
- tol (float) – Tolerance. Defaults to 1e-5.
- min_covar (float) – Minimum covariance. Defaults to 1e-7.
- sigma (float) – … Defaults to 1e-5.
- train (boolean) – Sets training mode. Remembers covariance matrix or resets to initial covariance matrix. Defaults to False.
-
found¶ Return found codes.
-
init_covars¶ Return initial covariance matrix.
-
init_weights¶ Return initial weights.
-
log_prob¶ Return log probabilities.
-
means¶ Return means.
-
missing¶ Return missing codes.
-
output¶ Return codes, probability and log probability.
-
probs¶ Return probabilities.
-
stds¶ Return Choleski based SD.
-
class
mrbles.core.FindBeadsCircle(min_r, max_r, param_1=10, param_2=10, annulus_width=2, min_dist=None, enlarge=1, auto_filt=True, border_clear=False, parallelize=True)[source]¶ Bases:
mrbles.core.FindBeadsImagingFind and identify bead objects from image.
Parameters changes for each setup/magnification/bead-set.
Parameters: - min_r (int) – Sets the minimum diameter of the bead in pixels.
- max_r (int) – Sets the maximum diameter of the bead in pixels.
- param_1 (int) – Sets the gradient steepness. CHECK
- param_2 (int) – Sets the sparsity. CHECK
- annulus_width (int, optional) – Sets the width of the annulus in pixels. Defaults to 2 pixels.
- min_dist (int, optional) – Sets the minimal distance between the centers of the beads in pixels. Defaults to 2x of the minimum diameter (min_r).
- enlarge (float, optional) – Enlarges the found diameter by this factor. 1 remains equal, 1.1 enlarges by 10% and 0.9 shrinks by 10%. Defaults to 1, no enlarging/shrinking.
-
static
circle_mask(image, min_dist, min_r, max_r, param_1, param_2, enlarge)[source]¶ Find initial circles using Hough transform and return mask.
-
static
circle_separate(mask, circles)[source]¶ Find and separate circles using watershed on initial mask.
-
circles_dim¶ Return circle dimensions.
-
static
convert(image)[source]¶ 8 Bit Convert.
Checks image data type and converts if necessary to uint8 array. image : M x N image array
-
labeled_annulus_mask¶ Return labeled annulus mask.
-
labeled_mask¶ Return labeled mask.
-
class
mrbles.core.FindBeadsImaging(bead_size, border_clear=True, circle_size=None, parallelize=False)[source]¶ Bases:
mrbles.data.ImageDataFrameFind and identify beads and their regions using imaging.
Parallel computing version.
Parameters: - bead_size (int) – Approximate width of beads (circles) in pixels.
- border_clear (boolean) – Beads touching border or ROI will be removed. Defaults to True.
- circle_size (int) – Set circle size for auto find circular ROI.
Variables: - area_min (float) – Sets the minimum area in pixels. Set to minimum size inside of ring. Defaults to 0.1 * area of set bead_size.
- area_max (float) – Sets the maximum area in pixels. Set maximum size outside of ring. Defaults to 1.5 * area of set bead_size.
- eccen_max (float) – Get or set maximum eccentricity of beads in value 0 to 1, where a perfect circle is 0. Defaults to 0.65.
-
area_max¶ Get or set minimum area of beads (circles) in pixels.
-
area_min¶ Get or set minimum area of beads (circles) in pixels.
-
bead_dims¶ Return found bead dimensions.
-
bead_labels¶ Return all positive labels of labeled mask.
-
bead_num¶ Return number of beads labeled mask.
-
bead_size¶ Get or set approximate width of beads (circles) in pixels.
-
static
circle_area(diameter)[source]¶ Return area of circle.
Parameters: diameter (float) – Diameter of circle.
-
classmethod
circle_roi(image, circle_size, hough_settings=None)[source]¶ Apply a circular image ROI.
Parameters: - image (NumPy array image)
- hough_settings (list, int) – Settings for HoughCircles in list. list[0] = dp, list[1] = param1, list[2] = param2
-
eccen_max¶ Get or set maximum eccentricity of beads from 0 to 1.
A perfect circle is 0 and parabola is 1.
-
static
eccentricity(axis_a, axis_b)[source]¶ Return eccentricity by major axes.
Parameters: axis_a : float
Size major axis a.- axis_b : float
- Size major axis b.
-
classmethod
filter_mask(mask, filter_params, filter_names, slice_types, border_clear=False)[source]¶ Filter labeled mask based on provided parameters.
-
classmethod
filter_properties(properties, filter_params, filter_names, slice_types)[source]¶ Get labels of areas outside of limits.
-
static
filter_property(properties, filter_param, filter_name, slice_type)[source]¶ Get labels of beads outside/inside/up/down of propert limits.
Parameters: - properties (photutils table) – Table with feature properties from labeled mask. >>> from photutils import source_properties, properties_table >>> tbl = properties_table(properties) >>> properties = source_properties(mask, mask)
- filter_param (float, int, list) – Parameters to filter by. If provided a list it will filter by range, inside or outside). If provided a value it filter up or down that value.
- slice_type (string) – ‘outside’ : < > ‘inside’ : >= <= ‘up’ : > ‘down’ : <
-
classmethod
make_mask_outside(mask, size, buffer=0)[source]¶ Return labeled mask of area around bead.
-
mask_types¶ Return list of mask types.
-
static
show_image_overlay(image, image_blend, alpha=0.3, cmap1='Greys_r', cmap2='jet')[source]¶ Overlay of 2 images using alpha blend.
Parameters: - image (NumPy array) – Base image.
- image_blend (NumPy arra) – Image to blend over base image.
- aplha (float) – Amount of blending. Value between 0 and 1. Defaults to 0.3.
- c_map1 (cmap) – Color scheme using cmap. See matplotlib for color schemes. Defaults to ‘Greys_r’, which are reversed grey values.
-
class
mrbles.core.ICP(target, matrix_method='std', offset=None, max_iter=100, tol=0.0001, outlier_pct=0.01)[source]¶ Bases:
future.types.newobject.newobjectIterative Closest Point (ICP).
Iterative Closest Point (ICP) algorithm to minimize the difference between two clouds of points.
Parameters: - matrix_method (string/function/list, optional) – Transformation matrix method. Standard methods: ‘max’, ‘mean’, ‘std’. Other options: own function or list of initial guesses. Defaults to ‘std’.
- offset (list of float, optional)
- max_iter (int, optional) – Maximum number of iterations. Defaults to 100.
- tol (float, optional) – Convergence threshold. ICP will stop after delta < tol. Defaults to 1e-4.
- outlier_pct (float, optional) – Discard percentile 0.x of furthest distance from target. Percentile given in fraction [0-1], e.g. ‘0.001’. Defaults to 0.
- train (boolean) – Turn on (True) or off (False) traning mode. This will keep the current tranformation from resetting to default initial values. Defaults to True.
- echo (boolean) – Turn on (True) or off (False) printing information while in process. Prints the delta for each iteration, the final number of iterations, and the final transformation and offset matrices.
Variables: - matrix (NumPy array) – This stores the transformation matrix.
- offset (NumPy vector) – This stores the offset vector.
- Functions –
- --------- –
- fit (function) – Function to find ICP using set parameters and attributes.
- transform (function) – Function to apply transformat data using current transformation matrix and offset vector.
-
static
matrix_create(func, input1, input2)[source]¶ Create identity matrix and set values with function on inputs e.g ‘np.mean’.
Parameters: - func (function) – Function to apply on input1 divided by input2, e.g. ‘np.std’. Insert function without function call: ().
- input1 (list, ndarray)
- input2 (list, ndarray)
Returns: matrix – Returns func(input1/input2)
Return type: ndarray
-
class
mrbles.core.SpectralUnmixing(ref_data)[source]¶ Bases:
mrbles.data.ImageDataFrameSpectrally unmix images using reference spectra.
Unmix the spectral images to dye images, e.g., 620nm, 630nm, 650nm images to Dy, Sm and Tm nanophospohorous lanthanides using reference spectra for each dye.
Parameters: ref_data (list, ndarray, Pandas DataFrame, mrbles.data.References) – Reference spectra for each dye channel as Numpy Array: N x M, where N are the spectral channels and M the dye channels. -
unmix(images)[source]¶ Unmix images based on initiated reference data.
Unmix the spectral images to dye images, e.g., 620nm, 630nm, 650nm images to Dy, Sm and Tm nanophospohorous lanthanides using reference spectra for each dye.
Parameters: image_data (NumPy array, Xarry DataArray, mrbles.Images) – Spectral images as NumPy array: N x M x P, where N are the spectral channels and M x P the image pixels (Y x X).
-
mrbles.data module¶
Data Classes and Functions¶
This file stores the data classes and functions for the MRBLEs Analysis module.
-
class
mrbles.data.ImageDataFrame(data=None)[source]¶ Bases:
future.types.newobject.newobjectXarray based dataframe object for images.
Variables: - data (Xarray DataArray) – Returns (cropped, if crop_x and/or crop_y is set) Xarray DataArray.
- xdata (Xarray DataArray) – Returns uncropped Xarray DataArray.
- sets (list) – Returns a list of all set names, if ‘set’ column is present.
- crop_x (slice) – Crop X slice. Set with slice().
- crop_y (slice) – Crop Y slice. Set with slice().
-
combine(images)[source]¶ Combine iamges with dataframe.
Parameters: images (Xarray DataArray, dict of Xarray DataArrays)
-
crop_x¶ Crop X slice. Set with slice().
-
crop_y¶ Crop Y slice. Set with slice().
-
data¶ Return cropped Xarray dataframe.
-
sets¶ Return list of sets.
-
shift_channel(channel, x_shift, y_shift)[source]¶ Shift images of channel by x and y pixels.
WARNING: This will shift the images permanently and sets inbound pixels to 0. Reload images to reset.
Parameters: - channel (str) – Channel name to shift.
- x_shift (int) – Pixels to shift in X dimension.
- y_shift (int) – Pixels to shift in Y dimension.
-
xdata¶ Return uncropped Xarray dataframe.
-
class
mrbles.data.ImageSetRead(file_path, series=0, output='xr')[source]¶ Bases:
mrbles.data.ImageDataFrameImage set data object that loads image set from file(s).
Parameters: - file_path (string/list [string, string, …]) – File path as string, e.g. ‘C:/folder/file.tif’, or as list of file paths, e.g. [‘C:/folder/file.tif’, ‘C:/folder/file.tif’].
- series (int, optional) – Sets the series number if file has multiple series. To Loads all series set to series=’all’. Defaults to 0.
- output (str, optional) – Sets default output method. Options: ‘nd’ for NumPy ndarray or ‘xd’ for xarray. Defaults to ‘ndarray’.
Variables: function descriptions. (See) –
Returns: - _dataframe (xarray dataframe) – Returned when calling the instance.
- _dataframe[idx] (NumPy ndarray) – Returns the index value or slice values: [start:stop:stride]. Warning: when using column names stop values are included.
Examples
>>> image_data_object = ImageSetRead('C:/folder/file.tif') >>> image_files = ['C:/folder/file.tif', 'C:/folder/file.tif'] >>> image_data_object = ImageSetRead(image_files, output='xd') >>> image_data_object['BF', 100:400, 100:400] (301L, 301L)
-
axes¶ Return data order.
Returns: data_order – Returns order as string with: P for position; F for file; T for timepoint, C for channel; Y for Y-axis; X for X-axis. Return type: string Examples
>>> image_data_object = ImageSetRead('C:/folder/file.tif') >>> image_data_object.axes 'TCYX'
-
c_names¶ Return channel names.
-
c_size¶ Return channel count.
-
f_names¶ Return file names.
-
f_size¶ Return file count.
-
is_multi_file¶ Return if from multiple files.
-
classmethod
load(file_path, series=0)[source]¶ Load image files into data structures.
Class method. Can be used without instantiating.
Parameters: - file_path (string/list [string, string, …]) – File path as string, e.g. ‘C:/folder/file.tif’, or as list of file paths, e.g. [‘C:/folder/file.tif’, ‘C:/folder/file.tif’].
- series (int, optional) – Sets the series number if file has multiple series (or positions). Use series=’all’ for loading all series. Defaults to 0.
Examples
>>> ImageSetRead.load('C:/folder/file.tif') >>> image_files = ['C:/folder/file.tif', 'C:/folder/file.tif'] >>> ImageSetRead.load(image_files)
-
p_size¶ Return position count.
-
s_size¶ Return series count.
-
static
scan_path(path, pattern='.*.tif')[source]¶ Scan folder recursively for files matching the pattern.
Parameters: - path (string) – Folder path as string, e.g. r’C:/folder/file.tif’.
- pattern (string) – General file pattern as search string, e.g. ‘20160728_MOL_*’, using regular expressions (regex). Defaults to ‘.*.tif’.
-
classmethod
scan_paths(paths, pattern='.*.tif')[source]¶ Scan folders recursively for files matching the pattern.
Parameters: - paths (list) – Folder paths as list, e.g. [‘C:/folder/file.tif’, …].
- pattern (string) – General file pattern as search string, e.g. ‘20160728_MOL_*’, using regular expressions (regex).
-
t_deltas¶ Return time deltas between each image acquisition.
Default in milliseconds (ms), check object.t_unit for time unit.
-
t_interval¶ Return set time interval.
Default in milliseconds (ms), check object.t_unit for time unit.
-
t_size¶ Return time-point count.
-
t_unit¶ Return time unit.
-
z_size¶ Return Z-slice count.
mrbles.kinetics module¶
Kinetics Classes and Functions¶
This file stores the kinetics classes and functions for the MRBLEs Analysis module.
-
class
mrbles.kinetics.GlobalFit[source]¶ Bases:
future.types.newobject.newobjectGlobal non-linear regression.
This class is based on the lmfit module pipeline. For mor information and functionalilty, please visit: https://lmfit.github.io/lmfit-py/
-
fit_metrics¶ Return fit metrics.
-
static
model_bind(Mt, Kd, Rmax)[source]¶ Langmuir Isothem model.
Assuming protein [M]total in excess model: [M] ≈ [M]total = [MP]+[M].
Model -> [MP] := ([M]total * Rmax) / (Kd + [M]total)
[M]total * Rmax- [MP] := ——————-
- Kd + [M]total
All concentrations must be in the same units!
Parameters: - Mt (float) – Total protein [M] concentration: [M]total = [M]free+[MP].
- Rmax (float) – Maximum response level in abitrary units.
-
classmethod
model_dataset(params, i, Mt)[source]¶ Model dataset function.
This extracts the data from the Parameters, used by lmfit.
-
classmethod
objective(params, Mt, data, sigma=None)[source]¶ Objective function of the Langmuir Isotherm model.
-
result¶ Return lmfit ModelResult object.
-
-
class
mrbles.kinetics.KModelSim(c_substrate, c_complex, kd_init, tol=0.0001)[source]¶ Bases:
future.types.newobject.newobjectKurt’s white paper for competive binding.
Assuming substrate (peptide on bead) or complex (protein) concentration in excess.
Parameters: - c_substrate (array) – NumPy array of substrate (peptide) concentrations.
- c_complex (array) – NumPy array of complex (protein) concentrations.
- kd_init (int) – Set range max for Kd’s starting from 0.
- tol (float) – Set tolerance error. Defaults to 1E-4.
Variables: - result (array) – Returns NumPy array of fit.
- Functions –
- --------- –
- fit (function) – Function to fit parameters.
- Examples –
>>> Mmat = np.logspace(0, 3, 20) # Matrix of protein concentrations, e.g. 20x between 0 to 3 uM. >>> Pt = np.array(([10]*10)) # Concentrations of each peptide, e.g. 10x 10 uM. >>> test_kshow = ba.kin.kshow(Pt, Mmat, 2, 1E-4) >>> test_kshow.fit() >>> plt.plot(test_kshow.result) ...
-
result¶ Return result from fit.
mrbles.path module¶
MRBLE-Path Classes and Functions¶
This file stores the MRBLE-Path classes and functions for the MRBLEs Analysis module.
-
class
mrbles.path.PathUnmix(references, blast=True)[source]¶ Bases:
mrbles.data.TableDataFrameMRBLE-Path unmixing algorithm.
Parameters: - references (Pandas DataFrame) – Dataframe with reference spectra.
- blast (bool) – Setting to convert blast E-scores. Defaults to True.
-
static
generate_test_refs(channels, spike_channel=None, signal_max=65536, scale=True)[source]¶ Generate test reference spectra.
- spike_channel : list
- List of channel numbers to spike.
- signal_max : int
- Maximum value. Defaults to 2**16: 65536.
- scale : bool
- Scale to 1. Defaults to True.
-
unmix(data, signal, z_score=True)[source]¶ Unmix data.
Parameters: - data (Pandas DataFrame) – Data that contains the various sets.
- signal (str) – Column with signal data.
- z_score (bool or list) – Convert to Z-score if set to True, or uses mean and SD values of provided list position 0 is mean, position 1 is SD. Defaults to True.
mrbles.pipeline module¶
Pipeline Classes and functions¶
This files contains the pipeline for the MRBLEs analysis.
-
class
mrbles.pipeline.Analyze(dataframe, seq_list=None, images=None, masks=None)[source]¶ Bases:
mrbles.data.TableDataFrameAnalyze data MRBLE data and return per-code statistics.
Parameters: - seq_list (list, Pandas DataFrame) – List (one column) or Pandas DataFrame with additional per-code information. In the case of a Pandas DataFrame all provided columns will be added, based on the row number, which corresponds to its code.
- flag_filt (boolean) – Sets if the flagged data is automatically filtered out. Defaults to True.
Variables: functions (dict) –
Dictionary of functions and their corresponding names. Default: {‘mean’: np.mean,
’median’: np.median, ‘sd’: np.std, ‘se’: sp.stats.sem, ‘N’: len, ‘CV’: sp.stats.variation}
-
analyze(assay_channel, min_prob=None, bkg_data=None)[source]¶ Calculate per-code statisics.
- assay_channel : str
- Assay channel name (column name) to calculate per-code statistics for.
- min_prob: float
- Filter by minimum probability interval, e.g. 0.95. Defaults to None.
- bkg_data : float/int, string, list, NumPy array, Pandas DataFrame
- If float/value is used, this value be subtracted. If string is used, column from internal dataframe is used. Otherwise, the data provided is subtracted, which needs to be the same size as the per-bead data. In the case of Pandas DataFrame, do slice the single exact column. Row number of the data is the code. Defaults to None.
-
data_per_bead¶ Return (normalized) data per bead.
-
data_per_code¶ Return (normalized) data per code.
-
mrble_report(assay_channel, filename, set_name=None, codes=None, files=None, sort=True, image_names=None, mask_names=None)[source]¶ Generate per-MRBLE PDF image report.
Parameters: - assay_channel (str) – Assay channel name, e.g. ‘Cy5_FF’
- filename (str) – Filename for generated PDF file.
- set_name (str) – Name of set, e.g. ‘Set A’
- codes (int, list of int) – Integer or list of integers with selected codes. Defaults to None.
- files (int, list of int) – Integer or list of integers with selected files. Defaults to None.
- sort (boolean) – Sort by code. Defaults to True.
- image_names (list of str) – List of image names. Defaults to [‘Dy’, ‘Sm’, ‘Tm’, ‘bkg’, ‘Eu’, assay_channel].
- mask_names (list of str) – List of mask names. Defaults to [‘mask_ring’, ‘mask_inside’, ‘mask_full’, ‘mask_bkg’].
-
norm_data¶ Return normalized data.
-
class
mrbles.pipeline.Decode(target, seq_list=None, decode_channels=None)[source]¶ Bases:
mrbles.data.TableDataFrameDecode MRBLEs.
Parameters: - target (list) – List of target ratios
- seq_list (Pandas DataFrame) – Columns with sequence information. Defaults to None.
- decode_channels (list) – Channel names. Defaults to None.
-
decode(data, combine_data=None)[source]¶ Decode MRBLEs.
Parameters: - data (Pandas DataFrame) – Data that contains decoding data.
- combine_data (Pandas DataFrame) – Data to be combined from previous pipeline steps. Defaults to None.
-
plot_clusters_2D(colors, ci_trace=None, min_prob=None)[source]¶ Plot ratio clusters in 2D.
Parameters: - colors (list) – List of color (NPL) names.
- ci_trace (float) – Set trace confidence line around clusters. Defaults to None.
- min_prob (float) – Set minimal probability level from 0 to 1, e.g. 0.95. Defaults to None.
-
class
mrbles.pipeline.Extract(function=None)[source]¶ Bases:
mrbles.data.TableDataFrameExtract data from images using masks.
Parameters: function (function) – This is the function used to extract data from each bead region. This can be replaced with any 1 parameter function, e.g. np.mean. Defaults to np.median. -
filter(bkg_factor=2.0, ref_factor=2.0, bkg='bkg.mask_full', ref='Eu.mask_inside')[source]¶ Filter and flag based on unmixed background and reference signal.
Parameters: - bkg_factor (float) – Filter factor of Standard Deviations away from mean background signal. Defaults to 2.0
- ref_factor (float) – Filter factor of Standard Deviations within mean of reference signal. Defaults to 2.0
- bkg (string) – Background signal column name. Defaults to ‘bkg.mask_full’
- ref (string) – Reference signal column name. Defaults to ‘Eu.mask_inside’
-
get(images, masks, combine_data=None)[source]¶ Extract data from images using masks.
Parameters: - images (Xarray DataArray, mrbles ImageDataFrame) – Images of which to take values from using provided labeled masks. Must be same number of dimensions as masks.
- masks (Xarray DataArray, mrbles ImageDataFrame) – Labeled mask of regions to take values from the provided images. Must be same number of dimensions as images, even if one dimension is only singular. Therefore, use [] around mask selection, even when only using a single channel: [‘inside’].
Examples
>>> per_mrble_data = mrbles.Extract(np.median) >>> per_mrble_data.run(images['100 nM', :, ['Cy5', 'Cy3']], masks['100 nM', :, ['ring']]) >>> per_mrble_data.data
-
-
class
mrbles.pipeline.Find(bead_size, pixel_size=None, border_clear=True, circle_size=None, min_r=None, max_r=None, annulus_width=None, **kwargs)[source]¶ Bases:
mrbles.data.ImageDataFrameFind MRBLEs in brightfield images.
This class provides the method to find MRBLEs and segment regions for each MRBLE in brightfield images, provided by mrbles.Images.
Mask output: mask_full, mask_ring, mask_inside, mask_outside, mask_bkg, mask_check.
Examples
>>> find_mrbles = mrbles.Find(bead_size=18, pixel_size=3.5, border_clear=True, circle_size=350) >>> find_mrbles.settings.parallelize = True >>> find_mrbles.find(assay_images[:, : , 'Brightfield']) Bead diameter AVG: 54.36 Bead diameter SD: 2.00 Bead diameter CV: 3.68% Total number of beads: 2386 >>> find_mrbles {'Set 1': <xarray.DataArray (f: 12, c: 6, y: 1024, x: 1024)> array([[[[0, ..., 0], ..., [0, ..., 0]]]], dtype=uint16) Coordinates: * c (c) <U12 'mask_full' 'mask_ring' 'mask_inside' 'mask_outside' ... Dimensions without coordinates: f, y, x, 'Set 2': ... >>> find_mrbles['Set 2', 3, 'mask_ring'] <xarray.DataArray (y: 860, x: 860)> array([[0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0]], dtype=uint16) Coordinates: c <U12 'mask_ring' Dimensions without coordinates: y, x
Super-Class wrapper for mrbles.core.FindBeadsImaging. Please see this class documentation for more information.
Parameters: - bead_size (int) – Approximate width of beads (circles) in pixels.
- pixel_size (float) – Optional setting for image pixel size. Outputs dimensions using provided conversion value. Adds additional converted to database with affic ‘_conv’. Defaults to None.
- border_clear (boolean) – Beads touching border or ROI will be removed. Defaults to True.
- circle_size (int) – Set circle size for auto find circular ROI.
- min_r (int) – Minimum size of beads. This is set only when using Circle Finding method.
- max_r (int) – Maximum size of beads. This is set only when using Circle Finding method.
- annulus_width (int) – Annulus width size. This is set only when using Circle Finding method.
Variables: - bead_dims (Pandas DataFrame) – Dataframe with individual MRBLE dimensions.
- beads_total (int) – Total number of MRBLEs found.
- beads_per_set (list of int) – Number of MRBLEs per set.
- settings (property) – Property provinding access to settings of mrbles.core.FindBeadsImaging. See property documentation for more information.
-
bead_dims¶ Return MRBLEs dimensions.
-
beads_per_set¶ Return total bead count in set(s).
-
beads_total¶ Return total bead count in set(s).
-
sets¶ Return list of sets.
-
settings¶ Return FindBeadsImaging object for settings purposes.
See FindBeadsImaging documentation for detailed settings.
Examples
>>> find_object = Find(bead_size=18) >>> find_object.settings.area_min = 20 >>> find_object.settings.area_max = 350 >>> find_object.settings.eccen_max = 0.65 >>> find_object.settings.circle_size = 350
-
class
mrbles.pipeline.Images(folders=None, file_patterns=None, data=None, channels=None)[source]¶ Bases:
mrbles.data.ImageDataFrameLoad images into mrbles dataframe.
There are two methods to load images into the mrbles dataframe: Method 1 - Provide dictionaries with folder and filename patterns. Method 2 - Provide a dictionary with numpy arrays.
This class facilitates loading images into the mrbles.data.ImageDataFrame. Please see this class documentation for more information.
For loading OME-TIFF image it uses mrbles.data.ImageSetRead. Please see this class documentation for more information.
>>> assay_folder = '../data' >>> assay_folders = {'Set 1': '../data1', 'Set 2': '../data2'} >>> assay_files = {'Set 1': 'image_set1_(0-9)(0-9).ome.tif', 'Set 2': 'image_set2_(0-9)(0-9).ome.tif'} >>> assay_images = mrbles.Images(assay_folder, assay_files) Found 12 files in Set 1 Found 11 files in Set 2
>>> image_arrays = {'Set 1': numpy_array_1, 'Set 2': numpy_array_2} >>> channel_names = ['Brightfield', 'Cy5', 'l-435', 'l-546', 'l-620'] >>> assay_images = mrbles.Images(data=image_arrays, channels=channel_names)
>>> assay_images {'Set 1': <xarray.DataArray (f: 12, c: 5, y: 1024, x: 1024)> array([[[[169., ..., 166.], ..., [101., ..., 121.]]]]) Coordinates: * c (c) object 'Brightfield', 'Cy5', 'l-435', 'l-546', ... Dimensions without coordinates: f, y, x, 'Set 2': ... >>> assay_images['Set 2', 3, 'Brightfield'] <xarray.DataArray (y: 1024, x: 1024)> array([[188., 163., 182., ..., 188., 174., 170.], ..., [144., 141., 142., ..., 162., 162., 154.]]) Coordinates: c <U11 'Brightfield' Dimensions without coordinates: y, x
Parameters: - folders (str, dict) – String of single folder or dict of multiple folders. The folder(s) provided will searched recursively. Dict keys must match file_patterns dict.
- file_patterns (dict) – Dict of multiple file patterns. Dict keys must match folders keys, if multiple folders.
- data (NumPy array) – Alternative method to loading OME-Tif files. Load a dict of NumPy arrays with dimension order (f, c, y, x): files (f), channels (c), Y-dimension (y), X-dimension (x)
- channels (list of str) – List of channel names. Defaults to None. Channels will be numbers.
Variables: -
flat_field(ff_image, channel, affix='_FF')[source]¶ Flat-Field correction.
Parameters: - ff_image (str, NumPy array) – Flat-field image file or NumPy array.
- channel (str) – Channel to apply flat-field correction.
- affix (str) – Affix for channel name to be appended. Defaults to ‘_FF’
-
rename_channel(old_name, new_name)[source]¶ Rename channel name.
Parameters: - old_name (str) – Original name of channel.
- new_name (str) – New name for old_name channel.
-
static
scan_path(path, pattern='*.tif')[source]¶ Scan folder recursively for files matching the pattern.
Parameters: - path (string) – Folder path as string, e.g. r’C:/folder/file.tif’.
- pattern (string) – File extenstion of general file pattern as search string, e.g. ‘peptides_x_([0-9][0-9])_MMStack_Pos0.ome.tif’ Defaults to ‘*.tif’.
-
class
mrbles.pipeline.Ratio(reference_spectra, background='bkg')[source]¶ Bases:
mrbles.data.ImageDataFrameGenerate spectrally unmix ratio images.
Parameters: - reference_spectra (list, ndarray, References object) – List, array, or References object of reference spectra for linear spectral unmixing.
- background (string) – Background key label. Defaults to ‘bkg’.
-
get(image_sets, reference, combine_data=None)[source]¶ Calculate unmixed and ratio images.
Parameters: - image_set (Xarray DataArray, mblres ImageDataFrame) – These are the images (emission channels) to be unmixed.
- reference (string) – Reference key label, e.g. ‘Eu’, used for ratio images.
- comb_data (Xarray DataArray, mblres ImageDataFrame) – These are the images that are combined with ‘image_set’. Must be same dimensions and type as ‘image_set’.
-
class
mrbles.pipeline.References(folders, files, object_channel, reference_channels, bead_size=16, dark_noise=99)[source]¶ Bases:
mrbles.data.TableDataFrameCreate reference spectra.
There are three methods to load images into the this class: Method 1 - Provide a dictionaries with folders and filenames. Method 2 - Provide a dictionary with numpy arrays. Method 3 - Provide a file with spectra data.
Parameters: - folders (dict) – Dictionary with keywords (e.g. ‘Dy’, ‘bkg’) and folders. Must correspond with files parameter.
- files (dict) – Dictionary with keywords (e.g. ‘Dy’, ‘bkg’) and filenames. Must correspond with folders parameter.
- object_channel (str) – Channel to be used for finding MRBLEs
- reference_channels (list) – List of channel names to be used for generating reference spectra.
- bead_size (int) – Bead diamater set in pixels. Defaults to 16.
- dark_noise (int) – Dark noise of the camera used for the images. Defaults to 99 (median dark noise of Andor Zyla 4.2 PLUS sCMOS).
Variables: -
static
get_spectrum(dark_noise, channels, mask)[source]¶ Get spectrum from image set using mask.
The median of the masked area is extracted, the camera dark noise subtracted, and normalized.
Parameters: - dark_noise (int) – Intrinsic dark noise of camera. Image taken when shutter closed.
- channels (slice, list) – Slice of channels
- mask (NumPy array) – Labeled mask.
mrbles.report module¶
Quality Control Report Classes and Functions¶
This file stores the quality control report classes and functions for the MRBLEs Analysis module.
-
class
mrbles.report.BeadsReport(data, images, masks, assay_channel, codes=None, files=None, sort=True)[source]¶ Bases:
future.types.newobject.newobjectPer-MRBLE images report.
This method generates the selected images per-MRBLE.
This method can take a lot of time, since it will generate images per-MRBLE. It takes about 5 minutes per 1,000 beads, for 12 images each, which makes a total of 11,000 images.
Parameters: - data (Pandas DataFrame) – Contains all the dimension, posotional, and intensity data per-MBRLE.
- images (mrbles.ImageDataFrame, Xarray DataArray) – Contains images.
- masks (Xarray DataArray) – Contains masks.
- assay_channel (str) – Assay channel name, e.g. ‘Cy5_FF’
- codes (int, list of int) – Integer or list of integers with selected codes. Defaults to None.
- files (int, list of int) – Integer or list of integers with selected files. Defaults to None.
- sort (boolean) – Sort by code. Defaults to True.
- Methods
- ——–
- generate() (method)
Variables: - time_sec (float) – Time required per-image generated in seconds. For instance, 300 beads times 12 images is 3600 images. Defaults to 0.0275
- parallelize (boolean) – Wether to use parallelization. Can be slowing down on low-power computers. Defaults to True.
-
class
mrbles.report.ClusterCheck(decode_object, *args, **kwargs)[source]¶ Bases:
mrbles.data.TableDataFrameCluster check reporting.
-
class
mrbles.report.GenerateCodes(colors, s0s, slopes, nsigma)[source]¶ Bases:
future.types.newobject.newobjectGenerate bead code set.
Parameters: - colors (list of str) – List of coding colors in a list of strings.
- s0s (liat of float) – List of standard deviations (SD) at intensity 0 for each encoding color.
- slopes (float) – List of slopes of the SDs versus intensity for each encoding color.
- nsigma (float) – The number of SD to separate coding levels.
Examples
>>> code_set_gen = GenerateCodes(['Dy', 'Sm', 'Tm'], [0.0039, 0.0055, 0.0029], [0.022, 0.016, 0.049], 6.4) >>> code_set_gen.result Dy Sm Tm 0 0.000000 0.000000 0.000000 >>> code_set_gen = GenerateCodes(['Dy', 'Sm'], [0.0039, 0.0055], [0.022, 0.016], 8.4) >>> code_set_gen.generate() Number of codes: 24 >>> code_set_gen.result Dy Sm 0 0.000000 0.000000 1 0.000000 0.106747 2 0.000000 0.246642 ...................... >>> code_set_gen.iterate(28) .................... Number of codes: 26 Number of codes: 26 Number of codes: 28 Final nsigma: 8.09 Iterations : 31
-
axis¶ Return number of axis (colors).
-
colors¶ Return color names.
-
generate(nsigma=None, depends=None)[source]¶ Generate codes with default nsigma or given nsigma.
Parameters: - nsigma (float, optional) – The number of SD to separate coding levels. Defaults to initial nsigma.
- depends (any, experimental, optional) – Used for Tm (3rd in array) dependence on Dy (1st array).
-
static
get_levels(std0, slope, nsigma)[source]¶ Predict the number of levels of a coding color.
The coding levels are based on s0, the standard deviation (SD) at intensity 0, and the slope between intensity and SD.
Parameters: - std0 (float) – The SD at intensity 0.
- slope (float) – The slope of the SD versus intensity.
- nsigma (float) – The number of SD to separate levels.
Returns: levels – Returns list of codes values for a given coding color.
Return type: list of float
-
iterate(num, nsimga_start=None, nsigma_step=0.01, max_iter=1000)[source]¶ Iterate nsigma until number of codes are found.
Does not work with dependence, such as Tm dependence on Dy.
Parameters: - num (int) – Number of required codes.
- nsigma_start (float, optional) – Start value of nsigma. Defaults to initial nsigma.
- nsigma_step (float, optional) – Iterarion step. Defaults to 0.01
- max_iter (int, optional) – Maximum iteration steps. Defaults to 1000.
-
levels¶ Return number of levels.
-
static
recursive_looper(iterators, pos=0)[source]¶ Recursive looper.
Implements the same functionality as nested for loops, but is more dynamic. Iterators can either be a list of methods which return iterables, a list of iterables, or a combination of both.
-
result¶ Return resulting ratios.
-
class
mrbles.report.PeptideScramble(seq)[source]¶ Bases:
future.types.newobject.newobjectRandomizes amino acid sequence
Parameters: seq (string) – Inset amino acid sequence as a string. Returns: seq – Returns string of shuffled amino acid sequence. Return type: string
-
class
mrbles.report.QCReport(data)[source]¶ Bases:
future.types.newobject.newobjectMRBLE library Quality Control report.
Parameters: data (Pandas DataFrame) – Per beads data.
Module contents¶
MRBLEs Analysis Package¶
This package provides the tools to: (1) find the MRBLEs in a monochrome bright-field microscopy image; (2) decode the MRBLEs beads by spectral unmxing, using reference spectra, and then spectrally decode the found beads using Iterative Closest Point Matching and Gaussian Mixture Modeling; (3) extract, statistical values of interest in additional fluorescence channels using the morphology of the MRBLEs, their locations, and respective code; (4) analyze affinity information based on titrations of MRBLEs assays.