forked from oist/optinist
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cnmf.py
337 lines (279 loc) · 10.6 KB
/
cnmf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import gc
import os
import numpy as np
import requests
from studio.app.common.core.experiment.experiment import ExptOutputPathIds
from studio.app.common.core.logger import AppLogger
from studio.app.common.core.utils.filepath_creater import (
create_directory,
join_filepath,
)
from studio.app.common.dataclass import ImageData
from studio.app.optinist.core.nwb.nwb import NWBDATASET
from studio.app.optinist.dataclass import EditRoiData, FluoData, IscellData, RoiData
logger = AppLogger.get_logger()
def get_roi(A, roi_thr, thr_method, swap_dim, dims):
from scipy.ndimage import binary_fill_holes
from skimage.measure import find_contours
d, nr = np.shape(A)
# for each patches
ims = []
coordinates = []
for i in range(nr):
pars = dict()
# we compute the cumulative sum of the energy of the Ath component
# that has been ordered from least to highest
patch_data = A.data[A.indptr[i] : A.indptr[i + 1]]
indx = np.argsort(patch_data)[::-1]
if thr_method == "nrg":
cumEn = np.cumsum(patch_data[indx] ** 2)
if len(cumEn) == 0:
pars = dict(
coordinates=np.array([]),
CoM=np.array([np.NaN, np.NaN]),
neuron_id=i + 1,
)
coordinates.append(pars)
continue
else:
# we work with normalized values
cumEn /= cumEn[-1]
Bvec = np.ones(d)
# we put it in a similar matrix
Bvec[A.indices[A.indptr[i] : A.indptr[i + 1]][indx]] = cumEn
else:
Bvec = np.zeros(d)
Bvec[A.indices[A.indptr[i] : A.indptr[i + 1]]] = (
patch_data / patch_data.max()
)
if swap_dim:
Bmat = np.reshape(Bvec, dims, order="C")
else:
Bmat = np.reshape(Bvec, dims, order="F")
r_mask = np.zeros_like(Bmat, dtype="bool")
contour = find_contours(Bmat, roi_thr)
for c in contour:
r_mask[np.round(c[:, 0]).astype("int"), np.round(c[:, 1]).astype("int")] = 1
# Fill in the hole created by the contour boundary
r_mask = binary_fill_holes(r_mask)
ims.append(r_mask + (i * r_mask))
return ims
def util_get_memmap(images: np.ndarray, file_path: str):
"""
convert np.ndarray to mmap
"""
from caiman.mmapping import prepare_shape
from caiman.paths import memmap_frames_filename
order = "C"
dims = images.shape[1:]
T = images.shape[0]
shape_mov = (np.prod(dims), T)
dir_path = join_filepath(file_path.split("/")[:-1])
basename = file_path.split("/")[-1]
fname_tot = memmap_frames_filename(basename, dims, T, order)
mmap_path = join_filepath([dir_path, fname_tot])
mmap_images = np.memmap(
mmap_path,
mode="w+",
dtype=np.float32,
shape=prepare_shape(shape_mov),
order=order,
)
mmap_images = np.reshape(mmap_images.T, [T] + list(dims), order="F")
mmap_images[:] = images[:]
return mmap_images, dims, mmap_path
def util_recursive_flatten_params(params, result_params: dict, nest_counter=0):
"""
Recursively flatten node parameters (operation for CaImAn CNMFParams)
"""
# avoid infinite loops
assert nest_counter <= 2, f"Nest depth overflow. [{nest_counter}]"
nest_counter += 1
for key, nested_param in params.items():
if type(nested_param) is dict:
util_recursive_flatten_params(nested_param, result_params, nest_counter)
else:
result_params[key] = nested_param
def util_download_model_files():
"""
download model files for component evaluation
"""
# NOTE: We specify the version of the CaImAn to download.
base_url = "https://github.com/flatironinstitute/CaImAn/raw/v1.9.12/model"
model_files = [
"cnn_model.h5",
"cnn_model.h5.pb",
"cnn_model.json",
"cnn_model_online.h5",
"cnn_model_online.h5.pb",
"cnn_model_online.json",
]
caiman_data_dir = os.path.join(os.path.expanduser("~"), "caiman_data")
if not os.path.exists(caiman_data_dir):
create_directory(caiman_data_dir)
model_dir = join_filepath([caiman_data_dir, "model"])
if not os.path.exists(model_dir):
create_directory(join_filepath(model_dir))
if len(os.listdir(model_dir)) < len(model_files):
for model in model_files:
url = f"{base_url}/{model}"
file_path = join_filepath([model_dir, model])
if not os.path.exists(file_path):
logger.info(f"Downloading {model}")
response = requests.get(url)
with open(file_path, "wb") as f:
f.write(response.content)
def caiman_cnmf(
images: ImageData, output_dir: str, params: dict = None, **kwargs
) -> dict(fluorescence=FluoData, iscell=IscellData):
from caiman import local_correlations, stop_server
from caiman.cluster import setup_cluster
from caiman.source_extraction.cnmf import cnmf, online_cnmf
from caiman.source_extraction.cnmf.params import CNMFParams
function_id = ExptOutputPathIds(output_dir).function_id
logger.info(f"start caiman_cnmf: {function_id}")
# NOTE: evaluate_components requires cnn_model files in caiman_data directory.
util_download_model_files()
# flatten cmnf params segments.
reshaped_params = {}
util_recursive_flatten_params(params, reshaped_params)
Ain = reshaped_params.pop("Ain", None)
do_refit = reshaped_params.pop("do_refit", None)
roi_thr = reshaped_params.pop("roi_thr", None)
use_online = reshaped_params.pop("use_online", False)
file_path = images.path
if isinstance(file_path, list):
file_path = file_path[0]
images = images.data
mmap_images, dims, mmap_path = util_get_memmap(images, file_path)
del images
gc.collect()
nwbfile = kwargs.get("nwbfile", {})
fr = nwbfile.get("imaging_plane", {}).get("imaging_rate", 30)
if reshaped_params is None:
ops = CNMFParams()
else:
ops = CNMFParams(params_dict={**reshaped_params, "fr": fr})
if "dview" in locals():
stop_server(dview=dview) # noqa: F821
c, dview, n_processes = setup_cluster(
backend="local", n_processes=None, single_thread=True
)
if use_online:
ops.change_params(
{
"fnames": [mmap_path],
# NOTE: These params uses np.inf as default in CaImAn.
# Yaml cannot serialize np.inf, so default value in yaml is None.
"max_comp_update_shape": reshaped_params["max_comp_update_shape"]
or np.inf,
"num_times_comp_updated": reshaped_params["update_num_comps"] or np.inf,
}
)
cnm = online_cnmf.OnACID(dview=dview, Ain=Ain, params=ops)
cnm.fit_online()
else:
cnm = cnmf.CNMF(n_processes=n_processes, dview=dview, Ain=Ain, params=ops)
cnm = cnm.fit(mmap_images)
if do_refit:
cnm = cnm.refit(mmap_images, dview=dview)
cnm.estimates.evaluate_components(mmap_images, cnm.params, dview=dview)
stop_server(dview=dview)
# contours plot
Cn = local_correlations(mmap_images.transpose(1, 2, 0))
Cn[np.isnan(Cn)] = 0
thr_method = "nrg"
swap_dim = False
idx_good = cnm.estimates.idx_components
idx_bad = cnm.estimates.idx_components_bad
if not isinstance(idx_good, list):
idx_good = idx_good.tolist()
if not isinstance(idx_bad, list):
idx_bad = idx_bad.tolist()
iscell = np.concatenate(
[
np.ones(len(idx_good), dtype=int),
np.zeros(len(idx_bad), dtype=int),
]
)
cell_ims = get_roi(
cnm.estimates.A[:, idx_good], roi_thr, thr_method, swap_dim, dims
)
cell_ims = np.stack(cell_ims).astype(float)
cell_ims[cell_ims == 0] = np.nan
cell_ims -= 1
n_rois = len(cell_ims)
if len(idx_bad) > 0:
non_cell_ims = get_roi(
cnm.estimates.A[:, idx_bad], roi_thr, thr_method, swap_dim, dims
)
non_cell_ims = np.stack(non_cell_ims).astype(float)
for i, j in enumerate(range(n_rois, n_rois + len(non_cell_ims))):
non_cell_ims[i, :] = np.where(non_cell_ims[i, :] != 0, j, 0)
non_cell_roi = np.nanmax(non_cell_ims, axis=0).astype(float)
else:
non_cell_ims = np.zeros((0, *dims))
non_cell_roi = np.zeros(dims)
non_cell_roi[non_cell_roi == 0] = np.nan
non_cell_ims[non_cell_ims == 0] = np.nan
n_noncell_rois = len(non_cell_ims)
im = np.vstack([cell_ims, non_cell_ims])
# NWBの追加
nwbfile = {}
# NWBにROIを追加
roi_list = []
n_cells = cnm.estimates.A.shape[-1]
for i in range(n_cells):
kargs = {}
kargs["image_mask"] = cnm.estimates.A.T[i].T.toarray().reshape(dims)
if hasattr(cnm.estimates, "accepted_list"):
kargs["accepted"] = i in cnm.estimates.accepted_list
if hasattr(cnm.estimates, "rejected_list"):
kargs["rejected"] = i in cnm.estimates.rejected_list
roi_list.append(kargs)
nwbfile[NWBDATASET.ROI] = {function_id: roi_list}
nwbfile[NWBDATASET.POSTPROCESS] = {function_id: {"all_roi_img": im}}
# iscellを追加
nwbfile[NWBDATASET.COLUMN] = {
function_id: {
"name": "iscell",
"description": "two columns - iscell & probcell",
"data": iscell,
}
}
# Fluorescence
fluorescence = cnm.estimates.C
nwbfile[NWBDATASET.FLUORESCENCE] = {
function_id: {
"Fluorescence": {
"table_name": "ROIs",
"region": list(range(n_rois + n_noncell_rois)),
"name": "Fluorescence",
"data": fluorescence.T,
"unit": "lumens",
}
}
}
info = {
"images": ImageData(
np.array(Cn * 255, dtype=np.uint8),
output_dir=output_dir,
file_name="images",
),
"fluorescence": FluoData(fluorescence, file_name="fluorescence"),
"iscell": IscellData(iscell, file_name="iscell"),
"all_roi": RoiData(
np.nanmax(im, axis=0), output_dir=output_dir, file_name="all_roi"
),
"cell_roi": RoiData(
np.nanmax(im[iscell != 0], axis=0),
output_dir=output_dir,
file_name="cell_roi",
),
"non_cell_roi": RoiData(
non_cell_roi, output_dir=output_dir, file_name="non_cell_roi"
),
"edit_roi_data": EditRoiData(mmap_images, im),
"nwbfile": nwbfile,
}
return info