From 02c7658f062ec4198fc5fb14df17f80834c30f0e Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Fri, 6 Nov 2026 13:51:08 -0500 Subject: [PATCH 1/2] Remove broken enclosed_thr feature --- caiman/base/rois.py | 37 ++------ caiman/source_extraction/volpy/mrcnn/utils.py | 93 +------------------ 2 files changed, 11 insertions(+), 119 deletions(-) diff --git a/caiman/base/rois.py b/caiman/base/rois.py index 9f241a0ec..b459b2931 100644 --- a/caiman/base/rois.py +++ b/caiman/base/rois.py @@ -171,7 +171,6 @@ def nf_match_neurons_in_binary_masks(masks_gt, labels=['Session 1', 'Session 2'], cmap='gray', D=None, - enclosed_thr=None, colors=['red', 'white']): """ Match neurons expressed as binary masks. Uses Hungarian matching algorithm @@ -199,9 +198,6 @@ def nf_match_neurons_in_binary_masks(masks_gt, D: list of ndarrays list of distances matrices - enclosed_thr: float - if not None set distance to at most the specified value when ground truth is a subset of inferred - Returns: idx_tp_1: indices true pos ground truth mask @@ -238,7 +234,7 @@ def nf_match_neurons_in_binary_masks(masks_gt, if D is None: # find distances and matches # find the distance between each masks - D = distance_masks([A_ben, A_cnmf], [cm_ben, cm_cnmf], min_dist, enclosed_thr=enclosed_thr) + D = distance_masks([A_ben, A_cnmf], [cm_ben, cm_cnmf], min_dist) level = 0.98 @@ -318,7 +314,6 @@ def register_ROIs(A1, use_opt_flow=True, thresh_cost=.7, max_dist=10, - enclosed_thr=None, print_assignment=False, plot_results=False, Cn=None, @@ -362,10 +357,6 @@ def register_ROIs(A1, max_dist: scalar max distance between centroids - enclosed_thr: float - if not None set distance to at most the specified value when ground - truth is a subset of inferred - print_assignment: bool print pairs of matched ROIs @@ -484,7 +475,7 @@ def register_ROIs(A1, cm_2 = com(A2, *dims) A1_tr = (A1 > 0).astype(float) A2_tr = (A2 > 0).astype(float) - D = distance_masks([A1_tr, A2_tr], [cm_1, cm_2], max_dist, enclosed_thr=enclosed_thr) + D = distance_masks([A1_tr, A2_tr], [cm_1, cm_2], max_dist) matches, costs = find_matches(D, print_assignment=print_assignment) matches = matches[0] @@ -561,8 +552,7 @@ def register_multisession(A, max_thr=0, use_opt_flow=True, thresh_cost=.7, - max_dist=10, - enclosed_thr=None): + max_dist=10): """ Register ROIs across multiple sessions using an intersection over union metric and the Hungarian algorithm for optimal matching. Registration occurs by @@ -594,10 +584,6 @@ def register_multisession(A, max_dist: scalar max distance between centroids - enclosed_thr: float - if not None set distance to at most the specified value when ground - truth is a subset of inferred - Returns: A_union: csc_matrix # pixels x # of total distinct components union of all kept ROIs @@ -637,8 +623,7 @@ def register_multisession(A, max_thr=max_thr, use_opt_flow=use_opt_flow, thresh_cost=thresh_cost, - max_dist=max_dist, - enclosed_thr=enclosed_thr) + max_dist=max_dist) mat_sess, mat_un, nm_sess, nm_un, _, A2 = reg_results logger.info(len(mat_sess)) @@ -710,7 +695,7 @@ def norm_nrg(a: np.ndarray) -> np.ndarray: return np.reshape(cumEn[inds_inv], a.shape) -def distance_masks(M_s:list, cm_s: list[list], max_dist: float, enclosed_thr: Optional[float] = None) -> list: +def distance_masks(M_s:list, cm_s: list[list], max_dist: float) -> list: """ Compute distance matrix based on an intersection over union metric. Matrix are compared in order, with matrix i compared with matrix i+1 @@ -726,9 +711,6 @@ def distance_masks(M_s:list, cm_s: list[list], max_dist: float, enclosed_thr: Op maximum distance among centroids allowed between components. This corresponds to a distance at which two components are surely disjoined - enclosed_thr: float - if not None set distance to at most the specified value when ground truth is a subset of inferred - Returns: D_s: list of matrix distances @@ -752,8 +734,7 @@ def distance_masks(M_s:list, cm_s: list[list], max_dist: float, enclosed_thr: Op cmgt_comp = np.array(cmgt_comp) cmtest_comp = np.array(cmtest_comp) - if enclosed_thr is not None: - gt_val = gt_comp.T.dot(gt_comp).diagonal() + for i in range(nb_gt): # for each components of gt k = gt_comp[:, np.repeat(i, nb_test)] + test_comp @@ -776,11 +757,7 @@ def distance_masks(M_s:list, cm_s: list[list], max_dist: float, enclosed_thr: Op # intersection is removed from union since union contains twice the overlapping area # having the values in this format 0-1 is helpful for the hungarian algorithm that follows - D[i, j] = 1 - 1. * intersection / \ - (union - intersection) - if enclosed_thr is not None: - if intersection == gt_val[j] or intersection == gt_val[i]: - D[i, j] = min(D[i, j], 0.5) + D[i, j] = 1 - 1. * intersection / (union - intersection) else: D[i, j] = 1. diff --git a/caiman/source_extraction/volpy/mrcnn/utils.py b/caiman/source_extraction/volpy/mrcnn/utils.py index 39ae8dc07..e8d437402 100644 --- a/caiman/source_extraction/volpy/mrcnn/utils.py +++ b/caiman/source_extraction/volpy/mrcnn/utils.py @@ -24,7 +24,7 @@ import torchvision.transforms.v2 as T from typing import Any, Optional -from caiman.base.rois import norm_nrg +from caiman.base.rois import norm_nrg, distance_masks class ScaleImage: @@ -131,89 +131,7 @@ def data_transform(train: bool = False): transforms.append(T.ToDtype(torch.float32, scale=False)) return T.Compose(transforms) - - -def distance_masks(M_s:list, cm_s:list[list], max_dist: float, enclosed_thr:Optional[float] = None) -> list: - """ - Compute distance matrix based on an intersection over union metric. Matrix are compared in order, - with matrix i compared with matrix i+1 - - Args: - M_s: tuples of 1-D arrays - The thresholded A matrices (masks) to compare, output of threshold_components - - cm_s: list of list of 2-ples - the centroids of the components in each M_s - - max_dist: float - maximum distance among centroids allowed between components. This corresponds to a distance - at which two components are surely disjoined - - enclosed_thr: float - if not None set distance to at most the specified value when ground truth is a subset of inferred - - Returns: - D_s: list of matrix distances - - Raises: - Exception: 'Nan value produced. Error in inputs' - - """ - D_s = [] - - for gt_comp, test_comp, cmgt_comp, cmtest_comp in zip(M_s[:-1], M_s[1:], cm_s[:-1], cm_s[1:]): - - # todo : better with a function that calls itself - # not to interfere with M_s - gt_comp = gt_comp.copy()[:, :] - test_comp = test_comp.copy()[:, :] - - # the number of components for each - nb_gt = np.shape(gt_comp)[-1] - nb_test = np.shape(test_comp)[-1] - D = np.ones((nb_gt, nb_test)) - - cmgt_comp = np.array(cmgt_comp) - cmtest_comp = np.array(cmtest_comp) - if enclosed_thr is not None: - gt_val = gt_comp.T.dot(gt_comp).diagonal() - for i in range(nb_gt): - # for each components of gt - k = gt_comp[:, np.repeat(i, nb_test)] + test_comp - # k is correlation matrix of this neuron to every other of the test - for j in range(nb_test): # for each components on the tests - dist = np.linalg.norm(cmgt_comp[i] - cmtest_comp[j]) - # we compute the distance of this one to the other ones - if dist < max_dist: - # union matrix of the i-th neuron to the jth one - union = k[:, j].sum() - # we could have used OR for union and AND for intersection while converting - # the matrice into real boolean before - - # product of the two elements' matrices - # we multiply the boolean values from the jth omponent to the ith - intersection = np.array(gt_comp[:, i].T.dot(test_comp[:, j]).todense()).squeeze() - - # if we don't have even a union this is pointless - if union > 0: - - # intersection is removed from union since union contains twice the overlapping area - # having the values in this format 0-1 is helpful for the hungarian algorithm that follows - D[i, j] = 1 - 1. * intersection / \ - (union - intersection) - if enclosed_thr is not None: - if intersection == gt_val[j] or intersection == gt_val[i]: - D[i, j] = min(D[i, j], 0.5) - else: - D[i, j] = 1. - - if np.isnan(D[i, j]): - raise Exception('Nan value produced. Error in inputs') - else: - D[i, j] = 1 - - D_s.append(D) - return D_s + def find_matches(D_s, print_assignment: bool = False) -> tuple[list, list]: """ @@ -323,10 +241,10 @@ def nf_match_neurons_in_binary_masks(masks_gt, labels=['Session 1', 'Session 2'], cmap='gray', D=None, - enclosed_thr=None, colors=['red', 'white']): """ Match neurons expressed as binary masks. Uses Hungarian matching algorithm + TODO this is mostly duplicated code from base.rois - eliminate repetition? Args: masks_gt: bool ndarray components x d1 x d2 @@ -351,9 +269,6 @@ def nf_match_neurons_in_binary_masks(masks_gt, D: list of ndarrays list of distances matrices - enclosed_thr: float - if not None set distance to at most the specified value when ground truth is a subset of inferred - Returns: idx_tp_1: indices true pos ground truth mask @@ -389,7 +304,7 @@ def nf_match_neurons_in_binary_masks(masks_gt, if D is None: # find distances and matches # find the distance between each masks - D = distance_masks([A_ben, A_cnmf], [cm_ben, cm_cnmf], min_dist, enclosed_thr=enclosed_thr) + D = distance_masks([A_ben, A_cnmf], [cm_ben, cm_cnmf], min_dist) level = 0.98 From 008b9bf6fdfeae66863d1fd84607e6dd82a6b24c Mon Sep 17 00:00:00 2001 From: Ethan Blackwood Date: Fri, 6 Nov 2026 14:08:33 -0500 Subject: [PATCH 2/2] Add notebook change I forgot to save --- demos/notebooks/demo_Ring_CNN.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demos/notebooks/demo_Ring_CNN.ipynb b/demos/notebooks/demo_Ring_CNN.ipynb index 0478f118b..1e2143a00 100644 --- a/demos/notebooks/demo_Ring_CNN.ipynb +++ b/demos/notebooks/demo_Ring_CNN.ipynb @@ -455,7 +455,7 @@ "m1, m2, nm1, nm2, perf = cm.base.rois.register_ROIs(estimates_gt.A_thr[:, estimates_gt.idx_components],\n", " cnm.estimates.A_thr[:, cnm.estimates.idx_components],\n", " dims, align_flag=False, thresh_cost=.7, plot_results=True,\n", - " Cn=cn_filter, enclosed_thr=None)[:-1]" + " Cn=cn_filter)[:-1]" ] }, {