diff --git a/caiman/base/movies.py b/caiman/base/movies.py index 5dec250cf..3e65883c6 100644 --- a/caiman/base/movies.py +++ b/caiman/base/movies.py @@ -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 @@ -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!') 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: + 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) diff --git a/caiman/caimanmanager.py b/caiman/caimanmanager.py index 82a79e8ce..45e2f38cf 100755 --- a/caiman/caimanmanager.py +++ b/caiman/caimanmanager.py @@ -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}") @@ -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}") diff --git a/caiman/cluster.py b/caiman/cluster.py index 19bae96b6..99261db2d 100644 --- a/caiman/cluster.py +++ b/caiman/cluster.py @@ -11,6 +11,7 @@ import ipyparallel import logging import multiprocessing +import multiprocessing.pool import numpy as np import os import platform @@ -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 @@ -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 @@ -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...") @@ -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: @@ -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. diff --git a/caiman/motion_correction.py b/caiman/motion_correction.py index 307495b30..d91081ad9 100644 --- a/caiman/motion_correction.py +++ b/caiman/motion_correction.py @@ -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 @@ -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 @@ -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) diff --git a/caiman/source_extraction/cnmf/cnmf.py b/caiman/source_extraction/cnmf/cnmf.py index 70954ed68..177bb5638 100644 --- a/caiman/source_extraction/cnmf/cnmf.py +++ b/caiman/source_extraction/cnmf/cnmf.py @@ -16,8 +16,6 @@ from copy import deepcopy import cv2 -import glob -import inspect import logging import numpy as np import os @@ -25,8 +23,8 @@ import psutil import pynwb import scipy -import sys import time +from typing import Optional import caiman from caiman.components_evaluation import estimate_components_quality @@ -41,7 +39,7 @@ from caiman.source_extraction.cnmf.pre_processing import preprocess_data from caiman.source_extraction.cnmf.spatial import update_spatial_components from caiman.source_extraction.cnmf.temporal import update_temporal_components, constrained_foopsi_parallel -from caiman.source_extraction.cnmf.utilities import update_order +from caiman.source_extraction.cnmf.utilities import all_same, estimate_n_pixels_per_process from caiman.utils.utils import save_dict_to_hdf5, load_dict_from_hdf5, hdf5_runmode @@ -61,28 +59,10 @@ class CNMF(object): See Also: @url http://www.cell.com/neuron/fulltext/S0896-6273(15)01084-3 .. image:: docs/img/quickintro.png - """ - def __init__(self, n_processes, k=5, gSig=[4, 4], gSiz=None, merge_thresh=0.8, p=2, dview=None, - Ain=None, Cin=None, b_in=None, f_in=None, do_merge=True, - ssub=2, tsub=2, p_ssub=1, p_tsub=1, method_init='greedy_roi', alpha_snmf=0.5, - rf=None, stride=None, memory_fact=1, gnb=1, nb_patch=1, only_init_patch=False, - method_deconvolution='oasis', n_pixels_per_process=4000, block_size_temp=5000, num_blocks_per_run_temp=20, - num_blocks_per_run_spat=20, - check_nan=True, skip_refinement=False, normalize_init=True, options_local_NMF=None, - minibatch_shape=100, minibatch_suff_stat=3, - update_num_comps=True, rval_thr=0.9, thresh_fitness_delta=-20, - thresh_fitness_raw=None, thresh_overlap=.5, - max_comp_update_shape=np.inf, num_times_comp_updated=np.inf, - batch_update_suff_stat=False, s_min=None, - remove_very_bad_comps=False, border_pix=0, low_rank_background=True, - update_background_components=True, rolling_sum=True, rolling_length=100, - min_corr=.85, min_pnr=20, ring_size_factor=1.5, - center_psf=False, use_dense=True, deconv_flag=True, - simultaneously=False, n_refit=0, del_duplicates=False, N_samples_exceptionality=None, - max_num_added=3, min_num_trial=2, thresh_CNN_noisy=0.5, - fr=30, decay_time=0.4, min_SNR=2.5, ssub_B=2, init_iter=2, - sniper_mode=False, use_peak_max=False, test_both=False, - expected_comps=500, params=None): + """ + def __init__(self, n_processes, dview=None, Ain=None, Cin=None, b_in=None, f_in=None, + params: Optional[CNMFParams] = None, skip_refinement: Optional[bool] = None, + remove_very_bad_comps: Optional[bool] = None, **param_kwargs): """ Constructor of CNMF objects @@ -107,14 +87,10 @@ def __init__(self, n_processes, k=5, gSig=[4, 4], gSiz=None, merge_thresh=0.8, p f_in - Used to build estimates - skip_refinement: boolean - If true it only performs one iteration of update spatial update temporal instead of two - - remove_very_bad_comps: boolean - Whether to remove components with very low values of component quality directly on the patch. - This might create some minor imprecisions, but can be important for performance because of bottlenecks - caused by handling many components (we have seen over 2000) that will need to be processed. + params: CNMFParams + Existing parameters to use (otherwise, they can be set afterwards with cnmf.params.change_params(...)) """ + logger = logging.getLogger('caiman') self.runmode = "CNMF" # Single field to query to determine where an hdf5 file comes from self.dview = dview # longer-term this should be removed from the CNMF object and moved to a RunContext @@ -123,10 +99,6 @@ def __init__(self, n_processes, k=5, gSig=[4, 4], gSiz=None, merge_thresh=0.8, p self.dims = None self.empty_merged = None - # these are member variables related to the CNMF workflow - self.skip_refinement = skip_refinement - self.remove_very_bad_comps = remove_very_bad_comps - self.provenance = [] # This will provide a rough record of the history of the object, largely with the intent of it # being useful in the serialized file form. The formatting for this will be a list of dicts, # the dicts all having at least the fields "event":str, "time":int, and "text":str @@ -135,36 +107,46 @@ def __init__(self, n_processes, k=5, gSig=[4, 4], gSiz=None, merge_thresh=0.8, p self.provenance.append({'event': 'create', 'time': int(time.time()), 'description': 'CNMF Object created'}) if params is None: - self.params = CNMFParams( - border_pix=border_pix, del_duplicates=del_duplicates, low_rank_background=low_rank_background, - memory_fact=memory_fact, n_processes=n_processes, nb_patch=nb_patch, only_init_patch=only_init_patch, - p_ssub=p_ssub, p_tsub=p_tsub, remove_very_bad_comps=remove_very_bad_comps, rf=rf, stride=stride, - check_nan=check_nan, n_pixels_per_process=n_pixels_per_process, - k=k, center_psf=center_psf, gSig=gSig, gSiz=gSiz, - init_iter=init_iter, method_init=method_init, min_corr=min_corr, min_pnr=min_pnr, - gnb=gnb, normalize_init=normalize_init, options_local_NMF=options_local_NMF, - ring_size_factor=ring_size_factor, rolling_length=rolling_length, rolling_sum=rolling_sum, - ssub=ssub, ssub_B=ssub_B, tsub=tsub, - num_blocks_per_run_spat=num_blocks_per_run_spat, - block_size_temp=block_size_temp, num_blocks_per_run_temp=num_blocks_per_run_temp, - update_background_components=update_background_components, - method_deconvolution=method_deconvolution, p=p, s_min=s_min, - do_merge=do_merge, merge_thresh=merge_thresh, - decay_time=decay_time, fr=fr, min_SNR=min_SNR, rval_thr=rval_thr, - N_samples_exceptionality=N_samples_exceptionality, batch_update_suff_stat=batch_update_suff_stat, - expected_comps=expected_comps, max_comp_update_shape=max_comp_update_shape, max_num_added=max_num_added, - min_num_trial=min_num_trial, minibatch_shape=minibatch_shape, minibatch_suff_stat=minibatch_suff_stat, - n_refit=n_refit, num_times_comp_updated=num_times_comp_updated, simultaneously=simultaneously, - sniper_mode=sniper_mode, test_both=test_both, thresh_CNN_noisy=thresh_CNN_noisy, - thresh_fitness_delta=thresh_fitness_delta, thresh_fitness_raw=thresh_fitness_raw, thresh_overlap=thresh_overlap, - update_num_comps=update_num_comps, use_dense=use_dense, use_peak_max=use_peak_max, alpha_snmf=alpha_snmf) + self.params = CNMFParams(**param_kwargs) else: self.params = params - params.set('patch', {'n_processes': n_processes}) + params.set('patch', {'n_processes': n_processes}, warn=False) + if param_kwargs: + logger.warning( + 'Ignoring extra parameters passed to CNMF constructor because a params object was passed. ' + 'If you want to update the params object, use params.change_params first.') + + # set skip_refinement and remove_very_bad_comps regardless of whether params was passed, + # to maintain legacy behavior + deprec_param_msg = 'Passing {0} to CNMF() is deprecated - use change_params({{"patch": {{"{0}": ...}}}}) instead.' + if skip_refinement is not None: + logger.warning(deprec_param_msg.format('skip_refinement')) + self.skip_refinement = skip_refinement + + if remove_very_bad_comps is not None: + logger.warning(deprec_param_msg.format('remove_very_bad_comps')) + self.remove_very_bad_comps = remove_very_bad_comps self.estimates = Estimates(A=Ain, C=Cin, b=b_in, f=f_in, dims=self.params.data['dims']) + @property + def skip_refinement(self) -> bool: + return self.params.patch.skip_refinement + + @skip_refinement.setter + def skip_refinement(self, val: bool): + self.params.change_params({'patch': {'skip_refinement': val}}) + + @property + def remove_very_bad_comps(self) -> bool: + return self.params.patch.remove_very_bad_comps + + @remove_very_bad_comps.setter + def remove_very_bad_comps(self, val: bool): + self.params.change_params({'patch': {'remove_very_bad_comps': val}}) + + def __str__(self): ret = f"Caiman CNMF Object. subfields:{list(self.__dict__.keys()) }" if hasattr(self.estimates, 'A') and self.estimates.A is not None: @@ -212,7 +194,10 @@ def fit_file(self, motion_correct=False, indices=None) -> None: if indices is None: indices = (slice(None), slice(None)) - fnames = self.params.get('data', 'fnames') + fnames = self.params.data.fnames + if fnames is None: + raise RuntimeError('No files were provided to fit (set on params.data.fnames)') + if os.path.exists(fnames[0]): _, extension = os.path.splitext(fnames[0])[:2] extension = extension.lower() @@ -229,15 +214,15 @@ def fit_file(self, motion_correct=False, indices=None) -> None: if np.isfortran(Yr): raise Exception('The file should be in C order (see save_memmap function)') else: - data_set_name = self.params.get('data', 'var_name_hdf5') + data_set_name = self.params.data.var_name_hdf5 if motion_correct: mc = MotionCorrect(fnames, dview=self.dview, **self.params.motion) mc.motion_correct(save_movie=True) fname_mc = mc.fname_tot_els if self.params.motion['pw_rigid'] else mc.fname_tot_rig - if self.params.get('motion', 'pw_rigid'): + if self.params.motion.pw_rigid: b0 = np.ceil(np.maximum(np.max(np.abs(mc.x_shifts_els)), np.max(np.abs(mc.y_shifts_els)))).astype(int) - if self.params.get('motion', 'is3D'): + if self.params.motion.is3D: self.estimates.shifts = [mc.x_shifts_els, mc.y_shifts_els, mc.z_shifts_els] else: self.estimates.shifts = [mc.x_shifts_els, mc.y_shifts_els] @@ -248,7 +233,7 @@ def fit_file(self, motion_correct=False, indices=None) -> None: # sub-optimal behavior. See # https://github.com/flatironinstitute/CaImAn/pull/618#discussion_r313960370 # for further details. - # b0 = 0 if self.params.get('motion', 'border_nan') == 'copy' else 0 + # b0 = 0 if self.params.motion.border_nan == 'copy' else 0 b0 = 0 fname_new = caiman.mmapping.save_memmap(fname_mc, base_name=base_name, order='C', var_name_hdf5=data_set_name, border_to_0=b0) @@ -278,8 +263,7 @@ def refit(self, images, dview=None): # We add the "history imported" note because the datestamp from the init of the new CNMF will be later than imported history (meaning right now) # so if you parse in list order you'll see a time-oddity here - cnm.params.patch['rf'] = None - cnm.params.patch['only_init'] = False + cnm.params.set('patch', {'rf': None, 'only_init': False}, warn=False) estimates = deepcopy(self.estimates) estimates.select_components(use_object=True) estimates.coordinates = None @@ -316,14 +300,15 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: dims_orig = images.shape[1:] dims_sliced = images[tuple(indices)].shape[1:] is_sliced = (dims_orig != dims_sliced) - if self.params.get('patch', 'rf') is None and (is_sliced or 'ndarray' in str(type(images))): + if self.params.patch.rf is None and (is_sliced or 'ndarray' in str(type(images))): images = images[tuple(indices)] self.dview = None logger.info("Parallel processing in a single patch is not available for data that is in memory or sliced") T = images.shape[0] - self.params.set('online', {'init_batch': T}) + self.params.set('online', {'init_batch': T}, warn=False) self.dims = images.shape[1:] + self.estimates.dims = self.dims Y = np.transpose(images, list(range(1, len(self.dims) + 1)) + [0]) Yr = np.transpose(np.reshape(images, (T, -1), order='F')) if np.isfortran(Yr): @@ -339,32 +324,27 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: except AttributeError: # if no memmapping because we're working with small data pass - logger.info(f"Using {self.params.get('patch', 'n_processes')} processes") - # FIXME The code below is really ugly and it's hard to tell if it's doing the right thing. - # These decisions should also probably be set higher up the call stack in some kind of a performance - # API (if we go with execution contexts, definitely there) - if self.params.get('preprocess', 'n_pixels_per_process') is None: - avail_memory_per_process = psutil.virtual_memory()[1] / 2.**30 / self.params.get('patch', 'n_processes') - mem_per_pix = 3.6977678498329843e-09 - npx_per_proc = int(avail_memory_per_process / 8. / mem_per_pix / T) - npx_per_proc = int(np.minimum(npx_per_proc, np.prod(self.dims) // self.params.get('patch', 'n_processes'))) - self.params.set('preprocess', {'n_pixels_per_process': npx_per_proc}) + logger.info(f"Using {self.params.patch.n_processes} processes") - self.params.set('spatial', {'n_pixels_per_process': self.params.get('preprocess', 'n_pixels_per_process')}) + npx_per_proc = self.params.spatial.n_pixels_per_process + if npx_per_proc is None: + npx_per_proc = estimate_n_pixels_per_process( + n_processes=self.params.patch.n_processes, T=T, dims=self.dims + ) - logger.info('using ' + str(self.params.get('preprocess', 'n_pixels_per_process')) + ' pixels per process') - logger.info('using ' + str(self.params.get('temporal', 'block_size_temp')) + ' block_size_temp') + logger.info(f'using {npx_per_proc} pixels per process') + logger.info(f'using {self.params.temporal.block_size_temp} block_size_temp') - if self.params.get('patch', 'rf') is None: # no patches + if self.params.patch.rf is None: # no patches logger.info('preprocessing ...') - Yr = self.preprocess(Yr) + Yr = self.preprocess(Yr, n_pixels_per_process=npx_per_proc) if self.estimates.A is None: logger.info('initializing ...') self.initialize(Y) - if self.params.get('patch', 'only_init'): # only return values after initialization - if not (self.params.get('init', 'method_init') == 'corr_pnr' and - self.params.get('init', 'ring_size_factor') is not None): + if self.params.patch.only_init: # only return values after initialization + if not (self.params.init.method_init == 'corr_pnr' and + self.params.init.ring_size_factor is not None): self.compute_residuals(Yr) self.estimates.bl = None self.estimates.c1 = None @@ -395,31 +375,26 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: return logger.info('update spatial ...') - self.update_spatial(Yr, use_init=True) + self.update_spatial(Yr, n_pixels_per_process=npx_per_proc) logger.info('update temporal ...') - if not self.skip_refinement: - # set this to zero for fast updating without deconvolution - self.params.set('temporal', {'p': 0}) + if self.skip_refinement: + logger.info('deconvolution...') + self.update_temporal(Yr) else: - self.params.set('temporal', {'p': self.params.get('preprocess', 'p')}) - logger.info('deconvolution ...') - - self.update_temporal(Yr) + # first use do_deconv=False for fast updating without deconvolution + self.update_temporal(Yr, do_deconv=False) - if not self.skip_refinement: logger.info('refinement...') - if self.params.get('merging', 'do_merge'): + if self.params.merging.do_merge: logger.info('merging components ...') self.merge_comps(Yr, mx=50, fast_merge=True) logger.info('Updating spatial ...') + self.update_spatial(Yr, n_pixels_per_process=npx_per_proc) - self.update_spatial(Yr, use_init=False) - # set it back to original value to perform full deconvolution - self.params.set('temporal', {'p': self.params.get('preprocess', 'p')}) logger.info('update temporal ...') - self.update_temporal(Yr, use_init=False) + self.update_temporal(Yr) # embed in the whole FOV if is_sliced: @@ -439,10 +414,8 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: self.estimates.b = b_FOV else: # use patches - if self.params.get('patch', 'stride') is None: - self.params.set('patch', {'stride': int(self.params.get('patch', 'rf') * 2 * .1)}) - logger.info( - ('Setting the stride to 10% of 2*rf automatically:' + str(self.params.get('patch', 'stride')))) + if self.params.patch.stride is None: + logger.info('Setting the stride to 10% of 2*rf automatically') # see rf2stride argument to run_CNMF_patches if not isinstance(images, np.memmap): raise Exception( @@ -457,11 +430,11 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: self.estimates.A, self.estimates.C, self.estimates.YrA, self.estimates.b, self.estimates.f, \ self.estimates.sn, self.estimates.optional_outputs = run_CNMF_patches( images.filename, self.dims + (T,), self.params, - dview=self.dview, memory_fact=self.params.get('patch', 'memory_fact'), - gnb=self.params.get('init', 'nb'), border_pix=self.params.get('patch', 'border_pix'), - low_rank_background=self.params.get('patch', 'low_rank_background'), - del_duplicates=self.params.get('patch', 'del_duplicates'), - indices=indices) + dview=self.dview, memory_fact=self.params.patch.memory_fact, + gnb=self.params.init.nb, border_pix=self.params.patch.border_pix, + low_rank_background=self.params.patch.low_rank_background, + del_duplicates=self.params.patch.del_duplicates, + indices=indices, rf2stride=lambda rf: int(rf * 2 * .1)) #print("D: Finished with run_CNMF_patches(), self.estimates.* are populated. Next step would be update_temporal() but first: Entering a shell.") #code.interact(local=dict(globals(), **locals()) ) @@ -474,31 +447,31 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: self.estimates.merged_ROIs = [0] - if self.params.get('init', 'center_psf'): # merge taking best neuron - if self.params.get('patch', 'nb_patch') > 0: + if self.params.init.center_psf: # merge taking best neuron + if self.params.patch.nb_patch > 0: while len(self.estimates.merged_ROIs) > 0: self.merge_comps(Yr, mx=np.inf, fast_merge=True) logger.info("update temporal") - self.update_temporal(Yr, use_init=False) + self.update_temporal(Yr) - self.params.set('spatial', {'se': np.ones((1,) * len(self.dims), dtype=np.uint8)}) logger.info('update spatial ...') - self.update_spatial(Yr, use_init=False) + # skip binary closing on original-resolution data + self.update_spatial(Yr, n_pixels_per_process=npx_per_proc, skip_closing=True) logger.info("update temporal") - self.update_temporal(Yr, use_init=False) + self.update_temporal(Yr) else: while len(self.estimates.merged_ROIs) > 0: self.merge_comps(Yr, mx=np.inf, fast_merge=True) - if self.params.get('init', 'nb') == 0: + if self.params.init.nb == 0: self.estimates.W, self.estimates.b0 = compute_W( Yr, self.estimates.A.toarray(), self.estimates.C, self.dims, - self.params.get('init', 'ring_size_factor') * - self.params.get('init', 'gSiz')[0], - ssub=self.params.get('init', 'ssub_B')) + self.params.init.ring_size_factor * + self.params.init.gSiz[0], + ssub=self.params.init.ssub_B) if len(self.estimates.C): self.deconvolve() @@ -510,7 +483,7 @@ def fit(self, images, indices=(slice(None), slice(None))) -> None: self.merge_comps(Yr, mx=np.inf) logger.info("Updating temporal components") - self.update_temporal(Yr, use_init=False) + self.update_temporal(Yr) self.estimates.normalize_components() @@ -542,12 +515,12 @@ def remove_components(self, ind_rm): self.N, self.estimates.noisyC, self.estimates.OASISinstances, self.estimates.C_on,\ expected_comps, self.ind_A,\ self.estimates.groups, self.estimates.AtA = remove_components_online( - ind_rm, self.params.get('init', 'nb'), self.estimates.Ab, - self.params.get('online', 'use_dense'), self.estimates.Ab_dense, + ind_rm, self.params.init.nb, self.estimates.Ab, + self.params.online.use_dense, self.estimates.Ab_dense, self.estimates.AtA, self.estimates.CY, self.estimates.CC, self.M, self.N, self.estimates.noisyC, self.estimates.OASISinstances, self.estimates.C_on, - self.params.get('online', 'expected_comps')) - self.params.set('online', {'expected_comps': expected_comps}) + self.params.online.expected_comps) + self.params.set('online', {'expected_comps': expected_comps}, warn=False) def compute_residuals(self, Yr) -> None: """ @@ -561,7 +534,7 @@ def compute_residuals(self, Yr) -> None: """ self.provenance.append({'event': 'compute_residuals', 'time': int(time.time()), 'description': f'Populated YrA with Computed/stored residuals'}) - block_size, num_blocks_per_run = self.params.get('temporal', 'block_size_temp'), self.params.get('temporal', 'num_blocks_per_run_temp') + block_size, num_blocks_per_run = self.params.temporal.block_size_temp, self.params.temporal.num_blocks_per_run_temp if 'csc_matrix' not in str(type(self.estimates.A)): self.estimates.A = scipy.sparse.csc_matrix(self.estimates.A) if 'array' not in str(type(self.estimates.b)): @@ -592,14 +565,14 @@ def deconvolve(self, p=None, method_deconvolution=None, bas_nonneg=None, constrained foopsi. """ - p = self.params.get('preprocess', 'p') if p is None else p - method_deconvolution = (self.params.get('temporal', 'method_deconvolution') + p = self.params.preprocess.p if p is None else p + method_deconvolution = (self.params.temporal.method_deconvolution if method_deconvolution is None else method_deconvolution) - bas_nonneg = (self.params.get('temporal', 'bas_nonneg') + bas_nonneg = (self.params.temporal.bas_nonneg if bas_nonneg is None else bas_nonneg) - noise_method = (self.params.get('temporal', 'noise_method') + noise_method = (self.params.temporal.noise_method if noise_method is None else noise_method) - s_min = self.params.get('temporal', 's_min') if s_min is None else s_min + s_min = self.params.temporal.s_min if s_min is None else s_min F = self.estimates.C + self.estimates.YrA args = dict() @@ -609,8 +582,8 @@ def deconvolve(self, p=None, method_deconvolution=None, bas_nonneg=None, args['noise_method'] = noise_method args['s_min'] = s_min args['optimize_g'] = optimize_g - args['noise_range'] = self.params.get('temporal', 'noise_range') - args['fudge_factor'] = self.params.get('temporal', 'fudge_factor') + args['noise_range'] = self.params.temporal.noise_range + args['fudge_factor'] = self.params.temporal.fudge_factor args_in = [(F[jj], None, jj, None, None, None, None, args) for jj in range(F.shape[0])] @@ -637,56 +610,67 @@ def deconvolve(self, p=None, method_deconvolution=None, bas_nonneg=None, self.estimates.lam = [results[8][i] for i in order] self.estimates.YrA = F - self.estimates.C - def update_temporal(self, Y, use_init=True, **kwargs) -> None: + def update_temporal(self, Y, use_init=None, do_deconv=True, **kwargs) -> None: """Updates temporal components Args: Y: np.array (d1*d2) x T input data - """ - lc = locals() - pr = inspect.signature(self.update_temporal) - params = [k for k, v in pr.parameters.items() if '=' in str(v)] - kw2 = {k: lc[k] for k in params} - kwargs_new = {**kw2, **kwargs} - self.params.set('temporal', kwargs_new) + logger = logging.getLogger('caiman') + + if use_init is not None: + logger.warning('The use_init parameter is deprecated and has no effect.') + + if kwargs: + self.params.change_params({'temporal': kwargs}) + + # if not do_deconv, override p temporarily + temporal_params = self.params.temporal + if not do_deconv: + temporal_params = {**temporal_params, 'p': 0} + self.provenance.append({'event': 'update_temporal', 'time': int(time.time()), 'description': f'Updated temporal components based on provided Y'}) self.estimates.C, self.estimates.A, self.estimates.b, self.estimates.f, self.estimates.S, \ self.estimates.bl, self.estimates.c1, self.estimates.neurons_sn, \ self.estimates.g, self.estimates.YrA, self.estimates.lam = update_temporal_components( Y, self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f, dview=self.dview, - **self.params.get_group('temporal')) + **temporal_params) self.estimates.R = self.estimates.YrA - def update_spatial(self, Y, use_init=True, **kwargs) -> None: + def update_spatial(self, Y, use_init=None, n_pixels_per_process: Optional[int] = None, skip_closing=False, **kwargs) -> None: """Updates spatial components modifies values self.estimates.A, self.estimates.b possibly self.estimates.C, self.estimates.f Args: Y: np.array (d1*d2) x T input data - use_init: bool - use Cin, f_in for computing A, b otherwise use C, f - """ - lc = locals() - pr = inspect.signature(self.update_spatial) - params = [k for k, v in pr.parameters.items() if '=' in str(v)] - kw2 = {k: lc[k] for k in params} - kwargs_new = {**kw2, **kwargs} - self.params.set('spatial', kwargs_new) - for key in kwargs_new: - if hasattr(self, key): - setattr(self, key, kwargs_new[key]) + logger = logging.getLogger('caiman') + + if use_init is not None: + logger.warning('The use_init parameter is deprecated and has no effect.') + + if kwargs: + self.params.change_params({'spatial': kwargs}) + for key in kwargs: + if hasattr(self, key): + setattr(self, key, kwargs[key]) + + spatial_params = self.params.spatial + if n_pixels_per_process is not None: + spatial_params = {**spatial_params, 'n_pixels_per_process': n_pixels_per_process} + + if skip_closing: + spatial_params = {**spatial_params, 'se': np.ones((1, 1), dtype=np.uint8)} self.provenance.append({'event': 'update_spatial', 'time': int(time.time()), 'description': f'Updated spatial components based on provided Y'}) self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f =\ update_spatial_components(Y, C=self.estimates.C, f=self.estimates.f, A_in=self.estimates.A, b_in=self.estimates.b, dview=self.dview, - sn=self.estimates.sn, dims=self.dims, **self.params.get_group('spatial')) + sn=self.estimates.sn, dims=self.dims, **spatial_params) def merge_comps(self, Y, mx=50, fast_merge=True) -> None: """merges components @@ -700,19 +684,19 @@ def merge_comps(self, Y, mx=50, fast_merge=True) -> None: self.estimates.f, self.estimates.S, self.estimates.sn, self.params.get_group('temporal'), self.params.get_group('spatial'), dview=self.dview, bl=self.estimates.bl, c1=self.estimates.c1, sn=self.estimates.neurons_sn, - g=self.estimates.g, thr=self.params.get('merging', 'merge_thr'), mx=mx, - fast_merge=fast_merge, merge_parallel=self.params.get('merging', 'merge_parallel')) + g=self.estimates.g, thr=self.params.merging.merge_thr, mx=mx, + fast_merge=fast_merge, merge_parallel=self.params.merging.merge_parallel) def initialize(self, Y, **kwargs) -> None: """Component initialization """ - self.params.set('init', kwargs) + self.params.set('init', kwargs, warn=False) estim = self.estimates - if (self.params.get('init', 'method_init') == 'corr_pnr' and - self.params.get('init', 'ring_size_factor') is not None): + if (self.params.init.method_init == 'corr_pnr' and + self.params.init.ring_size_factor is not None): estim.A, estim.C, estim.b, estim.f, estim.center, \ extra_1p = initialize_components( - Y, sn=estim.sn, options_total=self.params.to_dict(), + Y, sn=estim.sn, options_total=self.params, **self.params.get_group('init')) try: estim.S, estim.bl, estim.c1, estim.neurons_sn, \ @@ -722,12 +706,12 @@ def initialize(self, Y, **kwargs) -> None: estim.g, estim.YrA, estim.lam, estim.W, estim.b0 = extra_1p else: estim.A, estim.C, estim.b, estim.f, estim.center =\ - initialize_components(Y, sn=estim.sn, options_total=self.params.to_dict(), + initialize_components(Y, sn=estim.sn, options_total=self.params, **self.params.get_group('init')) self.estimates = estim - def preprocess(self, Yr): + def preprocess(self, Yr, n_pixels_per_process: Optional[int] = None): """ Examines data to remove corrupted pixels and computes the noise level estimate for each pixel. @@ -739,10 +723,14 @@ def preprocess(self, Yr): """ # TODO Weird that this returns Yr + preproc_params = self.params.preprocess + if n_pixels_per_process is not None: + preproc_params = {**preproc_params, 'n_pixels_per_process': n_pixels_per_process} + self.provenance.append({'event': 'preprocess', 'time': int(time.time()), 'description': f'Removed bad pixels and computed per-pixel noise based on provided Yr'}) Yr, self.estimates.sn, self.estimates.g, self.estimates.psx = preprocess_data( - Yr, dview=self.dview, **self.params.get_group('preprocess')) + Yr, dview=self.dview, **preproc_params) return Yr @@ -768,9 +756,7 @@ def load_CNMF(filename:str, n_processes=1, dview=None): for key, val in load_dict_from_hdf5(filename).items(): if key == 'params': - prms = CNMFParams() - for subdict in val.keys(): - prms.set(subdict, val[subdict]) + prms = CNMFParams(**val) setattr(new_obj, key, prms) elif key == 'dview': setattr(new_obj, key, dview) @@ -778,7 +764,7 @@ def load_CNMF(filename:str, n_processes=1, dview=None): estims = Estimates() for kk, vv in val.items(): if kk == 'discarded_components': - if vv is not None and vv != b'NoneType': + if vv is not None and not all_same(vv, b'NoneType'): discarded_components = Estimates() for kk__, vv__ in vv.items(): setattr(discarded_components, kk__, vv__) @@ -789,7 +775,7 @@ def load_CNMF(filename:str, n_processes=1, dview=None): setattr(new_obj, key, estims) else: setattr(new_obj, key, val) - if new_obj.estimates.dims is None or new_obj.estimates.dims == b'NoneType': + if new_obj.estimates.dims is None or all_same(new_obj.estimates.dims, b'NoneType'): new_obj.estimates.dims = new_obj.dims elif file_extension == '.nwb': with pynwb.NWBHDF5IO(filename, 'r') as io: diff --git a/caiman/source_extraction/cnmf/estimates.py b/caiman/source_extraction/cnmf/estimates.py index cf296071c..c0e5db3fa 100644 --- a/caiman/source_extraction/cnmf/estimates.py +++ b/caiman/source_extraction/cnmf/estimates.py @@ -1139,7 +1139,7 @@ def filter_components(self, imgs, params, new_dict={}, dview=None, select_mode:s CNN classifier values for each component """ dims = imgs.shape[1:] - params.set('quality', new_dict) + params.set('quality', new_dict, warn=False) opts = params.get_group('quality') flag = [a is None for a in [self.r_values, self.SNR_comp, self.cnn_preds]] diff --git a/caiman/source_extraction/cnmf/initialization.py b/caiman/source_extraction/cnmf/initialization.py index f7a57c83b..e5068892c 100644 --- a/caiman/source_extraction/cnmf/initialization.py +++ b/caiman/source_extraction/cnmf/initialization.py @@ -20,10 +20,12 @@ from sklearn.exceptions import ConvergenceWarning from sklearn.utils.extmath import randomized_svd, squared_norm, randomized_range_finder import sys +from typing import Sequence, Optional import warnings import caiman from caiman.source_extraction.cnmf.deconvolution import constrained_foopsi +from caiman.source_extraction.cnmf.params import CNMFParams from caiman.source_extraction.cnmf.pre_processing import get_noise_fft, get_noise_welch from caiman.source_extraction.cnmf.spatial import circular_constraint, connectivity_constraint from caiman.utils.stats import pd_solve, compressive_nmf @@ -70,7 +72,7 @@ def decimate_last_axis(y, sub): return Y_ds -def downscale(Y, ds, opencv=False): +def downscale(Y, ds: Sequence[int], opencv=False): """downscaling without zero padding faster version of skimage.transform._warps.block_reduce(Y, ds, np.nanmean, np.nan)""" logger = logging.getLogger("caiman") @@ -81,8 +83,8 @@ def downscale(Y, ds, opencv=False): Y = Y[..., None] ds = tuple(ds) + (1,) else: - Y_ds = caiman.base.movies.movie(Y.transpose(2, 0, 1)).resize(fx=1. / ds[0], fy=1. / ds[1], fz=1. / ds[2], - interpolation=cv2.INTER_AREA).transpose(1, 2, 0) + Y_ds = caiman.movie(Y.transpose(2, 0, 1)).resize( + fx=1. / ds[0], fy=1. / ds[1], fz=1. / ds[2], interpolation=cv2.INTER_AREA).transpose(1, 2, 0) logger.info('Downscaling using OpenCV') else: if d > 3: @@ -252,8 +254,8 @@ def initialize_components(Y, K=30, gSig=[5, 5], gSiz=None, ssub=1, tsub=1, nIter sn: ndarray per pixel noise - options_total: dict - the option dictionary + options_total: CNMFParams + full options object ssub_B: int, optional downsampling factor for 1-photon imaging background computation @@ -475,8 +477,7 @@ def ICA_PCA(Y_ds, nr, sigma_smooth=(.5, .5, .5), truncate=2, fun='logcosh', if masks.size > 0: - C_in = caiman.base.movies.movie( - m1).extract_traces_from_masks(np.array(masks)).T + C_in = caiman.movie(m1).extract_traces_from_masks(np.array(masks)).T A_in = np.reshape(masks, [-1, d1 * d2], order='F').T else: @@ -1156,9 +1157,9 @@ def HALS4shape(Yr, A, C, iters=2): @profile def greedyROI_corr(Y, Y_ds, max_number=None, gSiz=None, gSig=None, center_psf=True, min_corr=None, min_pnr=None, seed_method='auto', - min_pixel=3, bd=0, thresh_init=2, ring_size_factor=None, nb=1, options=None, - sn=None, save_video=False, video_name='initialization.mp4', ssub=1, - ssub_B=2, init_iter=2): + min_pixel=3, bd=0, thresh_init=2, ring_size_factor=None, nb=1, + options: Optional[CNMFParams] = None, sn=None, save_video=False, + video_name='initialization.mp4', ssub=1, ssub_B=2, init_iter=2): """ initialize neurons based on pixels' local correlations and peak-to-noise ratios. @@ -1199,9 +1200,12 @@ def greedyROI_corr(Y, Y_ds, max_number=None, gSiz=None, gSig=None, center_psf=Tr if min_corr is None or min_pnr is None: raise Exception( 'Either min_corr or min_pnr are None. Both of them must be real numbers.') + + if options is None: + raise ValueError('options is required to be a CNMFParams object.') logger.info('One photon initialization (GreedyCorr)') - o = options['temporal'].copy() + o = options.temporal.copy() o['s_min'] = None if o['p'] > 1: o['p'] = 1 @@ -1247,7 +1251,7 @@ def compute_B(b0, W, B): # actually computes -B to efficiently compute Y-B in p sn=np.sqrt(downscale((sn**2).reshape(dims, order='F'), tuple([ssub] * len(dims))).ravel() / tsub) / ssub, b_in=np.zeros((d1 * d2, 0), np.float32), - dview=None, dims=(d1, d2), **options['spatial']) + dview=None, dims=(d1, d2), **options.spatial) logger.info('Updating temporal components') C, A = caiman.source_extraction.cnmf.temporal.update_temporal_components( B, spr.csc_matrix(A, dtype=np.float32), @@ -1277,8 +1281,8 @@ def compute_B(b0, W, B): # actually computes -B to efficiently compute Y-B in p # 1st iteration on decimated data logger.info('Merging components') A, C = caiman.source_extraction.cnmf.merging.merge_components( - B, A, [], C, None, [], C, [], o, options['spatial'], - dview=None, thr=options['merging']['merge_thr'], mx=np.inf, fast_merge=True)[:2] + B, A, [], C, None, [], C, [], o, options.spatial, + dview=None, thr=options.merging.merge_thr, mx=np.inf, fast_merge=True)[:2] A = A.astype(np.float32) C = C.astype(np.float32) logger.info('Updating spatial components') @@ -1287,7 +1291,7 @@ def compute_B(b0, W, B): # actually computes -B to efficiently compute Y-B in p sn=np.sqrt(downscale((sn**2).reshape(dims, order='F'), tuple([ssub] * len(dims))).ravel() / tsub) / ssub, b_in=np.zeros((d1 * d2, 0), np.float32), - dview=None, dims=(d1, d2), **options['spatial']) + dview=None, dims=(d1, d2), **options.spatial) A = A.astype(np.float32) logger.info('Updating temporal components') C, A = caiman.source_extraction.cnmf.temporal.update_temporal_components( @@ -1326,22 +1330,25 @@ def compute_B(b0, W, B): # actually computes -B to efficiently compute Y-B in p logger.info('Merging components') A, C = caiman.source_extraction.cnmf.merging.merge_components( - B, A, [], C, None, [], C, [], o, options['spatial'], - dview=None, thr=options['merging']['merge_thr'], mx=np.inf, fast_merge=True)[:2] + B, A, [], C, None, [], C, [], o, options.spatial, + dview=None, thr=options.merging.merge_thr, mx=np.inf, fast_merge=True)[:2] A = A.astype(np.float32) C = C.astype(np.float32) + logger.info('Updating spatial components') - options['spatial']['se'] = np.ones((1,) * len((d1, d2)), dtype=np.uint8) + # skip binary closing on original-resolution data + spatial_opts = {**options.spatial, 'se': np.ones((1, 1), dtype=np.uint8)} A, _, C, _ = caiman.source_extraction.cnmf.spatial.update_spatial_components( B, C=C, f=np.zeros((0, T), np.float32), A_in=A, sn=sn, b_in=np.zeros((np.prod(dims), 0), np.float32), - dview=None, dims=dims, **options['spatial']) + dview=None, dims=dims, **spatial_opts) + logger.info('Updating temporal components') C, A, b__, f__, S, bl, c1, neurons_sn, g1, YrA, lam__ = \ caiman.source_extraction.cnmf.temporal.update_temporal_components( B, spr.csc_matrix(A, dtype=np.float32), np.zeros((np.prod(dims), 0), np.float32), C, np.zeros((0, T), np.float32), - dview=None, bl=None, c1=None, sn=None, g=None, **options['temporal']) + dview=None, bl=None, c1=None, sn=None, g=None, **options.temporal) A = A.toarray() if nb > 0 or nb == -1: diff --git a/caiman/source_extraction/cnmf/map_reduce.py b/caiman/source_extraction/cnmf/map_reduce.py index d9b3c4180..3ce41533e 100644 --- a/caiman/source_extraction/cnmf/map_reduce.py +++ b/caiman/source_extraction/cnmf/map_reduce.py @@ -11,11 +11,12 @@ import scipy from sklearn.decomposition import NMF import time +from typing import Sequence, Callable -from caiman.cluster import extract_patch_coordinates from caiman.mmapping import load_memmap +from caiman.source_extraction.cnmf.params import CNMFParams -def cnmf_patches(args_in): +def cnmf_patches(args_in: tuple[str, np.ndarray, tuple[int, ...], CNMFParams]): """Function that is run for each patches Will be called @@ -91,21 +92,21 @@ def cnmf_patches(args_in): slices.insert(0, slice(timesteps)) images = np.reshape(Yr.T, [timesteps] + list(dims), order='F') - if params.get('patch', 'in_memory'): + if params.patch.in_memory: images = np.array(images[tuple(slices)], dtype=np.float32) else: - images = images[slices] + images = images[tuple(slices)] logger.debug(name_log+'file loaded') if (np.sum(np.abs(np.diff(images.reshape(timesteps, -1).T)))) > 0.1: opts = copy(params) - opts.set('patch', {'n_processes': 1, 'rf': None, 'stride': None}) - for group in ('init', 'temporal', 'spatial'): - opts.set(group, {'nb': params.get('patch', 'nb_patch')}) - for group in ('preprocess', 'temporal'): - opts.set(group, {'p': params.get('patch', 'p_patch')}) + opts.change_params({ + 'patch': {'n_processes': 1, 'rf': None, 'stride': None}, + 'init': {'nb': opts.patch.nb_patch}, + 'temporal': {'p': opts.patch.p_patch}, + }) cnm = CNMF(n_processes=1, params=opts) @@ -118,13 +119,13 @@ def cnmf_patches(args_in): else: return None -def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, +def run_CNMF_patches(file_name, shape: tuple[int, ...], params: CNMFParams, gnb=1, dview=None, memory_fact=1, border_pix=0, low_rank_background=True, - del_duplicates=False, indices=[slice(None)]*3): + del_duplicates=False, indices=[slice(None)]*3, + rf2stride: Callable[[int], int] = lambda rf: 4): """Function that runs CNMF in patches Either in parallel or sequentially, and return the result for each. - It requires that ipyparallel is running Will basically initialize everything in order to compute on patches then call a function in parallel that will recreate the cnmf object and fit the values. @@ -165,6 +166,10 @@ def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, indices: List[slice] TODO + rf2stride: Callable[[int], int] + factory for default stride as a function of rf along each dimension. + TODO maybe eliminate this if nobody relies on the current default (which is different from in CNMF.fit()) + Returns: A_tot: matrix containing all the components from all the patches @@ -190,27 +195,28 @@ def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, d = np.prod(dims) T = shape[-1] - rf = params.get('patch', 'rf') + rf = params.patch.rf if rf is None: rf = 16 - if np.isscalar(rf): - rfs = [rf] * len(dims) + + if isinstance(rf, Sequence): + rfs = list(rf) else: - rfs = rf + rfs = [rf] * len(dims) - stride = params.get('patch', 'stride') + stride = params.patch.stride if stride is None: - stride = 4 - if np.isscalar(stride): - strides = [stride] * len(dims) + strides = [rf2stride(rf) for rf in rfs] + elif isinstance(stride, Sequence): + strides = list(stride) else: - strides = stride + strides = [stride] * len(dims) params_copy = deepcopy(params) npx_per_proc = np.prod(rfs) // memory_fact - params_copy.set('preprocess', {'n_pixels_per_process': npx_per_proc}) - params_copy.set('spatial', {'n_pixels_per_process': npx_per_proc}) - params_copy.set('temporal', {'n_pixels_per_process': npx_per_proc}) + params_copy.change_params({ + 'spatial': {'n_pixels_per_process': npx_per_proc} + }) idx_flat, idx_2d = extract_patch_coordinates( dims, rfs, strides, border_pix=border_pix, indices=indices[1:]) @@ -350,7 +356,7 @@ def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, idx_tot_A.append(idx_) idx_ptr_A.append(len(idx_)) C_tot[count, :] = C[ii, :] - if params.get('init', 'center_psf'): + if S_tot is not None: S_tot[count, :] = S[ii, :] YrA_tot[count, :] = YrA[ii, :] id_patch_tot.append(patch_id) @@ -480,3 +486,73 @@ def run_CNMF_patches(file_name, shape, params, gnb=1, dview=None, logger.info("Constructing background DONE") return A_tot, C_tot, YrA_tot, b, f, sn_tot, optional_outputs + + +def extract_patch_coordinates(dims: tuple, + rf: Sequence[int], + stride: Sequence[int], + 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: Sequence of int + dimensions of the original matrix that will be divided in patches + + rf: Sequence 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 + """ + 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 \ No newline at end of file diff --git a/caiman/source_extraction/cnmf/merging.py b/caiman/source_extraction/cnmf/merging.py index d2f1c93b5..78001a089 100644 --- a/caiman/source_extraction/cnmf/merging.py +++ b/caiman/source_extraction/cnmf/merging.py @@ -10,10 +10,6 @@ from scipy.sparse import csgraph, csc_matrix, lil_matrix, csr_matrix from caiman.source_extraction.cnmf.deconvolution import constrained_foopsi -from caiman.source_extraction.cnmf.spatial import update_spatial_components, threshold_components -from caiman.source_extraction.cnmf.temporal import update_temporal_components -from caiman.source_extraction.cnmf.utilities import update_order_greedy - def merge_components(Y, A, b, C, R, f, S, sn_pix, temporal_params, diff --git a/caiman/source_extraction/cnmf/online_cnmf.py b/caiman/source_extraction/cnmf/online_cnmf.py index 974566608..622a5a5a1 100644 --- a/caiman/source_extraction/cnmf/online_cnmf.py +++ b/caiman/source_extraction/cnmf/online_cnmf.py @@ -180,11 +180,11 @@ def _prepare_object(self, Yr, T, new_dims=None, idx_components=None): self.M = self.params.get('init', 'nb') + self.N if not self.params.get('online', 'update_num_comps'): - self.params.set('online', {'expected_comps': self.N}) + self.params.set('online', {'expected_comps': self.N}, warn=False) elif (self.params.get('online', 'expected_comps') <= self.N + self.params.get('online', 'max_num_added')): self.params.set('online', {'expected_comps': self.N + - self.params.get('online', 'max_num_added') + 200}) + self.params.get('online', 'max_num_added') + 200}, warn=False) expected_comps = self.params.get('online', 'expected_comps') if Yr.shape[-1] != self.params.get('online', 'init_batch'): @@ -300,7 +300,7 @@ def _prepare_object(self, Yr, T, new_dims=None, idx_components=None): if not self.is1p: self.params.set('init', {'gSiz': np.add(np.multiply(np.ceil( - self.params.get('init', 'gSig')).astype(int), 2), 1)}) + self.params.get('init', 'gSig')).astype(int), 2), 1)}, warn=False) self.estimates.Yr_buf = RingBuffer(Yr[:, self.params.get('online', 'init_batch') - self.params.get('online', 'minibatch_shape'): self.params.get('online', 'init_batch')].T.copy(), self.params.get('online', 'minibatch_shape')) @@ -360,10 +360,10 @@ def _prepare_object(self, Yr, T, new_dims=None, idx_components=None): if self.params.get('online', 'path_to_model') is None or self.params.get('online', 'sniper_mode') is False: loaded_model = None - self.params.set('online', {'sniper_mode': False}) + self.params.set('online', {'sniper_mode': False}, warn=False) else: logger.info('Using Keras with PyTorch backend') - model_name = self.params.get('online', 'path_to_model').split(".")[0] # Remove extension + model_name = os.path.splitext(self.params.get('online', 'path_to_model'))[0] # Remove extension if os.path.isfile(os.path.join(caiman_datadir(), model_name + ".pkl")): with open(os.path.join(caiman_datadir(), model_name + ".pkl"), 'rb') as f: @@ -603,7 +603,7 @@ def fit_next(self, t, frame_in, num_iters_hals=3): self.M += num_added if self.N + self.params.get('online', 'max_num_added') > expected_comps: expected_comps += 200 - self.params.set('online', {'expected_comps': expected_comps}) + self.params.set('online', {'expected_comps': expected_comps}, warn=False) self.estimates.CY.resize( [expected_comps + nb_, self.estimates.CY.shape[-1]]) self.estimates.C_on.resize( @@ -968,7 +968,7 @@ def initialize_online(self, model_LN=None, T=None): k=self.params.get('init', 'K'), gnb=self.params.get('init', 'nb'), method_init=self.params.get('init', 'method_init'), sn=self.estimates.sn, gSig=self.params.get('init', 'gSig'), return_object=False, - options_total=self.params.to_dict(), **init) + options_total=self.params, **init) if is1p: (self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f, self.estimates.YrA, self.estimates.W, self.estimates.b0) = tmp @@ -1024,7 +1024,7 @@ def initialize_online(self, model_LN=None, T=None): _, Ts = caiman.base.movies.get_file_size(fls, var_name_hdf5=self.params.get('data', 'var_name_hdf5')) dims = Y.shape[1:] - self.params.set('data', {'dims': dims}) + self.params.set('data', {'dims': dims}, warn=False) T1 = np.array(Ts).sum()*self.params.get('online', 'epochs') if T is None else T self._prepare_object(Yr, T1) if opts['show_movie']: @@ -1106,8 +1106,9 @@ def mc_next(self, t: int, frame: np.ndarray) -> np.ndarray: # tile_and_correct[_3d] and motion_correct_iteration[_fast] return the shifts needed to apply to get the corrected frame shift = tuple(-np.array(shift)) else: + max_shift_ds = int(self.params.online.max_shifts_online / self.params.online.ds_factor) frame_cor, shift = motion_correct_iteration_fast( - frame, templ, *(self.params.get('online', 'max_shifts_online'),)*2) + frame, templ, max_shift_ds, max_shift_ds) if self.is1p: M = np.float32([[1, 0, shift[1]], [0, 1, shift[0]]]) frame_cor = cv2.warpAffine(frame_orig, M, frame.shape[::-1], @@ -1181,7 +1182,7 @@ def fit_online(self, **kwargs): patience=self.params.get('ring_CNN', 'patience'), schedule=sch) logger.info(f'Training complete. Model saved in {path_to_model}.') - self.params.set('ring_CNN', {'path_to_model': path_to_model}) + self.params.set('ring_CNN', {'path_to_model': path_to_model}, warn=False) else: model_LN = None @@ -1209,7 +1210,7 @@ def fit_online(self, **kwargs): # Iterate through the epochs for iter in range(epochs): if iter == epochs - 1 and self.params.get('online', 'stop_detection'): - self.params.set('online', {'update_num_comps': False}) + self.params.set('online', {'update_num_comps': False}, warn=False) logger.info(f"Searching for new components set to: {self.params.get('online', 'update_num_comps')}") if iter > 0: # if not on first epoch process all files from scratch @@ -1333,7 +1334,7 @@ def fit_online(self, **kwargs): b0 = cv2.resize(b0, dims[::-1]) self.estimates.b0 = b0.reshape((-1, 1), order='F') - self.params.set('data', {'dims': dims}) + self.params.set('data', {'dims': dims}, warn=False) self.estimates.dims = dims if self.params.get('online', 'save_online_movie'): @@ -1520,7 +1521,7 @@ def bare_initialization(Y, init_batch=1000, k=1, method_init='greedy_roi', gnb=1 cnm_init.estimates.neurons_sn = np.std(YrA, axis=-1) cnm_init.estimates.lam = np.zeros(k) cnm_init.dims = Y.shape[:-1] - cnm_init.params.set('online', {'init_batch': init_batch}) + cnm_init.params.set('online', {'init_batch': init_batch}, warn=False) return cnm_init else: try: # XXX Can this try actually fail? @@ -1623,7 +1624,7 @@ def seeded_initialization(Y, Ain, dims=None, init_batch=1000, order_init=None, g cnm_init.estimates.neurons_sn = np.std(YrA, axis=-1) cnm_init.estimates.lam = np.zeros(nr) cnm_init.dims = Y.shape[:-1] - cnm_init.params.set('online', {'init_batch': init_batch}) + cnm_init.params.set('online', {'init_batch': init_batch}, warn=False) return cnm_init else: diff --git a/caiman/source_extraction/cnmf/params.py b/caiman/source_extraction/cnmf/params.py index bdd5e5a5b..b64c26ebb 100644 --- a/caiman/source_extraction/cnmf/params.py +++ b/caiman/source_extraction/cnmf/params.py @@ -1,78 +1,784 @@ #!/usr/bin/env python +from dataclasses import fields, InitVar +from functools import cache, cached_property import importlib.metadata import json import logging +import math import numpy as np import os +from pathlib import Path from pprint import pformat -import scipy +from pydantic import ( + ConfigDict, TypeAdapter, BeforeValidator, AfterValidator, InstanceOf, + PlainValidator, PlainSerializer, ValidationError, ValidationInfo, + WithJsonSchema, Field, field_validator, computed_field, model_validator) +from pydantic.dataclasses import dataclass +from pydantic.fields import FieldInfo +from pydantic.json_schema import SkipJsonSchema, PydanticJsonSchemaWarning +from pydantic_core import ArgsKwargs +import scipy.special from scipy.ndimage import generate_binary_structure, iterate_structure -from typing import Optional +from tabulate import tabulate +from typing import (Optional, Any, Union, Literal, Annotated, Callable, + Mapping, Iterator, TypeVar, ClassVar, cast, Type) +import warnings import caiman.base.movies -import caiman.utils.utils from caiman.paths import caiman_datadir -from caiman.source_extraction.cnmf.utilities import dict_compare +from caiman.source_extraction.cnmf import utilities +import caiman.utils.utils + + +try: + from pydantic import ValidateAs +except ImportError: + # polyfill for pydantic < 2.12 + _FromTypeT = TypeVar('_FromTypeT') + def ValidateAs(from_type: type[_FromTypeT], /, instantiation_hook: Callable[[_FromTypeT], Any]) -> Any: + def validate_as_validator(obj: Any) -> Any: + ta = TypeAdapter(from_type) + validated = ta.validate_python(obj) + return instantiation_hook(validated) + return PlainValidator(validate_as_validator) + + +# deal with 'NoneType', b'NoneType' strings +def interpret_string_none(obj: Any) -> Any: + if (isinstance(obj, str) and obj in ['None', 'NoneType'] + or isinstance(obj, bytes) and obj in [b'None', b'NoneType']): + return None + return obj + +SafeNone = Annotated[None, BeforeValidator(interpret_string_none)] +SafeAny = Annotated[Any, BeforeValidator(interpret_string_none)] + +T = TypeVar('T') +SafeOptional = Union[SafeNone, T] + + +# validation/serialization of types not supported by pydantic out of the box +NDArray = Annotated[ + InstanceOf[np.ndarray], # after applying np.asarray, just check that it is the right type + BeforeValidator(np.asarray), + PlainSerializer(lambda x: x.tolist()), + WithJsonSchema({}) +] + + +# deal with slices, potentially other objects that are saved as bytes (note should only be used on trusted data!) +def eval_bytes(obj: Any) -> Any: + if isinstance(obj, bytes): + return eval(obj.decode('utf-8')) + return obj + + +def preprocess_intslice(obj: Any) -> Any: + obj = eval_bytes(obj) + if isinstance(obj, slice): + obj = (obj.start, obj.stop, obj.step) + return obj + +IntSlice = Annotated[ + slice, + # anything convertible to a len-3 tuple of int or None, with 'NoneType' conversion, can be interpreted as a slice + ValidateAs(tuple[SafeOptional[int], SafeOptional[int], SafeOptional[int]], lambda tup: slice(*tup)), + BeforeValidator(preprocess_intslice), + # serialize as a tuple + PlainSerializer(lambda sl: (sl.start, sl.stop, sl.step)), + WithJsonSchema(TypeAdapter(tuple[Optional[int], Optional[int], Optional[int]]).json_schema()) +] + + +# string pre-processing to use for string literals +LiteralType = TypeVar('LiteralType', bound=str) +LitStr = Annotated[LiteralType, BeforeValidator(TypeAdapter(str).validate_python)] + + +# automatically package string in list, for fnames +ItemType = TypeVar('ItemType') +AutoListStr = Union[list[str], # first try parsing as the list of the desired type + Annotated[list[str], ValidateAs(str, lambda x: [x])] # otherwise pack in list +] + + +# for gSiz, potentially other values that have to be odd integers +OddInt = Annotated[int, AfterValidator(lambda x: x + 1 if x % 2 == 0 else x)] + + +# ("Self" type for python < 3.11) +GPSelf = TypeVar('GPSelf', bound='GroupParams') + +@dataclass(kw_only=True, eq=False, frozen=True) +class GroupParams(Mapping): + """ + Struct that can also be used as a non-mutable mapping, to be used + for subfields of CNMFParams, which have historically been dicts. + + Aliases and computed fields are used for parameters that are computed + from other fields (potentially elsewhere in CNMFParams) if an explicit + value is not provided. This allows these parameters to continue to be updated + when the params they depend on are changed. The field containing the user-provided + value (or None if none was provided) is prefixed with an underscore, but has + the un-prefixed name as an alias; this allows the name to be used in the constructor, + change_params, etc. This alias can also used to serialize the user-provided value + when the round_trip option is True (e.g., when saving to JSON, or when copying + the object using replace). When accessing the parameter using . attribute or + ['name'] mapping syntax, a property with the same name computes the actual value + to use if none has been provided. + """ + __pydantic_config__ = ConfigDict(extra='forbid', serialize_by_alias=True, ser_json_inf_nan='constants') + __pydantic_fields__: ClassVar[Mapping[str, FieldInfo]] # automatic, just declaring for typing purposes + + group_name: ClassVar[str] # name of the attribute on CNMFParams + removed_params: ClassVar[list[str]] = [] # to log a different message for params that have been removed rather than missing + + # back-reference to help with some computed fields + _full_params: 'SkipJsonSchema[Optional[CNMFParams]]' = Field(default=None, init=False, exclude=True, repr=False) -class CNMFParams(object): - """Class for setting and changing the various parameters.""" - def __init__(self, fnames=None, dims=None, dxy=(1, 1), - border_pix=0, del_duplicates=False, low_rank_background=True, - memory_fact=1, n_processes=1, nb_patch=1, p_ssub=2, p_tsub=2, - remove_very_bad_comps=False, rf=None, stride=None, - check_nan=True, n_pixels_per_process=None, - k=30, alpha_snmf=0.5, center_psf=False, gSig=[5, 5], gSiz=None, - init_iter=2, method_init='greedy_roi', min_corr=.85, - min_pnr=20, gnb=1, normalize_init=True, options_local_NMF=None, - ring_size_factor=1.5, rolling_length=100, rolling_sum=True, - ssub=2, ssub_B=2, tsub=2, - num_blocks_per_run_spat=20, - block_size_temp=5000, num_blocks_per_run_temp=20, - update_background_components=True, - method_deconvolution='oasis', p=2, s_min=None, - do_merge=True, merge_thresh=0.8, - decay_time=0.4, fr=30, min_SNR=2.5, rval_thr=0.8, - N_samples_exceptionality=None, batch_update_suff_stat=False, - expected_comps=500, iters_shape=5, max_comp_update_shape=np.inf, - max_num_added=5, min_num_trial=5, minibatch_shape=100, minibatch_suff_stat=5, - n_refit=0, num_times_comp_updated=np.inf, simultaneously=False, - sniper_mode=False, test_both=False, thresh_CNN_noisy=0.5, - thresh_fitness_delta=-50, thresh_fitness_raw=None, thresh_overlap=0.5, - update_freq=200, update_num_comps=True, use_dense=True, use_peak_max=True, - only_init_patch=True, var_name_hdf5='mov', max_merge_area=None, - use_corr_img=False, - params_from_file:Optional[str]=None, - params_dict={}, - ): - """Class for setting the processing parameters. All parameters for CNMF, online-CNMF, quality testing, - and motion correction can be set here and then used in the various processing pipeline steps. - - Params have default values; users can override the defaults in two intended ways: - A) During initialisation of the object, people can pass a nested dictionary through the - params_dict parameter, or the name of a jsonfile containing the same nested dictionary - through the params_from_file parameter - B) If the CNMFParams object already exists, they can call its change_params() method to pass in - a dict or change_params_from_jsonfile() to pass in a filename - With both of these, people only need to name and override values they wish to change; all others keep - their defaults. - - All other means of changing parameters are deprecated (including other constructor arguments) - and will be removed in some future version of Caiman (whether they give a deprecation warning or not). + @classmethod + @cache + def input_params(cls) -> set[str]: + """Param names that can be used in constructor etc. (excludes purely computed fields)""" + ta = TypeAdapter(cls) + # we don't care if some defaults aren't serializable + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=PydanticJsonSchemaWarning, message='Default value') + return set(ta.json_schema(mode='validation')['properties'].keys()) + + + @model_validator(mode='before') + @classmethod + def check_for_extra_fields(cls, data: Any, info: ValidationInfo) -> Any: + logger = logging.getLogger('caiman') + + warn_unused = True + if info.context is not None and 'warn_unused' in info.context: + warn_unused = info.context['warn_unused'] + + if isinstance(data, ArgsKwargs): # from constructor + if len(data.args) > 0: + # Shouldn't happen, but I think kw_only may be buggy + raise TypeError(f'{cls.__name__} does not take positional arguments.') + + if data.kwargs is None: + return data + + input_dict = data.kwargs + elif isinstance(data, dict): # from validate_* methods + input_dict = data + else: + return data + + # check for and remove extra fields + argnames = tuple(input_dict) + for argname in argnames: + if argname not in cls.input_params(): + del input_dict[argname] + if argname in cls.params(): + logger.warning(f'The parameter {cls.group_name}/{argname} was ignored because it is ' + 'computed from other parameters and cannot be set directly. ') + elif argname in cls.removed_params: + logger.warning(f'The parameter {cls.group_name}/{argname} has been removed; setting it has no effect.') + elif warn_unused: + logger.warning( + f'When creating {cls.group_name} params, provided key {argname} was not consumed. ' + 'This is a bug!') + return data - Args: - params_from_file - name of a json file used to initialise the object - params_dict - a dictionary used to initialise the object - Any parameter that is not set uses a default value - All other arguments are deprecated and should not be used. + @field_validator('*', mode='wrap') + @classmethod + def validation_wrapper(cls, value: Any, handler, info: ValidationInfo) -> Any: + """ + Function that wraps validation on every field. + This avoids raising a validation error when fields can't be converted, instead logging a warning. + """ + try: + return handler(value) + except ValidationError: + logger = logging.getLogger('caiman') + assert info.field_name is not None, 'Should have field name in model field validator' + + field_info = cls.__pydantic_fields__[info.field_name] + expected_type = field_info.annotation + name = field_info.alias or info.field_name + + logger.warning( + f'The value {repr(value)} provided for {cls.group_name}.{name} could not be converted ' + f'to the expected type {expected_type} and may not be valid.') + + return value + - Object Structure: - CNMFParams.data (these represent features of the data and other misc settings): + def replace(self: GPSelf, warn_unused=True, **changes) -> GPSelf: + """Create a GroupParams object with the given fields replaced""" + ta = TypeAdapter(type(self)) + # use round_trip=True to serialize underlying fields rather than computed properties + param_dict = ta.dump_python(self, round_trip=True) + param_dict.update(changes) + context = {'warn_unused': warn_unused} + new_obj = ta.validate_python(param_dict, context=context) + # set _full_params so computed fields remain consistent + object.__setattr__(new_obj, '_full_params', self._full_params) + return new_obj + + # support copy.replace (for 3.13 and above) + __replace__ = replace + + + def get_differing_params(self: GPSelf, other: GPSelf) -> Iterator[tuple[str, Any, Any]]: + """ + Returns an iterable of params that are not considered equal + Each return value is a tuple: (name, this_value, other_value) + """ + # here since we care about equality of the underlying fields, use + # __pydantic_fields__ which includes the underscore-prefixed names + for field, info in type(self).__pydantic_fields__.items(): + if info.exclude or info.init_var: + continue + + self_val = getattr(self, field) + other_val = getattr(other, field) + if not utilities.all_same(self_val, other_val): + # use alias when reporting mismatched field + fieldname = field if info.alias is None else info.alias + yield fieldname, self_val, other_val + + def __eq__(self, other) -> bool: + if isinstance(other, type(self)): + return not any(self.get_differing_params(other)) + else: + return NotImplemented + + def __ne__(self, other) -> bool: + if isinstance(other, type(self)): + return any(self.get_differing_params(other)) + else: + return NotImplemented + + + #---- read-only mapping interface (for algorithms that use the parameters, includes computed fields) ----# + + # define things that don't require parameter values as classmethods + + @classmethod + @cache + def params(cls) -> set[str]: + """Parameters available to read from this group""" + # Use the JSON schema to ensure we respect excluded fields, etc + ta = TypeAdapter(cls) + # we don't care if some defaults aren't serializable + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=PydanticJsonSchemaWarning, message='Default value') + return set(ta.json_schema(mode='serialization')['properties'].keys()) + + @classmethod + def __iter__(cls) -> Iterator[str]: + yield from cls.params() + + @classmethod + @cache + def __len__(cls) -> int: + return len(cls.params()) + + + def __getitem__(self, key: str) -> Any: + if key in self.params(): + return getattr(self, key) + raise KeyError(key) + + def copy(self) -> dict[str, Any]: + """Implement dict.copy - make a copy of the data as a (mutable) dict""" + # It should be safe to assign to a copy, so just make it a (shallow-copied) dict + return dict(self) + + +# Parameter group definitions (see docstring of CNMFParams for full documentation) + +@dataclass(kw_only=True, eq=False, frozen=True) +class DataParams(GroupParams): + """Parameters for features of the data and other misc settings""" + group_name = 'data' + + fnames: SafeOptional[AutoListStr] = None + fr: float = Field(default=30., gt=0) + decay_time: float = Field(default=0.4, gt=0) + dxy: tuple[float, float] = (1., 1.) # resolution, unit: pixels/um + var_name_hdf5: str = 'mov' + caiman_version: str = importlib.metadata.version('caiman') + last_commit: str = '-'.join(caiman.utils.utils.get_caiman_version()) + + @cached_property + def first_file_size(self) -> Optional[tuple[tuple[int, ...], int]]: + """get dims and T of first file, as in caiman.base.movies.get_file_size""" + logger = logging.getLogger('caiman') + + if self.fnames is not None and len(self.fnames) > 0: + try: + dims, T = caiman.base.movies.get_file_size(self.fnames[0], var_name_hdf5=self.var_name_hdf5) + return dims, cast(int, T) + except FileNotFoundError: + logger.warning('The first movie path in fnames was not found; cannot use dims.') + + + @model_validator(mode='after') + def refresh_file_size(self): + """ + Make sure file size & things that depend on it are updated at least when + the data params are changed (not foolproof but better than before) + """ + # this is how you clear cache for a cached_property + try: + object.__delattr__(self, 'first_file_size') + except AttributeError: + pass + return self + + @computed_field + @property + def dims(self) -> Optional[tuple[int, ...]]: + sz = self.first_file_size + if sz is not None: + return sz[0] + + + +@dataclass(kw_only=True, eq=False, frozen=True) +class PatchParams(GroupParams): + """Parameters for how the data is divided into patches""" + group_name = 'patch' + removed_params = ['p_ssub', 'p_tsub'] + + border_pix: int = 0 + del_duplicates: bool = False + in_memory: bool = True + low_rank_background: SafeOptional[bool] = True + memory_fact: float = 1. + n_processes: int = 1 + nb_patch: int = 1 + only_init: bool = True + p_patch: int = 0 # AR order within patch + remove_very_bad_comps: bool = False + rf: Union[int, list[int], SafeNone] = None + skip_refinement: bool = False + stride: Union[int, list[int], SafeNone] = None + + +@dataclass(kw_only=True, eq=False, frozen=True) +class PreprocessParams(GroupParams): + """Parameters for data preprocessing steps""" + group_name = 'preprocess' + + check_nan: bool = True + compute_g: bool = False # flag for estimating global time constant + include_noise: bool = False # flag for using noise values when estimating g + # number of autocovariance lags to be considered for time constant estimation + lags: int = 5 + max_num_samples_fft: int = 3 * 1024 + noise_method: LitStr[Literal['mean', 'median', 'logmexp']] = 'mean' # averaging method + # range of normalized frequencies over which to average + noise_range: list[float] = Field(default_factory=lambda: [0.25, 0.5]) + pixels: SafeOptional[list[int]] = None # pixels to be excluded due to saturation + sn: SafeOptional[NDArray] = None # noise level for each pixel + + @computed_field + @property + def p(self) -> int: + if self._full_params is None: + raise RuntimeError('Cannot access p without reference to full params') + return self._full_params.temporal.p + + @computed_field + @property + def n_pixels_per_process(self) -> Optional[int]: + if self._full_params is None: + raise RuntimeError('Cannot access n_pixels_to_process without reference to full params') + return self._full_params.spatial.n_pixels_per_process + + +@dataclass(kw_only=True, eq=False, frozen=True) +class InitParams(GroupParams): + """Parameters that control how CNMF should be initialized""" + group_name = 'init' + + K: SafeOptional[int] = 30 # number of components + SC_kernel: LitStr[Literal['heat', 'cos', 'binary']] = 'heat' # kernel for graph affinity matrix + SC_sigma: float = 1. # std for SC kernel + SC_thr: float = 0. # threshold for affinity matrix + SC_normalize: bool = True # standardize entries prior to computing affinity matrix + SC_use_NN: bool = False # sparsify affinity matrix by using only nearest neighbors + SC_nnn: int = 20 # number of nearest neighbors to use + alpha_snmf: float = 0.5 + center_psf: bool = False + # this sets the default to [5, 5], but automatically converts None to [-1, -1] + gSig: Annotated[list[int], + BeforeValidator(interpret_string_none), + BeforeValidator(lambda val: [-1, -1] if val is None else val) + ] = Field(default_factory=lambda: [5, 5]) + # default based on gSiz computed below + _gSiz: SafeOptional[list[OddInt]] = Field(default=None, alias='gSiz') + # init method used in calls to NMF if geedy_roi method for component initialisation is used (offline or online) + greedyroi_nmf_init_method: str = 'nndsvdar' + # max_iter used in calls to NMF if greedy_roi method for component initialisation is used (online or offline) + greedyroi_nmf_max_iter: int = 200 + init_iter: int = 2 + kernel: SafeOptional[NDArray] = None # user specified template for greedyROI + lambda_gnmf: float = 1. # regularization weight for graph NMF + snmf_l1_ratio: float = 0. # L1 ratio, used by sparse nmf mode only + maxIter: int = 5 # number of HALS iterations + max_iter_snmf: int = 500 + method_init: str = 'greedy_roi' # can be greedy_roi, corr_pnr, sparse_nmf, compressed_nmf, graph_nmf + min_corr: float = 0.85 + min_pnr: float = 20. + nIter: int = 5 # number of refinement iterations + nb: int = 1 # number of global background components + normalize_init: bool = True # whether to pixelwise equalize the movies during initialization + options_local_NMF: SafeOptional[dict] = None # unused - local_NMF is removed + perc_baseline_snmf: float = 20. + ring_size_factor: float = 1.5 + rolling_length: int = 100 + rolling_sum: bool = True + seed_method: LitStr[Literal['auto', 'manual', 'semi']] = 'auto' + sigma_smooth_snmf: tuple[float, float, float] = (0.5, 0.5, 0.5) + ssub: int = 2 # spatial downsampling factor + ssub_B: int = 2 + tsub: int = 2 # temporal downsampling factor + + @property + def gSiz(self) -> list[OddInt]: + if self._gSiz is not None: + return self._gSiz + return [2*gs + 1 for gs in self.gSig] + + @model_validator(mode='after') + def check_K_method(self): + """Log an error if K is incompatible with the initialization method""" + accept_none_K_methods = ['corr_pnr', 'sparse_nmf', 'graph_nmf'] + if self.K is None and self.method_init not in accept_none_K_methods: + logger = logging.getLogger('caiman') + logger.error(f'Parameter init.K cannot be set to None for the initialization method {self.method_init}.') + return self + + +def default_expandcore() -> np.ndarray: + """ + Generates the default morphological element used for footprint expansion + with the dilate method, which is a 5x5 matrix that is true where taxicab + distance from the center is <= 2 and false elsewhere. + """ + s1 = generate_binary_structure(2, 1) + s2 = iterate_structure(s1, 2) + return s2.astype(int) + +@dataclass(kw_only=True, eq=False, frozen=True) +class SpatialParams(GroupParams): + """Params that control how the algorithms handle spatial components""" + group_name = 'spatial' + + dist: float = 3. # expansion factor of ellipse + expandCore: NDArray = Field(default_factory=default_expandcore) + # Flag to extract connected components (might want to turn to False for dendritic imaging) + extract_cc: bool = True + maxthr: float = 0.1 # Max threshold + medw: SafeOptional[tuple[int, ...]] = None # window of median filter + # method for determining footprint of spatial components + method_exp: LitStr[Literal['ellipse', 'dilate']] = 'dilate' + # 'nnls_L0'. Nonnegative least square with L0 penalty + # 'lasso_lars' lasso lars function from scikit learn + method_ls: LitStr[Literal['nnls_L0', 'lasso_lars']] = 'lasso_lars' + # number of pixels to be processed by each worker + n_pixels_per_process: SafeOptional[int] = None + normalize_yyt_one: bool = True + nrgthr: float = 0.9999 # Energy threshold + # number of process to parallelize residual computation ** DECREASE IF MEMORY ISSUES + num_blocks_per_run_spat: int = 20 + se: SafeOptional[NDArray] = None # Morphological closing structuring element + ss: SafeOptional[NDArray] = None # Binary element for determining connectivity + thr_method: LitStr[Literal['max', 'nrg']] = 'nrg' # Method of thresholding ('max' or 'nrg') + # whether to update the background components in the spatial phase + update_background_components: bool = True + + @computed_field + @property + def nb(self) -> int: + if self._full_params is None: + raise RuntimeError('Cannot access nb without reference to full params') + return self._full_params.init.nb + + +@dataclass(kw_only=True, eq=False, frozen=True) +class TemporalParams(GroupParams): + """Params that control how the algorithms handle temporal components""" + group_name = 'temporal' + + ITER: int = 2 # block coordinate descent iterations + # flag for setting non-negative baseline (otherwise b >= min(y)) + bas_nonneg: bool = False + # number of pixels to parallelize residual computation ** DECREASE IF MEMORY ISSUES + block_size_temp: int = 5000 + # bias correction factor (between 0 and 1, close to 1) + fudge_factor: float = 0.96 + # number of autocovariance lags to be considered for time constant estimation + lags: int = 5 + optimize_g: bool = False # flag for optimizing time constants + # method for solving the constrained deconvolution problem + # if method cvxpy, primary and secondary (if problem unfeasible for approx + # solution) solvers to be used with cvxpy, can be 'ECOS','SCS' or 'CVXOPT' + method_deconvolution: LitStr[Literal['cvx', 'cvxpy', 'oasis']] = 'oasis' + noise_method: LitStr[Literal['mean', 'median', 'logmexp']] = 'mean' # averaging method + # range of normalized frequencies over which to average + noise_range: list[float] = Field(default_factory=lambda: [.25, .5]) + # number of process to parallelize residual computation ** DECREASE IF MEMORY ISSUES + num_blocks_per_run_temp: int = 20 + p: int = 2 # order of AR indicator dynamics + s_min: SafeOptional[float] = None # minimum spike threshold + solvers: list[LitStr[Literal['ECOS', 'SCS', 'CVXOPT']]] = Field(default_factory=lambda: ['ECOS', 'SCS']) + verbosity: bool = False + + @computed_field + @property + def nb(self) -> int: + if self._full_params is None: + raise RuntimeError('Cannot access nb without reference to full params') + return self._full_params.init.nb + + +@dataclass(kw_only=True, eq=False, frozen=True) +class MergingParams(GroupParams): + """Params that control how components are merged""" + group_name = 'merging' + + do_merge: bool = True + merge_thr: float = 0.8 + merge_parallel: bool = False + + +@dataclass(kw_only=True, eq=False, frozen=True) +class QualityParams(GroupParams): + """Params that control how the quality of traces is evaluated""" + group_name = 'quality' + + SNR_lowest: float = 0.5 # minimum accepted SNR value + cnn_lowest: float = 0.1 # minimum accepted value for CNN classifier + gSig_range: SafeOptional[list[list[int]]] = None # range for gSig scale for CNN classifier + min_SNR: float = 2.5 # transient SNR threshold + min_cnn_thr: float = 0.9 # threshold for CNN classifier + rval_lowest: float = -1. # minimum accepted space correlation + rval_thr: float = 0.8 # space correlation threshold + use_cnn: bool = True # use CNN based classifier + use_ecc: bool = False # flag for eccentricity based filtering (2D only) + max_ecc: float = 3. + + +@dataclass(kw_only=True, eq=False, frozen=True) +class OnlineParams(GroupParams): + """Params that control the online/OnACID mode""" + group_name = 'online' + + # timesteps to compute SNR (default computed below) + _N_samples_exceptionality: SafeOptional[int] = Field(default=None, alias='N_samples_exceptionality') + batch_update_suff_stat: bool = False + dist_shape_update: bool = False # update shapes in a distributed way + ds_factor: int = 1 # spatial downsampling for faster processing + epochs: int = 1 # number of epochs + expected_comps: int = 500 # number of expected components + full_XXt: bool = False # store entire XXt matrix (as opposed to a list of sub-matrices) + init_batch: int = 200 # length of mini batch for initialization + init_method: LitStr[Literal['bare', 'cnmf', 'seeded']] = 'bare' # initialization method for first batch + iters_shape: int = 5 # number of block-CD iterations + max_comp_update_shape: Union[int, float] = np.inf + max_num_added: int = 5 # maximum number of new components for each frame + max_shifts_online: int = 10 # maximum shifts during motion correction + min_SNR: float = 2.5 # minimum SNR for accepting a new trace + min_num_trial: int = 5 # number of mew possible components for each frame + minibatch_shape: int = 100 # number of frames in each minibatch + minibatch_suff_stat: int = 5 + motion_correct: bool = True # flag for motion correction + # filename of saved movie (appended to directory where data is located) + _movie_name_online: str = Field(default='online_movie.mp4', alias='movie_name_online') + normalize: bool = False # normalize frame + n_refit: int = 0 # Additional iterations to simultaneously refit + num_times_comp_updated: Union[int, float] = np.inf + opencv_codec: str = 'H264' # FourCC video codec for saving movie. Check http://www.fourcc.org/codecs.php + # path to CNN model for testing new comps + path_to_model: str = os.path.join(caiman_datadir(), 'model', 'cnn_model_online.pkl') + ring_CNN: bool = False # flag for using a ring CNN background model + rval_thr: float = 0.8 # space correlation threshold + save_online_movie: bool = False # flag for saving online movie + show_movie: bool = False # display movie online + simultaneously: bool = False # demix and deconvolve simultaneously + sniper_mode: bool = False # flag for using CNN + stop_detection: bool = False # flag for stop detecting new neurons at the last epoch + test_both: bool = False # flag for using both CNN and space correlation + thresh_CNN_noisy: float = 0.5 # threshold for online CNN classifier + thresh_fitness_delta: float = -50. + # threshold for trace SNR (default computed below) + _thresh_fitness_raw: SafeOptional[float] = Field(default=None, alias='thresh_fitness_raw') + thresh_overlap: float = 0.5 + update_freq: int = 200 # update every shape at least once every update_freq steps + update_num_comps: bool = True # flag for searching for new components + use_corr_img: bool = False # flag for using correlation image to detect new components + use_dense: bool = True # flag for representation and storing of A and b + use_peak_max: bool = True # flag for finding candidate centroids + W_update_factor: int = 1 # update W less often than shapes by a given factor + + @computed_field + @property + def N_samples_exceptionality(self) -> int: + """compute N_samples_exceptionality from other params if None""" + if self._N_samples_exceptionality is not None: + return self._N_samples_exceptionality + + if self._full_params is None: + raise RuntimeError('Cannot compute N_samples_exceptionality without reference to full params') + + fr = self._full_params.data.fr + decay_time = self._full_params.data.decay_time + return math.ceil(fr * decay_time) + + @computed_field + @property + def thresh_fitness_raw(self) -> float: + """computes thresh_fitness_raw from other params if None""" + if self._thresh_fitness_raw is not None: + return self._thresh_fitness_raw + return float(scipy.special.log_ndtr(-self.min_SNR) * self.N_samples_exceptionality) + + @computed_field + @property + def movie_name_online(self) -> str: + """Make movie_name_online relative to first movie path if it is available""" + if os.path.isabs(self._movie_name_online) or self._full_params is None: + return self._movie_name_online + + fnames = self._full_params.data.fnames + if fnames is None or len(fnames) == 0: + return self._movie_name_online + + return os.path.join(os.path.dirname(fnames[0]), self._movie_name_online) + + +@dataclass(kw_only=True, eq=False, frozen=True) +class MotionParams(GroupParams): + """Params that control motion correction""" + group_name = 'motion' + removed_params = ['num_splits_to_process_els', 'num_splits_to_process_rig'] + + # flag for allowing NaN in the boundaries + # - True: keep nans + # - False: replace with 0s + # - 'min': replace with minimum value in the frame + # - 'copy': copy edge values + border_nan: Union[bool, LitStr[Literal['min', 'copy']]] = 'copy' + gSig_filt: SafeOptional[tuple[int, ...]] = None # size of kernel for high pass spatial filtering in 1p data + is3D: bool = False # flag for 3D recordings for motion correction + max_deviation_rigid: int = 3 # maximum deviation between rigid and non-rigid + max_shifts: tuple[int, ...] = (6,6) # maximum shifts per dimension (in pixels) + min_mov: SafeOptional[float] = None # minimum value of movie + niter_rig: int = 1 # number of iterations rigid motion correction + nonneg_movie: bool = True # flag for producing a non-negative movie + num_frames_split: int = 80 # split across time every x frames (approximately) + overlaps: tuple[int, ...] = (32,32) # overlap between patches in pw-rigid motion correction + pw_rigid: bool = False # flag for performing pw-rigid motion correction + shifts_interpolate: bool = False # interpolate shifts based on patch locations instead of resizing + shifts_opencv: bool = True # flag for applying shifts using cubic interpolation (otherwise FFT) + strides: tuple[int, ...] = (96, 96) # how often to start a new patch in pw-rigid registration + upsample_factor_grid: int = 4 # motion field upsampling factor during FFT shifts + use_cuda: bool = False # flag for using a GPU + indices: tuple[IntSlice, ...] = (slice(None), slice(None)) # part of FOV to be corrected + + + def _compute_splits_from_data(self) -> Optional[int]: + """Compute splits_els and splits_rig values to use from data""" + if self._full_params is not None: + sz = self._full_params.data.first_file_size + if sz is not None: + # TODO maybe allow different num_splits per file, or use max? + T_first = sz[1] + return max(T_first // max(self.num_frames_split, 10), 1) + + @computed_field + @property + def splits_els(self) -> int: + """number of splits across time for pw-rigid registration""" + splits_from_data = self._compute_splits_from_data() + if splits_from_data is not None: + return splits_from_data + return 14 + + @computed_field + @property + def splits_rig(self) -> int: + """number of splits across time for rigid registration""" + splits_from_data = self._compute_splits_from_data() + if splits_from_data is not None: + return splits_from_data + return 14 + + +@dataclass(kw_only=True, eq=False, frozen=True) +class RingCNNParams(GroupParams): + """Params that control the ring neural networks used for 1P background estimation""" + group_name = 'ring_CNN' + + n_channels: int = 2 # number of "ring" kernels + use_bias: bool = False # use bias in the convolutions + use_add: bool = False # use an additive layer + pct: float = 0.01 # quantile loss specification + patience: int = 3 # patience for early stopping + max_epochs: int = 100 # maximum number of epochs + width: int = 5 # width of "ring" kernel + loss_fn: str = 'pct' # loss function + lr: float = 1e-3 # (initial) learning rate + lr_scheduler: SafeOptional[tuple[float, ...]] = None # learning rate scheduler function arguments + path_to_model: SafeOptional[str] = None # path to saved weights + remove_activity: bool = False # remove activity of last frame prior to background extraction + reuse_model: bool = False # reuse an already trained model + + +@dataclass(kw_only=True, frozen=True) +class CNMFParams: + """ + Class for setting the processing parameters. All parameters for CNMF, online-CNMF, quality testing, + and motion correction can be set here and then used in the various processing pipeline steps. + + The constructor supports setting params through 3 methods, in order of precedence (e.g., params + set through method A override those set through method B). Note that attempting to override a + group's parameters with an existing GroupParams object raises an error (a dict can be used instead). + + A) From individual group parameter objects passed to arguments matching the name of the group, as in: + CNMFParams(data=DataParams(fnames=['example.tif']), motion=MotionParams(max_shifts=10)) + This method allows for static type checking of each parameter value. + If preferred, raw dictionaries can also be passed instead of GroupParams objects, + as in: CNMFParams(data={'fnames': ['example.tif']}, motion={'max_shifts': 10}) + B) From a nested dictionary through the params_dict parameter, as in: + CNMFParams(params_dict={'data': {'fnames': ['example.tif']}, 'motion': {'max_shifts': 10}}) + C) From a JSON file through the params_from_file parameter. + + After construction, parameters can be changed from a nested dict using change_params() or from a + JSON file using change_params_from_jsonfile(). These are the preferred methods for updating params + because they automatically call check_consistency() to enforce consistency between different params. + + All other means of changing parameters are deprecated (including other constructor arguments) + and will be removed in some future version of Caiman (whether they give a deprecation warning or not). + + Args (keyword only): + params_from_file + name of a json file used to initialise the object + params_dict + a dictionary used to initialise the object + (e.g., data, init, preprocess...) + a dictionary or object used to override parameters for just this group + + Any parameter that is not set uses a default value + All other arguments are deprecated and should not be used. + + Object Structure: + CNMFParams.data (these represent features of the data and other misc settings): fnames list of complete paths to files that need to be processed @@ -97,7 +803,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), last_commit: str hash of last commit in the caiman repo. Pleaes do not override this. - CNMFParams.patch (these control how the data is divided into patches): + CNMFParams.patch (these control how the data is divided into patches): border_pix: int, default: 0 Number of pixels to exclude around each border. @@ -128,26 +834,24 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), p_patch: int, default: 0 order of AR dynamics when processing within a patch - remove_very_bad_comps: bool, default: True - Whether to remove (very) bad quality components during patch processing + remove_very_bad_comps: bool, default: False + Whether to remove components with very low values of component quality directly on the patch. + This might create some minor imprecisions, but can be important for performance because of bottlenecks + caused by handling many components (we have seen over 2000) that will need to be processed. - rf: int or list or None, default: None + rf: int or list[int] or None, default: None Half-size of patch in pixels. If None, no patches are constructed and the whole FOV is processed jointly. If list, it should be a list of two elements corresponding to the height and width of patches skip_refinement: bool, default: False - Whether to skip refinement of components - - p_ssub: float, default: 2 - Spatial downsampling factor + If true it only performs one iteration of update spatial update temporal instead of two + TODO: why is this in the patch section? - stride: int or None, default: None - Overlap between neighboring patches in pixels. + stride: int or list[int] or None, default: None + Overlap between neighboring patches in pixels. If None, when running CNMF.fit with + rf not None, it is automatically set to 10% of 2x rf along each dimension. - p_tsub: float, default: 2 - Temporal downsampling factor - - CNMFParams.preprocess (these control preprocessing steps for the data): + CNMFParams.preprocess (these control preprocessing steps for the data): check_nan: bool, default: True whether to check for NaNs @@ -163,27 +867,22 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), max_num_samples_fft: int, default: 3*1024 Chunk size for computing the PSD of the data (for memory considerations) - n_pixels_per_process: int, default: 1000 - Number of pixels to be allocated to each process - noise_method: 'mean'|'median'|'logmexp', default: 'mean' PSD averaging method for computing the noise std noise_range: [float, float], default: [.25, .5] range of normalized frequencies over which to compute the PSD for noise determination - p: int, default: 2 - order of AR indicator dynamics - pixels: list, default: None - pixels to be excluded due to saturation + pixels to be excluded due to saturation - sn: np.array or None, default: None + sn: np.ndarray or None, default: None noise level for each pixel - CNMFParams.init (these control how CNMF should be initialised): - K: int, default: 30 + CNMFParams.init (these control how CNMF should be initialised): + K: int or None, default: 30 number of components to be found (per patch or whole FOV depending on whether rf=None) + None is only supported for the following methods: 'corr_pnr', 'sparse_nmf', and 'graph_nmf'. SC_kernel: {'heat', 'cos', 'binary'}, default: 'heat' kernel for graph affinity matrix @@ -209,10 +908,10 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), center_psf: bool, default: False whether to use 1p data processing mode. Set to true for 1p - gSig: [int, int], default: [5, 5] + gSig: list of int, default: [5, 5] radius of average neurons (in pixels) - gSiz: [int, int], default: [int(round((x * 2) + 1)) for x in gSig], + gSiz: list of int, default: [int(round((x * 2) + 1)) for x in gSig], half-size of bounding box for each neuron greedyroi_nmf_init_method: str @@ -226,20 +925,23 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), init_iter: int, default: 2 number of iterations during corr_pnr (1p) initialization - kernel: np.array or None, default: None + kernel: np.ndarray or None, default: None user specified template for greedyROI lambda_gnmf: float, default: 1. regularization weight for graph NMF + snmf_l1_ratio: float, default: 0. + L1 ratio, used by sparse NMF mode only + maxIter: int, default: 5 number of HALS iterations during initialization max_iter_snmf : int, default: 500 maximum number of iterations for sparse NMF initialization - method_init: 'greedy_roi'|'corr_pnr'|'sparse_NMF'|'local_NMF' default: 'greedy_roi' - initialization method. use 'corr_pnr' for 1p processing and 'sparse_NMF' for dendritic processing. + method_init: 'greedy_roi'|'corr_pnr'|'sparse_nmf'|'compressed_nmf'|'graph_nmf' default: 'greedy_roi' + initialization method. use 'corr_pnr' for 1p processing and 'sparse_nmf' for dendritic processing. min_corr: float, default: 0.85 minimum value of correlation image for determining a candidate component during corr_pnr @@ -257,10 +959,11 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), whether to equalize the movies during initialization options_local_NMF: dict - dictionary with parameters to pass to local_NMF initializer + dictionary with parameters to pass to local_NMF initializer. + Now unused because the local_NMF method was removed. perc_baseline_snmf: float, default: 20 - percentile to be removed from the data in sparse_NMF prior to decomposition + percentile to be removed from the data in sparse_nmf prior to decomposition ring_size_factor: float, default: 1.5 radius of ring (*gSig) for computing background during corr_pnr @@ -280,21 +983,22 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), sigma_smooth_snmf : (float, float, float), default: (.5,.5,.5) std of Gaussian kernel for smoothing data in sparse_NMF - ssub: float, default: 2 + ssub: int, default: 2 spatial downsampling factor - ssub_B: float, default: 2 + ssub_B: int, default: 2 downsampling factor for background during corr_pnr - tsub: float, default: 2 + tsub: int, default: 2 temporal downsampling factor - CNMFParams.spatial (these control how the algorithms handle spatial components): + CNMFParams.spatial (these control how the algorithms handle spatial components): dist: float, default: 3 expansion factor of ellipse - expandCore: morphological element, default: None(?) + expandCore: np.ndarray morphological element for expanding footprints under dilate + default is a diamond generated by extract_cc: bool, default: True whether to extract connected components during thresholding @@ -313,12 +1017,9 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), 'nnls_L0'. Nonnegative least square with L0 penalty 'lasso_lars' lasso lars function from scikit learn - n_pixels_per_process: int, default: 1000 + n_pixels_per_process: int, default: number of pixels to be processed by each worker - nb: int, default: 1 - number of global background components. Do not set this directly; modify it in init. - normalize_yyt_one: bool, default: True Whether to normalize the C and A matrices so that diag(C*C.T) = 1 during update spatial @@ -328,10 +1029,10 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), num_blocks_per_run_spat: int, default: 20 Parallelization of A'*Y operation - se: np.array or None, default: None - Morphological closing structuring element (set to np.ones((3,)*len(dims), dtype=np.uint8) in cnmf.fit) + se: np.ndarray or None, default: None + Morphological closing structuring element (set to np.ones((3,)*len(dims), dtype=np.uint8) in cnmf.fit) - ss: np.array or None, default: None + ss: np.ndarray or None, default: None Binary element for determining connectivity (set to np.ones((3,)*len(dims), dtype=np.uint8) in cnmf.fit) thr_method: 'nrg'|'max', default: 'nrg' @@ -341,11 +1042,11 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), whether to update the spatial background components - CNMFParams.temporal (these control how the algorithms handle temporal components): + CNMFParams.temporal (these control how the algorithms handle temporal components): ITER: int, default: 2 block coordinate descent iterations - bas_nonneg: bool, default: True + bas_nonneg: bool, default: False whether to set a non-negative baseline (otherwise b >= min(y)) block_size_temp : int, default: 5000 @@ -360,13 +1061,10 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), optimize_g: bool, default: False flag for optimizing time constants - method_deconvolution: 'oasis'|'cvxpy'|'oasis', default: 'oasis' + method_deconvolution: 'cvx'|'cvxpy'|'oasis', default: 'oasis' method for solving the constrained deconvolution problem ('oasis','cvx' or 'cvxpy') if method cvxpy, primary and secondary (if problem unfeasible for approx solution) - nb: int, default: 1 - number of global background components. Do not set this directly; modify it in init. - noise_method: 'mean'|'median'|'logmexp', default: 'mean' PSD averaging method for computing the noise std @@ -382,13 +1080,13 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), s_min: float or None, default: None Minimum spike threshold amplitude (computed in the code if used). - solvers: 'ECOS'|'SCS', default: ['ECOS', 'SCS'] - solvers to be used with cvxpy, can be 'ECOS','SCS' or 'CVXOPT' + solvers: list of 'ECOS'|'SCS'|'CVXOPT', default: ['ECOS', 'SCS'] + solvers to be used with cvxpy, can be 'ECOS','SCS' or 'CVXOPT' verbosity: bool, default: False whether to be verbose - CNMFParams.merging (these control how components are merged): + CNMFParams.merging (these control how components are merged): do_merge: bool, default: True Whether or not to merge @@ -398,15 +1096,15 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), merge_parallel: bool, default: False Perform merging in parallel - CNMFParams.quality (these control how quality of traces are evaluated): + CNMFParams.quality (these control how quality of traces are evaluated): SNR_lowest: float, default: 0.5 minimum required trace SNR. Traces with SNR below this will get rejected cnn_lowest: float, default: 0.1 minimum required CNN threshold. Components with score lower than this will get rejected. - gSig_range: list or integers, default: None - gSig scale values for CNN classifier. In not None, multiple values are tested in the CNN classifier. + gSig_range: list of [int, int] or None, default: None + gSig scale values for CNN classifier. If not None, multiple values are tested in the CNN classifier. min_SNR: float, default: 2.5 trace SNR threshold. Traces with SNR above this will get accepted @@ -429,7 +1127,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), max_ecc: (undocumented) - CNMFParams.online (these control the Online/OnACID mode): + CNMFParams.online (these control the Online/OnACID mode): N_samples_exceptionality: int, default: np.ceil(decay_time*fr), Number of frames over which trace SNR is computed (usually length of a typical transient) @@ -485,7 +1183,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), motion_correct: bool, default: True Whether to perform motion correction during online processing - movie_name_online: str, default: 'online_movie.avi' + movie_name_online: str, default: 'online_movie.mp4' Name of saved movie (appended in the data directory) normalize: bool, default: False @@ -528,10 +1226,10 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), test_both: bool, default: False Whether to use both the CNN and space correlation for screening new components - thresh_CNN_noisy: float, default: 0,5, + thresh_CNN_noisy: float, default: 0.5, Threshold for the online CNN classifier - thresh_fitness_delta: float (negative) + thresh_fitness_delta: float (negative), default: -50 Derivative test for detecting traces thresh_fitness_raw: float (negative), default: computed from min_SNR @@ -558,13 +1256,14 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), W_update_factor: Update W less often than shapes by a given factor (XXX does this work?) - CNMFParams.motion (these control motion-correction): + CNMFParams.motion (these control motion-correction): border_nan: bool or str, default: 'copy' flag for allowing NaN in the boundaries. True allows NaN, whereas 'copy' copies the value of the nearest data point. - gSig_filt: int or None, default: None - size of kernel for high pass spatial filtering in 1p data. If None no spatial filtering is performed + gSig_filt: tuple of ints or None, default: None + size of kernel for high pass spatial filtering in 1p data. If None no spatial filtering is performed. + Only the first element is used in practice (the kernel is circular). is3D: bool, default: False flag for 3D recordings for motion correction @@ -572,7 +1271,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), max_deviation_rigid: int, default: 3 maximum deviation in pixels between rigid shifts and shifts of individual patches - max_shifts: (int, int), default: (6,6) + max_shifts: tuple of ints, default: (6,6) maximum shifts per dimension in pixels. min_mov: float or None, default: None @@ -590,7 +1289,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), num_splits_to_process_rig, default: None (Undocumented, changing this likely to break the code - FIXME why is this a parameter then?) - overlaps: (int, int), default: (24, 24) + overlaps: tuple of ints, default: (24, 24) overlap between patches in pixels in pw-rigid motion correction. pw_rigid: bool, default: False @@ -608,7 +1307,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), splits_rig: int, default: 14 number of splits across time for rigid registration. - strides: (int, int), default: (96, 96) + strides: tuple of int, default: (96, 96) how often to start a new patch in pw-rigid registration. Size of each patch will be strides + overlaps upsample_factor_grid" int, default: 4 @@ -620,7 +1319,7 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), indices: tuple(slice), default: (slice(None), slice(None)) Use that to apply motion correction only on a part of the FOV - CNMFParams.ring_CNN (these control the ring neural networks): + CNMFParams.ring_CNN (these control the ring neural networks): n_channels: int, default: 2 Number of "ring" kernels @@ -649,8 +1348,10 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), lr: float, default: 1e-3 (initial) learning rate - lr_scheduler: function, default: None - Learning rate scheduler function + lr_scheduler: tuple of float or None, default: None + Learning rate scheduler function. If provided, it should be a tuple + with 0 or more positional arguments to nn_models.rate_scheduler. + The arguments, in order, are factor, epoch_length, and samples_length. path_to_model: str, default: None Path to saved weights (if training then path to saved model weights) @@ -660,331 +1361,173 @@ def __init__(self, fnames=None, dims=None, dxy=(1, 1), reuse_model: bool, default: False Flag for reusing an already trained model (saved in path to model) + """ + __pydantic_config__ = ConfigDict(extra='forbid', ser_json_inf_nan='constants') + __pydantic_fields__: ClassVar[Mapping[str, FieldInfo]] # automatic, just declaring for typing purposes + + # mapping of alternate names of flat params (previously used in constructor) to their canonical names + flat_param_renames: ClassVar[dict[str, str]] = { + 'only_init_patch': 'only_init', + 'k': 'K', + 'gnb': 'nb', + 'merge_thresh': 'merge_thr' + } + + # mapping of nested param names to the group the parameter should be set on + # this is used to still set the parameter on the appropriate group while logging a warning. + canonical_groups: ClassVar[dict[str, dict[str, str]]] = { + 'temporal': {'nb': 'init'}, + 'spatial': {'nb': 'init'}, + 'preprocess': {'p': 'temporal', 'n_pixels_per_process': 'spatial'} + } + + + # init-only params - these are the normal arguments to the constructor + params_from_file: InitVar[Union[str, Path, None]] = None + params_dict: InitVar[Optional[dict[str, Any]]] = None + + # group fields + data: DataParams = Field(default_factory=DataParams) + patch: PatchParams = Field(default_factory=PatchParams) + preprocess: PreprocessParams = Field(default_factory=PreprocessParams) + init: InitParams = Field(default_factory=InitParams) + spatial: SpatialParams = Field(default_factory=SpatialParams) + temporal: TemporalParams = Field(default_factory=TemporalParams) + merging: MergingParams = Field(default_factory=MergingParams) + quality: QualityParams = Field(default_factory=QualityParams) + online: OnlineParams = Field(default_factory=OnlineParams) + motion: MotionParams = Field(default_factory=MotionParams) + ring_CNN: RingCNNParams = Field(default_factory=RingCNNParams) + + + @cached_property + def groups(self) -> list[str]: + return [f.name for f in fields(self)] + + @classmethod + @cache + def get_group_types(cls) -> dict[str, Type[GroupParams]]: + """Get name and type of each group params object. Depends on these being the only fields.""" + groups: dict[str, Type[GroupParams]] = {} + for info in fields(cls): + assert isinstance(info.type, type) and issubclass(info.type, GroupParams), \ + 'Each field should be a GroupParams subclass' + groups[info.name] = info.type + return groups + + + def __setstate__(self, state: dict[str, Any]): + """Ensure fields are objects of the proper type (i.e. when unpickling old-version CNMFParams)""" + for group, GroupClass in self.get_group_types().items(): + if isinstance(group_obj := state.get(group), dict): + state[group] = GroupClass(**group_obj) + + self.__dict__.update(state) + + + @model_validator(mode='before') + @classmethod + def _combine_parameters(cls, data: Any) -> Any: + """ + Combine nested and/or flat parameters from JSON, params_dict, and/or direct arguments + to a single neseted dict and pass this on to the dataclass constructor. + This avoids multiple rounds of validation and check_consistency. """ + if isinstance(data, ArgsKwargs): # from constructor + if len(data.args) > 0: + # Shouldn't happen, but I think kw_only may be buggy + raise TypeError('CNMFParams() does not take positional arguments.') + + if data.kwargs is None: + return data + + input_dict = data.kwargs + elif isinstance(data, dict): # from validate_* method of TypeAdapter + input_dict = data + else: + return data + + # Order: First JSON, then params_dict, finally individual arguments + # No support for combining full GroupParams objects with JSON or params_dict + # (will work for params_dict if the top-level keys don't overlap) + kwargs = input_dict.copy() + new_kwargs: dict[str, Any] = {} + + if (params_from_file := kwargs.pop('params_from_file', None)) is not None: + with open(params_from_file, 'r') as fh: + loaded_data = json.load(fh) + + if not isinstance(loaded_data, dict): + raise ValueError('Params loaded from JSON must be a dict') + + cls.update_nested_params(nested_params=new_kwargs, new_params=loaded_data) + + if (params_dict := kwargs.pop('params_dict', None)) is not None: + if not isinstance(params_dict, dict): + raise ValueError('params_dict must be a dict') + + cls.update_nested_params(nested_params=new_kwargs, new_params=params_dict) + + # add group params and flat params passed as keyword arguments + cls.update_nested_params(nested_params=new_kwargs, new_params=kwargs) + + return new_kwargs - if float(decay_time) == float(0.0): - raise Exception("A decay time of zero is not permitted") - - self.data = { - 'fnames': fnames, - 'dims': dims, - 'fr': fr, - 'decay_time': decay_time, - 'dxy': dxy, - 'var_name_hdf5': var_name_hdf5, - 'caiman_version': importlib.metadata.version('caiman'), - 'last_commit': None - } - - self.patch = { - 'border_pix': border_pix, - 'del_duplicates': del_duplicates, - 'in_memory': True, - 'low_rank_background': low_rank_background, - 'memory_fact': memory_fact, - 'n_processes': n_processes, - 'nb_patch': nb_patch, - 'only_init': only_init_patch, - 'p_patch': 0, # AR order within patch - 'remove_very_bad_comps': remove_very_bad_comps, - 'rf': rf, - 'skip_refinement': False, - 'p_ssub': p_ssub, # spatial downsampling factor - 'stride': stride, - 'p_tsub': p_tsub, # temporal downsampling factor - } - - self.preprocess = { - 'check_nan': check_nan, - 'compute_g': False, # flag for estimating global time constant - 'include_noise': False, # flag for using noise values when estimating g - # number of autocovariance lags to be considered for time constant estimation - 'lags': 5, - 'max_num_samples_fft': 3 * 1024, - 'n_pixels_per_process': n_pixels_per_process, - 'noise_method': 'mean', # averaging method ('mean','median','logmexp') - 'noise_range': [0.25, 0.5], # range of normalized frequencies over which to average - 'p': p, # order of AR indicator dynamics - 'pixels': None, # pixels to be excluded due to saturation - 'sn': None, # noise level for each pixel - } - - self.init = { - 'K': k, # number of components, - 'SC_kernel': 'heat', # kernel for graph affinity matrix - 'SC_sigma' : 1, # std for SC kernel - 'SC_thr': 0, # threshold for affinity matrix - 'SC_normalize': True, # standardize entries prior to - # computing affinity matrix - 'SC_use_NN': False, # sparsify affinity matrix by using - # only nearest neighbors - 'SC_nnn': 20, # number of nearest neighbors to use - 'alpha_snmf': alpha_snmf, - 'center_psf': center_psf, - 'gSig': gSig, - # size of bounding box - 'gSiz': gSiz, - 'greedyroi_nmf_init_method': 'nndsvdar', # init method used in calls to NMF if geedy_roi method for component initialisation is used (offline or online) - 'greedyroi_nmf_max_iter': 200, # max_iter used in calls to NMF if greedy_roi method for component initialisation is used (online or offline) - 'init_iter': init_iter, - 'kernel': None, # user specified template for greedyROI - 'lambda_gnmf': 1, # regularization weight for graph NMF - 'snmf_l1_ratio': 0.0, # L1 ratio, used by sparse nmf mode only - 'maxIter': 5, # number of HALS iterations - 'max_iter_snmf': 500, - 'method_init': method_init, # can be greedy_roi, corr_pnr sparse_nmf, local_NMF - 'min_corr': min_corr, - 'min_pnr': min_pnr, - 'nIter': 5, # number of refinement iterations - 'nb': gnb, # number of global background components - # whether to pixelwise equalize the movies during initialization - 'normalize_init': normalize_init, - # dictionary with parameters to pass to local_NMF initializer - 'options_local_NMF': options_local_NMF, - 'perc_baseline_snmf': 20, - 'ring_size_factor': ring_size_factor, - 'rolling_length': rolling_length, - 'rolling_sum': rolling_sum, - 'seed_method': 'auto', - 'sigma_smooth_snmf': (.5, .5, .5), - 'ssub': ssub, # spatial downsampling factor - 'ssub_B': ssub_B, - 'tsub': tsub, # temporal downsampling factor - } - - self.spatial = { - 'dist': 3, # expansion factor of ellipse - 'expandCore': iterate_structure(generate_binary_structure(2, 1), 2).astype(int), - # Flag to extract connected components (might want to turn to False for dendritic imaging) - 'extract_cc': True, - 'maxthr': 0.1, # Max threshold - 'medw': None, # window of median filter - # method for determining footprint of spatial components ('ellipse' or 'dilate') - 'method_exp': 'dilate', - # 'nnls_L0'. Nonnegative least square with L0 penalty - # 'lasso_lars' lasso lars function from scikit learn - 'method_ls': 'lasso_lars', - # number of pixels to be processed by each worker - 'n_pixels_per_process': n_pixels_per_process, - 'nb': gnb, # number of background components - 'normalize_yyt_one': True, - 'nrgthr': 0.9999, # Energy threshold - 'num_blocks_per_run_spat': num_blocks_per_run_spat, # number of process to parallelize residual computation ** DECREASE IF MEMORY ISSUES - 'se': None, # Morphological closing structuring element - 'ss': None, # Binary element for determining connectivity - 'thr_method': 'nrg', # Method of thresholding ('max' or 'nrg') - # whether to update the background components in the spatial phase - 'update_background_components': update_background_components, - } - - self.temporal = { - 'ITER': 2, # block coordinate descent iterations - # flag for setting non-negative baseline (otherwise b >= min(y)) - 'bas_nonneg': False, - # number of pixels to process at the same time for dot product. Make it - # smaller if memory problems - 'block_size_temp': block_size_temp, # number of pixels to parallelize residual computation ** DECREASE IF MEMORY ISSUES - # bias correction factor (between 0 and 1, close to 1) - 'fudge_factor': .96, - # number of autocovariance lags to be considered for time constant estimation - 'lags': 5, - 'optimize_g': False, # flag for optimizing time constants - # method for solving the constrained deconvolution problem ('oasis','cvx' or 'cvxpy') - # if method cvxpy, primary and secondary (if problem unfeasible for approx - # solution) solvers to be used with cvxpy, can be 'ECOS','SCS' or 'CVXOPT' - 'method_deconvolution': method_deconvolution, # 'cvxpy', # 'oasis' - 'nb': gnb, # number of background components - 'noise_method': 'mean', # averaging method ('mean','median','logmexp') - 'noise_range': [.25, .5], # range of normalized frequencies over which to average - 'num_blocks_per_run_temp': num_blocks_per_run_temp, # number of process to parallelize residual computation ** DECREASE IF MEMORY ISSUES - 'p': p, # order of AR indicator dynamics - 's_min': s_min, # minimum spike threshold - 'solvers': ['ECOS', 'SCS'], - 'verbosity': False, - } - - self.merging = { - 'do_merge': do_merge, - 'merge_thr': merge_thresh, - 'merge_parallel': False - } - - self.quality = { - 'SNR_lowest': 0.5, # minimum accepted SNR value - 'cnn_lowest': 0.1, # minimum accepted value for CNN classifier - 'gSig_range': None, # range for gSig scale for CNN classifier - 'min_SNR': min_SNR, # transient SNR threshold - 'min_cnn_thr': 0.9, # threshold for CNN classifier - 'rval_lowest': -1, # minimum accepted space correlation - 'rval_thr': rval_thr, # space correlation threshold - 'use_cnn': True, # use CNN based classifier - 'use_ecc': False, # flag for eccentricity based filtering (2D only) - 'max_ecc': 3 - } - - self.online = { - 'N_samples_exceptionality': N_samples_exceptionality, # timesteps to compute SNR - 'batch_update_suff_stat': batch_update_suff_stat, - 'dist_shape_update': False, # update shapes in a distributed way - 'ds_factor': 1, # spatial downsampling for faster processing - 'epochs': 1, # number of epochs - 'expected_comps': expected_comps, # number of expected components - 'full_XXt': False, # store entire XXt matrix (as opposed to a list of sub-matrices) - 'init_batch': 200, # length of mini batch for initialization - 'init_method': 'bare', # initialization method for first batch, - 'iters_shape': iters_shape, # number of block-CD iterations - 'max_comp_update_shape': max_comp_update_shape, - 'max_num_added': max_num_added, # maximum number of new components for each frame - 'max_shifts_online': 10, # maximum shifts during motion correction - 'min_SNR': min_SNR, # minimum SNR for accepting a new trace - 'min_num_trial': min_num_trial, # number of mew possible components for each frame - 'minibatch_shape': minibatch_shape, # number of frames in each minibatch - 'minibatch_suff_stat': minibatch_suff_stat, - 'motion_correct': True, # flag for motion correction - 'movie_name_online': 'online_movie.mp4', # filename of saved movie (appended to directory where data is located) - 'normalize': False, # normalize frame - 'n_refit': n_refit, # Additional iterations to simultaneously refit - # path to CNN model for testing new comps - 'num_times_comp_updated': num_times_comp_updated, - 'opencv_codec': 'H264', # FourCC video codec for saving movie. Check http://www.fourcc.org/codecs.php - 'path_to_model': os.path.join(caiman_datadir(), 'model', - 'cnn_model_online.pkl'), - 'ring_CNN': False, # flag for using a ring CNN background model - 'rval_thr': rval_thr, # space correlation threshold - 'save_online_movie': False, # flag for saving online movie - 'show_movie': False, # display movie online - 'simultaneously': simultaneously, # demix and deconvolve simultaneously - 'sniper_mode': sniper_mode, # flag for using CNN - 'stop_detection': False, # flag for stop detecting new neurons at the last epoch - 'test_both': test_both, # flag for using both CNN and space correlation - 'thresh_CNN_noisy': thresh_CNN_noisy, # threshold for online CNN classifier - 'thresh_fitness_delta': thresh_fitness_delta, - 'thresh_fitness_raw': thresh_fitness_raw, # threshold for trace SNR (computed below) - 'thresh_overlap': thresh_overlap, - 'update_freq': update_freq, # update every shape at least once every update_freq steps - 'update_num_comps': update_num_comps, # flag for searching for new components - 'use_corr_img': use_corr_img, # flag for using correlation image to detect new components - 'use_dense': use_dense, # flag for representation and storing of A and b - 'use_peak_max': use_peak_max, # flag for finding candidate centroids - 'W_update_factor': 1, # update W less often than shapes by a given factor - } - - self.motion = { - 'border_nan': 'copy', # flag for allowing NaN in the boundaries - 'gSig_filt': None, # size of kernel for high pass spatial filtering in 1p data - 'is3D': False, # flag for 3D recordings for motion correction - 'max_deviation_rigid': 3, # maximum deviation between rigid and non-rigid - 'max_shifts': (6, 6), # maximum shifts per dimension (in pixels) - 'min_mov': None, # minimum value of movie - 'niter_rig': 1, # number of iterations rigid motion correction - 'nonneg_movie': True, # flag for producing a non-negative movie - 'num_frames_split': 80, # split across time every x frames - 'num_splits_to_process_els': None, # Unused, will be removed in a future version of Caiman - 'num_splits_to_process_rig': None, # DO NOT MODIFY - 'overlaps': (32, 32), # overlap between patches in pw-rigid motion correction - 'pw_rigid': False, # flag for performing pw-rigid motion correction - 'shifts_interpolate': False, # interpolate shifts based on patch locations instead of resizing - 'shifts_opencv': True, # flag for applying shifts using cubic interpolation (otherwise FFT) - 'splits_els': 14, # number of splits across time for pw-rigid registration (usually overridden by code) - 'splits_rig': 14, # number of splits across time for rigid registration (usually overridden by code) - 'strides': (96, 96), # how often to start a new patch in pw-rigid registration - 'upsample_factor_grid': 4, # motion field upsampling factor during FFT shifts - 'use_cuda': False, # flag for using a GPU - 'indices': (slice(None), slice(None)) # part of FOV to be corrected - } - - self.ring_CNN = { - 'n_channels' : 2, # number of "ring" kernels - 'use_bias' : False, # use bias in the convolutions - 'use_add' : False, # use an additive layer - 'pct' : 0.01, # quantile loss specification - 'patience' : 3, # patience for early stopping - 'max_epochs': 100, # maximum number of epochs - 'width': 5, # width of "ring" kernel - 'loss_fn': 'pct', # loss function - 'lr': 1e-3, # (initial) learning rate - 'lr_scheduler': None, # learning rate scheduler function - 'path_to_model': None, # path to saved weights - 'remove_activity': False, # remove activity of last frame prior to background extraction - 'reuse_model': False # reuse an already trained model - } - - if params_from_file is not None: - self.change_params_from_jsonfile(params_from_file) - self.change_params(params_dict) + + @model_validator(mode='after') + def _check_post_validation(self): + # add reference to self in each GroupParams object, bypassing frozen + for field in fields(self): + object.__setattr__(getattr(self, field.name), '_full_params', self) + self.check_consistency() + return self def check_consistency(self): """ Populates the params object with some dataset dependent values and ensures that certain constraints are satisfied. """ logger = logging.getLogger("caiman") - self.data['last_commit'] = '-'.join(caiman.utils.utils.get_caiman_version()) - if self.data['dims'] is None and self.data['fnames'] is not None: - self.data['dims'] = caiman.base.movies.get_file_size(self.data['fnames'], var_name_hdf5=self.data['var_name_hdf5'])[0] - if self.data['fnames'] is not None: - # if fname was stored as string instead of list - if isinstance(self.data['fnames'], str): - self.data['fnames'] = [self.data['fnames']] - # convert reloaded data fnames from byte-encoded to string - if isinstance(self.data['fnames'][0], np.bytes_): - self.data['fnames'] = [fname.decode('utf-8') for fname in self.data['fnames']] - T = caiman.base.movies.get_file_size(self.data['fnames'], var_name_hdf5=self.data['var_name_hdf5'])[1] - if len(self.data['fnames']) > 1: - T = T[0] - num_splits = max(T//max(self.motion['num_frames_split'], 10), 1) - self.motion['splits_els'] = num_splits - self.motion['splits_rig'] = num_splits - if isinstance(self.data['fnames'][0],tuple): - self.online['movie_name_online'] = os.path.join(os.path.dirname(self.data['fnames'][0][0]), self.online['movie_name_online']) - else: - self.online['movie_name_online'] = os.path.join(os.path.dirname(self.data['fnames'][0]), self.online['movie_name_online']) - if self.online['N_samples_exceptionality'] is None: - self.online['N_samples_exceptionality'] = np.ceil(self.data['fr'] * self.data['decay_time']).astype('int') - if self.online['thresh_fitness_raw'] is None: - self.online['thresh_fitness_raw'] = scipy.special.log_ndtr( - -self.online['min_SNR']) * self.online['N_samples_exceptionality'] - self.online['max_shifts_online'] = (np.array(self.online['max_shifts_online']) / self.online['ds_factor']).astype(int) - if self.init['gSig'] is None: - self.init['gSig'] = [-1, -1] - if self.init['gSiz'] is None: - self.init['gSiz'] = [2*gs + 1 for gs in self.init['gSig']] - self.init['gSiz'] = tuple([gs + 1 if gs % 2 == 0 else gs for gs in self.init['gSiz']]) - if self.patch['rf'] is not None: - if np.any(np.array(self.patch['rf']) <= self.init['gSiz'][0]): - logger.warning(f"Changing rf from {self.patch['rf']} to {2 * self.init['gSiz'][0]} because the constraint rf > gSiz was not satisfied.") - if self.init['nb'] <= 0 and (self.patch['nb_patch'] != self.init['nb'] or - self.patch['low_rank_background'] is not None): - logger.warning(f"gnb={self.init['nb']}, hence setting keys nb_patch and low_rank_background in group patch automatically.") - self.set('patch', {'nb_patch': self.init['nb'], 'low_rank_background': None}) - if self.init['nb'] == -1 and self.spatial['update_background_components']: - logger.warning("gnb=-1, hence setting key update_background_components " + - "in group spatial automatically to False.") - self.set('spatial', {'update_background_components': False}) - if self.init['method_init'] == 'corr_pnr' and self.init['ring_size_factor'] is not None \ - and self.init['normalize_init']: - logger.warning("using CNMF-E's ringmodel for background hence setting key " + - "normalize_init in group init automatically to False.") - self.set('init', {'normalize_init': False}) - if self.motion['is3D']: + + data_updates = {} + data_updates['last_commit'] = '-'.join(caiman.utils.utils.get_caiman_version()) + + if self.init.method_init == 'corr_pnr' and self.init.ring_size_factor is not None: + if self.init.normalize_init: + logger.warning("using CNMF-E's ringmodel for background hence setting key " + + "normalize_init in group init automatically to False.") + self.set('init', {'normalize_init': False}, warn=False, verbose=False) + + + if self.init.nb <= 0 and (self.patch.nb_patch != self.init.nb or self.patch.low_rank_background is not None): + logger.warning(f"nb={self.init.nb}, hence setting keys nb_patch and low_rank_background in group patch automatically.") + self.set('patch', {'nb_patch': self.init.nb, 'low_rank_background': None}, warn=False, verbose=False) + + if self.init.nb == -1 and self.spatial.update_background_components: + logger.warning("nb=-1, hence setting key update_background_components " + + "in group spatial automatically to False.") + self.set('spatial', {'update_background_components': False}, warn=False, verbose=False) + + if self.motion.is3D: + motion_updates = {} for a in ('indices', 'max_shifts', 'strides', 'overlaps'): if len(self.motion[a]) != 3: if self.motion[a][0] == self.motion[a][1]: - self.motion[a] = (self.motion[a][0],) * 3 + motion_updates[a] = (self.motion[a][0],) * 3 logger.warning(f"is3D=True, hence setting key {a} to {self.motion[a]}") else: raise ValueError(f'{a} must be a tuple of length 3 for volumetric 3D data') + if motion_updates: + self.set('motion', motion_updates, warn=False, verbose=False) + for key in ('max_num_added', 'min_num_trial'): - if (self.online[key] == 0 and self.online['update_num_comps']): - self.set('online', {'update_num_comps': False}) + if (self.online[key] == 0 and self.online.update_num_comps): logger.warning(f"{key}=0, hence setting key online.update_num_comps to False.") - # FIXME The authoritative value is stored in the init field. This should later be refactored out - # into a general section, once we're passing around the CNMFParams object rather than splatting it out - # from **get_group - self.spatial['nb'] = self.init['nb'] - self.temporal['nb'] = self.init['nb'] + self.set('online', {'update_num_comps': False}, warn=False, verbose=False) + break + - def set(self, group:str, val_dict:dict, set_if_not_exists:bool=False, verbose=False) -> None: + def set(self, group: str, val_dict: dict, verbose=True, warn=True) -> None: """ Add key-value pairs to a group. Existing key-value pairs will be overwritten if specified in val_dict, but not deleted. @@ -992,36 +1535,34 @@ def set(self, group:str, val_dict:dict, set_if_not_exists:bool=False, verbose=Fa group: The name of the group val_dict: A dictionary with key-value pairs to be set for the group warn_unused: - set_if_not_exists: Whether to set a key-value pair in a group if the key does not currently exist in the group. (DEPRECATED) This is not intended for general use and does not run consistency checks on the CNMFParams object afterwards (or do any triggered actions on certain values being set like filenames). Usually the change_params() method is more appropriate. A future version of caiman may make this method private. """ - logger = logging.getLogger("caiman") - if set_if_not_exists: - logger.warning("The set_if_not_exists flag for CNMFParams.set() is deprecated and will be removed in a future version of Caiman") - # can't easily catch if it's passed but set to False, but that wouldn't do anything because of the default, - # and if they get that error it's at least really easy to fix - just remove the flag - # we don't want to support this because it makes the structure of the object unpredictable except at runtime + if warn: + # this is the only way to change a param without running consistency checks... + logger.warning("CNMFParams.set() is dangerous! Use CNMFParams.change_params() instead.") - if not hasattr(self, group): - raise KeyError(f'No group in CNMFParams named {group}') + d = self.get_group(group) + updates = {} - d = getattr(self, group) for k, v in val_dict.items(): - if k not in d and not set_if_not_exists: + if k not in d: if verbose: logger.warning( f"{group}/{k} not set: invalid target in CNMFParams object") else: - try: - if np.any(d[k] != v): - logger.info(f"Changing key {k} in group {group} from {d[k]} to {v}") - except ValueError: # d[k] and v also differ if above comparison fails, e.g. lists of different length + if verbose and not utilities.all_same(d[k], v): logger.info(f"Changing key {k} in group {group} from {d[k]} to {v}") - d[k] = v + updates[k] = v + + # apply changes, bypassing frozen + if updates: + d_new = d.replace(**updates) + object.__setattr__(self, group, d_new) + def get(self, group, key): """ Get a value for a given group and key. Raises an exception if no such group/key combination exists. @@ -1031,101 +1572,213 @@ def get(self, group, key): key: The key for the property in the group of interest. Returns: The value for the group/key combination. - """ - - if not hasattr(self, group): - raise KeyError(f'No group in CNMFParams named {group}') - - d = getattr(self, group) + """ + d = self.get_group(group) if key not in d: raise KeyError(f'No key {key} in group {group}') return d[key] - def get_group(self, group): + + def get_group(self, group: str) -> GroupParams: """ Get the dictionary of key-value pairs for a group. Args: group: The name of the group. """ + if group in self.groups: + return getattr(self, group) + raise KeyError(f'No group in CNMFParams named {group}') + + + def get_differing_params(self, other: 'CNMFParams') -> Iterator[tuple[str, Any, Any]]: + for groupname in self.groups: + this_group = self.get_group(groupname) + other_group = other.get_group(groupname) + for (name, self_val, other_val) in this_group.get_differing_params(other_group): + yield groupname + '.' + name, self_val, other_val - if not hasattr(self, group): - raise KeyError(f'No group in CNMFParams named {group}') - - return getattr(self, group) - - def __eq__(self, other): - - if not isinstance(other, CNMFParams): - return False - - parent_dict1 = self.to_dict() - parent_dict2 = other.to_dict() - - key_diff = np.setdiff1d(parent_dict1.keys(), parent_dict2.keys()) - if len(key_diff) > 0: - return False - - for k1, child_dict1 in parent_dict1.items(): - child_dict2 = parent_dict2[k1] - added, removed, modified, same = dict_compare(child_dict1, child_dict2) - if len(added) != 0 or len(removed) != 0 or len(modified) != 0 or len(same) != len(child_dict1): - return False - - return True - - def to_dict(self) -> dict: - """Returns the params class as a dictionary with subdictionaries for each - category.""" - return { - 'data': self.data, - 'init': self.init, - 'merging': self.merging, - 'motion': self.motion, - 'online': self.online, - 'patch': self.patch, - 'preprocess': self.preprocess, - 'ring_CNN': self.ring_CNN, - 'quality': self.quality, - 'spatial': self.spatial, - 'temporal': self.temporal - } - - def to_json(self) -> str: - """ Reversibly serialise CNMFParams to json """ - dictdata = self.to_dict() - # now we need to tweak dictdata to convert ndarrays to something json can represent - class NumpyEncoder(json.JSONEncoder): # Custom json encoder that handles ndarrays better - def default(self, obj): - if isinstance(obj, np.ndarray): - return obj.tolist() - elif isinstance(obj, np.integer): - return int(obj) - elif isinstance(obj, slice): - return list([obj.start, obj.stop, obj.step]) - return json.JSONEncoder.default(self, obj) - return json.dumps(dictdata, cls=NumpyEncoder) - - - def to_jsonfile(self, targfn:str) -> None: + + def to_dict(self) -> dict[str, GroupParams]: + """Convert to a dictionary mapping group names to objects to read params for that group.""" + return {group: self.get_group(group) for group in self.groups} + + + def to_dict_roundtrip(self, format: Literal['json', 'python'] = 'python') -> dict[str, dict[str, Any]]: + """Convert to a dict that can be used to recreate an identical object by passing as params_dict""" + ta = TypeAdapter(type(self)) + return ta.dump_python(self, round_trip=True, mode=format) + + + def to_json(self, verify=True) -> bytes: + """ + Reversibly serialise CNMFParams to json. If verify is true, test that it can be + deserialized correctly (meaning that all values match the original; it is + possible that this happens even if they don't all match the schema). + """ + logger = logging.getLogger('caiman') + ta = TypeAdapter(type(self)) + jsonstring = ta.dump_json(self, round_trip=True) + + if verify: + logger.debug('Testing reconstruction from JSON') + recon_obj = ta.validate_json(jsonstring) + + mismatched = list(self.get_differing_params(recon_obj)) + if len(mismatched) > 0: + # format a table of mismatched parameters + headers = ('Param name', 'Current value', 'Reconstructed value', 'Expected type') + table_rows = [] + for mismatch in mismatched: + group, param = mismatch[0].split('.') + param_type = self.get_group(group).__pydantic_fields__[param].annotation + if isinstance(param_type, type): + typename = param_type.__name__ + else: + typename = str(param_type) + table_rows.append(mismatch + (typename,)) + + mismatch_table = tabulate(table_rows, headers=headers) + logger.warning( + 'The following parameter(s) were not reconstructed correctly from JSON. ' + 'If this is an issue, please set each parameter to a value of the correct type.\n\n' + + mismatch_table + '\n') + else: + logger.debug('Reconstruction was successful.') + + return jsonstring + + + def to_jsonfile(self, targfn: Union[str, Path], verify=True) -> None: """ Reversibly serialise CNMFParams to a json file """ - with open(targfn, 'w') as targfh: - targfh.write(self.to_json()) + with open(targfn, 'wb') as targfh: + targfh.write(self.to_json(verify=verify)) def __repr__(self) -> str: formatted_outputs = [ - f'{group_name}:\n\n{pformat(group_dict)}' - for group_name, group_dict in self.to_dict().items() + f'{group_name}:\n\n{pformat(self.get_group(group_name))}' for group_name in self.groups ] return 'CNMFParams:\n\n' + '\n\n'.join(formatted_outputs) - def change_params(self, params_dict, allow_legacy:bool=True, warn_unused:bool=True, verbose:bool=False) -> None: + + @classmethod + def _update_group(cls, nested_params: dict[str, dict], group: str, group_params: Union[dict, GroupParams], + error_on_changing_override: bool): + """Helper to update one group of nested_params""" + logger = logging.getLogger('caiman') + + # if a dict, check whether any params need to be set on a different group + if not isinstance(group_params, GroupParams) and group in cls.canonical_groups: + wrong_group_params = group_params.keys() & cls.canonical_groups[group].keys() + for param in wrong_group_params: + new_group = cls.canonical_groups[group][param] + logger.warning(f'Setting parameter {param} on group {group} is deprecated; set on {new_group} instead.') + cls._update_group( + nested_params, new_group, {param: group_params[param]}, error_on_changing_override=error_on_changing_override) + + if len(wrong_group_params) > 0: + group_params = {k: v for k, v in group_params.items() if k not in wrong_group_params} + + if group not in nested_params: + if len(group_params) > 0: # leave missing otherwise + if isinstance(group_params, GroupParams): + # avoid directly converting to dict which uses computed values + # and can fail if _full_params is unavailable + nested_params[group] = TypeAdapter(type(group_params)).dump_python(group_params, round_trip=True) + else: + nested_params[group] = group_params + + elif isinstance(group_params, GroupParams): + raise ValueError(f'Cannot override other params for the {group} group with a {type(group_params).__name__} object') + else: # updating existing dict with a dict + overridden_params = nested_params[group].keys() & group_params.keys() + for param in overridden_params: + if not utilities.all_same(old := nested_params[group][param], new := group_params[param]): + if error_on_changing_override: + raise RuntimeError(f'Parameter {group}/{param} received two different values.') + else: + logger.warning(f'Parameter {group}/{param} was overridden (old = {old}, new = {new}) - was this intended?') + nested_params[group].update(group_params) # don't check every subkey here, they will be checked in GroupParams validator + + + @classmethod + def update_nested_params( + cls, nested_params: dict[str, dict], new_params: Mapping[str, Any], allow_legacy=True, + warn_unused=True, error_on_changing_override: Union[bool, Literal['within_new']] = 'within_new') -> dict[str, dict]: + """ + Update a nested params dict with a dict potentially containing both flat and nested params. + Does not check nested keys for validity. + Keys are processed in order, later ones overriding earlier ones, but a warning is logged + for each override if it changes the value of the parameter. If error_on_changing_override is true, + an error is raised instead. By default, an error is raised for changing overrides + only within new_params, not when something in new_params overrides something in nested_params. + + Pre-constructed objects of GroupParams subtypes are accepted under the group top-level keys, + but only if no params have previously been processed from that group (including existing keys in + nested_dict_in) because we don't know which params are user-specified vs. defaults. + """ + if error_on_changing_override == 'within_new': + # implement by combining new_params first, then combining with nested_params + # add an empty dict for each group present in nested_params to block updating with GroupParams + combined_new: dict[str, Any] = {group: {} for group in nested_params} + cls.update_nested_params( + combined_new, new_params, allow_legacy=allow_legacy, warn_unused=warn_unused, error_on_changing_override=True) + new_params = combined_new + error_on_changing_override = False + + logger = logging.getLogger('caiman') + groups = cls.get_group_types() + + legacy_used = False + for paramkey, paramval in new_params.items(): + # Handle proper pathed part. Latter half of the conditional is because of scoped keys with the same name as categories, because we apparently have those. ring_CNN is an example. + if paramkey in groups and isinstance(paramval, (dict, GroupParams)): + cls._update_group(nested_params, group=paramkey, group_params=paramval, error_on_changing_override=error_on_changing_override) + + # BEGIN code that we will remove in some future version of caiman + elif allow_legacy: + paramkey_orig = paramkey + if paramkey in cls.flat_param_renames: + # search for the renamed name (luckily there are not any that use different names for different groups) + paramkey = cls.flat_param_renames[paramkey] + + found = False + for group, GroupClass in groups.items(): + if paramkey in GroupClass.input_params(): # Is it known? + found = True + if group not in nested_params: + nested_params[group] = {paramkey: paramval} + else: + # deal with override + if paramkey in nested_params[group] and not utilities.all_same(old := nested_params[group][paramkey], paramval): + if error_on_changing_override: + raise RuntimeError(f'Parameter {group}/{paramkey} recevied two different values.') + else: + logger.warning(f'Parameter {group}/{paramkey} was overridden (old = {old}, new = {paramval}) - was this intended?') + + nested_params[group][paramkey] = paramval + if found: + legacy_used = True + elif warn_unused: + logger.warning(f"In setting CNMFParams, provided toplevel key {paramkey_orig} was not consumed. This is a bug!") + # END + else: + raise ValueError(f'Key {paramkey} does not match a parameter group, or the value is not a dictionary.') + + if legacy_used: + logger.warning("In setting CNMFParams, non-pathed parameters were used; this is deprecated. " + "In some future version of Caiman, allow_legacy will default to False (and eventually will be removed).") + + return nested_params + + + def change_params(self, params_dict: dict[str, Any], allow_legacy=True, warn_unused=True, verbose=False) -> None: """ Method for updating the params object by providing a dictionary. Args: - params_dict: dictionary with parameters to be changed - verbose: If true, will complain if the params dictionary is not complete + params_dict: dictionary with parameters to be changed. Values may be in raw format + read directly from JSON; they will be converted based on each field's declared type. allow_legacy: If True, throw a deprecation warning and then attempt to handle unconsumed keys using the older copy-it-everywhere logic. We will eventually remove this option and the corresponding code. @@ -1133,53 +1786,31 @@ def change_params(self, params_dict, allow_legacy:bool=True, warn_unused:bool=Tr were never used in populating the Params object. You really should not set this to False. Fix your code. """ - logger = logging.getLogger("caiman") - # When we're ready to remove allow_legacy, this code will get a lot simpler - - consumed = {} # Keep track of what parameters in params_dict were used to set something in params (just for legacy API) - nagged_once = False # So we don't nag people multiple times in the same call - for paramkey in params_dict: - if paramkey in list(self.__dict__.keys()) and isinstance(params_dict[paramkey], dict): # Handle proper pathed part. Latter half of the conditional is because of scoped keys with the same name as categories, because we apparently have those. ring_CNN is an example. - cat_handle = getattr(self, paramkey) - for k, v in params_dict[paramkey].items(): - if k == 'nb' and paramkey != 'init': - # Special casing to handle a misdesign in CNMFParams where some keys must have the same value in different - # sections. - logger.warning("The 'nb' parameter can only be set in the init part of CNMFParams. Attempts to set it elsewhere are ignored") - continue - if k not in cat_handle and warn_unused: - # For regular/pathed API, we can notice right away if the user gave us something that won't update the object - logger.warning(f"In setting CNMFParams, provided key {paramkey}/{k} was not consumed. This is a bug!") - else: - cat_handle[k] = v - # BEGIN code that we will remove in some future version of caiman - elif allow_legacy: - legacy_used = False - for category in list(self.__dict__.keys()): - cat_handle = getattr(self, category) # Thankfully a read-write handle - if paramkey in cat_handle: # Is it known? - legacy_used = True - consumed[paramkey] = True - cat_handle[paramkey] = params_dict[paramkey] # Do the update - if legacy_used: - if not nagged_once: - logger.warning(f"In setting CNMFParams, non-pathed parameters were used; this is deprecated. In some future version of Caiman, allow_legacy will default to False (and eventually will be removed)") - nagged_once = True - # END - if warn_unused: - for toplevel_k in params_dict: - if toplevel_k not in consumed and toplevel_k not in list(self.__dict__.keys()): # When we remove legacy behaviour, this logic will simplify and fold into above - logger.warning(f"In setting CNMFParams, provided toplevel key {toplevel_k} was unused. This is a bug!") + # First collect updates in the nested format (and remove those that don't match any real param) + # Start with an empty dict for each group, to prevent passing GroupParams objects (since that would + # confusingly override all params for that group) + nested_params = {group: {} for group in self.groups} + self.update_nested_params( + nested_params=nested_params, new_params=params_dict, allow_legacy=allow_legacy, warn_unused=warn_unused, + error_on_changing_override=True) + + # now update each group, attempting to convert each value + for group, group_updates in nested_params.items(): + if group_updates: + # update group, bypassing frozen + group_params = self.get_group(group) + new_group_params = group_params.replace(warn_unused=warn_unused, **group_updates) + object.__setattr__(self, group, new_group_params) + self.check_consistency() - def change_params_from_json(self, jsonstring:str, verbose:bool=False) -> None: + def change_params_from_json(self, jsonstring: str, verbose: bool = False) -> None: """ Same as change_params, except it takes json as input """ - to_load = json.loads(jsonstring) - self.change_params(to_load, verbose=verbose) + input_dict = json.loads(jsonstring) + self.change_params(input_dict, verbose=verbose) - def change_params_from_jsonfile(self, json_fn:str, verbose:bool=False) -> None: + def change_params_from_jsonfile(self, json_fn: str, verbose: bool = False) -> None: """ Same as change_params, except it takes a json file as input; pass the filename """ with open(json_fn, 'r') as json_fh: - to_load = json.load(json_fh) - self.change_params(to_load, verbose=verbose) - + jsonstring = json_fh.read() + self.change_params_from_json(jsonstring, verbose=verbose) diff --git a/caiman/source_extraction/cnmf/utilities.py b/caiman/source_extraction/cnmf/utilities.py index 2219736aa..695c7b879 100644 --- a/caiman/source_extraction/cnmf/utilities.py +++ b/caiman/source_extraction/cnmf/utilities.py @@ -10,18 +10,19 @@ import cv2 import logging -import numpy as np -import os -import pathlib import matplotlib.pyplot as plt +import numpy as np +import numpy.testing as npt +import psutil import scipy -from scipy.sparse import spdiags, issparse, csc_matrix, csr_matrix import scipy.ndimage as ndi +from scipy.sparse import csc_matrix, csr_matrix, issparse, spdiags import caiman.base.rois import caiman.cluster import caiman.mmapping import caiman.source_extraction.cnmf.initialization +import caiman.source_extraction.cnmf.map_reduce import caiman.utils.stats @@ -355,14 +356,31 @@ def peak_local_max(image, min_distance=1, threshold_abs=None, return out +def all_same(obj1, obj2) -> bool: + """ + An equals method that removes the weirdness around ndarrays and nans + (i.e., checks for equality of shape and all values for arrays, and + considers nans equal). + This is what np.array_equal(equal_nan=True) should do, but it raises an error for + non-numeric types; numpy seems to be stuck considering whether the isnan + function should be changed before taking action (https://github.com/numpy/numpy/issues/16377) + Meanwhile npt.assert_array_equal just does the right thing. + """ + try: + npt.assert_array_equal(obj1, obj2, strict=True) + return True + except AssertionError: + return False + + def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys - modified = {o : (d1[o], d2[o]) for o in intersect_keys if np.any(d1[o] != d2[o])} - same = set(o for o in intersect_keys if np.all(d1[o] == d2[o])) + same = set(o for o in intersect_keys if all_same(d1[o], d2[o])) + modified = {o : (d1[o], d2[o]) for o in intersect_keys - same} return added, removed, modified, same @@ -1156,7 +1174,7 @@ def fast_graph_Laplacian(mmap_file, dims, max_radius=10, kernel='heat', D = scipy.sparse.spdiags(W.sum(0), 0, Np, Np) L = D - W else: - indices, _ = caiman.cluster.extract_patch_coordinates(dims, rf, strides) + indices, _ = caiman.source_extraction.cnmf.map_reduce.extract_patch_coordinates(dims, rf, strides) pars = [] for i in range(len(indices)): pars.append([mmap_file, indices[i], kernel, sigma, thr, p, @@ -1280,3 +1298,15 @@ def nextpow2(value): while avalue > np.power(2, exponent): exponent += 1 return exponent + + +def estimate_n_pixels_per_process(n_processes: int, T: int, dims: tuple[int, ...]) -> int: + """ + Estimate a safe number of pixels to allocate to each parallel process at a time + """ + # FIXME The code below is really ugly and it's hard to tell if it's doing the right thing. + avail_memory_per_process = psutil.virtual_memory()[1] / n_processes / 2.0**30 + mem_per_pix = 3.6977678498329843e-09 + npx_per_proc = int(avail_memory_per_process / 8. / mem_per_pix / T) + npx_per_proc = int(np.minimum(npx_per_proc, np.prod(dims) // n_processes)) + return npx_per_proc \ No newline at end of file diff --git a/caiman/tests/comparison_humans.py b/caiman/tests/comparison_humans.py index 8c7d7f14c..57c7592c9 100644 --- a/caiman/tests/comparison_humans.py +++ b/caiman/tests/comparison_humans.py @@ -328,11 +328,8 @@ }, 'preprocess': { 'check_nan': check_nan, - 'n_pixels_per_process': n_pixels_per_process, - 'p': global_params['p'], }, 'spatial': { - 'nb': global_params['gnb'], 'num_blocks_per_run_spat': num_blocks_per_run, 'n_pixels_per_process': n_pixels_per_process, 'thr_method': 'nrg' @@ -340,7 +337,6 @@ 'temporal': { 'block_size_temp': block_size, 'method_deconvolution': 'oasis', - 'nb': global_params['gnb'], 'num_blocks_per_run_temp': num_blocks_per_run, 'p': global_params['p'], }, @@ -383,18 +379,23 @@ if plot_on: cnm2.estimates.plot_contours(img=Cn) # check quality of components and eliminate low quality - cnm2.params.set('quality', {'SNR_lowest': global_params['SNR_lowest'], - 'min_SNR': global_params['min_SNR'], - 'rval_thr': global_params['rval_thr'], - 'rval_lowest': global_params['min_rval_thr_rejected'], - #'Npeaks': global_params['Npeaks'], - 'use_cnn': True, - 'min_cnn_thr': global_params['min_cnn_thresh'], - 'cnn_lowest': global_params['max_classifier_probability_rejected'], - #'thresh_fitness_delta': global_params['max_fitness_delta_accepted'], - 'gSig_range': None}) - - cnm2.params.set('data',{'decay_time':params_movie['decay_time']}) + cnm2.params.change_params({ + 'quality': { + 'SNR_lowest': global_params['SNR_lowest'], + 'min_SNR': global_params['min_SNR'], + 'rval_thr': global_params['rval_thr'], + 'rval_lowest': global_params['min_rval_thr_rejected'], + #'Npeaks': global_params['Npeaks'], + 'use_cnn': True, + 'min_cnn_thr': global_params['min_cnn_thresh'], + 'cnn_lowest': global_params['max_classifier_probability_rejected'], + #'thresh_fitness_delta': global_params['max_fitness_delta_accepted'], + 'gSig_range': None + }, + 'data': { + 'decay_time': params_movie['decay_time'] + } + }) t1 = time.time() cnm2.estimates.evaluate_components(images, cnm2.params, dview=dview) diff --git a/caiman/tests/comparison_humans_online.py b/caiman/tests/comparison_humans_online.py index 75aeb0987..36a3fe0e0 100644 --- a/caiman/tests/comparison_humans_online.py +++ b/caiman/tests/comparison_humans_online.py @@ -211,18 +211,11 @@ 'use_dense': False, 'use_peak_max': True, }, - 'preprocess': { - 'p': global_params['p'], - }, 'quality': { 'min_SNR': global_params['min_SNR'], 'rval_thr': global_params['rval_thr'], }, - 'spatial': { - 'nb': gnb, - }, 'temporal': { - 'nb': gnb, 'p': global_params['p'], }, } @@ -241,7 +234,7 @@ # filter results by using the batch CNN use_cnn = False if use_cnn: - cnm.params.set('quality', {'min_cnn_thr': 0.1}) + cnm.params.change_params({'quality': {'min_cnn_thr': 0.1}}) cnm.estimates.evaluate_components_CNN(cnm.params) cnm.estimates.select_components(use_object=True) diff --git a/caiman/tests/test_onacid.py b/caiman/tests/test_onacid.py index 15248251c..dacb32bc8 100644 --- a/caiman/tests/test_onacid.py +++ b/caiman/tests/test_onacid.py @@ -49,18 +49,11 @@ def demo(): 'rf': patch_size // 2, 'stride': stride }, - 'preprocess': { - 'p': p - }, 'quality': { 'min_SNR': min_SNR # FIXME duplicated between online.min_SNR and quality.min_SNR }, - 'spatial': { - 'nb': gnb # FIXME duplicated between init.nb and spatial.nb and temporal.nb - }, 'temporal': { - 'nb': gnb, # FIXME duplicated between init.nb and spatial.nb and temporal.nb - 'p': p, # FIXME duplicated between preprocess.p and temporal.p + 'p': p }, } opts = cnmf.params.CNMFParams(params_dict=params_dict) diff --git a/caiman/tests/test_params.py b/caiman/tests/test_params.py new file mode 100644 index 000000000..b66b41cc5 --- /dev/null +++ b/caiman/tests/test_params.py @@ -0,0 +1,443 @@ +#!/usr/bin/env python +"""Test CNMFParams object functionality""" + +from copy import deepcopy +from dataclasses import FrozenInstanceError +import json +import math +import numpy as np +import numpy.testing as npt +import os +from pathlib import Path +from pydantic import ValidationError, TypeAdapter +import pytest +import scipy.special +from tabulate import tabulate +from typing import Any, cast + +from caiman.base import movies +from caiman.paths import caiman_datadir +from caiman.source_extraction.cnmf import params, cnmf +import caiman.utils.utils + + +# ---- UTILITIES ----- # + +def tabulate_differing_params(expected: params.CNMFParams, actual: params.CNMFParams) -> str: + return '\n\n' + tabulate(expected.get_differing_params(actual), headers=['Name', 'Expected', 'Actual']) + '\n\n' + + +def check_params_equal_expected(params_obj: params.CNMFParams, expected_params: dict[str, dict[str, Any]], + cause='was not correct.'): + """Validate the given CNMFParams object against a nested params dict""" + for groupname, gt_group in expected_params.items(): + group = params_obj.get_group(groupname) + for field, gt_val in gt_group.items(): + info = [cause] + if isinstance(gt_val, dict) and 'value' in gt_val: + if 'msg' in gt_val: + info.append(gt_val['msg']) + gt_val = gt_val['value'] + npt.assert_array_equal(group[field], gt_val, f'Field {groupname}.{field} ' + ' '.join(info)) + + +# example nested dict with some various parameters to test constructors with +params_dict: dict[str, Any] = { + 'data': { + 'var_name_hdf5': 'movie', + }, + 'init': { + 'K': 20, + 'nb': 2 # automatically updates spatial.nb and temporal.nb + }, + 'temporal': { + 'p': 3 + } +} + +# flat params version of the same parameters +params_dict_flat = { + 'var_name_hdf5': params_dict['data']['var_name_hdf5'], + 'k': params_dict['init']['K'], + 'gnb': params_dict['init']['nb'], + 'p': params_dict['temporal']['p'] +} + + +# ---- TESTS ---- # + +def test_validation(caplog: pytest.LogCaptureFixture): + """Test GroupParams type validators""" + temporal_params = params.TemporalParams(solvers=[b'CVXOPT', 'SCS'], noise_range=(0.25, 0.5)) # type: ignore + assert temporal_params.solvers == ['CVXOPT', 'SCS'], 'Bytes should be converted to string' + assert temporal_params.noise_range == [0.25, 0.5], 'Tuple should be converted to list' + assert len(caplog.records) == 0, 'Coercing these types should not cause a warning' + + # replace should be the same thing, but with an update + modified_params = temporal_params.replace(noise_method=b'logmexp') + assert modified_params.noise_method == 'logmexp', 'dataclasses.replace should update and validate' + unmodified_params = modified_params.replace(noise_method=temporal_params.noise_method) + assert unmodified_params == temporal_params, 'Should be the same after changing back' + + # test None interpretation + K/method_init dependency + caplog.clear() + init_params = params.InitParams(K='None', method_init='corr_pnr') # type: ignore + assert len(caplog.records) == 0, 'Should not warn converting "None" to None' + assert init_params.K is None, 'Should convert "None" to None' + init_params = init_params.replace(K=b'NoneType', method_init='greedy_roi') + assert init_params.K is None, 'Should convert b"NoneType" to None' + assert len(caplog.records) == 1 and caplog.records[0].levelname == 'ERROR' and \ + 'cannot be set to None' in caplog.records[0].getMessage(), \ + 'Should log error when K is set to None with incompatible init method' + + # test NDArray interpretation + caplog.clear() + preprocess_params = params.PreprocessParams(sn=[0.1, 0.2, 0.3]) # type: ignore + assert len(caplog.records) == 0, 'Should not warn converting list to ndarray' + assert isinstance(preprocess_params.sn, np.ndarray), 'Should convert list to ndarray' + npt.assert_array_equal(preprocess_params.sn, [0.1, 0.2, 0.3], 'Array should be equal to input') + preprocess_dumped = TypeAdapter(params.PreprocessParams).dump_python(preprocess_params, round_trip=True) + assert isinstance(preprocess_dumped['sn'], list), 'ndarray should be serialized to list' + + # test slice interpretation + caplog.clear() + motion_params = params.MotionParams(indices=(slice(None, None, 2), (1, -1, 2))) # type: ignore + assert len(caplog.records) == 0, 'Should not warn converting tuple to slice' + assert motion_params.indices == (slice(None, None, 2), slice(1, -1, 2)), '3-tuples should be converted to slices' + motion_dumped = TypeAdapter(params.MotionParams).dump_python(motion_params, round_trip=True) + assert motion_dumped['indices'] == ((None, None, 2), (1, -1, 2)), 'Slices should be serialized to 3-tuples' + + # test automatically wrapping scalar filename in list + caplog.clear() + data_params = params.DataParams(fnames='abc') # type: ignore + assert len(caplog.records) == 0, 'Should not warn converting scalar to list' + assert data_params.fnames == ['abc'], 'Scalar fnames should be wrapped in a list.' + + # test gSiz coercing to odd int + init_params = params.InitParams(gSiz=[4, 5]) # type: ignore (alias) + assert init_params.gSiz == [5, 5], 'Even ints should be converted to odd in gSiz' + + # test frozenness + with pytest.raises(FrozenInstanceError): + data_params.dxy = [1., 1.] # type: ignore + + # __getitem__ + assert data_params.var_name_hdf5 == data_params['var_name_hdf5'], '__getitem__ should work on GroupParams' + + # validation error handling + caplog.clear() + modified_params = temporal_params.replace(fudge_factor='foobar') + assert len(caplog.records) == 1 and caplog.records[0].levelname == "WARNING" and \ + "could not be converted" in caplog.records[0].message, 'Should warn appropriately when changing a value to the wrong type' + assert modified_params.fudge_factor == 'foobar', 'Should allow change even if there is a validation error' + + +def test_change_params_flat(): + """ + Test that change_params method changes params as expected + (result is used to validate each constructor) + """ + params_orig = params.CNMFParams() + params_changed = deepcopy(params_orig) + params_changed.change_params(params_dict_flat, verbose=False) + + assert params_changed.data.var_name_hdf5 == params_dict_flat['var_name_hdf5'], 'Normal flat param should be set' + object.__setattr__(params_changed.data, 'var_name_hdf5', params_orig.data.var_name_hdf5) + + assert params_changed.init.K == params_dict_flat['k'], 'Renamed flat param should be set' + object.__setattr__(params_changed.init, 'K', params_orig.init.K) + + assert params_changed.preprocess.p == params_changed.temporal.p == params_dict_flat['p'], \ + 'Shared flat param should be set on both groups' + object.__setattr__(params_changed.temporal, 'p', params_orig.temporal.p) + + assert params_changed.init.nb == params_changed.spatial.nb == params_changed.temporal.nb \ + == params_dict_flat['gnb'], 'Shared and renamed param should be set on all groups' + object.__setattr__(params_changed.init, 'nb', params_orig.init.nb) + + assert params_changed == params_orig, 'These should be the only changes. Differing parameters: ' + \ + tabulate_differing_params(params_orig, params_changed) + + +def test_change_params_nested(): + params_changed_flat = params.CNMFParams() + params_changed_flat.change_params(params_dict_flat, verbose=False) + + params_changed_nested = params.CNMFParams() + params_changed_nested.change_params(params_dict) + + assert params_changed_flat == params_changed_nested, \ + 'Equivalent flat and nested params changes should result in equal CNMFParams objects. Differences: ' + \ + tabulate_differing_params(params_changed_flat, params_changed_nested) + + # should not allow changing with a GroupParams object + with pytest.raises(ValueError): + params_changed_nested.change_params({'init': params.InitParams()}) + + +def test_redundant_change_params(caplog: pytest.LogCaptureFixture): + """Test setting a parameter that is shared between 2 groups""" + params_base = params.CNMFParams(temporal=params.TemporalParams(p=2)) + caplog.clear() + params_base.change_params({'preprocess': {'p': 1}}) + assert (len(caplog.records) == 1 and caplog.records[0].levelname == 'WARNING' and + 'set on temporal instead' in caplog.records[0].message), 'Should warn when setting param on wrong group' + assert params_base.preprocess.p == 1, 'Should set the parameter on the non-canonical group' + assert params_base.temporal.p == 1, 'Should set the parameter on the canonical group' + + try: + params_base.change_params({'preprocess': {'p': 2}, 'temporal': {'p': 2}}) + except Exception as e: + raise AssertionError('Should not error when setting shared parameter in 2 groups to matching values') from e + assert params_base.preprocess.p == 2, 'Should set the parameter on the non-canonical group' + assert params_base.temporal.p == 2, 'Should set the parameter on the canonical group' + + exc = None + try: + params_base.change_params({'preprocess': {'p': 1}, 'temporal': {'p': 2}}) + except RuntimeError as e: + exc = e + if exc is None or 'received two different values' not in exc.args[0]: + raise AssertionError('Should error when trying to set shared parameter in 2 groups to different values') from exc + + +def test_flat_constructor(): + """Test constructing CNMFParams with flat parameter names""" + params_changed_flat = params.CNMFParams() + params_changed_flat.change_params(params_dict_flat, verbose=False) + params_constr_flat = params.CNMFParams(**params_dict_flat) # type: ignore + assert params_changed_flat == params_constr_flat, \ + 'Constructing directly with flat params should work the same as change_params. Differences: ' + \ + tabulate_differing_params(params_changed_flat, params_constr_flat) + + +def test_dict_constructor(): + """Test constructing with params_dict""" + params_changed = params.CNMFParams() + params_changed.change_params(params_dict) + params_constr_dict = params.CNMFParams(params_dict=params_dict) + assert params_changed == params_constr_dict, \ + 'Constructing directly with dict should work the same as change_params. Differences: ' + \ + tabulate_differing_params(params_changed, params_constr_dict) + + +def test_json_constructor(tmp_path: Path): + """Test constructing from a JSON file""" + json_path = tmp_path / 'test_params.json' + with open(json_path, 'w') as fh: + json.dump(params_dict, fh) + + params_changed = params.CNMFParams() + params_changed.change_params(params_dict) + params_from_json = params.CNMFParams(params_from_file=json_path) + assert params_changed == params_from_json, \ + 'Constructing from JSON should work the same as change_params. Differences: ' + \ + tabulate_differing_params(params_changed, params_from_json) + + +def test_object_constructor(): + """Test constructing from individual GroupParams objects""" + data = params.DataParams(**params_dict['data']) + init = params.InitParams(**params_dict['init']) + temporal = params.TemporalParams(**params_dict['temporal']) + + params_changed = params.CNMFParams() + params_changed.change_params(params_dict) + params_from_objs = params.CNMFParams(data=data, init=init, temporal=temporal) + assert params_changed == params_from_objs, \ + 'Constructing from sub-objects should work the same as change_params. Differences: ' + \ + tabulate_differing_params(params_changed, params_from_objs) + + +def test_multi_dict_constructor(): + """Test constructing from multiple dicts of group params""" + params_changed = params.CNMFParams() + params_changed.change_params(params_dict) + params_from_dicts = params.CNMFParams(**params_dict) + assert params_changed == params_from_dicts, \ + 'Constructing from dicts for each group should work the same as change_params. Differences: ' + \ + tabulate_differing_params(params_changed, params_from_dicts) + + +def test_mixed_constructor(tmp_path: Path): + """Test valid and invalid combinations of constructor syntaxes""" + json_params = {'data': {'var_name_hdf5': 'movie'}, 'patch': {'border_pix': 5}} + dict_params = {'preprocess': {'check_nan': False}, 'init': {'K': 40}} + indiv_params = {'init': {'K': 45, 'center_psf': True}, 'spatial': {'dist': 4.}} + init_combined = {**dict_params['init'], **indiv_params['init']} + dict_plus_indiv_params = { + **dict_params, **indiv_params, + 'init': {k: {'value': v, 'msg': 'Common group should be overridden by group keyword arg'} + for k, v in init_combined.items()} + } + + # JSON plus dict, non-overlapping groups + json_path = tmp_path / 'partial_params.json' + with open(json_path, 'w') as fh: + json.dump(json_params, fh) + + json_plus_dict = params.CNMFParams(params_from_file=json_path, params_dict=dict_params) + check_params_equal_expected(json_plus_dict, {**json_params, **dict_params}, + ' not set correctly in JSON + dict constructor') + + dict_plus_indiv = params.CNMFParams(params_dict=dict_params, **indiv_params) # type: ignore + check_params_equal_expected(dict_plus_indiv, dict_plus_indiv_params, + ' not set correctly in dict + group keyword constructor') + + # try something that should raise an error + with pytest.raises(ValidationError) as ve: + params.CNMFParams( + params_dict=dict_params, init=params.InitParams(K=45, center_psf=True)) + + errs = ve.value.errors() + assert len(errs) == 1 and 'Cannot override other params' in errs[0]['msg'], \ + 'Trying to override param group with an object should raise an error' + + +def test_jsonfile_roundtrip(tmp_path: Path, caplog: pytest.LogCaptureFixture): + """Test that saving and restoring whole object to/from JSON file is successful""" + caplog.clear() + json_path = tmp_path / 'full_params.json' + params_orig = params.CNMFParams() + params_orig.to_jsonfile(str(json_path), verify=False) + params_recon = params.CNMFParams(params_from_file=json_path) + assert params_orig == params_recon, \ + 'Full object should be equal after saving and restoring from JSON file. Differences: ' + \ + tabulate_differing_params(params_orig, params_recon) + + assert len(caplog.records) == 0, 'Converting to and from JSON file should not cause a warning' + + +def test_hdf5_roundtrip(tmp_path: Path): + """Test that saving and restoring to/from HDF5 (as part of CNMF object) is successful""" + params_in = params.CNMFParams(data=params.DataParams(var_name_hdf5='movie2')) + n_processes = 4 + cnmf_obj = cnmf.CNMF(n_processes, params=params_in) + + # save and re-load + hdf5_path = tmp_path / 'test_cnmf.hdf5' + cnmf_obj.save(str(hdf5_path)) + cnmf_obj_reconstr = cnmf.load_CNMF(str(hdf5_path), n_processes=n_processes) + + assert cnmf_obj.params == cnmf_obj_reconstr.params, \ + 'Params should be the same after saving and re-loading from HDF5. Differences: ' + \ + tabulate_differing_params(cnmf_obj.params, cnmf_obj_reconstr.params) + + +def test_check_consistency(): + # make params to test corrections performed by check_consistency + demo_movie_path = os.path.join(caiman_datadir(), 'example_movies', 'demoMovie.tif') + dims, T = movies.get_file_size(demo_movie_path) + T = cast(int, T) + + input_params = { + 'data': { + 'fnames': [demo_movie_path], + 'fr': 15.5, + 'decay_time': 0.3 + }, + 'init': { + 'gSig': None, + 'gSiz': None, + # to trigger ring model check + 'method_init': 'corr_pnr', + 'ring_size_factor': 1.5, + 'normalize_init': True, + 'nb': -1 + }, + 'patch': { + 'nb_patch': 1, + 'low_rank_background': None + }, + 'online': { + 'movie_name_online': 'onlineMovie.tif', + 'N_samples_exceptionality': None, + 'thresh_fitness_raw': None, + 'min_SNR': 2.5, + 'max_num_added': 0, + 'update_num_comps': True + }, + 'motion': { + 'num_frames_split': 80, + 'is3D': True, + 'indices': (slice(None), slice(None)), + 'max_shifts': (5, 5, 6), + 'strides': (96, 96), + 'overlaps': (32, 32) + } + } + + num_splits = max(T // max(input_params['motion']['num_frames_split'], 10), 1) + nsamp_exc = math.ceil(input_params['data']['fr'] * input_params['data']['decay_time']) + + # corrected version of above + expected_params = { + 'data': { + 'last_commit': {'value': '-'.join(caiman.utils.utils.get_caiman_version()), + 'msg': 'Should be set to current CaImAn version.'}, + 'dims': {'value': dims, 'msg': 'Should be set to dimensions of given movie'} + }, + 'init': { + 'gSig': {'value': [-1, -1], 'msg': 'Should be set to [-1, -1] by default'}, + 'gSiz': {'value': [-1, -1], 'msg': 'Should equal 2*gSig+1 by default'}, + 'normalize_init': {'value': False, 'msg': 'Should turn off normalize_init with corr_pnr method'} + }, + 'patch': { + 'nb_patch': {'value': -1, 'msg': 'Should be set to nb when nb < 0'}, + }, + 'spatial': { + 'update_background_components': {'value': False, 'msg': 'Should be set to False when nb == -1'}, + 'nb': {'value': -1, 'msg': 'Should be set based on init.nb'}, + }, + 'temporal': { + 'nb': {'value': -1, 'msg': 'Should be set based on init.nb'} + }, + 'online': { + 'movie_name_online': {'value': os.path.join(os.path.dirname(demo_movie_path), input_params['online']['movie_name_online']), + 'msg': 'Relative path should be resolved from the directory of fnames[0].'}, + 'N_samples_exceptionality': {'value': nsamp_exc, 'msg': 'Should be set based on fr and decay_time'}, + 'thresh_fitness_raw': {'value': scipy.special.log_ndtr(-input_params['online']['min_SNR']) * nsamp_exc, + 'msg': 'Should be set based on SNR threshold and N_samples_exceptionality'}, + 'update_num_comps': {'value': False, 'msg': 'Should be set to False when online.max_num_added == 0'} + }, + 'motion': { + 'splits_els': {'value': num_splits, 'msg': 'Should be set based on number of frames and num_frames_split'}, + 'splits_rig': {'value': num_splits, 'msg': 'Should be set based on number of frames and num_frames_split'}, + 'indices': {'value': (slice(None), slice(None), slice(None)), 'msg': 'Should be expanded to 3D'}, + 'max_shifts': {'value': input_params['motion']['max_shifts'], 'msg': 'Should be left alone when already 3D'}, + 'strides': {'value': (96, 96, 96), 'msg': 'Should be expanded to 3D'}, + 'overlaps': {'value': (32, 32, 32), 'msg': 'Should be expanded to 3D'} + } + } + + params_obj = params.CNMFParams(params_dict=input_params) + check_params_equal_expected(params_obj, expected_params, 'was not updated in check_consistency.') + + # another gSig/gSiz case + params_obj.change_params({'init': {'gSiz': [6, 5]}}) + check_params_equal_expected(params_obj, {'init': {'gSiz': {'value': [7, 5], 'msg': 'Should be changed so each entry is odd'}}}) + + # another combination for patch + params_obj.change_params({ + 'init': {'nb': -2}, + 'patch': {'nb_patch': -2, 'low_rank_background': True}, + 'spatial': {'update_background_components': True} + }) + + check_params_equal_expected(params_obj, { + 'patch': {'low_rank_background': {'value': None, 'msg': 'Should be set to None when nb < 0'}}, + 'spatial': {'update_background_components': {'value': True, 'msg': 'Should not be changed unless nb == -1'}} + }) + + params_obj.change_params({ + 'online': {'min_num_trial': 0, 'update_num_comps': True} + }) + + check_params_equal_expected(params_obj, { + 'online': {'update_num_comps': {'value': False, 'msg': 'Should be set to False when online.min_num_trial == 0'}} + }) + + +if __name__ == '__main__': + retcode = pytest.main(['--verbose', __file__]) + exit(retcode) \ No newline at end of file diff --git a/caiman/tests/test_toydata.py b/caiman/tests/test_toydata.py index eeb5ce32b..08812b8bb 100644 --- a/caiman/tests/test_toydata.py +++ b/caiman/tests/test_toydata.py @@ -77,19 +77,15 @@ def get_params_dicts(D: int): dims = TOYDATA_DIMS[D] return { 'no-patch': { - 'data': {'dims': dims}, 'init': {'K': 4, 'gSig': [2, 2, 2][:D]}, - 'preprocess': {'p': 1, 'n_pixels_per_process': np.prod(dims)}, 'spatial': {'n_pixels_per_process': np.prod(dims), 'thr_method': 'nrg', 'extract_cc': False}, 'temporal': {'p': 1, 'block_size_temp': np.prod(dims)}, }, 'patch': { - 'data': {'dims': dims}, 'init': {'K': 4, 'gSig': [2, 2, 2][:D]}, 'patch': {'rf': [d // 2 for d in dims], 'stride': 1} # use one big patch to get the same results as without patches }, 'patch-not-lowrank': { - 'data': {'dims': dims}, 'init': {'K': 4, 'gSig': [2, 2, 2][:D]}, 'patch': {'rf': [d // 2 for d in dims], 'stride': 1, 'low_rank_background': False} } diff --git a/caiman/utils/utils.py b/caiman/utils/utils.py index 1b8b16f2e..a41fe1790 100644 --- a/caiman/utils/utils.py +++ b/caiman/utils/utils.py @@ -22,6 +22,8 @@ import numpy as np import os import pickle +from pydantic import TypeAdapter +from pydantic.dataclasses import is_pydantic_dataclass import scipy from scipy.ndimage import gaussian_filter import ssl @@ -488,8 +490,12 @@ def recursively_save_dict_contents_to_group(h5file:h5py.File, path:str, dic:dict 'strides', 'overlaps', 'gSig']: logger.info(f'{key} is a tuple ****') h5file[path + key] = np.array(item) - elif type(item).__name__ in ['CNMFParams', 'Estimates']: # parameter object + elif type(item).__name__ == 'Estimates': # object recursively_save_dict_contents_to_group(h5file, path + key + '/', item.__dict__) + elif is_pydantic_dataclass(type(item)): + ta = TypeAdapter(type(item)) + item_dict = ta.dump_python(item, round_trip=True) + recursively_save_dict_contents_to_group(h5file, path + key + '/', item_dict) else: raise ValueError(f"Cannot save {type(item)} type for key '{key}'.") @@ -524,11 +530,11 @@ def recursively_load_dict_contents_from_group(h5file:h5py.File, path:str) -> dic ans[key] = None elif key in ['dims', 'medw', 'sigma_smooth_snmf', 'dxy', 'max_shifts', 'strides', 'overlaps'] and isinstance(val, np.ndarray): - ans[key] = tuple(val) + ans[key] = tuple(val.tolist()) elif isinstance(val, np.bool_): # sigh ans[key] = bool(val) else: - ans[key] = item[()] + ans[key] = val elif isinstance(item, h5py._hl.group.Group): if key in ('A', 'W', 'Ab', 'downscale_matrix', 'upscale_matrix'): diff --git a/demos/general/demo_OnACID.py b/demos/general/demo_OnACID.py index a6da153e8..51206d9f2 100755 --- a/demos/general/demo_OnACID.py +++ b/demos/general/demo_OnACID.py @@ -65,7 +65,7 @@ def main(): use_CNN = True if use_CNN: # threshold for CNN classifier - opts.set('quality', {'min_cnn_thr': 0.05}) + opts.change_params({'quality': {'min_cnn_thr': 0.05}}) cnm.estimates.evaluate_components_CNN(opts) cnm.estimates.plot_contours(img=Cn, idx=cnm.estimates.idx_components) @@ -85,4 +85,5 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_OnACID_mesoscope.py b/demos/general/demo_OnACID_mesoscope.py index 4e1fe86f6..4fc93f0fd 100755 --- a/demos/general/demo_OnACID_mesoscope.py +++ b/demos/general/demo_OnACID_mesoscope.py @@ -84,12 +84,16 @@ def main(): T_detect = 1e3*np.array(cnm.t_detect) T_shapes = 1e3*np.array(cnm.t_shapes) T_track = 1e3*np.array(cnm.t_online) - T_motion - T_detect - T_shapes - plt.figure() - plt.stackplot(np.arange(len(T_motion)), T_motion, T_track, T_detect, T_shapes) - plt.legend(labels=['motion', 'tracking', 'detect', 'shapes'], loc=2) - plt.title('Processing time allocation') - plt.xlabel('Frame #') - plt.ylabel('Processing time [ms]') + + if not cfg.no_play: + plt.ion() + plt.figure() + plt.stackplot(np.arange(len(T_motion)), T_motion, T_track, T_detect, T_shapes) + plt.legend(labels=['motion', 'tracking', 'detect', 'shapes'], loc=2) + plt.title('Processing time allocation') + plt.xlabel('Frame #') + plt.ylabel('Processing time [ms]') + plt.show() # Prepare result visualisations (might take time) c, dview, n_processes = cm.cluster.setup_cluster(backend=cfg.cluster_backend, n_processes=cfg.cluster_nproc) @@ -120,8 +124,6 @@ def main(): cnm.save(os.path.splitext(fnames[0])[0] + '_results.hdf5') dview.terminate() - if not cfg.no_play: - matplotlib.pyplot.show(block=True) def handle_args(): parser = argparse.ArgumentParser(description="Full OnACID Caiman demo") @@ -135,4 +137,5 @@ def handle_args(): return parser.parse_args() ######## -main() \ No newline at end of file +if __name__ == '__main__': + main() diff --git a/demos/general/demo_behavior.py b/demos/general/demo_behavior.py index 169aaad45..edeb53562 100755 --- a/demos/general/demo_behavior.py +++ b/demos/general/demo_behavior.py @@ -113,4 +113,5 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_caiman_basic.py b/demos/general/demo_caiman_basic.py index e01606d2d..236303c02 100755 --- a/demos/general/demo_caiman_basic.py +++ b/demos/general/demo_caiman_basic.py @@ -132,4 +132,5 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_pipeline.py b/demos/general/demo_pipeline.py index 76f098393..73443586b 100755 --- a/demos/general/demo_pipeline.py +++ b/demos/general/demo_pipeline.py @@ -19,7 +19,7 @@ import cv2 import glob import logging -import matplotlib +import matplotlib.pyplot as plt import numpy as np import os @@ -67,6 +67,7 @@ def main(): # To close the video press q if not cfg.no_play: + plt.ion() ds_ratio = 0.2 moviehandle = m_orig.resize(1, 1, ds_ratio) moviehandle.play(q_max=99.5, fr=60, magnification=2) @@ -179,7 +180,7 @@ def main(): # Stop the cluster and clean up log files caiman.stop_server(dview=dview) if not cfg.no_play: - matplotlib.pyplot.show(block=True) + plt.show() if not cfg.keep_logs: log_files = glob.glob('*_LOG_*') @@ -198,5 +199,6 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_pipeline_NWB.py b/demos/general/demo_pipeline_NWB.py index 79d13b3a5..b12251616 100755 --- a/demos/general/demo_pipeline_NWB.py +++ b/demos/general/demo_pipeline_NWB.py @@ -246,5 +246,6 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_pipeline_cnmfE.py b/demos/general/demo_pipeline_cnmfE.py index 11709d03b..51512710f 100755 --- a/demos/general/demo_pipeline_cnmfE.py +++ b/demos/general/demo_pipeline_cnmfE.py @@ -91,8 +91,7 @@ def main(): # Parameters for source extraction and deconvolution (CNMF-E algorithm) Ain = None # possibility to seed with predetermined binary masks - opts.change_params(params_dict={'dims': dims, # we rework the source files - 'border_pix': bord_px}) # number of pixels to not consider in the borders) + opts.change_params(params_dict={'patch': {'border_pix': bord_px}}) # number of pixels to not consider in the borders) # compute some summary images (correlation and peak to noise) # change swap dim if output looks weird, it is a problem with tiffile @@ -150,5 +149,6 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/demo_pipeline_voltage_imaging.py b/demos/general/demo_pipeline_voltage_imaging.py index 0e6d6eb2a..773c2a617 100755 --- a/demos/general/demo_pipeline_voltage_imaging.py +++ b/demos/general/demo_pipeline_voltage_imaging.py @@ -286,5 +286,6 @@ def handle_args(): return parser.parse_args() ######## -main() +if __name__ == '__main__': + main() diff --git a/demos/general/params_demo_OnACID.json b/demos/general/params_demo_OnACID.json index d871c6f98..422bab9de 100644 --- a/demos/general/params_demo_OnACID.json +++ b/demos/general/params_demo_OnACID.json @@ -19,7 +19,7 @@ "rf": 16, "stride": 3 }, -"preprocess": { +"temporal": { "p": 1 } } diff --git a/demos/general/params_demo_OnACID_mesoscope.json b/demos/general/params_demo_OnACID_mesoscope.json index 623501a18..5083f40f9 100644 --- a/demos/general/params_demo_OnACID_mesoscope.json +++ b/demos/general/params_demo_OnACID_mesoscope.json @@ -8,9 +8,6 @@ "nb": 2, "K": 2 }, - "preprocess": { - "p": 1 - }, "temporal": { "p": 1 }, diff --git a/demos/general/params_demo_caiman_basic_with_patches.json b/demos/general/params_demo_caiman_basic_with_patches.json index 7cd7bae8e..63ac90c54 100644 --- a/demos/general/params_demo_caiman_basic_with_patches.json +++ b/demos/general/params_demo_caiman_basic_with_patches.json @@ -15,9 +15,6 @@ "merging": { "merge_thr": 0.80 }, -"preprocess": { - "p": 2 - }, "temporal": { "p": 2 }, diff --git a/demos/general/params_demo_caiman_basic_without_patches.json b/demos/general/params_demo_caiman_basic_without_patches.json index 229fffe0e..f21b12456 100644 --- a/demos/general/params_demo_caiman_basic_without_patches.json +++ b/demos/general/params_demo_caiman_basic_without_patches.json @@ -11,9 +11,6 @@ "merging": { "merge_thr": 0.80 }, -"preprocess": { - "p": 2 - }, "temporal": { "p": 2 }, diff --git a/demos/general/params_demo_pipeline.json b/demos/general/params_demo_pipeline.json index 567f1d255..f20b9c0c2 100644 --- a/demos/general/params_demo_pipeline.json +++ b/demos/general/params_demo_pipeline.json @@ -21,9 +21,6 @@ "max_deviation_rigid": 3, "border_nan": "copy" }, - "preprocess": { - "p": 1 - }, "temporal": { "p": 1 }, diff --git a/demos/general/params_demo_pipeline_NWB.json b/demos/general/params_demo_pipeline_NWB.json index 6cca1d199..24bca670f 100644 --- a/demos/general/params_demo_pipeline_NWB.json +++ b/demos/general/params_demo_pipeline_NWB.json @@ -21,9 +21,6 @@ "max_deviation_rigid": 3, "border_nan": "copy" }, - "preprocess": { - "p": 1 - }, "temporal": { "p": 1 }, diff --git a/demos/general/params_demo_pipeline_cnmfE.json b/demos/general/params_demo_pipeline_cnmfE.json index 8f68a2cea..a12151fda 100644 --- a/demos/general/params_demo_pipeline_cnmfE.json +++ b/demos/general/params_demo_pipeline_cnmfE.json @@ -27,9 +27,6 @@ "max_deviation_rigid": 3, "border_nan": "copy" }, - "preprocess": { - "p": 1 - }, "temporal": { "p": 1, "method_deconvolution": "oasis" diff --git a/demos/notebooks/demo_OnACID_mesoscope.ipynb b/demos/notebooks/demo_OnACID_mesoscope.ipynb index 0c4c732b4..bda935de0 100644 --- a/demos/notebooks/demo_OnACID_mesoscope.ipynb +++ b/demos/notebooks/demo_OnACID_mesoscope.ipynb @@ -107,7 +107,7 @@ "gSig = tuple(np.ceil(np.array(gSig)/ds_factor).astype('int')) # recompute gSig if downsampling is involved\n", "mot_corr = True # flag for online motion correction \n", "pw_rigid = False # flag for pw-rigid motion correction (slower but potentially more accurate)\n", - "max_shifts_online = np.ceil(10./ds_factor).astype('int') # maximum allowed shift during motion correction\n", + "max_shifts_online = 10 # maximum allowed shift during motion correction\n", "sniper_mode = True # flag using a CNN to detect new neurons (o/w space correlation is used)\n", "init_batch = 200 # number of frames for initialization (presumably from the first file)\n", "expected_comps = 500 # maximum number of expected components used for memory pre-allocation (exaggerate here)\n", @@ -117,28 +117,43 @@ "epochs = 2 # number of passes over the data\n", "show_movie = False # show the movie with the results as the data gets processed\n", "\n", - "params_dict = {'fnames': fnames,\n", - " 'fr': fr,\n", - " 'decay_time': decay_time,\n", - " 'gSig': gSig,\n", - " 'p': p,\n", - " 'min_SNR': min_SNR,\n", - " 'rval_thr': rval_thr,\n", - " 'ds_factor': ds_factor,\n", - " 'nb': gnb,\n", - " 'motion_correct': mot_corr,\n", - " 'init_batch': init_batch,\n", - " 'init_method': 'bare',\n", - " 'normalize': True,\n", - " 'expected_comps': expected_comps,\n", - " 'sniper_mode': sniper_mode,\n", - " 'dist_shape_update' : dist_shape_update,\n", - " 'min_num_trial': min_num_trial,\n", - " 'K': K,\n", - " 'epochs': epochs,\n", - " 'max_shifts_online': max_shifts_online,\n", - " 'pw_rigid': pw_rigid,\n", - " 'show_movie': show_movie}\n", + "params_dict = {\n", + " 'data': {\n", + " 'fnames': fnames,\n", + " 'fr': fr,\n", + " 'decay_time': decay_time\n", + " },\n", + " 'init': {\n", + " 'gSig': gSig,\n", + " 'nb': gnb,\n", + " 'K': K\n", + " },\n", + " 'temporal': {\n", + " 'p': p\n", + " },\n", + " 'quality': {\n", + " 'min_SNR': min_SNR,\n", + " 'rval_thr': rval_thr,\n", + " },\n", + " 'online': {\n", + " 'ds_factor': ds_factor,\n", + " 'motion_correct': mot_corr,\n", + " 'init_batch': init_batch,\n", + " 'init_method': 'bare',\n", + " 'normalize': True,\n", + " 'expected_comps': expected_comps,\n", + " 'sniper_mode': sniper_mode,\n", + " 'dist_shape_update' : dist_shape_update,\n", + " 'min_num_trial': min_num_trial,\n", + " 'epochs': epochs,\n", + " 'max_shifts_online': max_shifts_online,\n", + " 'show_movie': show_movie\n", + " },\n", + " 'motion': {\n", + " 'pw_rigid': pw_rigid\n", + " } \n", + "}\n", + "\n", "opts = cnmf.params.CNMFParams(params_dict=params_dict)" ] }, diff --git a/demos/notebooks/demo_Ring_CNN.ipynb b/demos/notebooks/demo_Ring_CNN.ipynb index 0478f118b..1aa098a65 100644 --- a/demos/notebooks/demo_Ring_CNN.ipynb +++ b/demos/notebooks/demo_Ring_CNN.ipynb @@ -149,7 +149,7 @@ " fld_name = os.path.dirname(path_to_model)\n", " res_name = os.path.join(fld_name, 'onacid_results.hdf5')\n", " cnm = cnmf.online_cnmf.load_OnlineCNMF(res_name)\n", - " cnm.params.data['fnames'] = fnames" + " cnm.params.change_params({'data': {'fnames': fnames}})" ] }, { @@ -351,7 +351,7 @@ "metadata": {}, "outputs": [], "source": [ - "cnm.params.merging['merge_thr'] = 0.7\n", + "cnm.params.change_params({'merging': {'merge_thr': 0.7}})\n", "cnm.estimates.c1 = np.zeros(cnm.estimates.A.shape[-1])\n", "cnm.estimates.bl = np.zeros(cnm.estimates.A.shape[-1])\n", "cnm.estimates.neurons_sn = np.zeros(cnm.estimates.A.shape[-1])\n", diff --git a/demos/notebooks/demo_caiman_cnmf_3D.ipynb b/demos/notebooks/demo_caiman_cnmf_3D.ipynb index 04a9baf0c..8d56cb5d0 100644 --- a/demos/notebooks/demo_caiman_cnmf_3D.ipynb +++ b/demos/notebooks/demo_caiman_cnmf_3D.ipynb @@ -370,10 +370,13 @@ "outputs": [], "source": [ "# set parameters\n", - "K = 20 # number of neurons expected per patch\n", - "gSig = [4, 4, 2] # expected half size of neurons\n", - "merge_thresh = 0.8 # merging threshold, max correlation allowed\n", - "p = 2 # order of the autoregressive system" + "opts_dict = {\n", + " 'k': 20, # number of neurons expected per patch\n", + " 'gSig': [4, 4, 2], # expected half size of neurons\n", + " 'merge_thresh': 0.8, # merging threshold, max correlation allowed\n", + " 'p': 2, # order of the autoregressive system\n", + " 'spatial': {'se': np.ones((3, 3, 1), dtype=np.uint8)}\n", + "}" ] }, { @@ -390,8 +393,8 @@ "outputs": [], "source": [ "# INIT\n", - "cnm = cnmf.CNMF(n_processes, k=K, gSig=gSig, merge_thresh=merge_thresh, p=p, dview=dview)\n", - "cnm.params.set('spatial', {'se': np.ones((3,3,1), dtype=np.uint8)})" + "params = cnmf.params.CNMFParams(params_dict=opts_dict)\n", + "cnm = cnmf.CNMF(n_processes, params=params, dview=dview)" ] }, { @@ -436,13 +439,16 @@ "outputs": [], "source": [ "# set parameters\n", - "rf = 15 # half-size of the patches in pixels. rf=25, patches are 50x50\n", - "stride = 10 # amount of overlap between the patches in pixels\n", - "K = 10 # number of neurons expected per patch\n", - "gSig = [4, 4, 2] # expected half size of neurons\n", - "merge_thresh = 0.8 # merging threshold, max correlation allowed\n", - "p = 2 # order of the autoregressive system\n", - "print('set')" + "opts_dict = {\n", + " 'rf': 15, # half-size of the patches in pixels. rf=25, patches are 50x50\n", + " 'stride': 10, # amount of overlap between the patches in pixels\n", + " 'k': 10, # number of neurons expected per patch\n", + " 'gSig': [4, 4, 2], # expected half size of neurons\n", + " 'merge_thresh': 0.8, # merging threshold, max correlation allowed\n", + " 'p': 2, # order of the autoregressive system,\n", + " 'only_init_patch': True,\n", + " 'spatial': {'se': np.ones((3, 3, 1), dtype=np.uint8)}\n", + "}" ] }, { @@ -459,16 +465,8 @@ "outputs": [], "source": [ "%%time\n", - "cnm = cnmf.CNMF(n_processes, \n", - " k=K, \n", - " gSig=gSig, \n", - " merge_thresh=merge_thresh, \n", - " p=p, \n", - " dview=dview,\n", - " rf=rf, \n", - " stride=stride, \n", - " only_init_patch=True)\n", - "cnm.params.set('spatial', {'se': np.ones((3,3,1), dtype=np.uint8)})\n", + "params = cnmf.params.CNMFParams(params_dict=opts_dict)\n", + "cnm = cnmf.CNMF(n_processes, params=params, dview=dview)\n", "cnm.fit(images)\n", "print(('Number of components:' + str(cnm.estimates.A.shape[-1])))" ] @@ -530,7 +528,7 @@ "outputs": [], "source": [ "%%time\n", - "cnm.params.set('temporal', {'p': p})\n", + "cnm.params.change_params({'temporal': {'p': opts_dict['p']}})\n", "cnm2 = cnm.refit(images)" ] }, diff --git a/demos/notebooks/demo_dendritic.ipynb b/demos/notebooks/demo_dendritic.ipynb index 55018ab5f..09a178e77 100644 --- a/demos/notebooks/demo_dendritic.ipynb +++ b/demos/notebooks/demo_dendritic.ipynb @@ -172,28 +172,42 @@ "ssub = 1 # spatial subsampling during initialization\n", "tsub = 1 # temporal subsampling during initialization\n", "\n", - "opts_dict = {'fnames': fnames,\n", - " 'fr': fr,\n", - " 'decay_time': decay_time,\n", - " 'strides': strides,\n", - " 'overlaps': overlaps,\n", - " 'max_shifts': max_shifts,\n", - " 'max_deviation_rigid': max_deviation_rigid,\n", - " 'pw_rigid': pw_rigid,\n", - " 'p': p,\n", - " 'nb': gnb,\n", - " 'rf': rf,\n", - " 'K': K, \n", - " 'stride': stride_cnmf,\n", - " 'method_init': method_init,\n", - " 'alpha_snmf': alpha, # used only for sparse_nmf\n", - " 'rolling_sum': True,\n", - " 'only_init': True,\n", - " 'ssub': ssub,\n", - " 'tsub': tsub,\n", - " 'merge_thr': merge_thr}\n", + "opts_dict = {\n", + " 'data': params.DataParams(\n", + " fnames=fnames,\n", + " fr=fr,\n", + " decay_time=decay_time\n", + " ),\n", + " 'init': params.InitParams(\n", + " K=K,\n", + " nb=gnb,\n", + " method_init=method_init,\n", + " alpha_snmf=alpha, # used only for sparse_nmf\n", + " rolling_sum=True,\n", + " ssub=ssub,\n", + " tsub=tsub\n", + " ),\n", + " 'patch': params.PatchParams(\n", + " stride=stride_cnmf,\n", + " only_init=True,\n", + " rf=rf\n", + " ),\n", + " 'temporal': params.TemporalParams(\n", + " p=p\n", + " ),\n", + " 'merging': params.MergingParams(\n", + " merge_thr=merge_thr\n", + " ),\n", + " 'motion': params.MotionParams(\n", + " max_shifts=max_shifts,\n", + " max_deviation_rigid=max_deviation_rigid,\n", + " pw_rigid=pw_rigid,\n", + " strides=strides,\n", + " overlaps=overlaps\n", + " )\n", + "}\n", "\n", - "opts = params.CNMFParams(params_dict=opts_dict)" + "opts = params.CNMFParams(**opts_dict)" ] }, { @@ -456,10 +470,14 @@ "min_SNR = 4 # signal to noise ratio for accepting a component\n", "rval_thr = 0.85 # space correlation threshold for accepting a component\n", "\n", - "cnm2.params.set('quality', {'decay_time': decay_time,\n", - " 'min_SNR': min_SNR,\n", - " 'rval_thr': rval_thr,\n", - " 'use_cnn': False}) # do not use cnn for dentritic data\n", + "cnm2.params.change_params({\n", + " 'quality': {\n", + " 'decay_time': decay_time,\n", + " 'min_SNR': min_SNR,\n", + " 'rval_thr': rval_thr,\n", + " 'use_cnn': False # do not use cnn for dentritic data\n", + " }\n", + "})\n", "\n", "cnm2.estimates.evaluate_components(images, cnm2.params, dview=dview);" ] diff --git a/demos/notebooks/demo_online_3D.ipynb b/demos/notebooks/demo_online_3D.ipynb index d5668db48..c3138615b 100644 --- a/demos/notebooks/demo_online_3D.ipynb +++ b/demos/notebooks/demo_online_3D.ipynb @@ -242,24 +242,38 @@ }, "outputs": [], "source": [ - "params_dict = {'fnames': fname, # filename(s) to be processed\n", - " 'fr': 30, # frame rate (Hz)\n", - " 'K': N, # (upper bound on) number of components\n", - " 'is3D': True, # flag for volumetric data\n", - " 'decay_time': 1, # length of typical transient in seconds\n", - " 'gSig': (4, 4, 2), # gaussian width of a 3D gaussian kernel, which approximates a neuron\n", - " 'p': 1, # order of the autoregressive system\n", - " 'nb': 1, # number of background components\n", - " 'only_init': False, # whether to run only the initialization\n", - " 'normalize_init': False, # whether to equalize the movies during initialization\n", - " 'motion_correct': True, # flag for performing motion correction\n", - " 'max_shifts': (4, 4, 2), # maximum allowed rigid shifts (in pixels)\n", - " 'nonneg_movie': False, # flag for producing a non-negative movie\n", - " 'init_batch': 200, # length of mini batch for initialization\n", - " 'init_method': 'cnmf', # initialization method for initial batch\n", - " 'batch_update_suff_stat': True,# flag for updating sufficient statistics (used for updating shapes)\n", - " 'thresh_overlap': 0, # space overlap threshold for screening new components\n", - " }\n", + "params_dict = {\n", + " 'data': {\n", + " 'fnames': fname, # filename(s) to be processed\n", + " 'fr': 30, # frame rate (Hz)\n", + " 'decay_time': 1 # length of typical transient in seconds\n", + " },\n", + " 'init': {\n", + " 'K': N, # (upper bound on) number of components\n", + " 'nb': 1, # number of background components\n", + " 'gSig': (4, 4, 2), # gaussian width of a 3D gaussian kernel, which approximates a neuron\n", + " 'normalize_init': False # whether to equalize the movies during initialization\n", + " },\n", + " 'patch': {\n", + " 'only_init': False # whether to run only the initialization\n", + " },\n", + " 'temporal': {\n", + " 'p': 1 # order of the autoregressive system\n", + " },\n", + " 'online': {\n", + " 'motion_correct': True, # flag for performing motion correction\n", + " 'init_batch': 200, # length of mini batch for initialization\n", + " 'init_method': 'cnmf', # initialization method for initial batch\n", + " 'batch_update_suff_stat': True,# flag for updating sufficient statistics (used for updating shapes)\n", + " 'thresh_overlap': 0 # space overlap threshold for screening new components\n", + " },\n", + " 'motion': {\n", + " 'is3D': True, # flag for volumetric data\n", + " 'max_shifts': (4, 4, 2), # maximum allowed rigid shifts (in pixels)\n", + " 'nonneg_movie': False # flag for producing a non-negative movie\n", + " }\n", + "}\n", + "\n", "opts = cnmf.params.CNMFParams(params_dict=params_dict)" ] }, diff --git a/demos/notebooks/demo_pipeline.ipynb b/demos/notebooks/demo_pipeline.ipynb index 8c7cffc17..907f40817 100644 --- a/demos/notebooks/demo_pipeline.ipynb +++ b/demos/notebooks/demo_pipeline.ipynb @@ -269,7 +269,7 @@ "metadata": {}, "source": [ "## Set initial parameters\n", - "In general in Caiman, estimators are first initialized with a set of parameters, and then they are fit against actual data in a separate step. In this section, we'll define a `parameters` object that will subsequently be used to initialize our different estimators. \n", + "In general in Caiman, estimators are first initialized with a set of parameters, and then they are fit against actual data in a separate step. In this section, we'll define a `parameters` object that will subsequently be used to initialize our different estimators. Those parameters *not* explicitly defined will assume default values.\n", "\n", "The parameters are divided into different categories. We will not discuss them in detail in this section, but will go over them when needed (and note that in this notebook we will mostly focus on CNMF and later steps):" ] @@ -281,43 +281,61 @@ "outputs": [], "source": [ "# general dataset-dependent parameters\n", - "fr = 30 # imaging rate in frames per second\n", - "decay_time = 0.4 # length of a typical transient in seconds\n", - "dxy = (2., 2.) # spatial resolution in x and y in (um per pixel)\n", + "data_params = params.DataParams(\n", + " fr=30, # imaging rate in frames per second\n", + " decay_time=0.4, # length of a typical transient in seconds\n", + " dxy=(2., 2.) # spatial resolution in x and y in (um per pixel)\n", + ")\n", "\n", "# motion correction parameters\n", - "strides = (48, 48) # start a new patch for pw-rigid motion correction every x pixels\n", - "overlaps = (24, 24) # overlap between patches (width of patch = strides+overlaps)\n", - "max_shifts = (6,6) # maximum allowed rigid shifts (in pixels)\n", - "max_deviation_rigid = 3 # maximum shifts deviation allowed for patch with respect to rigid shifts\n", - "pw_rigid = True # flag for performing non-rigid motion correction\n", + "motion_params = params.MotionParams(\n", + " strides=(48, 48), # start a new patch for pw-rigid motion correction every x pixels\n", + " overlaps=(24, 24), # overlap between patches (width of patch = strides+overlaps)\n", + " max_shifts=(6,6), # maximum allowed rigid shifts (in pixels)\n", + " max_deviation_rigid=3, # maximum shifts deviation allowed for patch with respect to rigid shifts\n", + " pw_rigid=True # flag for performing non-rigid motion correction\n", + ")\n", "\n", "# CNMF parameters for source extraction and deconvolution\n", - "p = 1 # order of the autoregressive system (set p=2 if there is visible rise time in data)\n", - "gnb = 2 # number of global background components (set to 1 or 2)\n", - "merge_thr = 0.85 # merging threshold, max correlation allowed\n", - "bas_nonneg = True # enforce nonnegativity constraint on calcium traces (technically on baseline)\n", - "rf = 15 # half-size of the patches in pixels (patch width is rf*2 + 1)\n", - "stride_cnmf = 10 # amount of overlap between the patches in pixels (overlap is stride_cnmf+1) \n", - "K = 4 # number of components per patch\n", - "gSig = np.array([4, 4]) # expected half-width of neurons in pixels (Gaussian kernel standard deviation)\n", - "gSiz = 2*gSig + 1 # Gaussian kernel width and hight\n", - "method_init = 'greedy_roi' # initialization method (if analyzing dendritic data see demo_dendritic.ipynb)\n", - "ssub = 1 # spatial subsampling during initialization \n", - "tsub = 1 # temporal subsampling during intialization\n", + "init_params = params.InitParams(\n", + " method_init = 'greedy_roi', # initialization method (if analyzing dendritic data see demo_dendritic.ipynb)\n", + " K=4, # number of components per patch\n", + " nb=2, # number of global background components (set to 1 or 2)\n", + " gSig=[4, 4], # expected half-width of neurons in pixels (Gaussian kernel standard deviation)\n", + " gSiz=None, # Gaussian kernel width and height - None means 2*gSig + 1 for each dimension\n", + " ssub=1, # spatial subsampling during initialization \n", + " tsub=1 # temporal subsampling during intialization\n", + ")\n", + "\n", + "patch_params = params.PatchParams(\n", + " rf=15, # half-size of the patches in pixels (patch width is rf*2 + 1)\n", + " stride=10 # amount of overlap between the patches in pixels (overlap is stride_cnmf+1) \n", + ")\n", + "\n", + "temporal_params = params.TemporalParams(\n", + " p=1, # order of the autoregressive system (set p=2 if there is visible rise time in data)\n", + " bas_nonneg=True # enforce nonnegativity constraint on calcium traces (technically on baseline)\n", + ")\n", + "\n", + "merging_params = params.MergingParams(\n", + " merge_thr=0.85 # merging threshold, max correlation allowed\n", + ")\n", + "\n", "\n", "# parameters for component evaluation\n", - "min_SNR = 2.0 # signal to noise ratio for accepting a component\n", - "rval_thr = 0.85 # space correlation threshold for accepting a component\n", - "cnn_thr = 0.99 # threshold for CNN based classifier\n", - "cnn_lowest = 0.1 # neurons with cnn probability lower than this value are rejected" + "quality_params = params.QualityParams(\n", + " min_SNR=2.0, # signal to noise ratio for accepting a component\n", + " rval_thr=0.85, # space correlation threshold for accepting a component\n", + " min_cnn_thr=0.99, # threshold for CNN based classifier\n", + " cnn_lowest=0.1 # neurons with cnn probability lower than this value are rejected\n", + ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "We place the above parameter values in a dictionary that is passed to the `CNMFParams` class (those parameters *not* explicitly defined will assume default values):" + "We then pass each parameter object to the `CNMFParams` class (any category missing from the arguments list assumes all default values) :" ] }, { @@ -326,43 +344,22 @@ "metadata": {}, "outputs": [], "source": [ - "parameter_dict = {'fnames': movie_path,\n", - " 'fr': fr,\n", - " 'dxy': dxy,\n", - " 'decay_time': decay_time,\n", - " 'strides': strides,\n", - " 'overlaps': overlaps,\n", - " 'max_shifts': max_shifts,\n", - " 'max_deviation_rigid': max_deviation_rigid,\n", - " 'pw_rigid': pw_rigid,\n", - " 'p': p,\n", - " 'nb': gnb,\n", - " 'rf': rf,\n", - " 'K': K, \n", - " 'gSig': gSig,\n", - " 'gSiz': gSiz,\n", - " 'stride': stride_cnmf,\n", - " 'method_init': method_init,\n", - " 'rolling_sum': True,\n", - " 'only_init': True,\n", - " 'ssub': ssub,\n", - " 'tsub': tsub,\n", - " 'merge_thr': merge_thr, \n", - " 'bas_nonneg': bas_nonneg,\n", - " 'min_SNR': min_SNR,\n", - " 'rval_thr': rval_thr,\n", - " 'use_cnn': True,\n", - " 'min_cnn_thr': cnn_thr,\n", - " 'cnn_lowest': cnn_lowest}\n", - "\n", - "parameters = params.CNMFParams(params_dict=parameter_dict) # CNMFParams is the parameters class" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This parameters object (`parameters`) is basically a collection of dictionaries, each containing a different parameter category. These different dictionaries can be accessed using dot notation. Some parameters are related to the dataset in general (`parameters.data`), while most are related to specific aspects of the workflow such as motion correction (`parameters.motion`) or quality evaluation (`parameters.quality`).\n", + "parameters = params.CNMFParams( # CNMFParams is the parameters class\n", + " data=data_params,\n", + " motion=motion_params,\n", + " init=init_params,\n", + " patch=patch_params,\n", + " temporal=temporal_params,\n", + " merging=merging_params,\n", + " quality=quality_params\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "From the main parameters object (`parameters`) you can access sub-objects for various parameter categories using dot notation (e.g., `parameters.data` is a `DataParams` object). Some parameters are related to the dataset in general (`parameters.data`), while most are related to specific aspects of the workflow such as motion correction (`parameters.motion`) or quality evaluation (`parameters.quality`).\n", " \n", "For instance, if you want to inspect the dataset-dependent parameters:" ] @@ -380,7 +377,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To access a particular parameter in this parameter field, you just need to get the value from the dictionary using the appropriate key. For instance, to get the frame rate:" + "To access a particular parameter in this category, you just need to get the value from the sub-object using the appropriate key; both dot and bracket notations are supported, although only dot notation supports static type checking. For instance, to get the frame rate:" ] }, { @@ -389,7 +386,9 @@ "metadata": {}, "outputs": [], "source": [ - "parameters.data['fr'] " + "fr = parameters.data.fr # preferred if you care about type checking\n", + "fr = parameters.data['fr'] # does the same thing\n", + "fr" ] }, { @@ -797,7 +796,7 @@ " \n", "If the parameters were not good, then you could change them using the `change_params()` method, which takes in a dictionary of new parameter values. For instance, if we wanted to change gSig to 5:
\n", "\n", - " new_parameters = {'gSig': 5}\n", + " new_parameters = {'init': {'gSig': [5, 5]}}\n", " cnmf_model.params.change_params(params_dict=new_parameters)\n", " \n", "
It is not always efficient to cobble together iterative parameter search from scratch, especially if you end up needing to do a grid search in a large parameter space. Mesmerize is a great package built to make parameter exploration in Caiman faster and more convenient: it keeps track of all your different results, and includes powerful GPU-based tools (based on the fastplotlib library) for visualization of results in Jupyter notebooks.\n", @@ -1587,9 +1586,9 @@ ], "metadata": { "kernelspec": { - "display_name": "caiman_pytorch2", + "display_name": "caiman-dev-torch", "language": "python", - "name": "caiman_pytorch2" + "name": "python3" }, "language_info": { "codemirror_mode": { diff --git a/demos/notebooks/demo_realtime_cnmfE.ipynb b/demos/notebooks/demo_realtime_cnmfE.ipynb index bae65754e..a31d7e752 100644 --- a/demos/notebooks/demo_realtime_cnmfE.ipynb +++ b/demos/notebooks/demo_realtime_cnmfE.ipynb @@ -817,7 +817,7 @@ " model_LN, history, path_to_model = fit_NL_model(\n", " model_LN, m, epochs=cnm3.params.get('ring_CNN', 'max_epochs'),\n", " patience=cnm3.params.get('ring_CNN', 'patience'), schedule=sch)\n", - " cnm3.params.set('ring_CNN', {'path_to_model': path_to_model})" + " cnm3.params.change_params({'ring_CNN': {'path_to_model': path_to_model}})" ] }, { diff --git a/demos/notebooks/demo_seeded_CNMF.ipynb b/demos/notebooks/demo_seeded_CNMF.ipynb index b9b784659..7ead62767 100644 --- a/demos/notebooks/demo_seeded_CNMF.ipynb +++ b/demos/notebooks/demo_seeded_CNMF.ipynb @@ -387,11 +387,15 @@ "min_cnn_thr = 0.99 # threshold for CNN based classifier\n", "cnn_lowest = 0.05 # neurons with cnn probability lower than this value are rejected\n", "#cnm_seeded.estimates.restore_discarded_components()\n", - "cnm_seeded.params.set('quality', {'min_SNR': min_SNR,\n", - " 'rval_thr': rval_thr,\n", - " 'use_cnn': True,\n", - " 'min_cnn_thr': min_cnn_thr,\n", - " 'cnn_lowest': cnn_lowest})\n", + "cnm_seeded.params.change_params({\n", + " 'quality': {\n", + " 'min_SNR': min_SNR,\n", + " 'rval_thr': rval_thr,\n", + " 'use_cnn': True,\n", + " 'min_cnn_thr': min_cnn_thr,\n", + " 'cnn_lowest': cnn_lowest\n", + " }\n", + "})\n", "\n", "#%% COMPONENT EVALUATION\n", "# the components are evaluated in three ways:\n", @@ -457,11 +461,15 @@ "outputs": [], "source": [ "#cnm.estimates.restore_discarded_components()\n", - "cnm.params.set('quality', {'min_SNR': min_SNR,\n", - " 'rval_thr': rval_thr,\n", - " 'use_cnn': True,\n", - " 'min_cnn_thr': min_cnn_thr,\n", - " 'cnn_lowest': cnn_lowest})\n", + "cnm.params.change_params({\n", + " 'quality': {\n", + " 'min_SNR': min_SNR,\n", + " 'rval_thr': rval_thr,\n", + " 'use_cnn': True,\n", + " 'min_cnn_thr': min_cnn_thr,\n", + " 'cnn_lowest': cnn_lowest\n", + " }\n", + "})\n", "\n", "#%% COMPONENT EVALUATION\n", "# the components are evaluated in three ways:\n", @@ -554,7 +562,7 @@ "# swap_dim should be set to True if the movie is in MATLAB format (time is last instead of first axis)\n", "Cn = cm.local_correlations(images, swap_dim=False)\n", "Cn[np.isnan(Cn)] = 0\n", - "save_path = fnames[0].split('.')[0] + '_local_corr.png'\n", + "save_path = os.path.splitext(fnames[0])[0] + '_local_corr.png'\n", "imsave(save_path,Cn)\n", "\n", "'''\n", diff --git a/environment-minimal.yml b/environment-minimal.yml index f92c00cb5..b3704b54b 100644 --- a/environment-minimal.yml +++ b/environment-minimal.yml @@ -18,6 +18,7 @@ dependencies: - peakutils >=1.3.5 - pims - psutil +- pydantic >=2.5 - pynwb - pyside6 - pytest @@ -26,6 +27,7 @@ dependencies: - scikit-learn >=1.2 - scipy >= 1.10.1 - setuptools +- tabulate - tifffile - torchvision - tqdm diff --git a/environment.yml b/environment.yml index 582b09cb7..e13103a71 100644 --- a/environment.yml +++ b/environment.yml @@ -25,6 +25,7 @@ dependencies: - peakutils >=1.3.5 - pims - psutil +- pydantic >=2.5 - pynwb - pyqtgraph - pyside6 @@ -35,6 +36,7 @@ dependencies: - scikit-learn >=1.2 - scipy >= 1.10.1 - setuptools +- tabulate - tifffile - tk - torchinfo diff --git a/pyproject.toml b/pyproject.toml index 5a7e30ffc..8ee86fb15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ dependencies = [ "peakutils >= 1.3.5", "pims", "psutil", + "pydantic >= 2.5", "pynwb", "pyside6", "pytest", @@ -44,6 +45,7 @@ dependencies = [ "scikit-image >= 0.19.0, != 0.26.0", "scikit-learn >= 1.2", "scipy >= 1.10.1", + "tabulate", "torchvision", "tifffile", "tqdm", diff --git a/test_demos.sh b/test_demos.sh index f9199b3e9..38a0f3169 100755 --- a/test_demos.sh +++ b/test_demos.sh @@ -32,8 +32,6 @@ if [ $OS == "Linux" ]; then fi fi -# Tell matplotlib to try to plot less to begin with by specifying a postscript backend -export MPLCONFIG=ps cd `dirname ${BASH_SOURCE[0]}`