API Reference

BaSiC

Main BaSiC class.

enum basicpy.basicpy.FittingMode(value)

Fit method enum.

Member Type:

str

Valid values are as follows:

ladmap: str = <FittingMode.ladmap: 'ladmap'>
approximate: str = <FittingMode.approximate: 'approximate'>
enum basicpy.basicpy.ResizeMode(value)

Resize method enum.

Member Type:

str

Valid values are as follows:

jax: str = <ResizeMode.jax: 'jax'>
skimage: str = <ResizeMode.skimage: 'skimage'>
skimage_dask: str = <ResizeMode.skimage_dask: 'skimage_dask'>
enum basicpy.basicpy.TimelapseTransformMode(value)

Timelapse transformation enum.

Member Type:

str

Valid values are as follows:

additive: str = <TimelapseTransformMode.additive: 'additive'>
multiplicative: str = <TimelapseTransformMode.multiplicative: 'multiplicative'>
pydantic model basicpy.basicpy.BaSiC

A class for fitting and applying BaSiC illumination correction profiles.

Show JSON schema
{
   "title": "BaSiC",
   "description": "A class for fitting and applying BaSiC illumination correction profiles.",
   "type": "object",
   "properties": {
      "baseline": {
         "title": "Baseline"
      },
      "darkfield": {
         "title": "Darkfield"
      },
      "fitting_mode": {
         "description": "Must be one of ['ladmap', 'approximate']",
         "default": "ladmap",
         "allOf": [
            {
               "$ref": "#/definitions/FittingMode"
            }
         ]
      },
      "epsilon": {
         "title": "Epsilon",
         "description": "Weight regularization term.",
         "default": 0.1,
         "type": "number"
      },
      "flatfield": {
         "title": "Flatfield"
      },
      "get_darkfield": {
         "title": "Get Darkfield",
         "description": "When True, will estimate the darkfield shading component.",
         "default": false,
         "type": "boolean"
      },
      "smoothness_flatfield": {
         "title": "Smoothness Flatfield",
         "description": "Weight of the flatfield term in the Lagrangian.",
         "default": 1.0,
         "type": "number"
      },
      "smoothness_darkfield": {
         "title": "Smoothness Darkfield",
         "description": "Weight of the darkfield term in the Lagrangian.",
         "default": 1.0,
         "type": "number"
      },
      "sparse_cost_darkfield": {
         "title": "Sparse Cost Darkfield",
         "description": "Weight of the darkfield sparse term in the Lagrangian.",
         "default": 0.01,
         "type": "number"
      },
      "autosegment": {
         "title": "Autosegment",
         "description": "When not False, automatically segment the image before fitting.When True, `threshold_otsu` from `scikit-image` is used and the brighter pixels are taken.When a callable is given, it is used as the segmentation function.",
         "default": false,
         "type": "boolean"
      },
      "autosegment_margin": {
         "title": "Autosegment Margin",
         "description": "Margin of the segmentation mask to the thresholded region.",
         "default": 10,
         "type": "integer"
      },
      "max_iterations": {
         "title": "Max Iterations",
         "description": "Maximum number of iterations for single optimization.",
         "default": 500,
         "type": "integer"
      },
      "max_reweight_iterations": {
         "title": "Max Reweight Iterations",
         "description": "Maximum number of reweighting iterations.",
         "default": 10,
         "type": "integer"
      },
      "max_reweight_iterations_baseline": {
         "title": "Max Reweight Iterations Baseline",
         "description": "Maximum number of reweighting iterations for baseline.",
         "default": 5,
         "type": "integer"
      },
      "max_workers": {
         "title": "Max Workers",
         "description": "Maximum number of threads used for processing.",
         "default": 2,
         "type": "integer"
      },
      "rho": {
         "title": "Rho",
         "description": "Parameter rho for mu update.",
         "default": 1.5,
         "type": "number"
      },
      "mu_coef": {
         "title": "Mu Coef",
         "description": "Coefficient for initial mu value.",
         "default": 12.5,
         "type": "number"
      },
      "max_mu_coef": {
         "title": "Max Mu Coef",
         "description": "Maximum allowed value of mu, divided by the initial value.",
         "default": 10000000.0,
         "type": "number"
      },
      "optimization_tol": {
         "title": "Optimization Tol",
         "description": "Optimization tolerance.",
         "default": 0.001,
         "type": "number"
      },
      "optimization_tol_diff": {
         "title": "Optimization Tol Diff",
         "description": "Optimization tolerance for update diff.",
         "default": 0.01,
         "type": "number"
      },
      "resize_mode": {
         "description": "Resize mode to use when downsampling images. Must be one of 'jax', 'skimage', and 'skimage_dask'",
         "default": "jax",
         "allOf": [
            {
               "$ref": "#/definitions/ResizeMode"
            }
         ]
      },
      "resize_params": {
         "title": "Resize Params",
         "description": "Parameters for the resize function when downsampling images.",
         "default": {},
         "type": "object"
      },
      "reweighting_tol": {
         "title": "Reweighting Tol",
         "description": "Reweighting tolerance in mean absolute difference of images.",
         "default": 0.01,
         "type": "number"
      },
      "sort_intensity": {
         "title": "Sort Intensity",
         "description": "Whether or not to sort the intensities of the image.",
         "default": false,
         "type": "boolean"
      },
      "working_size": {
         "title": "Working Size",
         "description": "Size for running computations. None means no rescaling.",
         "default": 128,
         "anyOf": [
            {
               "type": "integer"
            },
            {
               "type": "array",
               "items": {
                  "type": "integer"
               }
            }
         ]
      }
   },
   "additionalProperties": false,
   "definitions": {
      "FittingMode": {
         "title": "FittingMode",
         "description": "Fit method enum.",
         "enum": [
            "ladmap",
            "approximate"
         ],
         "type": "string"
      },
      "ResizeMode": {
         "title": "ResizeMode",
         "description": "Resize method enum.",
         "enum": [
            "jax",
            "skimage",
            "skimage_dask"
         ],
         "type": "string"
      }
   }
}

Config:
  • arbitrary_types_allowed: bool = True

  • extra: str = forbid

Fields:
field autosegment: bool = False

When not False, automatically segment the image before fitting.When True, threshold_otsu from scikit-image is used and the brighter pixels are taken.When a callable is given, it is used as the segmentation function.

Validated by:
field autosegment_margin: int = 10

Margin of the segmentation mask to the thresholded region.

Validated by:
field baseline: Optional[ndarray] = None

Holds the baseline for the shading model.

Validated by:
field darkfield: ndarray [Optional]

Holds the darkfield component for the shading model.

Validated by:
field epsilon: float = 0.1

Weight regularization term.

Validated by:
field fitting_mode: FittingMode = FittingMode.ladmap

Must be one of [‘ladmap’, ‘approximate’]

Validated by:
field flatfield: ndarray [Optional]

Holds the flatfield component for the shading model.

Validated by:
field get_darkfield: bool = False

When True, will estimate the darkfield shading component.

Validated by:
field max_iterations: int = 500

Maximum number of iterations for single optimization.

Validated by:
field max_mu_coef: float = 10000000.0

Maximum allowed value of mu, divided by the initial value.

Validated by:
field max_reweight_iterations: int = 10

Maximum number of reweighting iterations.

Validated by:
field max_reweight_iterations_baseline: int = 5

Maximum number of reweighting iterations for baseline.

Validated by:
field max_workers: int = 2

Maximum number of threads used for processing.

Validated by:
field mu_coef: float = 12.5

Coefficient for initial mu value.

Validated by:
field optimization_tol: float = 0.001

Optimization tolerance.

Validated by:
field optimization_tol_diff: float = 0.01

Optimization tolerance for update diff.

Validated by:
field resize_mode: ResizeMode = ResizeMode.jax

Resize mode to use when downsampling images. Must be one of ‘jax’, ‘skimage’, and ‘skimage_dask’

Validated by:
field resize_params: Dict = {}

Parameters for the resize function when downsampling images.

Validated by:
field reweighting_tol: float = 0.01

Reweighting tolerance in mean absolute difference of images.

Validated by:
field rho: float = 1.5

Parameter rho for mu update.

Validated by:
field smoothness_darkfield: float = 1.0

Weight of the darkfield term in the Lagrangian.

Validated by:
field smoothness_flatfield: float = 1.0

Weight of the flatfield term in the Lagrangian.

Validated by:
field sort_intensity: bool = False

Whether or not to sort the intensities of the image.

Validated by:
field sparse_cost_darkfield: float = 0.01

Weight of the darkfield sparse term in the Lagrangian.

Validated by:
field working_size: Union[int, List[int], None] = 128

Size for running computations. None means no rescaling.

Validated by:
autotune(images, fitting_weight=None, skip_shape_warning=False, *, optmizer=None, n_iter=100, search_space=None, init_params=None, timelapse=False, histogram_qmin=0.01, histogram_qmax=0.99, vmin_factor=0.6, vrange_factor=1.5, histogram_bins=1000, histogram_use_fitting_weight=True, fourier_l0_norm_image_threshold=0.1, fourier_l0_norm_fourier_radius=10, fourier_l0_norm_threshold=0.0, fourier_l0_norm_cost_coef=30, early_stop=True, early_stop_n_iter_no_change=15, early_stop_torelance=1e-06, random_state=None)

Automatically tune the parameters of the model.

Return type:

None

Parameters:
  • images – input images to fit and correct. See fit.

  • fitting_weight – Relative fitting weight for each pixel. See fit.

  • skip_shape_warning – if True, warning for last dimension less than 10 is suppressed.

  • optimizer – optimizer to use. Defaults to hyperactive.optimizers.HillClimbingOptimizer.

  • n_iter – number of iterations for the optimizer. Defaults to 100.

  • search_space – search space for the optimizer. Defaults to a reasonable range for each parameter.

  • init_params – initial parameters for the optimizer. Defaults to a reasonable initial value for each parameter.

  • timelapse – if True, corrects the timelapse/photobleaching offsets.

  • histogram_qmin – the minimum quantile to use for the histogram. Defaults to 0.01.

  • histogram_qmax – the maximum quantile to use for the histogram. Defaults to 0.99.

  • histogram_bins – the number of bins to use for the histogram. Defaults to 100.

  • hisogram_use_fitting_weight – if True, uses the weight for the histogram. Defaults to True.

  • fourier_l0_norm_image_threshold – float The threshold for image values for the fourier L0 norm calculation.

  • fourier_l0_norm_fourier_radius – float The Fourier radius for the fourier L0 norm calculation.

  • fourier_l0_norm_threshold – float The maximum preferred value for the fourier L0 norm.

  • fourier_l0_norm_cost_coef – float The cost coefficient for the fourier L0 norm.

  • early_stop – if True, stops the optimization when the change in entropy is less than early_stop_torelance. Defaults to True.

  • early_stop_n_iter_no_change – the number of iterations for early stopping. Defaults to 10.

  • early_stop_torelance – the absolute value torelance for early stopping.

  • random_state – random state for the optimizer.

validator debug_log_values  »  all fields

Use a validator to echo input values.

fit(images, fitting_weight=None, skip_shape_warning=False)

Generate illumination correction profiles from images.

Return type:

None

Parameters:
  • images – Input images to fit shading model. Must be 3-dimensional or 4-dimensional array with dimension of (T,Y,X) or (T,Z,Y,X). T can be either of time or mosaic position. Multichannel images should be independently corrected for each channel.

  • fitting_weight – Relative fitting weight for each pixel. Higher value means more contribution to fitting. Must has the same shape as images.

  • skip_shape_warning – if True, warning for last dimension less than 10 is suppressed.

Example

>>> from basicpy import BaSiC
>>> from basicpy import datasets as bdata
>>> images = bdata.wsi_brain()
>>> basic = BaSiC()  # use default settings
>>> basic.fit(images)
fit_transform(images, fitting_weight=None, skip_shape_warning=False, timelapse=False)

Fit and transform on data.

Return type:

Union[Tuple[ndarray, ndarray], ndarray]

Parameters:

images – input images to fit and correct. See fit.

Returns:

corrected images

Example

>>> corrected = basic.fit_transform(images)
classmethod load_model(model_dir)

Create a new instance from a model folder.

Return type:

BaSiC

save_model(model_dir, overwrite=False)

Save current model to folder.

Return type:

None

Parameters:

model_dir – path to model directory

Raises:

FileExistsError – if model directory already exists

transform(images, timelapse=False, frames=None)

Apply profile to images.

Return type:

Union[Tuple[ndarray, ndarray], ndarray]

Parameters:
  • images – input images to correct. See fit.

  • timelapse – If True, corrects the timelapse/photobleaching offsets, assuming that the residual is the product of flatfield and the object fluorescence. Also accepts “multiplicative” (the same as True) or “additive” (residual is the object fluorescence).

  • frames – Frames to use for transformation. Defaults to None (all frames).

Returns:

corrected images

Example

>>> basic.fit(images)
>>> corrected = basic.transform(images)
property reweight_score

The BaSiC fit final reweighting score.

property score

The BaSiC fit final score.

property settings: Dict

Current settings.

Returns:

current settings

Tools

Utilities to support BaSiC.