Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 7 additions & 30 deletions caiman/base/rois.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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
Expand All @@ -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.

Expand Down
93 changes: 4 additions & 89 deletions caiman/source_extraction/volpy/mrcnn/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed duplicated function; importing from caiman.base.rois instead

"""
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]:
"""
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion demos/notebooks/demo_Ring_CNN.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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]"
]
},
{
Expand Down
Loading