Python API¶
The pure-compute layer of napari-colocalization is independent of napari
and Qt — you can import the metric, masking, and analysis functions from
a script or notebook and use them on plain ndarrays.
The function reference below is generated directly from the source
docstrings. The narrative and examples on this page are written by hand;
the ::: blocks are filled in automatically by mkdocstrings at build
time.
Module layout¶
napari_colocalization
├── _metrics.py pearson, spearman, li_icq, manders, costes_threshold
├── _masking.py shapes_to_label_mask, labels_to_label_mask, iter_regions
├── _analysis.py analyse_pairwise, analyse_all_to_all, COLUMNS
├── _sample_data.py make_sample_data, make_sample_data_3d,
│ make_sample_data_cbs006rbm
└── _widget.py ColocalizationWidget (Qt-only)
The leading underscore is a convention from the napari plugin template; the symbols below are stable and intended to be imported.
Metrics — napari_colocalization._metrics¶
Pure-numpy colocalization metrics.
No napari / qtpy imports here — every function in this module operates on ndarrays so it can be tested headlessly and reused from scripts. PCC and Manders delegate to scikit-image; SRCC uses scipy.stats; Costes auto-threshold is implemented locally because scikit-image does not provide it.
pearson ¶
Pearson correlation coefficient and two-tailed p-value.
Wraps :func:skimage.measure.pearson_corr_coeff. Returns
(nan, nan) for inputs with fewer than two samples or zero
variance in either channel — both edge cases for which PCC is
mathematically undefined.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
b
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
mask
|
Boolean array with the same shape as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
pcc
|
The Pearson correlation coefficient in
TYPE:
|
p_value
|
Two-tailed p-value for the null hypothesis that the
coefficient is zero.
TYPE:
|
Examples:
spearman ¶
Spearman rank correlation coefficient and p-value.
Uses :func:scipy.stats.spearmanr on the masked, flattened
intensities. Robust to monotonic non-linearity and outliers.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
b
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
mask
|
Boolean array with the same shape as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
rho
|
Spearman's rank correlation coefficient in
TYPE:
|
p_value
|
Two-tailed p-value for the rank correlation, or
TYPE:
|
Examples:
li_icq ¶
Li's Intensity Correlation Quotient (ICQ).
For each pixel i, form the covariance contribution
P_i = (a_i - mean(a)) * (b_i - mean(b)). The ICQ is the
fraction of pixels for which this product is positive,
re-centred to lie on [-0.5, 0.5]:
.. math:: \mathrm{ICQ} = \frac{|{i : P_i > 0}|}{N} - 0.5
Following Li et al. (2004), values close to +0.5 indicate
dependent (co-varying) staining, 0 indicates random
staining, and -0.5 indicates segregated (anti-varying)
staining.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
b
|
Same-shape intensity arrays of any dimensionality.
TYPE:
|
mask
|
Boolean array with the same shape as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
icq
|
Value in
TYPE:
|
Notes
Pixels with P_i == 0 (typically because one channel
equals its mean exactly at that pixel) are excluded from the
fraction's numerator and denominator, mirroring the
convention adopted by ImageJ's Coloc 2 plugin.
References
Li, Q. et al. (2004). A Syntaxin 1, Galpha(o), and N-type Calcium Channel Complex at a Presynaptic Nerve Terminal: Analysis by Quantitative Immunocolocalization. J. Neurosci. 24(16), 4070-4081.
Examples:
manders ¶
Manders' colocalization coefficients M1 and M2.
M1 is the fraction of the channel-A intensity that lies in
pixels where channel B is above threshold_b. M2 is the
symmetric counterpart for channel B above threshold_a.
Asymmetry between the two is meaningful — it reflects the
difference in how much of each channel co-occurs with the
other.
Wraps :func:skimage.measure.manders_coloc_coeff, which
expects a binary mask for the second image; we threshold
internally and then call it twice.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape, non-negative intensity arrays.
TYPE:
|
b
|
Same-shape, non-negative intensity arrays.
TYPE:
|
threshold_a
|
Per-channel thresholds. Use :func:
TYPE:
|
threshold_b
|
Per-channel thresholds. Use :func:
TYPE:
|
mask
|
Boolean array selecting the analysed region.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
m1, m2 : float
|
Each in |
Examples:
costes_threshold ¶
Costes' iterative auto-threshold for Manders' M1 / M2.
Implements the algorithm of Costes et al. (2004):
- Fit a least-squares regression line
b = m * a + cover the analysed region. - Walk a candidate threshold
T_adownward frommax(a). At each step, setT_b = m * T_a + cso the threshold pair lies on the regression line. - The "below-threshold" subset is every pixel with
a <= T_aorb <= T_b. Compute its Pearson correlation. Stop at the firstT_awhere that PCC drops to zero or below — at that point the below-threshold pixels are no longer correlated, i.e. background.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape intensity arrays.
TYPE:
|
b
|
Same-shape intensity arrays.
TYPE:
|
mask
|
Restrict the regression and search to this region.
TYPE:
|
n_steps
|
Number of candidate thresholds along
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
threshold_a, threshold_b : float
|
Per-channel thresholds suitable to feed into
:func: |
Notes
The Costes randomisation significance test (which scrambles pixel blocks to produce a p-value for PCC) is not implemented.
References
Costes, S.V. et al. (2004). Automatic and quantitative measurement of protein-protein colocalization in live cells. Biophys. J. 86(6), 3993-4003.
Masking — napari_colocalization._masking¶
Region-of-interest helpers.
These functions convert a napari Shapes or Labels layer into an integer label mask (0 = background, 1..N = regions) and iterate over the non-zero regions. The helpers duck-type the layer interface — they do not import napari — so they can be tested with simple stand-in objects.
shapes_to_label_mask ¶
Rasterise a napari Shapes layer to an integer label mask.
Uses Shapes.to_labels(labels_shape=image_shape). The
resulting mask has shape image_shape, with 0 outside any
shape and 1..N inside each shape (where shape i of
the layer maps to label i + 1).
| PARAMETER | DESCRIPTION |
|---|---|
shapes_layer
|
Any object that exposes
TYPE:
|
image_shape
|
The desired output shape, typically the spatial shape of the image being analysed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
mask
|
Integer label image of shape
TYPE:
|
labels_to_label_mask ¶
Validate and return integer data from a napari Labels layer.
| PARAMETER | DESCRIPTION |
|---|---|
labels_layer
|
Any object that exposes a
TYPE:
|
image_shape
|
The expected shape;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
mask
|
The label data, dtype-cast to
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the layer's data shape does not match |
iter_regions ¶
Yield (label_id, bool_mask) for each non-zero region.
| PARAMETER | DESCRIPTION |
|---|---|
label_mask
|
Integer label image.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
label_id
|
The integer label value (1, 2, ...). When
TYPE::
|
bool_mask
|
Boolean mask of the same shape as
TYPE::
|
Examples:
Analysis — napari_colocalization._analysis¶
COLUMNS is the canonical column order shared by the table, the CSV
export, and the row dicts:
('region', 'channel_a', 'channel_b', 'n_pixels',
'pcc', 'pcc_pvalue', 'srcc', 'srcc_pvalue',
'icq',
'm1', 'm2', 'threshold_a', 'threshold_b')
High-level orchestrators that produce a result row per region.
These accept ndarrays plus a label mask, walk every non-zero region, compute the requested metrics, and return a list of dicts suitable for direct insertion into a table or a CSV.
analyse_pairwise ¶
analyse_pairwise(a, b, *, label_mask=None, metrics=ALL_METRICS, threshold_method='costes', threshold_a=None, threshold_b=None, channel_a='A', channel_b='B')
Compute selected metrics for each region of two grayscale arrays.
Walks every non-zero region of label_mask (or analyses the
whole image when label_mask is None) and computes the
requested metrics within each region. Missing metrics are
written as NaN so the output schema is constant.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Same-shape intensity arrays (2D or 3D).
TYPE:
|
b
|
Same-shape intensity arrays (2D or 3D).
TYPE:
|
label_mask
|
Integer label image (0 = background, 1..N = regions).
TYPE:
|
metrics
|
Which metrics to compute. Defaults to all four.
TYPE:
|
threshold_method
|
Only used when
TYPE:
|
threshold_a
|
Required when
TYPE:
|
threshold_b
|
Required when
TYPE:
|
channel_a
|
Display names for the two channels — written into the result rows so they round-trip into the table and CSV.
TYPE:
|
channel_b
|
Display names for the two channels — written into the result rows so they round-trip into the table and CSV.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
rows
|
One row per region. Each row has the keys listed in
:data:
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
analyse_all_to_all ¶
analyse_all_to_all(image, channel_axis, *, label_mask=None, metrics=ALL_METRICS, threshold_method='costes', threshold_a=None, threshold_b=None, channel_names=None)
Compute metrics for every channel pair (i, j), i < j.
Iterates over each unordered pair of channels along
channel_axis and dispatches to :func:analyse_pairwise.
For N channels this produces N*(N-1)/2 × R rows,
where R is the number of non-zero regions in label_mask
(or 1 for the whole image).
| PARAMETER | DESCRIPTION |
|---|---|
image
|
N-dimensional array with one channel axis. The remaining axes are spatial (the plugin supports up to 3 spatial axes, i.e. 4D total).
TYPE:
|
channel_axis
|
Axis index along which channels are enumerated.
TYPE:
|
label_mask
|
Integer label image whose shape matches
TYPE:
|
metrics
|
Forwarded to :func:
TYPE:
|
threshold_method
|
Forwarded to :func:
TYPE:
|
threshold_a
|
Forwarded to :func:
TYPE:
|
threshold_b
|
Forwarded to :func:
TYPE:
|
channel_names
|
One name per channel along
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
rows
|
Concatenation of the per-pair results from
:func:
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Sample data — napari_colocalization._sample_data¶
make_sample_data_cbs006rbm downloads the CBS006RBM benchmark image
from the Colocalization Benchmark Source
on first use and caches it under ~/.cache/napari-colocalization/.
Synthetic two-channel sample data for colocalization.
Synthetic samples (2D, 3D): gaussian blobs with channel B copying 60 % of channel A's blobs plus independent blobs and noise, giving PCC ~ 0.7 and Manders M1/M2 ~ 0.6.
CBS006RBM: red and blue channels with ~50 % colocalization, from the Colocalization Benchmark Source. The TIFF is downloaded once and cached in ~/.cache/napari-colocalization/.
make_sample_data_3d ¶
3D sample: 32x128x128 (Z, Y, X) volumes of gaussian blobs.
make_sample_data_cbs006rbm ¶
2D sample from the Colocalization Benchmark Source (CBS006RBM).
Red and blue channels with ~50 % colocalization. Downloaded once and cached under ~/.cache/napari-colocalization/.
Source: https://colocalization-benchmark.com/
Putting it together: scripted analysis¶
import numpy as np
import pandas as pd
from napari_colocalization._analysis import analyse_pairwise, COLUMNS
a = np.load('channel_a.npy')
b = np.load('channel_b.npy')
mask = np.load('cell_labels.npy') # 0 = bg, 1..N = cells
rows = analyse_pairwise(
a, b,
label_mask=mask,
metrics=('pcc', 'srcc', 'mcc'),
threshold_method='costes',
channel_a='dna', channel_b='tubulin',
)
df = pd.DataFrame(rows, columns=COLUMNS)
df.to_csv('colocalization_per_cell.csv', index=False)
print(df.describe())
Stability¶
- The function signatures, return shapes and
COLUMNStuple above are intended to be stable across point releases. - Internal helpers prefixed with
_(private functions inside each module) may change without notice. ColocalizationWidget(_widget.py) is the GUI surface and not part of the scripting API; for scripts, driveanalyse_*directly.