From 6a4465720a119ef89a34a949de1ddb2a246b342e Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Mon, 27 Oct 2025 00:06:29 -0400 Subject: [PATCH 01/18] Take indices into account when applying piecewise shifts --- caiman/motion_correction.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 9036e2e4a..4f3977817 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -456,16 +456,28 @@ 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 + patch_centers = tuple([ + list(dim_inds.start + dim_inds.step * np.array(dim_centers_orig)) + for dim_inds, dim_centers_orig in zip(self.indices, patch_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 = True if any(dim_inds != slice(None) for dim_inds in self.indices) else self.shifts_interpolate + 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) ] @@ -473,7 +485,7 @@ def apply_shifts_movie(self, fname, rigid_shifts: Optional[bool] = None, save_me # 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) ] From 0b228456c07c3c5b9627567a60ab12af5d80002b Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Fri, 9 Jan 2026 09:56:07 -0500 Subject: [PATCH 02/18] Replace unnecessary ternary with 'or' --- caiman/motion_correction.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 4f3977817..48c187767 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -470,7 +470,7 @@ def apply_shifts_movie(self, fname, rigid_shifts: Optional[bool] = None, save_me # 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 = True if any(dim_inds != slice(None) for dim_inds in self.indices) else self.shifts_interpolate + 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 From 4f3cd0196b0e3dc04c5d3d906e0951691fa4eba1 Mon Sep 17 00:00:00 2001 From: Pat Gunn Date: Fri, 30 Jan 2026 11:48:34 -0500 Subject: [PATCH 03/18] VERSION to 1.13.2 after release --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index b50dd27dd..61ce01b30 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.13.1 +1.13.2 From 6fc2d4296fb1b0960c4df155c988d6b89c167401 Mon Sep 17 00:00:00 2001 From: Pat Gunn Date: Fri, 30 Jan 2026 14:18:11 -0500 Subject: [PATCH 04/18] For now, switch primary maintainer email to my personal; may change again before next release --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 8b1eb271d..64dbdd6a4 100755 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ name='caiman', version=version, author='Andrea Giovannucci, Eftychios Pnevmatikakis, Johannes Friedrich, Valentina Staneva, Ben Deverett, Erick Cobos, Jeremie Kalfon', - author_email='pgunn@flatironinstitute.org', + author_email='pgunn01@gmail.com', url='https://github.com/flatironinstitute/CaImAn', license='GPL-2', description='Advanced algorithms for ROI detection and deconvolution of Calcium Imaging datasets.', From 683650d1e4cedf9c64091af45d6701308374f0a5 Mon Sep 17 00:00:00 2001 From: Pat Gunn Date: Fri, 30 Jan 2026 14:18:45 -0500 Subject: [PATCH 05/18] README: tighten language and help guidance --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eeb36f7e6..97646ef38 100644 --- a/README.md +++ b/README.md @@ -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. From d08d89f4c939f6a54f08beb74caf5d2dd880b15c Mon Sep 17 00:00:00 2001 From: Pat Gunn Date: Fri, 30 Jan 2026 15:49:22 -0500 Subject: [PATCH 06/18] Python 3.13 and later don't include setuptools by default; adding it as a dep --- docs/docs_require.txt | 1 + environment-minimal.yml | 1 + environment.yml | 1 + pyproject.toml | 1 + 4 files changed, 4 insertions(+) diff --git a/docs/docs_require.txt b/docs/docs_require.txt index 8a2879979..4a9a05ae3 100644 --- a/docs/docs_require.txt +++ b/docs/docs_require.txt @@ -16,6 +16,7 @@ torch scikit-image scikit-learn scipy +setuptools tifffile tqdm zarr diff --git a/environment-minimal.yml b/environment-minimal.yml index 981a2dd18..cbf370942 100644 --- a/environment-minimal.yml +++ b/environment-minimal.yml @@ -25,6 +25,7 @@ dependencies: - scikit-image >=0.19.0 - scikit-learn >=1.2 - scipy >= 1.10.1 +- setuptools - tifffile - torchvision - tqdm diff --git a/environment.yml b/environment.yml index a0b96d974..392bf76da 100644 --- a/environment.yml +++ b/environment.yml @@ -34,6 +34,7 @@ dependencies: - scikit-image >=0.19.0 - scikit-learn >=1.2 - scipy >= 1.10.1 +- setuptools - tifffile - tk - torchinfo diff --git a/pyproject.toml b/pyproject.toml index 6fe59d278..706ce2a47 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = [ "pyside6", "pytest", "pytest-cov", + "setuptools", "torch", "scikit-image >= 0.19.0", "scikit-learn >= 1.2", From 56d629a6132e32be27f29b3a3b58b5510d8798b8 Mon Sep 17 00:00:00 2001 From: mannypaeza Date: Sun, 1 Feb 2026 12:53:00 -0500 Subject: [PATCH 07/18] MRCNN and volpy fixes --- .../volpy/mrcnn/mrcnn_training.ipynb | 6 ++--- .../source_extraction/volpy/mrcnn/neurons.py | 4 ++-- .../volpy/mrcnn/visualize.py | 23 ++++++++++--------- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb b/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb index 658f481b6..e8c2b366d 100644 --- a/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb +++ b/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb @@ -175,7 +175,7 @@ "\n", "if config.RANDOM_SPLIT:\n", " print(\"Using random split for train/validation sets.\")\n", - " indices = list(range(len(dataset_train_instance)))\n", + " indices = list(range(len(dataset_train)))\n", " np.random.shuffle(indices)\n", " train_indices = indices[:-config.NUM_TEST_RANDOM]\n", " val_indices = indices[-config.NUM_TEST_RANDOM:]\n", @@ -363,9 +363,9 @@ ], "metadata": { "kernelspec": { - "display_name": "caiman_pytorch2", + "display_name": "caiman", "language": "python", - "name": "caiman_pytorch2" + "name": "caiman" }, "language_info": { "codemirror_mode": { diff --git a/caiman/source_extraction/volpy/mrcnn/neurons.py b/caiman/source_extraction/volpy/mrcnn/neurons.py index 4d28ba929..328ceb305 100644 --- a/caiman/source_extraction/volpy/mrcnn/neurons.py +++ b/caiman/source_extraction/volpy/mrcnn/neurons.py @@ -267,7 +267,7 @@ def train_validate(config, plot_results=False): if config.RANDOM_SPLIT: print("Using random split for train/validation sets.") - indices = list(range(len(dataset_train_instance))) + indices = list(range(len(dataset_train))) np.random.shuffle(indices) train_indices = indices[:-config.NUM_TEST_RANDOM] val_indices = indices[-config.NUM_TEST_RANDOM:] @@ -390,7 +390,7 @@ def run_inference(config, plot_results=True): if args.mode == 'train': # Call evaluation at the end of training, passing the plotting flag - train_and_validate(config, plot_results=args.plot_results) + train_validate(config, plot_results=args.plot_results) elif args.mode == 'infer': # Call inference, passing the plotting flag run_inference(config, plot_results=args.plot_results) diff --git a/caiman/source_extraction/volpy/mrcnn/visualize.py b/caiman/source_extraction/volpy/mrcnn/visualize.py index d6325a75e..a3607fbb7 100644 --- a/caiman/source_extraction/volpy/mrcnn/visualize.py +++ b/caiman/source_extraction/volpy/mrcnn/visualize.py @@ -9,6 +9,7 @@ Revised by Eric Thompson, Changjia Cai, and Manuel Paez """ +import colorsys import numpy as np import matplotlib import matplotlib.pyplot as plt @@ -45,7 +46,7 @@ def apply_mask(image: np.ndarray, mask: np.ndarray, image[:, :, c]) return image -def apply_masks(image: np.ndarray, mask: np.ndarray, +def apply_masks(image: np.ndarray, data_masks: np.ndarray, color: tuple[float, float, float], alpha: float = 0.5) -> np.ndarray: """ Applies a single mask to an image. @@ -176,7 +177,7 @@ def draw_box(box: np.ndarray, color: str = 'white', ax: plt.Axes = None, - rect (patches.Rectangle): The created matplotlib Rectangle object. """ if ax is None: - ax = pl.gca() + ax = plt.gca() box_origin = (box[0], box[1]) box_height = box[3] - box[1] @@ -193,7 +194,7 @@ def draw_box(box: np.ndarray, color: str = 'white', ax: plt.Axes = None, return ax, rect -def draw_boxes(box: np.ndarray, color: str = 'white', ax=None, +def draw_boxes(boxes: np.ndarray, color: str = 'white', ax=None, line_width: float = 0.5) -> tuple[plt.Axes, patches.Rectangle]: """ Draws a single bounding box on a given axes object. @@ -209,7 +210,7 @@ def draw_boxes(box: np.ndarray, color: str = 'white', ax=None, A tuple containing the axes object and the created Rectangle patch. """ if ax is None: - ax = pl.gca() + ax = plt.gca() num_boxes = len(boxes) all_rects = [] @@ -253,35 +254,35 @@ def plot_volpy_segs(image: np.ndarray, # Mean ax1.imshow(image[:,:,1], cmap='gray', vmin=np.percentile(image[:,:,1], min_v), - vmax=np.percentile(image[:,:,1], max_v)); + vmax=np.percentile(image[:,:,1], max_v)) ax1.set_title('Mean Image') ax2.imshow(image[:,:,1], cmap='gray', vmin=np.percentile(image[:,:,1], min_v), - vmax=np.percentile(image[:,:,1], max_v)); + vmax=np.percentile(image[:,:,1], max_v)) for mask in masks: ax2.plot(mask['all_points_x'], mask['all_points_y'], color=outline_color, - linewidth=outline_width); + linewidth=outline_width) ax2.set_title('Mean Image Seg') # Corr ax3.imshow(image[:,:,2], cmap='gray', vmin=np.percentile(image[:,:,2], min_v), - vmax=np.percentile(image[:,:,2], max_v)); + vmax=np.percentile(image[:,:,2], max_v)) ax3.set_title('Corr Image') ax4.imshow(image[:,:,2], cmap='gray', vmin=np.percentile(image[:,:,2], min_v), - vmax=np.percentile(image[:,:,2], max_v)); + vmax=np.percentile(image[:,:,2], max_v)) for mask in masks: ax4.plot(mask['all_points_x'], mask['all_points_y'], color=outline_color, - linewidth=outline_width); + linewidth=outline_width) ax4.set_title('Corr Image Seg') if title is not None: - plt.suptitle(title, y=0.99, fontsize=16); + plt.suptitle(title, y=0.99, fontsize=16) plt.tight_layout() From aed67632794e183e19f99a3450a91e017af5b115 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Mon, 2 Feb 2026 16:26:07 -0500 Subject: [PATCH 08/18] Fix not accounting for Nones in slice --- caiman/motion_correction.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 7021f963f..4af42bdb7 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -466,10 +466,12 @@ def apply_shifts_movie(self, fname, rigid_shifts: Optional[bool] = None, save_me 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 - patch_centers = tuple([ - list(dim_inds.start + dim_inds.step * np.array(dim_centers_orig)) - for dim_inds, dim_centers_orig in zip(self.indices, patch_centers_orig) - ]) + # 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 From fa07d9855f4e6d2b1c94fd230c81cd40fc45e27f Mon Sep 17 00:00:00 2001 From: Pat Gunn Date: Wed, 11 Feb 2026 16:57:09 -0500 Subject: [PATCH 09/18] volpy:spikepursuit: Fix a typo --- caiman/source_extraction/volpy/spikepursuit.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/caiman/source_extraction/volpy/spikepursuit.py b/caiman/source_extraction/volpy/spikepursuit.py index ef2062a65..ce087e333 100644 --- a/caiman/source_extraction/volpy/spikepursuit.py +++ b/caiman/source_extraction/volpy/spikepursuit.py @@ -190,7 +190,9 @@ def volspike(pars): raise Exception('Dimensions of movie and ROIs do not accord') # extract the context region from the entire movie - bwexp = dilation(bw, _shift_footprint_old(np.ones([args['context_size']), args['context_size']])) + bwexp = dilation(bw, + _shift_footprint_old(np.ones([args['context_size']]), args['context_size'])) + Xinds = np.where(np.any(bwexp > 0, axis=1) > 0)[0] Yinds = np.where(np.any(bwexp > 0, axis=0) > 0)[0] bw = bw[Xinds[0]:Xinds[-1] + 1, Yinds[0]:Yinds[-1] + 1] From 2be682060671bba1a92918f34d387e9592350286 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Mon, 16 Feb 2026 11:50:48 -0500 Subject: [PATCH 10/18] Use linear interpolation where appropriate for interpolate_shifts --- caiman/motion_correction.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 4af42bdb7..988cca15f 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -1899,7 +1899,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. @@ -1912,6 +1912,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) @@ -1920,7 +1923,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): @@ -2183,9 +2186,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) @@ -2434,10 +2437,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) From 0fe7a12e488af6691732597ab0c4ee57e7596137 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Thu, 19 Feb 2026 00:03:12 -0500 Subject: [PATCH 11/18] Exclude scikit-image 0.26.0 due to remove_small_* regression --- environment.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/environment.yml b/environment.yml index 392bf76da..b68644591 100644 --- a/environment.yml +++ b/environment.yml @@ -31,7 +31,7 @@ dependencies: - pytest - pytest-cov - pytorch -- scikit-image >=0.19.0 +- scikit-image >=0.19.0, !=0.26.0 - scikit-learn >=1.2 - scipy >= 1.10.1 - setuptools From a0be6a728e0fe92b7636c20481c59a0456e205a5 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Thu, 19 Feb 2026 10:09:38 -0500 Subject: [PATCH 12/18] Update environment-minimal.yml and pyproject.toml --- environment-minimal.yml | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/environment-minimal.yml b/environment-minimal.yml index cbf370942..e7bd0c874 100644 --- a/environment-minimal.yml +++ b/environment-minimal.yml @@ -22,7 +22,7 @@ dependencies: - pyside6 - pytest - pytorch -- scikit-image >=0.19.0 +- scikit-image >=0.19.0, !=0.26.0 - scikit-learn >=1.2 - scipy >= 1.10.1 - setuptools diff --git a/pyproject.toml b/pyproject.toml index 706ce2a47..246d2d128 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ dependencies = [ "pytest-cov", "setuptools", "torch", - "scikit-image >= 0.19.0", + "scikit-image >= 0.19.0, != 0.26.0", "scikit-learn >= 1.2", "scipy >= 1.10.1", "torchvision", From 6044864a1603c4317b4b43d1a69c58ececb53168 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Thu, 19 Feb 2026 14:41:59 -0500 Subject: [PATCH 13/18] Use cumulative energy method that keeps ties as ties for consistency --- caiman/base/rois.py | 34 +++++++++++------ caiman/source_extraction/cnmf/utilities.py | 18 +++------ caiman/source_extraction/volpy/mrcnn/utils.py | 29 ++------------- caiman/utils/visualization.py | 37 +++++++++---------- 4 files changed, 47 insertions(+), 71 deletions(-) diff --git a/caiman/base/rois.py b/caiman/base/rois.py index 052707521..9f241a0ec 100644 --- a/caiman/base/rois.py +++ b/caiman/base/rois.py @@ -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 @@ -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) @@ -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: diff --git a/caiman/source_extraction/cnmf/utilities.py b/caiman/source_extraction/cnmf/utilities.py index 7f783064d..5e31ba75d 100644 --- a/caiman/source_extraction/cnmf/utilities.py +++ b/caiman/source_extraction/cnmf/utilities.py @@ -710,7 +710,7 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_ movie in 2D (dx,dy): tuple - dimensions of the square used to identify neurons (should be set to the galue of gsiz) + dimensions of the square used to identify neurons (should be set to the value of gsiz) A: np.ndarray or sparse matrix Matrix of Spatial components (d x K) @@ -739,7 +739,7 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_ """ (dx, dy) = xxx_todo_changeme if issparse(A): - A = np.array(A.todense()) + A = A.toarray() else: A = np.array(A) @@ -755,12 +755,8 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_ Bmat = np.zeros((np.minimum(nr, max_number), d1, d2)) for i in range(np.minimum(nr, max_number)): - indx = np.argsort(A[:, i], axis=None)[::-1] - cumEn = np.cumsum(A[:, i].flatten()[indx]**2) - cumEn /= cumEn[-1] - Bvec = np.zeros(d) - Bvec[indx] = cumEn - Bmat[i] = np.reshape(Bvec, Cn.shape, order='F') + comp_nrg = caiman.base.rois.norm_nrg(A[:, i]) + Bmat[i] = np.reshape(comp_nrg, Cn.shape, order='F') T = Y.shape[-1] @@ -807,11 +803,7 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_ A = np.concatenate([A, a_f], axis=1) C = np.concatenate([C, c__], axis=0) - indx = np.argsort(a_f, axis=None)[::-1] - cumEn = np.cumsum(a_f.flatten()[indx]**2) - cumEn /= cumEn[-1] - Bvec = np.zeros(d) - Bvec[indx] = cumEn + Bvec = caiman.base.rois.norm_nrg(a_f) bmat = np.reshape(Bvec, Cn.shape, order='F') plt.contour(y, x, bmat, [thr]) plt.pause(.01) diff --git a/caiman/source_extraction/volpy/mrcnn/utils.py b/caiman/source_extraction/volpy/mrcnn/utils.py index 55a9e5e52..39ae8dc07 100644 --- a/caiman/source_extraction/volpy/mrcnn/utils.py +++ b/caiman/source_extraction/volpy/mrcnn/utils.py @@ -24,6 +24,9 @@ import torchvision.transforms.v2 as T from typing import Any, Optional +from caiman.base.rois import norm_nrg + + class ScaleImage: """ Scale image so it is between 0-1: works on floats only @@ -473,29 +476,3 @@ def normalize_image(image): image_shifted = image - image.min() image_normed = image_shifted/image_shifted.max() return np.array(image_normed, dtype=np.float32) - -def norm_nrg(a_): - """ - Calculates the normalized cumulative energy map of an array. - - The function flattens the input array, sorts its elements in descending - order, and computes the normalized cumulative energy. The resulting energy - values are then placed back into an array with the original shape at the - locations corresponding to the original element values. - - Args: - a_ (np.ndarray): The input NumPy array. - - Returns: - np.ndarray: An array of the same shape as the input, containing the - normalized cumulative energy values. - """ - 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') \ No newline at end of file diff --git a/caiman/utils/visualization.py b/caiman/utils/visualization.py index c65cf8c18..a926758e3 100644 --- a/caiman/utils/visualization.py +++ b/caiman/utils/visualization.py @@ -405,26 +405,22 @@ def get_contours(A, dims, thr=0.9, thr_method='nrg', swap_dim=False, slice_dim: # for each patches for i in range(nr): - pars:dict = dict() - # we compute the cumulative sum of the energy of the Ath component that has been ordered from least to highest + if A.indptr[i] == A.indptr[i + 1]: + # component is all zeros + pars = dict( + coordinates=np.array([]), + CoM=np.array([np.nan, np.nan]), + neuron_id=i + 1, + ) + coordinates.append(pars) + continue + patch_data = A.data[A.indptr[i]:A.indptr[i + 1]] - indx = np.argsort(patch_data)[::-1] + if thr_method == 'nrg': - cumEn = np.cumsum(patch_data[indx]**2) - if len(cumEn) == 0: - pars = dict( - coordinates=np.array([]), - CoM=np.array([np.nan, np.nan]), - neuron_id=i + 1, - ) - coordinates.append(pars) - continue - else: - # we work with normalized values - cumEn /= cumEn[-1] - Bvec = np.ones(d) - # we put it in a similar matrix - Bvec[A.indices[A.indptr[i]:A.indptr[i + 1]][indx]] = cumEn + comp_nrg = caiman.base.rois.norm_nrg(patch_data) + Bvec = np.ones(d) + Bvec[A.indices[A.indptr[i]:A.indptr[i + 1]]] = comp_nrg else: if thr_method != 'max': warn("Unknown threshold method. Choosing max") @@ -441,7 +437,7 @@ def get_slice_coords(B: np.ndarray) -> np.ndarray: d1, d2 = B.shape vertices = find_contours(B.T, thr) # this fix is necessary for having disjoint figures and borders plotted correctly - v = np.atleast_2d([np.nan, np.nan]) + v = np.array([[np.nan, np.nan]]) for _, vtx in enumerate(vertices): num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :])) if num_close_coords < 2: @@ -453,9 +449,10 @@ def get_slice_coords(B: np.ndarray) -> np.ndarray: # case one is border vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0) v = np.concatenate( - (v, vtx, np.atleast_2d([np.nan, np.nan])), axis=0) + (v, vtx, np.array([[np.nan, np.nan]])), axis=0) return v + pars = {} if len(dims) == 2: pars['coordinates'] = get_slice_coords(Bmat) else: From 60faeba823f51e6ca31a1dbfcb3dfc1792a97f97 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Sat, 7 Feb 2026 22:50:21 -0500 Subject: [PATCH 14/18] Change np.array(..., copy=None) to np.asarray(...) to make compatible with numpy 1.x --- caiman/motion_correction.py | 13 +++++-------- environment-minimal.yml | 2 +- environment.yml | 2 +- pyproject.toml | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 988cca15f..230222a93 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -1373,10 +1373,8 @@ 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.complex64) + target_image_cpx = np.asarray(target_image, dtype=np.complex64) src_freq = np.fft.fftn(src_image_cpx) target_freq = np.fft.fftn(target_image_cpx) else: @@ -1567,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.') @@ -1707,7 +1704,7 @@ def apply_shifts_dft(src_freq, shifts, diffphase, is_freq=True, border_nan=True) 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 diff --git a/environment-minimal.yml b/environment-minimal.yml index e7bd0c874..f92c00cb5 100644 --- a/environment-minimal.yml +++ b/environment-minimal.yml @@ -12,7 +12,7 @@ dependencies: - keras - matplotlib - moviepy -- numpy >=2.0.0 +- numpy - numpydoc - opencv - peakutils >=1.3.5 diff --git a/environment.yml b/environment.yml index b68644591..582b09cb7 100644 --- a/environment.yml +++ b/environment.yml @@ -18,7 +18,7 @@ dependencies: - matplotlib - moviepy - mypy -- numpy >=2.0.0 +- numpy - numpydoc - opencv - panel >=1.0.2 diff --git a/pyproject.toml b/pyproject.toml index 246d2d128..5a7e30ffc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dependencies = [ "matplotlib", "moviepy", "mypy", - "numpy >= 2.0.0", + "numpy", "numpydoc", "opencv-python", "panel >= 1.0.2", From 58840b366ba36fc4f8ccd5a94ead34765b7180c3 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Wed, 18 Feb 2026 17:16:41 -0500 Subject: [PATCH 15/18] Convert types where needed to account for new promotion rules in numpy 2 --- caiman/motion_correction.py | 10 ++-- .../source_extraction/cnmf/deconvolution.py | 56 +++---------------- .../source_extraction/cnmf/initialization.py | 28 +++++----- caiman/source_extraction/cnmf/map_reduce.py | 2 +- caiman/source_extraction/cnmf/merging.py | 3 +- caiman/source_extraction/cnmf/oasis.pyx | 6 +- caiman/source_extraction/cnmf/online_cnmf.py | 4 +- .../source_extraction/cnmf/pre_processing.py | 51 ++--------------- caiman/source_extraction/cnmf/spatial.py | 12 ++-- caiman/source_extraction/cnmf/temporal.py | 2 +- caiman/source_extraction/cnmf/utilities.py | 45 +++++++++++++++ caiman/tests/test_pre_processing.py | 14 ----- caiman/tests/test_utilities.py | 9 +++ 13 files changed, 101 insertions(+), 141 deletions(-) delete mode 100644 caiman/tests/test_pre_processing.py diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 230222a93..307495b30 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -1373,8 +1373,8 @@ 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.asarray(src_image, dtype=np.complex64) - target_image_cpx = np.asarray(target_image, dtype=np.complex64) + 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: @@ -1382,7 +1382,7 @@ def register_translation_3d(src_image, target_image, upsample_factor = 1, 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() @@ -1699,7 +1699,7 @@ 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) @@ -1725,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] diff --git a/caiman/source_extraction/cnmf/deconvolution.py b/caiman/source_extraction/cnmf/deconvolution.py index fd4d684b8..cb10161e7 100644 --- a/caiman/source_extraction/cnmf/deconvolution.py +++ b/caiman/source_extraction/cnmf/deconvolution.py @@ -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.cnmf import utilities + 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., @@ -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) @@ -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 = 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. @@ -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 diff --git a/caiman/source_extraction/cnmf/initialization.py b/caiman/source_extraction/cnmf/initialization.py index 359ff379c..f7a57c83b 100644 --- a/caiman/source_extraction/cnmf/initialization.py +++ b/caiman/source_extraction/cnmf/initialization.py @@ -306,7 +306,7 @@ def initialize_components(Y, K=30, gSig=[5, 5], gSiz=None, ssub=1, tsub=1, nIter img += np.finfo(np.float32).eps Y = Y / np.reshape(img, d + (-1,), order='F') - alpha_snmf /= np.mean(img) # normalize alpha for sparse nmf + alpha_snmf /= float(np.mean(img)) # normalize alpha for sparse nmf else: Y = np.array(Y) @@ -448,7 +448,7 @@ def ICA_PCA(Y_ds, nr, sigma_smooth=(.5, .5, .5), truncate=2, fun='logcosh', m = scipy.ndimage.gaussian_filter(np.transpose( Y_ds, [2, 0, 1]), sigma=sigma_smooth, mode='nearest', truncate=truncate) if remove_baseline: - bl = np.percentile(m, perc_baseline, axis=0) + bl = np.percentile(m, np.float64(perc_baseline), axis=0) # use double for pct as in numpy 1.x m1 = np.maximum(0, m - bl) else: bl = np.zeros(m.shape[1:]) @@ -488,7 +488,7 @@ def ICA_PCA(Y_ds, nr, sigma_smooth=(.5, .5, .5), truncate=2, fun='logcosh', model = NMF(n_components=nb, init='random', random_state=0) - b_in = model.fit_transform(np.maximum(m1, 0)).astype(np.float32) + b_in = model.fit_transform(np.maximum(m1, np.float64(0))).astype(np.float32) f_in = model.components_.astype(np.float32) center = caiman.base.rois.com(A_in, d1, d2) @@ -543,7 +543,7 @@ def sparseNMF(Y_ds, nr, max_iter_snmf=200, alpha=0.5, sigma_smooth=(.5, .5, .5), mode='nearest', truncate=truncate) if remove_baseline: logger.info('Removing baseline') - bl = np.percentile(m, perc_baseline, axis=0) + bl = np.percentile(m, np.float64(perc_baseline), axis=0) # use double for pct as in numpy 1.x m1 = np.maximum(0, m - bl) else: logger.info('Not removing baseline') @@ -563,7 +563,7 @@ def sparseNMF(Y_ds, nr, max_iter_snmf=200, alpha=0.5, sigma_smooth=(.5, .5, .5), shuffle=False, alpha_W=alpha, l1_ratio=l1_ratio) - C = mdl.fit_transform(yr).T + C = mdl.fit_transform(yr.astype(np.float64, copy=False)).T A = mdl.components_.T A_in = A C_in = C @@ -571,7 +571,7 @@ def sparseNMF(Y_ds, nr, max_iter_snmf=200, alpha=0.5, sigma_smooth=(.5, .5, .5), m1 = yr.T - A_in.dot(C_in) + np.maximum(0, bl.flatten())[:, np.newaxis] model = NMF(n_components=nb, init='random', random_state=0, max_iter=max_iter_snmf) - b_in = model.fit_transform(np.maximum(m1, 0)).astype(np.float32) + b_in = model.fit_transform(np.maximum(m1, np.float64(0))).astype(np.float32) f_in = model.components_.astype(np.float32) center = caiman.base.rois.com(A_in, *dims) @@ -631,7 +631,7 @@ def compressedNMF(Y_ds, nr, r_ov=10, max_iter_snmf=500, m1 = yr.T - A_in.dot(C_in) + np.maximum(0, bl.flatten(order='F'))[:, np.newaxis] model = NMF(n_components=nb, init='random', random_state=0, max_iter=max_iter_snmf) - b_in = model.fit_transform(np.maximum(m1, 0)).astype(np.float32) + b_in = model.fit_transform(np.maximum(m1, np.float64(0))).astype(np.float32) f_in = model.components_.astype(np.float32) center = caiman.base.rois.com(A_in, *dims) @@ -660,7 +660,7 @@ def graphNMF(Y_ds, nr, max_iter_snmf=500, lambda_gnmf=1, yr = np.reshape(m1, [T, d], order='F') mdl = NMF(n_components=nr, verbose=False, init='nndsvd', tol=1e-10, max_iter=5) - C = mdl.fit_transform(yr).T + C = mdl.fit_transform(yr.astype(np.float64, copy=False)).T A = mdl.components_.T W = caiman.source_extraction.cnmf.utilities.fast_graph_Laplacian_patches( [np.reshape(m, [T, d], order='F').T, [], SC_kernel, SC_sigma, SC_thr, @@ -683,7 +683,7 @@ def graphNMF(Y_ds, nr, max_iter_snmf=500, lambda_gnmf=1, m1 = yr.T - A_in.dot(C_in) + np.maximum(0, bl.flatten(order='F'))[:, np.newaxis] model = NMF(n_components=nb, init='random', random_state=0, max_iter=max_iter_snmf) - b_in = model.fit_transform(np.maximum(m1, 0)).astype(np.float32) + b_in = model.fit_transform(np.maximum(m1, np.float64(0))).astype(np.float32) f_in = model.components_.astype(np.float32) center = caiman.base.rois.com(A_in, *dims) @@ -955,7 +955,7 @@ def onclick(event): model = NMF(n_components=nb, max_iter=nmf_max_iter, init=nmf_init_method) - b_in = model.fit_transform(np.maximum(res, 0)).astype(np.float32) + b_in = model.fit_transform(np.maximum(res, np.float64(0))).astype(np.float32) f_in = model.components_.astype(np.float32) return A, C, np.array(center, dtype='uint16'), b_in, f_in @@ -1357,8 +1357,8 @@ def compute_B(b0, W, B): # actually computes -B to efficiently compute Y-B in p print(nb) if use_NMF: model = NMF(n_components=nb, init='nndsvdar') - b_in = model.fit_transform(np.maximum(B, 0)) - f_in = np.linalg.lstsq(b_in, B)[0] + b_in = model.fit_transform(np.maximum(B, np.float64(0))) # preserve numpy 1.x promotion + f_in = np.linalg.lstsq(b_in, B, rcond=-1)[0] else: b_in, s_in, f_in = spr.linalg.svds(B, k=nb) f_in *= s_in[:, np.newaxis] @@ -1668,7 +1668,7 @@ def onclick(event): # v_search[r, c] = 0 # continue y0 = np.diff(data_filtered[:, r, c]) - if y0.max() < 3 * y0.std(): + if y0.max() < 3 * float(y0.std()): v_search[r, c] = 0 continue @@ -1972,7 +1972,7 @@ def process_pixel(p): index = get_indices_of_pixels_on_ring(p) B = X[index] tmp = np.array(B.dot(B.T)) - tmp[np.diag_indices(len(tmp))] += np.trace(tmp) * 1e-5 + tmp[np.diag_indices(len(tmp))] += float(np.trace(tmp)) * 1e-5 tmp2 = X[p] data = pd_solve(tmp, B.dot(tmp2)) return index, data diff --git a/caiman/source_extraction/cnmf/map_reduce.py b/caiman/source_extraction/cnmf/map_reduce.py index 929b7e37b..d9b3c4180 100644 --- a/caiman/source_extraction/cnmf/map_reduce.py +++ b/caiman/source_extraction/cnmf/map_reduce.py @@ -422,7 +422,7 @@ def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, # Filter out nan components in the bg components nan_components = np.any(np.isnan(F_tot), axis=1) F_tot = F_tot[~nan_components, :] - mdl.fit(np.maximum(F_tot, 0)) + mdl.fit(np.maximum(F_tot, np.float64(0))) Bm = Bm[:, ~nan_components] f = mdl.components_.squeeze() f = np.atleast_2d(f) diff --git a/caiman/source_extraction/cnmf/merging.py b/caiman/source_extraction/cnmf/merging.py index f5c2281cf..d2f1c93b5 100644 --- a/caiman/source_extraction/cnmf/merging.py +++ b/caiman/source_extraction/cnmf/merging.py @@ -147,11 +147,12 @@ def merge_components(Y, A, b, C, R, f, S, sn_pix, temporal_params, A_corr = A_corr.tocsc() FF2 = A_corr > 0 C_corr = scipy.sparse.lil_matrix(A_corr.shape) + C_64 = C.astype(np.float64, copy=False) # preserve numpy 1.x promotion for ii in range(nr): overlap_indices = A_corr[ii, :].nonzero()[1] if len(overlap_indices) > 0: # we chesk the correlation of the calcium traces for each overlapping components - corr_values = [scipy.stats.pearsonr(C[ii, :], C[jj, :])[ + corr_values = [scipy.stats.pearsonr(C_64[ii, :], C_64[jj, :])[ 0] for jj in overlap_indices] C_corr[ii, overlap_indices] = corr_values diff --git a/caiman/source_extraction/cnmf/oasis.pyx b/caiman/source_extraction/cnmf/oasis.pyx index 44ef328d1..08b370fc0 100644 --- a/caiman/source_extraction/cnmf/oasis.pyx +++ b/caiman/source_extraction/cnmf/oasis.pyx @@ -886,7 +886,7 @@ def constrained_oasisAR1(np.ndarray[SINGLE, ndim=1] y, SINGLE g, SINGLE sn, RSS = res.dot(res) else: # optimize b and dependent on optimize_g g too - b = np.percentile(y, 15) # initial estimate of baseline + b = np.percentile(y, np.float64(15)) # initial estimate of baseline, force using double as in numpy 1.x if b_nonneg: b = fmax(b, 0) c, P = oasis1strun(y - b, g, c) @@ -918,8 +918,8 @@ def constrained_oasisAR1(np.ndarray[SINGLE, ndim=1] y, SINGLE g, SINGLE sn, for j in range(P[i].l): tmp[P[i].t + j] = aa aa *= g - tmp -= 1. / T / (1 - g) * np.sum([(1 - g**P[i].l) ** 2 / P[i].w - for i in range(P.size())]) + tmp -= 1. / T / (1 - g) * float(np.sum([(1 - g**P[i].l) ** 2 / P[i].w + for i in range(P.size())])) aa = tmp.dot(tmp) bb = res.dot(tmp) cc = RSS - thresh diff --git a/caiman/source_extraction/cnmf/online_cnmf.py b/caiman/source_extraction/cnmf/online_cnmf.py index c5006c1a0..974566608 100644 --- a/caiman/source_extraction/cnmf/online_cnmf.py +++ b/caiman/source_extraction/cnmf/online_cnmf.py @@ -1578,7 +1578,7 @@ def seeded_initialization(Y, Ain, dims=None, init_batch=1000, order_init=None, g not_px = np.array(not_px).flatten() Yr = np.reshape(Y, (Ain.shape[0], Y.shape[-1]), order='F') model = NMF(n_components=gnb, init='nndsvdar', max_iter=10) - _ = model.fit_transform(np.maximum(Yr[not_px], 0)) # Done to update the model object + _ = model.fit_transform(np.maximum(Yr[not_px], np.float64(0))) # Done to update the model object f_in = model.components_.squeeze() f_in = np.atleast_2d(f_in) Y_resf = np.dot(Yr, f_in.T) @@ -1594,7 +1594,7 @@ def seeded_initialization(Y, Ain, dims=None, init_batch=1000, order_init=None, g print(count) idx_domain = np.where(Ain[:,idx_in])[0] Ain[idx_domain,idx_in] = model_comp.fit_transform(\ - np.maximum(Yr_no_bg[idx_domain], 0)).squeeze() + np.maximum(Yr_no_bg[idx_domain], np.float64(0))).squeeze() Cin[idx_in] = model_comp.components_.squeeze() Yr_no_bg[idx_domain] -= np.outer(Ain[idx_domain, idx_in],Cin[idx_in]) else: diff --git a/caiman/source_extraction/cnmf/pre_processing.py b/caiman/source_extraction/cnmf/pre_processing.py index ace43f01a..fd93639fd 100644 --- a/caiman/source_extraction/cnmf/pre_processing.py +++ b/caiman/source_extraction/cnmf/pre_processing.py @@ -17,6 +17,7 @@ import tempfile import caiman.mmapping +from caiman.source_extraction.cnmf import utilities def interpolate_missing_data(Y): @@ -178,14 +179,15 @@ def get_noise_fft(Y, noise_range=[0.25, 0.5], noise_method='logmexp', max_num_sa psdx_list.append(np.sum(1. / T * dft * dft, 1)) psdx = np.reshape(psdx_list, Y.shape[:-1] + (-1,)) else: - xdft = np.fft.rfft(Y, axis=-1) + # maintain numpy 1.x FFT behavior returning complex128 + xdft = np.fft.rfft(Y.astype(np.float64, copy=False), axis=-1) xdft = xdft[..., ind[:xdft.shape[-1]]] psdx = 1. / T * abs(xdft)**2 psdx *= 2 sn = mean_psd(psdx, method=noise_method) else: - xdft = np.fliplr(np.fft.rfft(Y)) + xdft = np.fliplr(np.fft.rfft(Y.astype(np.float64, copy=False))) psdx = 1. / T * (xdft**2) psdx[1:] *= 2 sn = mean_psd(psdx[ind[:psdx.shape[0]]], method=noise_method) @@ -402,7 +404,7 @@ def estimate_time_constant(Y, sn, p=None, lags=5, include_noise=False, pixels=No lags += p XC = np.zeros((npx, 2 * lags + 1)) for j in range(npx): - XC[j, :] = np.squeeze(axcov(np.squeeze(Y[pixels[j], :]), lags)) + XC[j, :] = np.squeeze(utilities.axcov(np.squeeze(Y[pixels[j], :]), lags)) gv = np.zeros(npx * lags) if not include_noise: @@ -428,49 +430,6 @@ def estimate_time_constant(Y, sn, p=None, lags=5, include_noise=False, pixels=No return g -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 - - def preprocess_data(Y, sn=None, dview=None, n_pixels_per_process=100, noise_range=[0.25, 0.5], noise_method='logmexp', compute_g=False, p=2, lags=5, include_noise=False, diff --git a/caiman/source_extraction/cnmf/spatial.py b/caiman/source_extraction/cnmf/spatial.py index f367a48e8..1d8801d90 100644 --- a/caiman/source_extraction/cnmf/spatial.py +++ b/caiman/source_extraction/cnmf/spatial.py @@ -344,7 +344,7 @@ def regression_ipyparallel(pars): # skip if no components OR pixel has 0 activity if np.size(c) > 0 and noise_sn[px] > 0: - sn = noise_sn[px] ** 2 * T + sn = float(noise_sn[px]) ** 2 * T # float() to preserve numpy 1.x automatic promotion if method_least_square == 'lasso_lars_old': raise Exception("Obsolete parameter") # Old code, support was removed @@ -353,13 +353,15 @@ def regression_ipyparallel(pars): elif method_least_square == 'lasso_lars': # lasso lars function from scikit learn lambda_lasso = 0 if np.size(cct_) == 0 else \ - .5 * noise_sn[px] * np.sqrt(np.max(cct_)) / T + .5 * float(noise_sn[px]) * float(np.sqrt(np.max(cct_))) / T # float() to preserve numpy 1.x automatic promotion model = make_pipeline( StandardScaler(with_mean=False), linear_model.LassoLars(alpha=lambda_lasso, positive=True, fit_intercept=True) ) - a = model.fit(np.array(c.T), np.ravel(y))['lassolars'].coef_ + # promote to avoid numpy 2.x promotion issues within fit + a = model.fit(np.array(c.T, dtype=np.float64), + np.ravel(y).astype(np.float64, copy=False))['lassolars'].coef_ else: raise Exception( @@ -477,7 +479,7 @@ def threshold_components(A, dims, medw=None, thr_method='max', maxthr=0.1, nrgth data:list = [] for r in res: At, i = r - indptr.append(indptr[-1]+At.indptr[-1]) + indptr.append(indptr[-1] + int(At.indptr[-1])) indices.extend(At.indices.tolist()) data.extend(At.data.tolist()) @@ -992,7 +994,7 @@ def computing_indicator(Y, A_in, b, C, f, nb, method, dims, min_size, max_size, not_px = ~px if nb > 1: - f = NMF(nb, init='nndsvda').fit(np.maximum(Y[not_px, :], 0)).components_ + f = NMF(nb, init='nndsvda').fit(np.maximum(Y[not_px, :], np.float64(0))).components_ else: if Y.shape[-1] < 30000: f = Y[not_px, :].mean(0) diff --git a/caiman/source_extraction/cnmf/temporal.py b/caiman/source_extraction/cnmf/temporal.py index 343f904c3..0b5caf015 100644 --- a/caiman/source_extraction/cnmf/temporal.py +++ b/caiman/source_extraction/cnmf/temporal.py @@ -389,7 +389,7 @@ def update_iteration(parrllcomp, len_parrllcomp, nb, C, S, bl, nr, dview.results.clear() try: - if scipy.linalg.norm(Cin - C, 'fro') <= 1e-3*scipy.linalg.norm(C, 'fro'): + if scipy.linalg.norm(Cin - C, 'fro') <= 1e-3 * float(scipy.linalg.norm(C, 'fro')): logger.info("stopping: overall temporal component not changing" + " significantly") break diff --git a/caiman/source_extraction/cnmf/utilities.py b/caiman/source_extraction/cnmf/utilities.py index 7f783064d..2219736aa 100644 --- a/caiman/source_extraction/cnmf/utilities.py +++ b/caiman/source_extraction/cnmf/utilities.py @@ -1235,3 +1235,48 @@ def fast_graph_Laplacian_pixel(pars): ind = np.where(w>0)[0] return indices[ind].tolist(), w[ind].tolist() + + +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) + # use float64 to maintain numpy 1.x always-double-precision behavior + xcov = np.fft.fft(data.astype(np.float64, copy=False), 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 diff --git a/caiman/tests/test_pre_processing.py b/caiman/tests/test_pre_processing.py deleted file mode 100644 index b31ec95ea..000000000 --- a/caiman/tests/test_pre_processing.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python - -import numpy.testing as npt -import numpy as np -from caiman.source_extraction import cnmf as cnmf - - -def test_axcov(): - data = np.random.randn(1000) - maxlag = 5 - C = cnmf.pre_processing.axcov(data, maxlag) - print(C) - - npt.assert_allclose(C, np.concatenate((np.zeros(maxlag), np.array([1]), np.zeros(maxlag))), atol=1) diff --git a/caiman/tests/test_utilities.py b/caiman/tests/test_utilities.py index d07c88b5e..c98c79341 100644 --- a/caiman/tests/test_utilities.py +++ b/caiman/tests/test_utilities.py @@ -115,3 +115,12 @@ def test_peak_local_max(): for m in (1, 2, 3, 4): npt.assert_array_equal(peak_local_max(img, min_distance=m), utilities.peak_local_max(img, min_distance=m)) + + +def test_axcov(): + data = np.random.randn(1000) + maxlag = 5 + C = utilities.axcov(data, maxlag) + print(C) + + npt.assert_allclose(C, np.concatenate((np.zeros(maxlag), np.array([1]), np.zeros(maxlag))), atol=1) From 2da11e4d07598c3d0c546f5db5ed3c52ad1de6d8 Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Thu, 19 Feb 2026 14:46:52 -0500 Subject: [PATCH 16/18] Change imports to grandparent package (cnmf) --- caiman/source_extraction/cnmf/deconvolution.py | 4 ++-- caiman/source_extraction/cnmf/pre_processing.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/caiman/source_extraction/cnmf/deconvolution.py b/caiman/source_extraction/cnmf/deconvolution.py index cb10161e7..24c66dc25 100644 --- a/caiman/source_extraction/cnmf/deconvolution.py +++ b/caiman/source_extraction/cnmf/deconvolution.py @@ -11,7 +11,7 @@ import sys from warnings import warn -from caiman.source_extraction.cnmf import utilities +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, @@ -999,7 +999,7 @@ def estimate_time_constant(fluor, p=2, sn=None, lags=5, fudge_factor=1.): sn = GetSn(fluor) lags += p - xc = utilities.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)]), diff --git a/caiman/source_extraction/cnmf/pre_processing.py b/caiman/source_extraction/cnmf/pre_processing.py index fd93639fd..16a38bbd7 100644 --- a/caiman/source_extraction/cnmf/pre_processing.py +++ b/caiman/source_extraction/cnmf/pre_processing.py @@ -17,7 +17,7 @@ import tempfile import caiman.mmapping -from caiman.source_extraction.cnmf import utilities +from caiman.source_extraction import cnmf def interpolate_missing_data(Y): @@ -404,7 +404,7 @@ def estimate_time_constant(Y, sn, p=None, lags=5, include_noise=False, pixels=No lags += p XC = np.zeros((npx, 2 * lags + 1)) for j in range(npx): - XC[j, :] = np.squeeze(utilities.axcov(np.squeeze(Y[pixels[j], :]), lags)) + XC[j, :] = np.squeeze(cnmf.utilities.axcov(np.squeeze(Y[pixels[j], :]), lags)) gv = np.zeros(npx * lags) if not include_noise: From f81a791e9a3c29dfdb21422a41712cb743cc3bda Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Fri, 20 Feb 2026 00:23:50 -0500 Subject: [PATCH 17/18] Fix apparent typo in plot_contours, making c/color/line_color args work --- caiman/utils/visualization.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/caiman/utils/visualization.py b/caiman/utils/visualization.py index a926758e3..0fad8d446 100644 --- a/caiman/utils/visualization.py +++ b/caiman/utils/visualization.py @@ -1030,7 +1030,7 @@ def arrow_key_image_control(event): plt.show() def plot_contours(A, Cn, thr=None, thr_method='max', maxthr=0.2, nrgthr=0.9, display_numbers=True, max_number=None, - cmap=None, swap_dim=False, colors='w', vmin=None, vmax=None, coordinates=None, + cmap=None, swap_dim=False, color='w', vmin=None, vmax=None, coordinates=None, contour_args={}, number_args={}, **kwargs): """Plots contour of spatial components against a background image and returns their coordinates @@ -1084,8 +1084,7 @@ def plot_contours(A, Cn, thr=None, thr_method='max', maxthr=0.2, nrgthr=0.9, dis for key in ['c', 'colors', 'line_color']: if key in kwargs.keys(): - color = kwargs[key] - kwargs.pop(key) + color = kwargs.pop(key) ax = plt.gca() if vmax is None and vmin is None: @@ -1101,14 +1100,14 @@ def plot_contours(A, Cn, thr=None, thr_method='max', maxthr=0.2, nrgthr=0.9, dis v = c['coordinates'] c['bbox'] = [np.floor(np.nanmin(v[:, 1])), np.ceil(np.nanmax(v[:, 1])), np.floor(np.nanmin(v[:, 0])), np.ceil(np.nanmax(v[:, 0]))] - plt.plot(*v.T, c=colors, **contour_args) + plt.plot(*v.T, c=color, **contour_args) if display_numbers: nr = A.shape[1] if max_number is None: max_number = nr for i, c in zip(range(np.minimum(nr, max_number)), coordinates): - ax.text(c['CoM'][1], c['CoM'][0], str(i + 1), color=colors, **number_args) + ax.text(c['CoM'][1], c['CoM'][0], str(i + 1), color=color, **number_args) return coordinates def plot_shapes(Ab, dims, num_comps=15, size=(15, 15), comps_per_row=None, From 2bd05dfecc8732c1b345a1f317ad388183fef7ea Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Fri, 20 Feb 2026 00:39:10 -0500 Subject: [PATCH 18/18] Factor out get_slice_coords for easier testing --- caiman/utils/visualization.py | 47 +++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/caiman/utils/visualization.py b/caiman/utils/visualization.py index 0fad8d446..8f27913cb 100644 --- a/caiman/utils/visualization.py +++ b/caiman/utils/visualization.py @@ -362,6 +362,27 @@ def plot_unit(uid, scl): .redim.range(unit_id=(0, nr-1), scale=(0.0, 1.0))) +def get_slice_coords(B: np.ndarray, thr: float) -> np.ndarray: + """Get contour coordinates for a 2D slice""" + d1, d2 = B.shape + vertices = find_contours(B.T, thr) + # this fix is necessary for having disjoint figures and borders plotted correctly + v = np.array([[np.nan, np.nan]]) + for _, vtx in enumerate(vertices): + num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :])) + if num_close_coords < 2: + if num_close_coords == 0: + # case angle + newpt = np.round(np.mean(vtx[[0, -1], :], axis=0) / [d2, d1]) * [d2, d1] + vtx = np.concatenate((newpt[np.newaxis, :], vtx, newpt[np.newaxis, :]), axis=0) + else: + # case one is border + vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0) + v = np.concatenate( + (v, vtx, np.array([[np.nan, np.nan]])), axis=0) + return v + + def get_contours(A, dims, thr=0.9, thr_method='nrg', swap_dim=False, slice_dim: Optional[int] = None): """Gets contour of spatial components and returns their coordinates @@ -431,30 +452,10 @@ def get_contours(A, dims, thr=0.9, thr_method='nrg', swap_dim=False, slice_dim: Bmat = np.reshape(Bvec, dims, order='C') else: Bmat = np.reshape(Bvec, dims, order='F') - - def get_slice_coords(B: np.ndarray) -> np.ndarray: - """Get contour coordinates for a 2D slice""" - d1, d2 = B.shape - vertices = find_contours(B.T, thr) - # this fix is necessary for having disjoint figures and borders plotted correctly - v = np.array([[np.nan, np.nan]]) - for _, vtx in enumerate(vertices): - num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :])) - if num_close_coords < 2: - if num_close_coords == 0: - # case angle - newpt = np.round(np.mean(vtx[[0, -1], :], axis=0) / [d2, d1]) * [d2, d1] - vtx = np.concatenate((newpt[np.newaxis, :], vtx, newpt[np.newaxis, :]), axis=0) - else: - # case one is border - vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0) - v = np.concatenate( - (v, vtx, np.array([[np.nan, np.nan]])), axis=0) - return v pars = {} if len(dims) == 2: - pars['coordinates'] = get_slice_coords(Bmat) + pars['coordinates'] = get_slice_coords(Bmat, thr) else: # make a list of the contour coordinates for each 2D slice pars['coordinates'] = [] @@ -462,7 +463,7 @@ def get_slice_coords(B: np.ndarray) -> np.ndarray: slice_dim = 0 if swap_dim else -1 for s in range(dims[slice_dim]): B = Bmat.take(s, axis=slice_dim) - pars['coordinates'].append(get_slice_coords(B)) + pars['coordinates'].append(get_slice_coords(B, thr)) pars['CoM'] = np.squeeze(cm[i, :]) pars['neuron_id'] = i + 1 @@ -494,6 +495,8 @@ def nb_view_patches3d(Y_r, A, C, dims, image_type='mean', Yr=None, max_projection: boolean plot max projection along specified axis if True, plot layers if False + FIXME - type checking reveals that this code path can't work, namely + coors is a list of dicts that doesn't have a "shape" attribute axis: int (0, 1 or 2) axis along which max projection is performed or layers are shown