Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6a44657
Take indices into account when applying piecewise shifts
ethanbb Oct 27, 2025
0b22845
Replace unnecessary ternary with 'or'
ethanbb Jan 9, 2026
4f3cd01
VERSION to 1.13.2 after release
pgunn Jan 30, 2026
6fc2d42
For now, switch primary maintainer email to my personal; may change a…
pgunn Jan 30, 2026
683650d
README: tighten language and help guidance
pgunn Jan 30, 2026
d08d89f
Python 3.13 and later don't include setuptools by default; adding it …
pgunn Jan 30, 2026
56d629a
MRCNN and volpy fixes
Feb 1, 2026
186f733
Merge pull request #1563 from manuelpaeza/cai-pytorch-4
pgunn Feb 1, 2026
9326f19
Merge branch 'dev' of https://github.com/flatironinstitute/CaImAn int…
ethanbb Feb 2, 2026
aed6763
Fix not accounting for Nones in slice
ethanbb Feb 2, 2026
fa07d98
volpy:spikepursuit: Fix a typo
pgunn Feb 11, 2026
2be6820
Use linear interpolation where appropriate for interpolate_shifts
ethanbb Feb 16, 2026
fdb0ca7
Merge pull request #1538 from proektlab/apply-pw-shifts-indices
pgunn Feb 17, 2026
0fe7a12
Exclude scikit-image 0.26.0 due to remove_small_* regression
ethanbb Feb 19, 2026
a0be6a7
Update environment-minimal.yml and pyproject.toml
ethanbb Feb 19, 2026
a874c29
Merge pull request #1571 from proektlab/skimage-remove_small-regression
pgunn Feb 19, 2026
6044864
Use cumulative energy method that keeps ties as ties for consistency
ethanbb Feb 19, 2026
60faeba
Change np.array(..., copy=None) to np.asarray(...) to make compatible…
ethanbb Feb 8, 2026
58840b3
Convert types where needed to account for new promotion rules in numpy 2
ethanbb Feb 18, 2026
2da11e4
Change imports to grandparent package (cnmf)
ethanbb Feb 19, 2026
f81a791
Fix apparent typo in plot_contours, making c/color/line_color args work
ethanbb Feb 20, 2026
2bd05df
Factor out get_slice_coords for easier testing
ethanbb Feb 20, 2026
4d17e94
Merge pull request #1572 from proektlab/numpy-1-and-2
pgunn Apr 16, 2026
fd9ff6c
Merge pull request #1573 from proektlab/cumen-pixel-sorting
pgunn Jun 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,10 @@ Caiman also provides commandline demos, similar to the notebooks, demonstrating
# How to get help
- [Online documentation](https://caiman.readthedocs.io/en/latest/) contains a lot of general information about Caiman, the parameters, how to interpret its outputs, and more.
- [GitHub Discussions](https://github.com/flatironinstitute/Caiman/discussions) is our preferred venue for users to ask for help.
- The [Gitter forum](https://app.gitter.im/#/room/#agiovann_Constrained_NMF:gitter.im) is our old forum: we sometimes will ask people to join us there when something can best be solved in real time (e.g., installation problems).
- If you have found a bug, we recommend searching the [issues at github](https://github.com/flatironinstitute/Caiman/issues) and opening a new issue if you can't find the solution there.
- If there is a feature you would like to see implemented, feel free to come chat at the above forums or open an issue at Github.
- If you have found a bug or have a feature request, search the [issues at github](https://github.com/flatironinstitute/Caiman/issues) and open a new issue if you can't find a solution there.

# How to contribute
Caiman is an open-source project and improves because of contributions from users all over the world. If there is something about Caiman that you would like to work on, then please reach out. We are always looking for more contributors, so please come read the [contributors page](./CONTRIBUTING.md) for more details about how.
Caiman is an open-source project and improves because of contributions from users all over the world. If there is something about Caiman that you would like to work on, reach out. The [contributors page](./CONTRIBUTING.md) has details on how contribution works.

# Videos
There are multiple online videos by Andrea Giovannucci from past Caiman workshops/events that are an excellent start for newcomers.
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.13.1
1.13.2
34 changes: 22 additions & 12 deletions caiman/base/rois.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import tempfile
import time
from typing import Any, Optional
import warnings
import zipfile

from caiman.motion_correction import tile_and_correct, get_patch_centers, interpolate_shifts
Expand Down Expand Up @@ -57,7 +58,10 @@ def com(A, d1: int, d2: int, d3: Optional[int] = None, order: str = 'F') -> np.n
coor = np.stack([c.ravel(order=order) for c in coors])

# take weighted sum of pixel positions along each coordinate
cm = (coor @ A / A.sum(axis=0)).T
with warnings.catch_warnings():
# ignore 0 / 0 (should give nan)
warnings.filterwarnings('ignore', category=RuntimeWarning, message='invalid value encountered in divide')
cm = (coor @ A / A.sum(axis=0)).T
return np.array(cm)


Expand Down Expand Up @@ -687,17 +691,23 @@ def extract_active_components(assignments, indices, only=True):
return components


def norm_nrg(a_):

a = a_.copy()
dims = a.shape
a = a.reshape(-1, order='F')
indx = np.argsort(a, axis=None)[::-1]
cumEn = np.cumsum(a.flatten()[indx]**2)
cumEn /= cumEn[-1]
a = np.zeros(np.prod(dims))
a[indx] = cumEn
return a.reshape(dims, order='F')
def norm_nrg(a: np.ndarray) -> np.ndarray:
"""
Construct an array of the same shape as a containing energy
(squared values) accumulated from highest to lowest-valued pixel,
normalized so the maximum value is 1. This version maintains ties
between pixel values, such that in each set of tied pixels, each pixel
in the set gets the total energy from all pixels in that set added to its
cumulative energy.
"""
if a.size == 0:
return a.copy()

vals_asc, inds_inv, counts = np.unique(a, return_inverse=True, return_counts=True)
energy = vals_asc ** 2 * counts # each energy value is multiplied by its frequency to get the same total
cumEn = np.cumsum(energy[::-1])[::-1] # accumulate from high to low
cumEn /= cumEn[0]
return np.reshape(cumEn[inds_inv], a.shape)


def distance_masks(M_s:list, cm_s: list[list], max_dist: float, enclosed_thr: Optional[float] = None) -> list:
Expand Down
66 changes: 40 additions & 26 deletions caiman/motion_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,24 +459,38 @@ def apply_shifts_movie(self, fname, rigid_shifts: Optional[bool] = None, save_me
sh[0], sh[1]), 0, is_freq=False, border_nan=self.border_nan) for img, sh in zip(
Y, self.shifts_rig)]
else:
# take potential upsampling into account when recreating patch grid
dims = Y.shape[1:]
patch_centers = get_patch_centers(dims, overlaps=self.overlaps, strides=self.strides,
shifts_opencv=self.shifts_opencv, upsample_factor_grid=self.upsample_factor_grid)
# take indices and potential upsampling into account when recreating patch grid
dims = Y[0][self.indices].shape
patch_centers_orig = get_patch_centers(
dims, overlaps=self.overlaps, strides=self.strides,
shifts_opencv=self.shifts_opencv, upsample_factor_grid=self.upsample_factor_grid)

# if only a portion of the original image was used, offset/multiply patch centers to now apply to the whole movie
# compute one dimension at a time.
patch_centers = tuple([] for _ in patch_centers_orig)
for dim_inds, dim_centers_orig, dim_centers in zip(self.indices, patch_centers_orig, patch_centers):
start = dim_inds.start if dim_inds.start is not None else 0
step = dim_inds.step if dim_inds.step is not None else 1
dim_centers.extend([start + step * center for center in dim_centers_orig])

# force shifts_interpolate if there was any cropping - easier than making a special-case path that
# resizes the shifts and extrapolates to the border but doesn't fully take patch centers into account
shifts_interpolate = self.shifts_interpolate or any(dim_inds != slice(None) for dim_inds in self.indices)

if self.is3D:
# x_shifts_els and y_shifts_els are switched intentionally
m_reg = [
apply_pw_shifts_remap_3d(img, shifts_y=-x_shifts, shifts_x=-y_shifts, shifts_z=-z_shifts,
patch_centers=patch_centers, border_nan=self.border_nan,
shifts_interpolate=self.shifts_interpolate)
shifts_interpolate=shifts_interpolate)
for img, x_shifts, y_shifts, z_shifts in zip(Y, self.x_shifts_els, self.y_shifts_els, self.z_shifts_els)
]

else:
# x_shifts_els and y_shifts_els are switched intentionally
m_reg = [
apply_pw_shifts_remap_2d(img, shifts_y=-x_shifts, shifts_x=-y_shifts, patch_centers=patch_centers,
border_nan=self.border_nan, shifts_interpolate=self.shifts_interpolate)
border_nan=self.border_nan, shifts_interpolate=shifts_interpolate)
for img, x_shifts, y_shifts in zip(Y, self.x_shifts_els, self.y_shifts_els)
]

Expand Down Expand Up @@ -1359,18 +1373,16 @@ def register_translation_3d(src_image, target_image, upsample_factor = 1,
target_freq = target_image
# real data needs to be fft'd.
elif space.lower() == 'real':
src_image_cpx = np.array(
src_image, dtype=np.complex64, copy=None)
target_image_cpx = np.array(
target_image, dtype=np.complex64, copy=None)
src_image_cpx = np.asarray(src_image, dtype=np.complex128) # numpy 1.x always treats FFT input as complex128
target_image_cpx = np.asarray(target_image, dtype=np.complex128)
src_freq = np.fft.fftn(src_image_cpx)
target_freq = np.fft.fftn(target_image_cpx)
else:
raise ValueError('Error: register_translation_3d only knows the "real" and "fourier" values for the ``space`` argument.')

shape = src_freq.shape
image_product = src_freq * target_freq.conj()
cross_correlation = np.fft.ifftn(image_product)
cross_correlation = np.fft.ifftn(image_product.astype(np.complex128, copy=False))
new_cross_corr = np.abs(cross_correlation)

CCmax = cross_correlation.max()
Expand Down Expand Up @@ -1553,12 +1565,11 @@ def register_translation(src_image, target_image, upsample_factor=1,
src_freq_1 = cv2.dft(
src_image, flags=cv2.DFT_COMPLEX_OUTPUT + cv2.DFT_SCALE)
src_freq = src_freq_1[:, :, 0] + 1j * src_freq_1[:, :, 1]
src_freq = np.array(src_freq, dtype=np.complex128, copy=None)
src_freq = np.asarray(src_freq, dtype=np.complex128)
target_freq_1 = cv2.dft(
target_image, flags=cv2.DFT_COMPLEX_OUTPUT + cv2.DFT_SCALE)
target_freq = target_freq_1[:, :, 0] + 1j * target_freq_1[:, :, 1]
target_freq = np.array(
target_freq, dtype=np.complex128, copy=None)
target_freq = np.asarray(target_freq, dtype=np.complex128)
else:
raise ValueError('Error: register_translation only knows the "real" and "fourier" values for the ``space`` argument.')

Expand Down Expand Up @@ -1688,12 +1699,12 @@ def apply_shifts_dft(src_freq, shifts, diffphase, is_freq=True, border_nan=True)
is3D = len(src_freq.shape) == 3
if not is_freq:
if is3D:
src_freq = np.fft.fftn(src_freq)
src_freq = np.fft.fftn(src_freq.astype(np.complex128, copy=False))
else:
src_freq = np.dstack([np.real(src_freq), np.imag(src_freq)])
src_freq = cv2.dft(src_freq, flags=cv2.DFT_COMPLEX_OUTPUT + cv2.DFT_SCALE)
src_freq = src_freq[:, :, 0] + 1j * src_freq[:, :, 1]
src_freq = np.array(src_freq, dtype=np.complex128, copy=None)
src_freq = np.asarray(src_freq, dtype=np.complex128)

if not is3D:
nr, nc = src_freq.shape
Expand All @@ -1714,7 +1725,7 @@ def apply_shifts_dft(src_freq, shifts, diffphase, is_freq=True, border_nan=True)

Greg = Greg.dot(np.exp(1j * diffphase))
if is3D:
new_img = np.real(np.fft.ifftn(Greg))
new_img = np.real(np.fft.ifftn(Greg.astype(np.complex128, copy=False)))
else:
Greg = np.dstack([np.real(Greg), np.imag(Greg)])
new_img = cv2.idft(Greg)[:, :, 0]
Expand Down Expand Up @@ -1885,7 +1896,7 @@ def sliding_window_3d(image: np.ndarray, overlaps: tuple[int, int, int], strides
yield inds + corner + (patch,)


def interpolate_shifts(shifts, coords_orig: tuple, coords_new: tuple) -> np.ndarray:
def interpolate_shifts(shifts, coords_orig: tuple, coords_new: tuple, method="linear") -> np.ndarray:
"""
Interpolate piecewise shifts onto new coordinates. Pixels outside the original coordinates will be filled with edge values.

Expand All @@ -1898,6 +1909,9 @@ def interpolate_shifts(shifts, coords_orig: tuple, coords_new: tuple) -> np.ndar

coords_new: tuple of float vectors
coordinates along each dimension at which to output interpolated shifts

method: str
interpolation method (for scipy.interpolate.interpn)

Returns:
ndarray of interpolated shifts, of shape tuple(len(coords) for coords in coords_new)
Expand All @@ -1906,7 +1920,7 @@ def interpolate_shifts(shifts, coords_orig: tuple, coords_new: tuple) -> np.ndar
coords_new_clipped = [np.clip(coord, min(coord_orig), max(coord_orig)) for coord, coord_orig in zip(coords_new, coords_orig)]
coords_new_stacked = np.stack(np.meshgrid(*coords_new_clipped, indexing='ij'), axis=-1)
shifts_grid = np.reshape(shifts, tuple(len(coord) for coord in coords_orig))
return scipy.interpolate.interpn(coords_orig, shifts_grid, coords_new_stacked, method="cubic")
return scipy.interpolate.interpn(coords_orig, shifts_grid, coords_new_stacked, method=method)


def iqr(a):
Expand Down Expand Up @@ -2169,9 +2183,9 @@ def tile_and_correct(img, template, strides, overlaps, max_shifts, newoverlaps=N
if shifts_interpolate:
patch_centers_orig = get_patch_centers(img.shape, strides=strides, overlaps=overlaps)
patch_centers_new = get_patch_centers(img.shape, strides=newstrides, overlaps=newoverlaps)
shift_img_x = interpolate_shifts(shift_img_x, patch_centers_orig, patch_centers_new)
shift_img_y = interpolate_shifts(shift_img_y, patch_centers_orig, patch_centers_new)
diffs_phase_grid_us = interpolate_shifts(diffs_phase_grid, patch_centers_orig, patch_centers_new)
shift_img_x = interpolate_shifts(shift_img_x, patch_centers_orig, patch_centers_new, method="cubic")
shift_img_y = interpolate_shifts(shift_img_y, patch_centers_orig, patch_centers_new, method="cubic")
diffs_phase_grid_us = interpolate_shifts(diffs_phase_grid, patch_centers_orig, patch_centers_new, method="cubic")
else:
shift_img_x = cv2.resize(
shift_img_x, dim_new_grid[::-1], interpolation=cv2.INTER_CUBIC)
Expand Down Expand Up @@ -2420,10 +2434,10 @@ def tile_and_correct_3d(img:np.ndarray, template:np.ndarray, strides:tuple, over
if shifts_interpolate:
patch_centers_orig = get_patch_centers(img.shape, strides=strides, overlaps=overlaps)
patch_centers_new = get_patch_centers(img.shape, strides=newstrides, overlaps=newoverlaps)
shift_img_x = interpolate_shifts(shift_img_x, patch_centers_orig, patch_centers_new)
shift_img_y = interpolate_shifts(shift_img_y, patch_centers_orig, patch_centers_new)
shift_img_z = interpolate_shifts(shift_img_z, patch_centers_orig, patch_centers_new)
diffs_phase_grid_us = interpolate_shifts(diffs_phase_grid, patch_centers_orig, patch_centers_new)
shift_img_x = interpolate_shifts(shift_img_x, patch_centers_orig, patch_centers_new, method="cubic")
shift_img_y = interpolate_shifts(shift_img_y, patch_centers_orig, patch_centers_new, method="cubic")
shift_img_z = interpolate_shifts(shift_img_z, patch_centers_orig, patch_centers_new, method="cubic")
diffs_phase_grid_us = interpolate_shifts(diffs_phase_grid, patch_centers_orig, patch_centers_new, method="cubic")
else:
shift_img_x = resize_sk(
shift_img_x, dim_new_grid[::-1], order=3)
Expand Down
56 changes: 7 additions & 49 deletions caiman/source_extraction/cnmf/deconvolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
Extract neural activity from a fluorescence trace using a constrained deconvolution approach
"""

from math import log, sqrt, exp
import numpy as np
import scipy.signal
import scipy.linalg

import sys
from warnings import warn
from math import log, sqrt, exp

import sys
from caiman.source_extraction import cnmf


def constrained_foopsi(fluor, bl=None, c1=None, g=None, sn=None, p=None, method_deconvolution='oasis', bas_nonneg=True,
noise_range=[.25, .5], noise_method='logmexp', lags=5, fudge_factor=1.,
Expand Down Expand Up @@ -747,7 +748,7 @@ def constrained_oasisAR2(y, g, sn, optimize_b=True, b_nonneg=True, optimize_g=0,

# this window size seems necessary and sufficient
possible_spikes = [x + np.arange(-2, 3)
for x in np.where(s > s.max() / 10.)[0]]
for x in np.where(s > float(s.max()) / 10.)[0]]
ff = np.array(possible_spikes, dtype=int).ravel()
ff = np.unique(ff[(ff >= 0) * (ff < T)])
mask = np.zeros(T, dtype=bool)
Expand Down Expand Up @@ -998,11 +999,11 @@ def estimate_time_constant(fluor, p=2, sn=None, lags=5, fudge_factor=1.):
sn = GetSn(fluor)

lags += p
xc = axcov(fluor, lags)
xc = cnmf.utilities.axcov(fluor, lags)
xc = xc[:, np.newaxis]

A = scipy.linalg.toeplitz(c=np.ravel(xc[lags + np.arange(lags)]),
r=np.ravel(xc[lags + np.arange(p)])) - sn**2 * np.eye(lags, p)
r=np.ravel(xc[lags + np.arange(p)])) - float(sn)**2 * np.eye(lags, p)
g = np.linalg.lstsq(A, xc[lags + 1:], rcond=None)[0]
gr = np.roots(np.concatenate([np.array([1]), -g.flatten()]))
gr = (gr + gr.conjugate()) / 2.
Expand Down Expand Up @@ -1050,46 +1051,3 @@ def GetSn(fluor, range_ff=[0.25, 0.5], method='logmexp'):
return np.sqrt(np.exp(np.mean(np.log(Pxx_ind / 2))))
else:
raise Exception('Invalid method requested for GetSn')

def axcov(data, maxlag=5):
"""
Compute the autocovariance of data at lag = -maxlag:0:maxlag

Args:
data : array
Array containing fluorescence data

maxlag : int
Number of lags to use in autocovariance calculation

Returns:
axcov : array
Autocovariances computed from -maxlag:0:maxlag
"""

data = data - np.mean(data)
T = len(data)
bins = np.size(data)
xcov = np.fft.fft(data, np.power(2, nextpow2(2 * bins - 1)))
xcov = np.fft.ifft(np.square(np.abs(xcov)))
xcov = np.concatenate([xcov[np.arange(xcov.size - maxlag, xcov.size)],
xcov[np.arange(0, maxlag + 1)]])
return np.real(xcov / T)


def nextpow2(value):
"""
Find exponent such that 2^exponent is equal to or greater than abs(value).

Args:
value : int

Returns:
exponent : int
"""

exponent = 0
avalue = np.abs(value)
while avalue > np.power(2, exponent):
exponent += 1
return exponent
Loading
Loading