Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
b3132a7
First draft of CNMFParams serialization overhaul
ethanbb Jan 19, 2026
dc9e6a7
Fix equality checking; verify reconstruction when serializing; use ty…
ethanbb Jan 20, 2026
a4cd600
Add first test in test_params
ethanbb Jan 20, 2026
a047a59
Switch to pydantic; checkpoint before making dataclasses frozen
ethanbb Jan 22, 2026
dee597a
Make all GroupParams and CNMFParams frozen to prevent direct assignment
ethanbb Jan 22, 2026
126ca57
Add change_params test
ethanbb Jan 25, 2026
663bbe5
Add warn=False or remove existing uses of params.set
ethanbb Jan 25, 2026
aa9af7b
Simplify CNMF constructor, fix skip_refinement, fix CNFMParams docstring
ethanbb Jan 25, 2026
2d6db27
More direct params setting fixes
ethanbb Jan 25, 2026
a6ac888
Set spatial.se based on corr_pnr which was previously done only durin…
ethanbb Jan 25, 2026
cde7098
Provide params object to initialize_components and make copying a Gro…
ethanbb Jan 25, 2026
31bb7db
Fix circular imports
ethanbb Jan 26, 2026
6e235a3
Finish test_params, fix constructor logic so tests pass
ethanbb Jan 26, 2026
c8ec239
Fix, test and clearly document behavior when initialization methods a…
ethanbb Jan 26, 2026
e1e1288
Fix HDF5 roundtrip (dealing with b'None'); improve some validators us…
ethanbb Jan 27, 2026
d60fe31
Switch to processing flat params in before model validator & ditch bi…
ethanbb Jan 30, 2026
ab15040
Enforce ssub, ssub_B, tsub are ints to match usage in downscale
ethanbb Jan 30, 2026
084c421
Use computed fields to keep track of which fields should continue to …
ethanbb Feb 2, 2026
e8caad3
Fix dims not being set in estimates; remove old unused use_init logic
ethanbb Feb 2, 2026
080ed0f
Fix remaining tests - robust check for b'NoneType' and fix splitting …
ethanbb Feb 2, 2026
6a6fefc
Fix demos for windows (multiprocessing), remove blocking plt.show()
ethanbb Feb 2, 2026
6acf131
Merge branch 'demos-fixes' into improve-params-serialization
ethanbb Feb 2, 2026
0be49a7
Fix some residual params issues appearing in demos and use object syn…
ethanbb Feb 3, 2026
d4e8a72
Add a few more tests & minor cleanup
ethanbb Feb 4, 2026
f6767ba
Add polyfill for ValidateAs
ethanbb Feb 4, 2026
01785af
Make copy and deepcopy null the _full_params back-reference
ethanbb Feb 4, 2026
6ba3702
Use PlainValidator for ValidateAs
ethanbb Feb 4, 2026
b08de59
Fix missing setattr of _full_params in set
ethanbb Feb 4, 2026
8741607
Avoid using staticmethod in unsupported way
ethanbb Feb 4, 2026
90cd324
Whoops, use real name for the cached property being deleted
ethanbb Feb 4, 2026
4747751
Make requested changes, including undoing import changes in initializ…
ethanbb Feb 5, 2026
3a3d5a7
Oops, fix one import I forgot
ethanbb Feb 5, 2026
54e358d
Use input_params rather than params in update_nested_params to avoid …
ethanbb Feb 6, 2026
07caa6c
Remove redundancy in p and n_pixels_per_process & generally avoid cha…
ethanbb Feb 11, 2026
e7be503
Factor out estimate_n_pixels_per_process
ethanbb Feb 11, 2026
5d9f35b
Remove p_ssub and p_tsub, which are unused anywhere in the code
ethanbb Feb 11, 2026
f470a15
Add rename for 'merge_thresh' I missed
ethanbb Mar 1, 2026
032ade2
Log a better warning when trying to set a deprecated (removed) param
ethanbb Mar 2, 2026
7085fed
Restore original binary closing behavior for CNMFE
ethanbb Mar 4, 2026
253d41a
Update test_params to reflect restored se behavior
ethanbb Mar 4, 2026
40233c2
Resolve minor typing error in params
ethanbb Mar 11, 2026
c901c14
Numeric type fix for rf2stride
ethanbb Mar 11, 2026
c1fef6a
Correct type for gSig_range
ethanbb Mar 12, 2026
63a1809
Add __setstate__ method for unpickling backward-compatibility
ethanbb Mar 23, 2026
27cefb4
Add another validator to deal with slices encoded as bytes
ethanbb Mar 23, 2026
6bab658
Fix loading old CNMF object with skip_refinement and remove_very_bad_…
ethanbb Mar 23, 2026
f4006fc
Undo overly optimistic removal of conversion from HDF5 load function …
ethanbb Mar 31, 2026
fb712e1
Use alias when reporting differing params
ethanbb Mar 31, 2026
57739e2
Merge branch 'dev' into improve-params-serialization
ethanbb Jun 25, 2026
1cffd3c
Fix copy method to properly use computed fields; add to_dict_roundtrip
ethanbb Jun 25, 2026
01e1fa1
Add wrapper serializer for numpy scalars
ethanbb Jul 1, 2026
c0f10e2
Avoid cycles when checking for numpy scalars
ethanbb Jul 1, 2026
4ed3f53
Fix constructing slice incorrectly in numpy scalar helper
ethanbb Jul 1, 2026
9a681e1
Fix inf and nan serialization to JSON
ethanbb Jul 2, 2026
3424b68
Revert adding global field serializer - causes more issues than it fi…
ethanbb Jul 2, 2026
cae7b7e
Make JSON schema for IntSlice more precise
ethanbb Jul 2, 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
8 changes: 5 additions & 3 deletions caiman/base/movies.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ def extract_traces_from_masks(self, masks: np.ndarray) -> caiman.base.traces.tra
traces = caiman.base.traces.trace(np.dot(A, np.transpose(Y)).T, **self.__dict__)
return traces

def resize(self, fx=1, fy=1, fz=1, interpolation=cv2.INTER_AREA):
def resize(self, fx=1., fy=1., fz=1., interpolation=cv2.INTER_AREA):
"""
Resizing caiman movie into a new one. Note that the temporal
dimension is controlled by fz and fx, fy, fz correspond to
Expand Down Expand Up @@ -1813,13 +1813,15 @@ def get_file_size(file_name, var_name_hdf5:str='mov') -> tuple[tuple, Union[int,
raise Exception('Unknown file type')
dims = tuple(dims)
else:
raise Exception('File not found!')
raise FileNotFoundError('File not found!')

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To catch more specifically and log a useful warning when checking data params

elif isinstance(file_name, tuple):
dims = caiman.base.movies.load(file_name[0], var_name_hdf5=var_name_hdf5).shape
T = len(file_name)

elif isinstance(file_name, list):
if len(file_name) == 1:
if len(file_name) == 0:
Comment thread
ethanbb marked this conversation as resolved.
Resolved
raise ValueError('No files to load')
elif len(file_name) == 1:
dims, T = get_file_size(file_name[0], var_name_hdf5=var_name_hdf5)
else:
dims, T = zip(*[get_file_size(fn, var_name_hdf5=var_name_hdf5)
Expand Down
6 changes: 3 additions & 3 deletions caiman/caimanmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ def do_nt_run_demotests(targdir: str) -> None:
# Windows platform can't run shell scripts, and doing it in batch files
# is a terrible idea. So we'll do a minimal implementation of run_demos for
# windows inline here.
os.environ['MPLCONFIG'] = 'ps' # Not sure this does anything on windows
demos = glob.glob('demos/general/*.py') # Should still work on windows I think
demos = glob.glob('demos/general/*.py', root_dir=caiman_datadir())
for demo in demos:
print("========================================")
print(f"Testing {demo}")
Expand All @@ -178,7 +177,8 @@ def do_nt_run_demotests(targdir: str) -> None:
elif "demo_pipeline_voltage_imaging.py" in demo:
print(f" Skipping tests on {demo}: This needs Keras, an optional dependency")
else:
out, err, ret = runcmd(["python", demo], ignore_error=False)
demo_path = os.path.join(caiman_datadir(), demo)
out, err, ret = runcmd(["python", demo_path], ignore_error=False)
if ret != 0:
print(f" Tests failed with returncode {ret}")
print(f" Failed test is {demo}")
Expand Down
80 changes: 6 additions & 74 deletions caiman/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import ipyparallel
import logging
import multiprocessing
import multiprocessing.pool
import numpy as np
import os
import platform
Expand All @@ -21,78 +22,8 @@
import time
from typing import Any, Optional, Union

def extract_patch_coordinates(dims: tuple,
rf: Union[list, tuple],
stride: Union[list[int], tuple],
border_pix: int = 0,
indices=[slice(None)] * 2) -> tuple[list, list]:
"""
Partition the FOV in patches
and return the indexed in 2D and 1D (flatten, order='F') formats

Args:
dims: tuple of int
dimensions of the original matrix that will be divided in patches

rf: tuple of int
radius of receptive field, corresponds to half the size of the square patch

stride: tuple of int
degree of overlap of the patches
"""

# TODO: Find a new home for this function
sl_start = [0 if sl.start is None else sl.start for sl in indices]
sl_stop = [dim if sl.stop is None else sl.stop for (sl, dim) in zip(indices, dims)]
sl_step = [1 for sl in indices] # not used
dims_large = dims
dims = np.minimum(np.array(dims) - border_pix, sl_stop) - np.maximum(border_pix, sl_start)

coords_flat = []
shapes = []
iters = [list(range(rf[i], dims[i] - rf[i], 2 * rf[i] - stride[i])) + [dims[i] - rf[i]] for i in range(len(dims))]

coords = np.empty(list(map(len, iters)) + [len(dims)], dtype=object)
for count_0, xx in enumerate(iters[0]):
coords_x = np.arange(xx - rf[0], xx + rf[0] + 1)
coords_x = coords_x[(coords_x >= 0) & (coords_x < dims[0])]
coords_x += border_pix * 0 + np.maximum(sl_start[0], border_pix)

for count_1, yy in enumerate(iters[1]):
coords_y = np.arange(yy - rf[1], yy + rf[1] + 1)
coords_y = coords_y[(coords_y >= 0) & (coords_y < dims[1])]
coords_y += border_pix * 0 + np.maximum(sl_start[1], border_pix)

if len(dims) == 2:
idxs = np.meshgrid(coords_x, coords_y)

coords[count_0, count_1] = idxs
shapes.append(idxs[0].shape[::-1])

coords_ = np.ravel_multi_index(idxs, dims_large, order='F')
coords_flat.append(coords_.flatten())
else: # 3D data

if border_pix > 0:
raise Exception(
'The parameter border pix must be set to 0 for 3D data since border removal is not implemented')

for count_2, zz in enumerate(iters[2]):
coords_z = np.arange(zz - rf[2], zz + rf[2] + 1)
coords_z = coords_z[(coords_z >= 0) & (coords_z < dims[2])]
idxs = np.meshgrid(coords_x, coords_y, coords_z)
shps = idxs[0].shape
shapes.append([shps[1], shps[0], shps[2]])
coords[count_0, count_1, count_2] = idxs
coords_ = np.ravel_multi_index(idxs, dims, order='F')
coords_flat.append(coords_.flatten())

for i, c in enumerate(coords_flat):
assert len(c) == np.prod(shapes[i])

return list(map(np.sort, coords_flat)), shapes

def start_server(ipcluster: str = "ipcluster", ncpus: int = None) -> None:
def start_server(ipcluster: str = "ipcluster", ncpus: Optional[int] = None) -> None:
"""
programmatically start the ipyparallel server

Expand Down Expand Up @@ -126,7 +57,7 @@ def start_server(ipcluster: str = "ipcluster", ncpus: int = None) -> None:
logger.debug('Making sure everything is up and running')
client.direct_view().execute('__a=1', block=True) # when done on all, we're set to go

def stop_server(ipcluster: str = 'ipcluster', pdir: str = None, profile: str = None, dview=None) -> None:
def stop_server(ipcluster: str = 'ipcluster', pdir: Optional[str] = None, profile: Optional[str] = None, dview=None) -> None:
"""
programmatically stops the ipyparallel server

Expand All @@ -141,7 +72,7 @@ def stop_server(ipcluster: str = 'ipcluster', pdir: str = None, profile: str = N

"""
logger = logging.getLogger("caiman")
if 'multiprocessing' in str(type(dview)):
if isinstance(dview, multiprocessing.pool.Pool):
dview.terminate()
else:
logger.info("Stopping cluster...")
Expand All @@ -156,6 +87,7 @@ def stop_server(ipcluster: str = 'ipcluster', pdir: str = None, profile: str = N
shell=True,
stderr=subprocess.PIPE,
close_fds=(os.name != 'nt'))
assert proc.stderr is not None, 'Should have stderr when using PIPE'

line_out = proc.stderr.readline()
if b'CRITICAL' in line_out:
Expand All @@ -179,7 +111,7 @@ def setup_cluster(backend:str = 'multiprocessing',
n_processes:Optional[int] = None,
single_thread:bool = False,
ignore_preexisting:bool = False,
maxtasksperchild:int = None) -> tuple[Any, Any, Optional[int]]:
maxtasksperchild:Optional[int] = None) -> tuple[Any, Any, Optional[int]]:
"""
Setup and/or restart a parallel cluster.

Expand Down
18 changes: 14 additions & 4 deletions caiman/motion_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,13 +1105,13 @@ def process_movie_parallel(arg_in):

# logger.debug('median computing')
template = Yr.bin_median()
idx_dot = len(fname.split('.')[-1])
fname_no_ext = os.path.splitext(fname)[0]
if save_hdf5:
Yr.save(fname[:-idx_dot] + 'hdf5')
np.savez(fname[:-idx_dot] + 'npz', shifts=shifts,
Yr.save(f'{fname_no_ext}.hdf5')
np.savez(f'{fname_no_ext}.npz', shifts=shifts,
xcorrs=xcorrs, template=template)
del Yr
return fname[:-idx_dot]
return f'{fname_no_ext}.'
else:
return None

Expand Down Expand Up @@ -1967,6 +1967,12 @@ def high_pass_filter_space(img_orig, gSig_filt=None, freq=None, order=None):
Function for high passing the image(s) with centered Gaussian if gSig_filt
is specified or Butterworth filter if freq and order are specified

FIXME:
- gSig_filt is expected to be a sequence, but only the first element is ever used
(kernel is always circular)
- does not support 3D images - assumes 3D = movie and only filters along last
2 dimensions (X and Z).

Args:
img_orig: 2-d or 3-d array
input image/movie
Expand All @@ -1985,6 +1991,10 @@ def high_pass_filter_space(img_orig, gSig_filt=None, freq=None, order=None):
image/movie after filtering
"""
if freq is None or order is None: # Gaussian
if gSig_filt is None:
raise ValueError(
'Must provide either gSig_filt (for Gaussian) or both freq and order (for Butterworth)')

ksize = tuple([(3 * i) // 2 * 2 + 1 for i in gSig_filt])
ker = cv2.getGaussianKernel(ksize[0], gSig_filt[0])
ker2D = ker.dot(ker.T)
Expand Down
Loading
Loading