Skip to content

imaging_preprocess.py

activate(imaging_schema_name, scan_schema_name=None, *, create_schema=True, create_tables=True, linking_module=None)

Activate this schema.

Parameters:

Name Type Description Default
imaging_schema_name str

Schema name on the database server to activate the imaging module.

required
scan_schema_name str

Schema name on the database server to activate the scan module. Omitted, if the scan module is already activated.

None
create_schema bool

When True (default), create schema in the database if it does not yet exist.

True
create_tables bool

When True (default), create tables in the database if they do not yet exist.

True
linking_module str

A module name or a module containing the required dependencies to activate the imaging module: + all that are required by the scan module.

None

Dependencies: Upstream tables: + Session: A parent table to Scan, identifying a scanning session. + Equipment: A parent table to Scan, identifying a scanning device.

Source code in element_calcium_imaging/imaging_preprocess.py
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
def activate(
    imaging_schema_name: str,
    scan_schema_name: str = None,
    *,
    create_schema: bool = True,
    create_tables: bool = True,
    linking_module: str = None,
):
    """Activate this schema.

    Args:
        imaging_schema_name (str): Schema name on the database server to activate the
            `imaging` module.
        scan_schema_name (str): Schema name on the database server to activate the
            `scan` module. Omitted, if the `scan` module is already activated.
        create_schema (bool): When True (default), create schema in the database if it
            does not yet exist.
        create_tables (bool): When True (default), create tables in the database if they
            do not yet exist.
        linking_module (str): A module name or a module containing the required
            dependencies to activate the `imaging` module: + all that are required by
            the `scan` module.

    Dependencies:
    Upstream tables:
        + Session: A parent table to Scan, identifying a scanning session.
        + Equipment: A parent table to Scan, identifying a scanning device.
    """

    if isinstance(linking_module, str):
        linking_module = importlib.import_module(linking_module)
    assert inspect.ismodule(
        linking_module
    ), "The argument 'dependency' must be a module's name or a module"

    global _linking_module
    _linking_module = linking_module

    scan.activate(
        scan_schema_name,
        create_schema=create_schema,
        create_tables=create_tables,
        linking_module=linking_module,
    )
    schema.activate(
        imaging_schema_name,
        create_schema=create_schema,
        create_tables=create_tables,
        add_objects=_linking_module.__dict__,
    )
    imaging_report.activate(f"{imaging_schema_name}_report", imaging_schema_name)

PreprocessMethod

Bases: Lookup

Method(s) used for preprocessing of calcium imaging data.

Attributes:

Name Type Description
preprocess_method str

Preprocessing method.

preprocess_method_desc str

Processing method description.

Source code in element_calcium_imaging/imaging_preprocess.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@schema
class PreprocessMethod(dj.Lookup):
    """Method(s) used for preprocessing of calcium imaging data.

    Attributes:
        preprocess_method (str): Preprocessing method.
        preprocess_method_desc (str): Processing method description.
    """

    definition = """  #  Method/package used for pre-processing
    preprocess_method: varchar(16)
    ---
    preprocess_method_desc: varchar(1000)
    """

PreprocessParamSet

Bases: Lookup

Parameter set used for the preprocessing of the calcium imaging scans.

A hash of the parameters of the analysis suite is also stored in order to avoid duplicated entries.

Attributes:

Name Type Description
paramset_idx int

Unique parameter set ID.

PreprocessMethod foreign key

A primary key from PreprocessMethod.

paramset_desc str

Parameter set description.

param_set_hash uuid

A universally unique identifier for the parameter set.

params longblob

Parameter Set, a dictionary of all applicable parameters to the analysis suite.

Source code in element_calcium_imaging/imaging_preprocess.py
 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
@schema
class PreprocessParamSet(dj.Lookup):
    """Parameter set used for the preprocessing of the calcium imaging scans.

    A hash of the parameters of the analysis suite is also stored in order
    to avoid duplicated entries.

    Attributes:
        paramset_idx (int): Unique parameter set ID.
        PreprocessMethod (foreign key): A primary key from PreprocessMethod.
        paramset_desc (str): Parameter set description.
        param_set_hash (uuid): A universally unique identifier for the parameter set.
        params (longblob): Parameter Set, a dictionary of all applicable parameters to
            the analysis suite.
    """

    definition = """  #  Parameter set used for pre-processing of calcium imaging data
    paramset_idx:  smallint
    ---
    -> PreprocessMethod
    paramset_desc: varchar(128)
    param_set_hash: uuid
    unique index (param_set_hash)
    params: longblob  # dictionary of all applicable parameters
    """

    @classmethod
    def insert_new_params(
        cls,
        preprocess_method: str,
        paramset_idx: int,
        paramset_desc: str,
        params: dict,
    ):
        """Insert a parameter set into PreprocessParamSet table.
        This function automates the parameter set hashing and avoids insertion of an
            existing parameter set.

        Attributes:
            preprocess_method (str): Method used for processing of calcium imaging scans.
            paramset_idx (int): Unique parameter set ID.
            paramset_desc (str): Parameter set description.
            params (dict): Parameter Set, all applicable parameters.
        """
        param_dict = {
            "preprocess_method": preprocess_method,
            "paramset_idx": paramset_idx,
            "paramset_desc": paramset_desc,
            "params": params,
            "param_set_hash": dict_to_uuid(params),
        }
        q_param = cls & {"param_set_hash": param_dict["param_set_hash"]}

        if q_param:  # If the specified param-set already exists
            p_name = q_param.fetch1("paramset_idx")
            if p_name == paramset_idx:  # If the existed set has the same name: job done
                return
            else:  # If not same name: human error, trying to add the same paramset with different name
                raise dj.DataJointError(
                    "The specified param-set already exists - name: {}".format(p_name)
                )
        else:
            cls.insert1(param_dict)

insert_new_params(preprocess_method, paramset_idx, paramset_desc, params) classmethod

Insert a parameter set into PreprocessParamSet table. This function automates the parameter set hashing and avoids insertion of an existing parameter set.

Attributes:

Name Type Description
preprocess_method str

Method used for processing of calcium imaging scans.

paramset_idx int

Unique parameter set ID.

paramset_desc str

Parameter set description.

params dict

Parameter Set, all applicable parameters.

Source code in element_calcium_imaging/imaging_preprocess.py
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
@classmethod
def insert_new_params(
    cls,
    preprocess_method: str,
    paramset_idx: int,
    paramset_desc: str,
    params: dict,
):
    """Insert a parameter set into PreprocessParamSet table.
    This function automates the parameter set hashing and avoids insertion of an
        existing parameter set.

    Attributes:
        preprocess_method (str): Method used for processing of calcium imaging scans.
        paramset_idx (int): Unique parameter set ID.
        paramset_desc (str): Parameter set description.
        params (dict): Parameter Set, all applicable parameters.
    """
    param_dict = {
        "preprocess_method": preprocess_method,
        "paramset_idx": paramset_idx,
        "paramset_desc": paramset_desc,
        "params": params,
        "param_set_hash": dict_to_uuid(params),
    }
    q_param = cls & {"param_set_hash": param_dict["param_set_hash"]}

    if q_param:  # If the specified param-set already exists
        p_name = q_param.fetch1("paramset_idx")
        if p_name == paramset_idx:  # If the existed set has the same name: job done
            return
        else:  # If not same name: human error, trying to add the same paramset with different name
            raise dj.DataJointError(
                "The specified param-set already exists - name: {}".format(p_name)
            )
    else:
        cls.insert1(param_dict)

PreprocessParamSteps

Bases: Manual

Ordered list of paramset_idx that will be run.

When pre-processing is not performed, do not create an entry in Step Part table

Attributes:

Name Type Description
preprocess_param_steps_id int
preprocess_param_steps_name str
preprocess_param_steps_desc str
Source code in element_calcium_imaging/imaging_preprocess.py
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
@schema
class PreprocessParamSteps(dj.Manual):
    """Ordered list of paramset_idx that will be run.

    When pre-processing is not performed, do not create an entry in `Step` Part table

    Attributes:
        preprocess_param_steps_id (int):
        preprocess_param_steps_name (str):
        preprocess_param_steps_desc (str):
    """

    definition = """
    preprocess_param_steps_id: smallint
    ---
    preprocess_param_steps_name: varchar(32)
    preprocess_param_steps_desc: varchar(128)
    """

    class Step(dj.Part):
        """ADD DEFINITION

        Attributes:
            PreprocessParamSteps (foreign key): A primary key from PreprocessParamSteps.
            step_number (int):
            PreprocessParamSet (foreign key): A primary key from PreprocessParamSet.
        """

        definition = """
        -> master
        step_number: smallint                  # Order of operations
        ---
        -> PreprocessParamSet
        """

Step

Bases: Part

ADD DEFINITION

Attributes:

Name Type Description
PreprocessParamSteps foreign key

A primary key from PreprocessParamSteps.

step_number int
PreprocessParamSet foreign key

A primary key from PreprocessParamSet.

Source code in element_calcium_imaging/imaging_preprocess.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class Step(dj.Part):
    """ADD DEFINITION

    Attributes:
        PreprocessParamSteps (foreign key): A primary key from PreprocessParamSteps.
        step_number (int):
        PreprocessParamSet (foreign key): A primary key from PreprocessParamSet.
    """

    definition = """
    -> master
    step_number: smallint                  # Order of operations
    ---
    -> PreprocessParamSet
    """

PreprocessTask

Bases: Manual

This table defines a calcium imaging preprocessing task for a combination of a Scan and a PreprocessParamSteps entries, including all the inputs (scan, method, steps). The task defined here is then run in the downstream table Preprocess. This table supports definitions of both loading of pre-generated, results, triggering of new analysis, or skipping of preprocessing step.

Attributes:

Name Type Description
Scan foreign key

A primary key from Scan.

PreprocessParamSteps foreign key

A primary key from PreprocessParamSteps.

preprocess_output_dir str

Output directory for the results of preprocessing.

task_mode str

One of 'load' (load computed analysis results), 'trigger' (trigger computation), 'none' (no pre-processing). Default none.

Source code in element_calcium_imaging/imaging_preprocess.py
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
@schema
class PreprocessTask(dj.Manual):
    """This table defines a calcium imaging preprocessing task for a combination of a
    `Scan` and a `PreprocessParamSteps` entries, including all the inputs (scan, method,
    steps). The task defined here is then run in the downstream table
    Preprocess. This table supports definitions of both loading of pre-generated,
    results, triggering of new analysis, or skipping of preprocessing step.

    Attributes:
        Scan (foreign key): A primary key from Scan.
        PreprocessParamSteps (foreign key): A primary key from PreprocessParamSteps.
        preprocess_output_dir (str): Output directory for the results of preprocessing.
        task_mode (str, optional): One of 'load' (load computed analysis results), 'trigger'
            (trigger computation), 'none' (no pre-processing). Default none.
    """

    definition = """
    # Manual table for defining a pre-processing task ready to be run
    -> scan.Scan
    -> PreprocessParamSteps
    ---
    preprocess_output_dir: varchar(255)  # Pre-processing output directory relative
                                         # to the root data directory
    task_mode='none': enum('none','load', 'trigger') # 'none': no pre-processing
                                                     # 'load': load analysis results
                                                     # 'trigger': trigger computation
    """

Preprocess

Bases: Imported

Perform the computation of an entry (task) defined in the PreprocessTask table.

  • If task_mode == "none": no pre-processing performed
  • If task_mode == "trigger": Not implemented
  • If task_mode == "load": Not implemented

Attributes:

Name Type Description
PreprocessTask foreign key
preprocess_time datetime
package_version str

Version of the analysis package used in processing the data.

Source code in element_calcium_imaging/imaging_preprocess.py
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
@schema
class Preprocess(dj.Imported):
    """Perform the computation of an entry (task) defined in the PreprocessTask table.

    + If `task_mode == "none"`: no pre-processing performed
    + If `task_mode == "trigger"`: Not implemented
    + If `task_mode == "load"`: Not implemented

    Attributes:
        PreprocessTask (foreign key):
        preprocess_time (datetime, optional):
        package_version (str, optional): Version of the analysis package used in
            processing the data.
    """

    definition = """
    -> PreprocessTask
    ---
    preprocess_time=null: datetime  # Time of generation of pre-processing results
    package_version='': varchar(16)
    """

    def make(self, key):
        """Execute the preprocessing analysis steps defined in PreprocessTask."""

        task_mode, output_dir = (PreprocessTask & key).fetch1(
            "task_mode", "preprocess_output_dir"
        )
        _ = find_full_path(get_imaging_root_data_dir(), output_dir)

        if task_mode == "none":
            print(f"No pre-processing run on entry: {key}")
        elif task_mode in ["load", "trigger"]:
            raise NotImplementedError(
                "Pre-processing steps are not implemented."
                "Please overwrite this `make` function with"
                "desired pre-processing steps."
            )
        else:
            raise ValueError(f"Unknown task mode: {task_mode}")

        self.insert1({**key, "package_version": ""})

make(key)

Execute the preprocessing analysis steps defined in PreprocessTask.

Source code in element_calcium_imaging/imaging_preprocess.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def make(self, key):
    """Execute the preprocessing analysis steps defined in PreprocessTask."""

    task_mode, output_dir = (PreprocessTask & key).fetch1(
        "task_mode", "preprocess_output_dir"
    )
    _ = find_full_path(get_imaging_root_data_dir(), output_dir)

    if task_mode == "none":
        print(f"No pre-processing run on entry: {key}")
    elif task_mode in ["load", "trigger"]:
        raise NotImplementedError(
            "Pre-processing steps are not implemented."
            "Please overwrite this `make` function with"
            "desired pre-processing steps."
        )
    else:
        raise ValueError(f"Unknown task mode: {task_mode}")

    self.insert1({**key, "package_version": ""})

ProcessingMethod

Bases: Lookup

Package used for processing of calcium imaging data (e.g. Suite2p, CaImAn, etc.).

Attributes:

Name Type Description
processing_method str

Processing method.

processing_method_desc str

Processing method description.

Source code in element_calcium_imaging/imaging_preprocess.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@schema
class ProcessingMethod(dj.Lookup):
    """Package used for processing of calcium imaging data (e.g. Suite2p, CaImAn, etc.).

    Attributes:
        processing_method (str): Processing method.
        processing_method_desc (str): Processing method description.
    """

    definition = """# Package used for processing of calcium imaging data (e.g. Suite2p, CaImAn, etc.).
    processing_method: char(8)
    ---
    processing_method_desc: varchar(1000)  # Processing method description
    """

    contents = [
        ("suite2p", "suite2p analysis suite"),
        ("caiman", "caiman analysis suite"),
        ("extract", "extract analysis suite"),
    ]

ProcessingParamSet

Bases: Lookup

Parameter set used for the processing of the calcium imaging scans, including both the analysis suite and its respective input parameters.

A hash of the parameters of the analysis suite is also stored in order to avoid duplicated entries.

Attributes:

Name Type Description
paramset_idx int

Unique parameter set ID.

ProcessingMethod foreign key

A primary key from ProcessingMethod.

paramset_desc str

Parameter set description.

param_set_hash uuid

A universally unique identifier for the parameter set.

params longblob

Parameter Set, a dictionary of all applicable parameters to the analysis suite.

Source code in element_calcium_imaging/imaging_preprocess.py
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@schema
class ProcessingParamSet(dj.Lookup):
    """Parameter set used for the processing of the calcium imaging scans,
    including both the analysis suite and its respective input parameters.

    A hash of the parameters of the analysis suite is also stored in order
    to avoid duplicated entries.

    Attributes:
        paramset_idx (int): Unique parameter set ID.
        ProcessingMethod (foreign key): A primary key from ProcessingMethod.
        paramset_desc (str): Parameter set description.
        param_set_hash (uuid): A universally unique identifier for the parameter set.
        params (longblob): Parameter Set, a dictionary of all applicable parameters to
            the analysis suite.
    """

    definition = """# Processing Parameter Set
    paramset_idx: smallint  # Unique parameter set ID.
    ---
    -> ProcessingMethod
    paramset_desc: varchar(1280)  # Parameter-set description
    param_set_hash: uuid  # A universally unique identifier for the parameter set
    unique index (param_set_hash)
    params: longblob  # Parameter Set, a dictionary of all applicable parameters to the analysis suite.
    """

    @classmethod
    def insert_new_params(
        cls,
        processing_method: str,
        paramset_idx: int,
        paramset_desc: str,
        params: dict,
    ):
        """Insert a parameter set into ProcessingParamSet table.

        This function automates the parameter set hashing and avoids insertion of an
            existing parameter set.

        Attributes:
            processing_method (str): Processing method/package used for processing of
                calcium imaging.
            paramset_idx (int): Unique parameter set ID.
            paramset_desc (str): Parameter set description.
            params (dict): Parameter Set, all applicable parameters to the analysis
                suite.
        """
        if processing_method == "extract":
            assert (
                params.get("extract") is not None and params.get("suite2p") is not None
            ), ValueError(
                "Please provide the processing parameters in the {'suite2p': {...}, 'extract': {...}} dictionary format."
            )

            # Force Suite2p to only run motion correction.
            params["suite2p"]["do_registration"] = True
            params["suite2p"]["roidetect"] = False

        param_dict = {
            "processing_method": processing_method,
            "paramset_idx": paramset_idx,
            "paramset_desc": paramset_desc,
            "params": params,
            "param_set_hash": dict_to_uuid(params),
        }
        q_param = cls & {"param_set_hash": param_dict["param_set_hash"]}

        if q_param:  # If the specified param-set already exists
            p_name = q_param.fetch1("paramset_idx")
            if p_name == paramset_idx:  # If the existed set has the same name: job done
                return
            else:  # If not same name: human error, trying to add the same paramset with different name
                raise dj.DataJointError(
                    "The specified param-set already exists - name: {}".format(p_name)
                )
        else:
            cls.insert1(param_dict)

insert_new_params(processing_method, paramset_idx, paramset_desc, params) classmethod

Insert a parameter set into ProcessingParamSet table.

This function automates the parameter set hashing and avoids insertion of an existing parameter set.

Attributes:

Name Type Description
processing_method str

Processing method/package used for processing of calcium imaging.

paramset_idx int

Unique parameter set ID.

paramset_desc str

Parameter set description.

params dict

Parameter Set, all applicable parameters to the analysis suite.

Source code in element_calcium_imaging/imaging_preprocess.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@classmethod
def insert_new_params(
    cls,
    processing_method: str,
    paramset_idx: int,
    paramset_desc: str,
    params: dict,
):
    """Insert a parameter set into ProcessingParamSet table.

    This function automates the parameter set hashing and avoids insertion of an
        existing parameter set.

    Attributes:
        processing_method (str): Processing method/package used for processing of
            calcium imaging.
        paramset_idx (int): Unique parameter set ID.
        paramset_desc (str): Parameter set description.
        params (dict): Parameter Set, all applicable parameters to the analysis
            suite.
    """
    if processing_method == "extract":
        assert (
            params.get("extract") is not None and params.get("suite2p") is not None
        ), ValueError(
            "Please provide the processing parameters in the {'suite2p': {...}, 'extract': {...}} dictionary format."
        )

        # Force Suite2p to only run motion correction.
        params["suite2p"]["do_registration"] = True
        params["suite2p"]["roidetect"] = False

    param_dict = {
        "processing_method": processing_method,
        "paramset_idx": paramset_idx,
        "paramset_desc": paramset_desc,
        "params": params,
        "param_set_hash": dict_to_uuid(params),
    }
    q_param = cls & {"param_set_hash": param_dict["param_set_hash"]}

    if q_param:  # If the specified param-set already exists
        p_name = q_param.fetch1("paramset_idx")
        if p_name == paramset_idx:  # If the existed set has the same name: job done
            return
        else:  # If not same name: human error, trying to add the same paramset with different name
            raise dj.DataJointError(
                "The specified param-set already exists - name: {}".format(p_name)
            )
    else:
        cls.insert1(param_dict)

CellCompartment

Bases: Lookup

Cell compartments that can be imaged (e.g. 'axon', 'soma', etc.)

Attributes:

Name Type Description
cell_compartment str

Cell compartment.

Source code in element_calcium_imaging/imaging_preprocess.py
370
371
372
373
374
375
376
377
378
379
380
381
382
@schema
class CellCompartment(dj.Lookup):
    """Cell compartments that can be imaged (e.g. 'axon', 'soma', etc.)

    Attributes:
        cell_compartment (str): Cell compartment.
    """

    definition = """# Cell compartments
    cell_compartment: char(16)
    """

    contents = zip(["axon", "soma", "bouton"])

MaskType

Bases: Lookup

Available labels for segmented masks (e.g. 'soma', 'axon', 'dendrite', 'neuropil').

Attributes:

Name Type Description
mask_type str

Mask type.

Source code in element_calcium_imaging/imaging_preprocess.py
385
386
387
388
389
390
391
392
393
394
395
396
397
@schema
class MaskType(dj.Lookup):
    """Available labels for segmented masks (e.g. 'soma', 'axon', 'dendrite', 'neuropil').

    Attributes:
        mask_type (str): Mask type.
    """

    definition = """# Possible types of a segmented mask
    mask_type: varchar(16)
    """

    contents = zip(["soma", "axon", "dendrite", "neuropil", "artefact", "unknown"])

ProcessingTask

Bases: Manual

A pairing of processing params and scans to be loaded or triggered

This table defines a calcium imaging processing task for a combination of a Scan and a ProcessingParamSet entries, including all the inputs (scan, method, method's parameters). The task defined here is then run in the downstream table Processing. This table supports definitions of both loading of pre-generated results and the triggering of new analysis for all supported analysis methods.

Attributes:

Name Type Description
Preprocess foreign key

Primary key from Preprocess.

ProcessingParamSet foreign key

Primary key from ProcessingParamSet.

processing_output_dir str

Output directory of the processed scan relative to the root data directory.

task_mode str

One of 'load' (load computed analysis results) or 'trigger' (trigger computation).

Source code in element_calcium_imaging/imaging_preprocess.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
@schema
class ProcessingTask(dj.Manual):
    """A pairing of processing params and scans to be loaded or triggered

    This table defines a calcium imaging processing task for a combination of a
    `Scan` and a `ProcessingParamSet` entries, including all the inputs (scan, method,
    method's parameters). The task defined here is then run in the downstream table
    `Processing`. This table supports definitions of both loading of pre-generated results
    and the triggering of new analysis for all supported analysis methods.

    Attributes:
        Preprocess (foreign key): Primary key from Preprocess.
        ProcessingParamSet (foreign key): Primary key from ProcessingParamSet.
        processing_output_dir (str): Output directory of the processed scan relative to the root data directory.
        task_mode (str): One of 'load' (load computed analysis results) or 'trigger'
            (trigger computation).
    """

    definition = """# Manual table for defining a processing task ready to be run
    -> Preprocess
    -> ProcessingParamSet
    ---
    processing_output_dir: varchar(255)  #  Output directory of the processed scan relative to root data directory
    task_mode='load': enum('load', 'trigger')  # 'load': load computed analysis results, 'trigger': trigger computation
    """

    @classmethod
    def infer_output_dir(cls, key, relative=False, mkdir=False):
        """Infer an output directory for an entry in ProcessingTask table.

        Args:
            key (dict): Primary key from the ProcessingTask table.
            relative (bool): If True, processing_output_dir is returned relative to
                imaging_root_dir. Default False.
            mkdir (bool): If True, create the processing_output_dir directory.
                Default True.

        Returns:
            dir (str): A default output directory for the processed results (processed_output_dir
                in ProcessingTask) based on the following convention:
                processed_dir / scan_dir / {processing_method}_{paramset_idx}
                e.g.: sub4/sess1/scan0/suite2p_0
        """
        acq_software = (scan.Scan & key).fetch1("acq_software")
        filetypes = dict(
            ScanImage="*.tif", Scanbox="*.sbx", NIS="*.nd2", PrairieView="*.tif"
        )

        scan_dir = find_full_path(
            get_imaging_root_data_dir(),
            get_calcium_imaging_files(key, filetypes[acq_software])[0],
        ).parent
        root_dir = find_root_directory(get_imaging_root_data_dir(), scan_dir)

        method = (
            (ProcessingParamSet & key).fetch1("processing_method").replace(".", "-")
        )

        processed_dir = pathlib.Path(get_processed_root_data_dir())
        output_dir = (
            processed_dir
            / scan_dir.relative_to(root_dir)
            / f'{method}_{key["paramset_idx"]}'
        )

        if mkdir:
            output_dir.mkdir(parents=True, exist_ok=True)

        return output_dir.relative_to(processed_dir) if relative else output_dir

    @classmethod
    def generate(cls, scan_key, paramset_idx=0):
        """Generate a ProcessingTask for a Scan using an parameter ProcessingParamSet

        Generate an entry in the ProcessingTask table for a particular scan using an
        existing parameter set from the ProcessingParamSet table.

        Args:
            scan_key (dict): Primary key from Scan table.
            paramset_idx (int): Unique parameter set ID.
        """
        key = {**scan_key, "paramset_idx": paramset_idx}

        processed_dir = get_processed_root_data_dir()
        output_dir = cls.infer_output_dir(key, relative=False, mkdir=True)

        method = (ProcessingParamSet & {"paramset_idx": paramset_idx}).fetch1(
            "processing_method"
        )

        try:
            if method == "suite2p":
                from element_interface import suite2p_loader

                suite2p_loader.Suite2p(output_dir)
            elif method == "caiman":
                from element_interface import caiman_loader

                caiman_loader.CaImAn(output_dir)
            elif method == "extract":
                from element_interface import extract_loader

                extract_loader.EXTRACT(output_dir)

            else:
                raise NotImplementedError(
                    "Unknown/unimplemented method: {}".format(method)
                )
        except FileNotFoundError:
            task_mode = "trigger"
        else:
            task_mode = "load"

        cls.insert1(
            {
                **key,
                "processing_output_dir": output_dir.relative_to(
                    processed_dir
                ).as_posix(),
                "task_mode": task_mode,
            }
        )

    auto_generate_entries = generate

infer_output_dir(key, relative=False, mkdir=False) classmethod

Infer an output directory for an entry in ProcessingTask table.

Parameters:

Name Type Description Default
key dict

Primary key from the ProcessingTask table.

required
relative bool

If True, processing_output_dir is returned relative to imaging_root_dir. Default False.

False
mkdir bool

If True, create the processing_output_dir directory. Default True.

False

Returns:

Name Type Description
dir str

A default output directory for the processed results (processed_output_dir in ProcessingTask) based on the following convention: processed_dir / scan_dir / {processing_method}_{paramset_idx} e.g.: sub4/sess1/scan0/suite2p_0

Source code in element_calcium_imaging/imaging_preprocess.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
@classmethod
def infer_output_dir(cls, key, relative=False, mkdir=False):
    """Infer an output directory for an entry in ProcessingTask table.

    Args:
        key (dict): Primary key from the ProcessingTask table.
        relative (bool): If True, processing_output_dir is returned relative to
            imaging_root_dir. Default False.
        mkdir (bool): If True, create the processing_output_dir directory.
            Default True.

    Returns:
        dir (str): A default output directory for the processed results (processed_output_dir
            in ProcessingTask) based on the following convention:
            processed_dir / scan_dir / {processing_method}_{paramset_idx}
            e.g.: sub4/sess1/scan0/suite2p_0
    """
    acq_software = (scan.Scan & key).fetch1("acq_software")
    filetypes = dict(
        ScanImage="*.tif", Scanbox="*.sbx", NIS="*.nd2", PrairieView="*.tif"
    )

    scan_dir = find_full_path(
        get_imaging_root_data_dir(),
        get_calcium_imaging_files(key, filetypes[acq_software])[0],
    ).parent
    root_dir = find_root_directory(get_imaging_root_data_dir(), scan_dir)

    method = (
        (ProcessingParamSet & key).fetch1("processing_method").replace(".", "-")
    )

    processed_dir = pathlib.Path(get_processed_root_data_dir())
    output_dir = (
        processed_dir
        / scan_dir.relative_to(root_dir)
        / f'{method}_{key["paramset_idx"]}'
    )

    if mkdir:
        output_dir.mkdir(parents=True, exist_ok=True)

    return output_dir.relative_to(processed_dir) if relative else output_dir

generate(scan_key, paramset_idx=0) classmethod

Generate a ProcessingTask for a Scan using an parameter ProcessingParamSet

Generate an entry in the ProcessingTask table for a particular scan using an existing parameter set from the ProcessingParamSet table.

Parameters:

Name Type Description Default
scan_key dict

Primary key from Scan table.

required
paramset_idx int

Unique parameter set ID.

0
Source code in element_calcium_imaging/imaging_preprocess.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
@classmethod
def generate(cls, scan_key, paramset_idx=0):
    """Generate a ProcessingTask for a Scan using an parameter ProcessingParamSet

    Generate an entry in the ProcessingTask table for a particular scan using an
    existing parameter set from the ProcessingParamSet table.

    Args:
        scan_key (dict): Primary key from Scan table.
        paramset_idx (int): Unique parameter set ID.
    """
    key = {**scan_key, "paramset_idx": paramset_idx}

    processed_dir = get_processed_root_data_dir()
    output_dir = cls.infer_output_dir(key, relative=False, mkdir=True)

    method = (ProcessingParamSet & {"paramset_idx": paramset_idx}).fetch1(
        "processing_method"
    )

    try:
        if method == "suite2p":
            from element_interface import suite2p_loader

            suite2p_loader.Suite2p(output_dir)
        elif method == "caiman":
            from element_interface import caiman_loader

            caiman_loader.CaImAn(output_dir)
        elif method == "extract":
            from element_interface import extract_loader

            extract_loader.EXTRACT(output_dir)

        else:
            raise NotImplementedError(
                "Unknown/unimplemented method: {}".format(method)
            )
    except FileNotFoundError:
        task_mode = "trigger"
    else:
        task_mode = "load"

    cls.insert1(
        {
            **key,
            "processing_output_dir": output_dir.relative_to(
                processed_dir
            ).as_posix(),
            "task_mode": task_mode,
        }
    )

Processing

Bases: Computed

Perform the computation of an entry (task) defined in the ProcessingTask table. The computation is performed only on the scans with ScanInfo inserted.

Attributes:

Name Type Description
ProcessingTask foreign key

Primary key from ProcessingTask.

processing_time datetime

Process completion datetime.

package_version str

Version of the analysis package used in processing the data.

Source code in element_calcium_imaging/imaging_preprocess.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
@schema
class Processing(dj.Computed):
    """Perform the computation of an entry (task) defined in the ProcessingTask table.
    The computation is performed only on the scans with ScanInfo inserted.

    Attributes:
        ProcessingTask (foreign key): Primary key from ProcessingTask.
        processing_time (datetime): Process completion datetime.
        package_version (str, optional): Version of the analysis package used in
            processing the data.
    """

    definition = """
    -> ProcessingTask
    ---
    processing_time     : datetime  # Time of generation of this set of processed, segmented results
    package_version=''  : varchar(16)
    """

    # Run processing only on Scan with ScanInfo inserted
    @property
    def key_source(self):
        """Limit the Processing to Scans that have their metadata ingested to the
        database."""

        return ProcessingTask & scan.ScanInfo

    def make(self, key):
        """Execute the calcium imaging analysis defined by the ProcessingTask."""

        task_mode, output_dir = (ProcessingTask & key).fetch1(
            "task_mode", "processing_output_dir"
        )

        if not output_dir:
            output_dir = ProcessingTask.infer_output_dir(key, relative=True, mkdir=True)
            # update processing_output_dir
            ProcessingTask.update1(
                {**key, "processing_output_dir": output_dir.as_posix()}
            )
        output_dir = find_full_path(get_imaging_root_data_dir(), output_dir).as_posix()

        if task_mode == "load":
            method, imaging_dataset = get_loader_result(key, ProcessingTask)
            if method == "suite2p":
                if (scan.ScanInfo & key).fetch1("nrois") > 0:
                    raise NotImplementedError(
                        "Suite2p ingestion error - Unable to handle"
                        + " ScanImage multi-ROI scanning mode yet"
                    )
                suite2p_dataset = imaging_dataset
                key = {**key, "processing_time": suite2p_dataset.creation_time}
            elif method == "caiman":
                caiman_dataset = imaging_dataset
                key = {**key, "processing_time": caiman_dataset.creation_time}
            elif method == "extract":
                raise NotImplementedError(
                    "To use EXTRACT with this DataJoint Element please set `task_mode=trigger`"
                )
            else:
                raise NotImplementedError("Unknown method: {}".format(method))
        elif task_mode == "trigger":
            method = (ProcessingParamSet * ProcessingTask & key).fetch1(
                "processing_method"
            )

            preprocess_paramsets = (
                PreprocessParamSteps.Step()
                & dict(preprocess_param_steps_id=key["preprocess_param_steps_id"])
            ).fetch("paramset_idx")

            if len(preprocess_paramsets) == 0:
                # No pre-processing steps were performed on the acquired dataset, so process the raw/acquired files.
                image_files = (scan.ScanInfo.ScanFile & key).fetch("file_path")
                image_files = [
                    find_full_path(get_imaging_root_data_dir(), image_file)
                    for image_file in image_files
                ]

            else:
                preprocess_output_dir = (PreprocessTask & key).fetch1(
                    "preprocess_output_dir"
                )

                preprocess_output_dir = find_full_path(
                    get_imaging_root_data_dir(), preprocess_output_dir
                )

                if not preprocess_output_dir.exists():
                    raise FileNotFoundError(
                        f"Pre-processed output directory not found ({preprocess_output_dir})"
                    )

                image_files = list(preprocess_output_dir.glob("*.tif"))

            if method == "suite2p":
                import suite2p

                suite2p_params = (ProcessingTask * ProcessingParamSet & key).fetch1(
                    "params"
                )
                suite2p_params["save_path0"] = output_dir
                (
                    suite2p_params["fs"],
                    suite2p_params["nplanes"],
                    suite2p_params["nchannels"],
                ) = (scan.ScanInfo & key).fetch1("fps", "ndepths", "nchannels")

                input_format = pathlib.Path(image_files[0]).suffix
                suite2p_params["input_format"] = input_format[1:]

                suite2p_paths = {
                    "data_path": [image_files[0].parent.as_posix()],
                    "tiff_list": [f.as_posix() for f in image_files],
                }

                suite2p.run_s2p(ops=suite2p_params, db=suite2p_paths)  # Run suite2p

                _, imaging_dataset = get_loader_result(key, ProcessingTask)
                suite2p_dataset = imaging_dataset
                key = {**key, "processing_time": suite2p_dataset.creation_time}

            elif method == "caiman":
                from element_interface.caiman_loader import _process_scanimage_tiff
                from element_interface.run_caiman import run_caiman

                caiman_params = (ProcessingTask * ProcessingParamSet & key).fetch1(
                    "params"
                )
                sampling_rate, ndepths, nchannels = (scan.ScanInfo & key).fetch1(
                    "fps", "ndepths", "nchannels"
                )

                is3D = bool(ndepths > 1)
                if is3D:
                    raise NotImplementedError(
                        "Caiman pipeline is not yet capable of analyzing 3D scans."
                    )

                # handle multi-channel tiff image before running CaImAn
                if nchannels > 1:
                    channel_idx = caiman_params.get("channel_to_process", 0)
                    tmp_dir = pathlib.Path(output_dir) / "channel_separated_tif"
                    tmp_dir.mkdir(exist_ok=True)
                    _process_scanimage_tiff(
                        [f.as_posix() for f in image_files], output_dir=tmp_dir
                    )
                    image_files = tmp_dir.glob(f"*_chn{channel_idx}.tif")

                run_caiman(
                    file_paths=[f.as_posix() for f in image_files],
                    parameters=caiman_params,
                    sampling_rate=sampling_rate,
                    output_dir=output_dir,
                    is3D=is3D,
                )

                _, imaging_dataset = get_loader_result(key, ProcessingTask)
                caiman_dataset = imaging_dataset
                key["processing_time"] = caiman_dataset.creation_time

            elif method == "extract":
                import suite2p
                from element_interface.extract_trigger import EXTRACT_trigger
                from scipy.io import savemat

                # Motion Correction with Suite2p
                params = (ProcessingTask * ProcessingParamSet & key).fetch1("params")

                params["suite2p"]["save_path0"] = output_dir
                (
                    params["suite2p"]["fs"],
                    params["suite2p"]["nplanes"],
                    params["suite2p"]["nchannels"],
                ) = (scan.ScanInfo & key).fetch1("fps", "ndepths", "nchannels")

                input_format = pathlib.Path(image_files[0]).suffix
                params["suite2p"]["input_format"] = input_format[1:]

                suite2p_paths = {
                    "data_path": [image_files[0].parent.as_posix()],
                    "tiff_list": [f.as_posix() for f in image_files],
                }

                suite2p.run_s2p(ops=params["suite2p"], db=suite2p_paths)

                # Convert data.bin to registered_scans.mat
                scanfile_fullpath = pathlib.Path(output_dir) / "suite2p/plane0/data.bin"

                data_shape = (scan.ScanInfo * scan.ScanInfo.Field & key).fetch1(
                    "nframes", "px_height", "px_width"
                )
                data = np.memmap(scanfile_fullpath, shape=data_shape, dtype=np.int16)

                scan_matlab_fullpath = scanfile_fullpath.parent / "registered_scan.mat"

                # Save the motion corrected movie (data.bin) in a .mat file
                savemat(
                    scan_matlab_fullpath,
                    {"M": np.transpose(data, axes=[1, 2, 0])},
                )

                # Execute EXTRACT

                ex = EXTRACT_trigger(
                    scan_matlab_fullpath, params["extract"], output_dir
                )
                ex.run()

                _, extract_dataset = get_loader_result(key, ProcessingTask)
                key["processing_time"] = extract_dataset.creation_time

        else:
            raise ValueError(f"Unknown task mode: {task_mode}")

        self.insert1({**key, "package_version": ""})

key_source property

Limit the Processing to Scans that have their metadata ingested to the database.

make(key)

Execute the calcium imaging analysis defined by the ProcessingTask.

Source code in element_calcium_imaging/imaging_preprocess.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def make(self, key):
    """Execute the calcium imaging analysis defined by the ProcessingTask."""

    task_mode, output_dir = (ProcessingTask & key).fetch1(
        "task_mode", "processing_output_dir"
    )

    if not output_dir:
        output_dir = ProcessingTask.infer_output_dir(key, relative=True, mkdir=True)
        # update processing_output_dir
        ProcessingTask.update1(
            {**key, "processing_output_dir": output_dir.as_posix()}
        )
    output_dir = find_full_path(get_imaging_root_data_dir(), output_dir).as_posix()

    if task_mode == "load":
        method, imaging_dataset = get_loader_result(key, ProcessingTask)
        if method == "suite2p":
            if (scan.ScanInfo & key).fetch1("nrois") > 0:
                raise NotImplementedError(
                    "Suite2p ingestion error - Unable to handle"
                    + " ScanImage multi-ROI scanning mode yet"
                )
            suite2p_dataset = imaging_dataset
            key = {**key, "processing_time": suite2p_dataset.creation_time}
        elif method == "caiman":
            caiman_dataset = imaging_dataset
            key = {**key, "processing_time": caiman_dataset.creation_time}
        elif method == "extract":
            raise NotImplementedError(
                "To use EXTRACT with this DataJoint Element please set `task_mode=trigger`"
            )
        else:
            raise NotImplementedError("Unknown method: {}".format(method))
    elif task_mode == "trigger":
        method = (ProcessingParamSet * ProcessingTask & key).fetch1(
            "processing_method"
        )

        preprocess_paramsets = (
            PreprocessParamSteps.Step()
            & dict(preprocess_param_steps_id=key["preprocess_param_steps_id"])
        ).fetch("paramset_idx")

        if len(preprocess_paramsets) == 0:
            # No pre-processing steps were performed on the acquired dataset, so process the raw/acquired files.
            image_files = (scan.ScanInfo.ScanFile & key).fetch("file_path")
            image_files = [
                find_full_path(get_imaging_root_data_dir(), image_file)
                for image_file in image_files
            ]

        else:
            preprocess_output_dir = (PreprocessTask & key).fetch1(
                "preprocess_output_dir"
            )

            preprocess_output_dir = find_full_path(
                get_imaging_root_data_dir(), preprocess_output_dir
            )

            if not preprocess_output_dir.exists():
                raise FileNotFoundError(
                    f"Pre-processed output directory not found ({preprocess_output_dir})"
                )

            image_files = list(preprocess_output_dir.glob("*.tif"))

        if method == "suite2p":
            import suite2p

            suite2p_params = (ProcessingTask * ProcessingParamSet & key).fetch1(
                "params"
            )
            suite2p_params["save_path0"] = output_dir
            (
                suite2p_params["fs"],
                suite2p_params["nplanes"],
                suite2p_params["nchannels"],
            ) = (scan.ScanInfo & key).fetch1("fps", "ndepths", "nchannels")

            input_format = pathlib.Path(image_files[0]).suffix
            suite2p_params["input_format"] = input_format[1:]

            suite2p_paths = {
                "data_path": [image_files[0].parent.as_posix()],
                "tiff_list": [f.as_posix() for f in image_files],
            }

            suite2p.run_s2p(ops=suite2p_params, db=suite2p_paths)  # Run suite2p

            _, imaging_dataset = get_loader_result(key, ProcessingTask)
            suite2p_dataset = imaging_dataset
            key = {**key, "processing_time": suite2p_dataset.creation_time}

        elif method == "caiman":
            from element_interface.caiman_loader import _process_scanimage_tiff
            from element_interface.run_caiman import run_caiman

            caiman_params = (ProcessingTask * ProcessingParamSet & key).fetch1(
                "params"
            )
            sampling_rate, ndepths, nchannels = (scan.ScanInfo & key).fetch1(
                "fps", "ndepths", "nchannels"
            )

            is3D = bool(ndepths > 1)
            if is3D:
                raise NotImplementedError(
                    "Caiman pipeline is not yet capable of analyzing 3D scans."
                )

            # handle multi-channel tiff image before running CaImAn
            if nchannels > 1:
                channel_idx = caiman_params.get("channel_to_process", 0)
                tmp_dir = pathlib.Path(output_dir) / "channel_separated_tif"
                tmp_dir.mkdir(exist_ok=True)
                _process_scanimage_tiff(
                    [f.as_posix() for f in image_files], output_dir=tmp_dir
                )
                image_files = tmp_dir.glob(f"*_chn{channel_idx}.tif")

            run_caiman(
                file_paths=[f.as_posix() for f in image_files],
                parameters=caiman_params,
                sampling_rate=sampling_rate,
                output_dir=output_dir,
                is3D=is3D,
            )

            _, imaging_dataset = get_loader_result(key, ProcessingTask)
            caiman_dataset = imaging_dataset
            key["processing_time"] = caiman_dataset.creation_time

        elif method == "extract":
            import suite2p
            from element_interface.extract_trigger import EXTRACT_trigger
            from scipy.io import savemat

            # Motion Correction with Suite2p
            params = (ProcessingTask * ProcessingParamSet & key).fetch1("params")

            params["suite2p"]["save_path0"] = output_dir
            (
                params["suite2p"]["fs"],
                params["suite2p"]["nplanes"],
                params["suite2p"]["nchannels"],
            ) = (scan.ScanInfo & key).fetch1("fps", "ndepths", "nchannels")

            input_format = pathlib.Path(image_files[0]).suffix
            params["suite2p"]["input_format"] = input_format[1:]

            suite2p_paths = {
                "data_path": [image_files[0].parent.as_posix()],
                "tiff_list": [f.as_posix() for f in image_files],
            }

            suite2p.run_s2p(ops=params["suite2p"], db=suite2p_paths)

            # Convert data.bin to registered_scans.mat
            scanfile_fullpath = pathlib.Path(output_dir) / "suite2p/plane0/data.bin"

            data_shape = (scan.ScanInfo * scan.ScanInfo.Field & key).fetch1(
                "nframes", "px_height", "px_width"
            )
            data = np.memmap(scanfile_fullpath, shape=data_shape, dtype=np.int16)

            scan_matlab_fullpath = scanfile_fullpath.parent / "registered_scan.mat"

            # Save the motion corrected movie (data.bin) in a .mat file
            savemat(
                scan_matlab_fullpath,
                {"M": np.transpose(data, axes=[1, 2, 0])},
            )

            # Execute EXTRACT

            ex = EXTRACT_trigger(
                scan_matlab_fullpath, params["extract"], output_dir
            )
            ex.run()

            _, extract_dataset = get_loader_result(key, ProcessingTask)
            key["processing_time"] = extract_dataset.creation_time

    else:
        raise ValueError(f"Unknown task mode: {task_mode}")

    self.insert1({**key, "package_version": ""})

Curation

Bases: Manual

Curated results

If no curation is applied, the curation_output_dir can be set to the value of processing_output_dir.

Attributes:

Name Type Description
Processing foreign key

Primary key from Processing.

curation_id int

Unique curation ID.

curation_time datetime

Time of generation of this set of curated results.

curation_output_dir str

Output directory of the curated results, relative to root data directory.

manual_curation bool

If True, manual curation has been performed on this result.

curation_note str

Notes about the curation task.

Source code in element_calcium_imaging/imaging_preprocess.py
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
@schema
class Curation(dj.Manual):
    """Curated results

    If no curation is applied, the curation_output_dir can be set to
    the value of processing_output_dir.

    Attributes:
        Processing (foreign key): Primary key from Processing.
        curation_id (int): Unique curation ID.
        curation_time (datetime): Time of generation of this set of curated results.
        curation_output_dir (str): Output directory of the curated results, relative to
            root data directory.
        manual_curation (bool): If True, manual curation has been performed on this
            result.
        curation_note (str, optional): Notes about the curation task.
    """

    definition = """# Curation(s) results
    -> Processing
    curation_id: int
    ---
    curation_time: datetime  # Time of generation of this set of curated results
    curation_output_dir: varchar(255)  # Output directory of the curated results, relative to root data directory
    manual_curation: bool  # Has manual curation been performed on this result?
    curation_note='': varchar(2000)
    """

    def create1_from_processing_task(self, key, is_curated=False, curation_note=""):
        """Create a Curation entry for a given ProcessingTask key.

        Args:
            key (dict): Primary key set of an entry in the ProcessingTask table.
            is_curated (bool): When True, indicates a manual curation.
            curation_note (str): User's note on the specifics of the curation.
        """
        if key not in Processing():
            raise ValueError(
                f"No corresponding entry in Processing available for: {key};"
                f"Please run `Processing.populate(key)`"
            )

        output_dir = (ProcessingTask & key).fetch1("processing_output_dir")
        method, imaging_dataset = get_loader_result(key, ProcessingTask)

        if method == "suite2p":
            suite2p_dataset = imaging_dataset
            curation_time = suite2p_dataset.creation_time
        elif method == "caiman":
            caiman_dataset = imaging_dataset
            curation_time = caiman_dataset.creation_time
        elif method == "extract":
            extract_dataset = imaging_dataset
            curation_time = extract_dataset.creation_time
        else:
            raise NotImplementedError("Unknown method: {}".format(method))

        # Synthesize curation_id
        curation_id = (
            dj.U().aggr(self & key, n="ifnull(max(curation_id)+1,1)").fetch1("n")
        )
        self.insert1(
            {
                **key,
                "curation_id": curation_id,
                "curation_time": curation_time,
                "curation_output_dir": output_dir,
                "manual_curation": is_curated,
                "curation_note": curation_note,
            }
        )

create1_from_processing_task(key, is_curated=False, curation_note='')

Create a Curation entry for a given ProcessingTask key.

Parameters:

Name Type Description Default
key dict

Primary key set of an entry in the ProcessingTask table.

required
is_curated bool

When True, indicates a manual curation.

False
curation_note str

User's note on the specifics of the curation.

''
Source code in element_calcium_imaging/imaging_preprocess.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
def create1_from_processing_task(self, key, is_curated=False, curation_note=""):
    """Create a Curation entry for a given ProcessingTask key.

    Args:
        key (dict): Primary key set of an entry in the ProcessingTask table.
        is_curated (bool): When True, indicates a manual curation.
        curation_note (str): User's note on the specifics of the curation.
    """
    if key not in Processing():
        raise ValueError(
            f"No corresponding entry in Processing available for: {key};"
            f"Please run `Processing.populate(key)`"
        )

    output_dir = (ProcessingTask & key).fetch1("processing_output_dir")
    method, imaging_dataset = get_loader_result(key, ProcessingTask)

    if method == "suite2p":
        suite2p_dataset = imaging_dataset
        curation_time = suite2p_dataset.creation_time
    elif method == "caiman":
        caiman_dataset = imaging_dataset
        curation_time = caiman_dataset.creation_time
    elif method == "extract":
        extract_dataset = imaging_dataset
        curation_time = extract_dataset.creation_time
    else:
        raise NotImplementedError("Unknown method: {}".format(method))

    # Synthesize curation_id
    curation_id = (
        dj.U().aggr(self & key, n="ifnull(max(curation_id)+1,1)").fetch1("n")
    )
    self.insert1(
        {
            **key,
            "curation_id": curation_id,
            "curation_time": curation_time,
            "curation_output_dir": output_dir,
            "manual_curation": is_curated,
            "curation_note": curation_note,
        }
    )

MotionCorrection

Bases: Imported

Results of motion correction shifts performed on the imaging data.

Attributes:

Name Type Description
Curation foreign key

Primary key from Curation.

scan.Channel.proj(motion_correct_channel='channel') int

Channel used for motion correction in this processing task.

Source code in element_calcium_imaging/imaging_preprocess.py
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
@schema
class MotionCorrection(dj.Imported):
    """Results of motion correction shifts performed on the imaging data.

    Attributes:
        Curation (foreign key): Primary key from Curation.
        scan.Channel.proj(motion_correct_channel='channel') (int): Channel used for
            motion correction in this processing task.
    """

    definition = """# Results of motion correction
    -> Curation
    ---
    -> scan.Channel.proj(motion_correct_channel='channel') # channel used for motion correction in this processing task
    """

    class RigidMotionCorrection(dj.Part):
        """Details of rigid motion correction performed on the imaging data.

        Attributes:
            MotionCorrection (foreign key): Primary key from MotionCorrection.
            outlier_frames (longblob): Mask with true for frames with outlier shifts
                (already corrected).
            y_shifts (longblob): y motion correction shifts (pixels).
            x_shifts (longblob): x motion correction shifts (pixels).
            z_shifts (longblob, optional): z motion correction shifts (z-drift, pixels).
            y_std (float): standard deviation of y shifts across all frames (pixels).
            x_std (float): standard deviation of x shifts across all frames (pixels).
            z_std (float, optional): standard deviation of z shifts across all frames
                (pixels).
        """

        definition = """# Details of rigid motion correction performed on the imaging data
        -> master
        ---
        outlier_frames=null : longblob  # mask with true for frames with outlier shifts (already corrected)
        y_shifts            : longblob  # (pixels) y motion correction shifts
        x_shifts            : longblob  # (pixels) x motion correction shifts
        z_shifts=null       : longblob  # (pixels) z motion correction shifts (z-drift)
        y_std               : float     # (pixels) standard deviation of y shifts across all frames
        x_std               : float     # (pixels) standard deviation of x shifts across all frames
        z_std=null          : float     # (pixels) standard deviation of z shifts across all frames
        """

    class NonRigidMotionCorrection(dj.Part):
        """Piece-wise rigid motion correction - tile the FOV into multiple 3D
        blocks/patches.

        Attributes:
            MotionCorrection (foreign key): Primary key from MotionCorrection.
            outlier_frames (longblob, null): Mask with true for frames with outlier
                shifts (already corrected).
            block_height (int): Block height in pixels.
            block_width (int): Block width in pixels.
            block_depth (int): Block depth in pixels.
            block_count_y (int): Number of blocks tiled in the y direction.
            block_count_x (int): Number of blocks tiled in the x direction.
            block_count_z (int): Number of blocks tiled in the z direction.
        """

        definition = """# Details of non-rigid motion correction performed on the imaging data
        -> master
        ---
        outlier_frames=null : longblob # mask with true for frames with outlier shifts (already corrected)
        block_height        : int      # (pixels)
        block_width         : int      # (pixels)
        block_depth         : int      # (pixels)
        block_count_y       : int      # number of blocks tiled in the y direction
        block_count_x       : int      # number of blocks tiled in the x direction
        block_count_z       : int      # number of blocks tiled in the z direction
        """

    class Block(dj.Part):
        """FOV-tiled blocks used for non-rigid motion correction.

        Attributes:
            NonRigidMotionCorrection (foreign key): Primary key from
                NonRigidMotionCorrection.
            block_id (int): Unique block ID.
            block_y (longblob): y_start and y_end in pixels for this block
            block_x (longblob): x_start and x_end in pixels for this block
            block_z (longblob): z_start and z_end in pixels for this block
            y_shifts (longblob): y motion correction shifts for every frame in pixels
            x_shifts (longblob): x motion correction shifts for every frame in pixels
            z_shift=null (longblob, optional): x motion correction shifts for every frame
                in pixels
            y_std (float): standard deviation of y shifts across all frames in pixels
            x_std (float): standard deviation of x shifts across all frames in pixels
            z_std=null (float, optional): standard deviation of z shifts across all frames
                in pixels
        """

        definition = """# FOV-tiled blocks used for non-rigid motion correction
        -> master.NonRigidMotionCorrection
        block_id        : int
        ---
        block_y         : longblob  # (y_start, y_end) in pixel of this block
        block_x         : longblob  # (x_start, x_end) in pixel of this block
        block_z         : longblob  # (z_start, z_end) in pixel of this block
        y_shifts        : longblob  # (pixels) y motion correction shifts for every frame
        x_shifts        : longblob  # (pixels) x motion correction shifts for every frame
        z_shifts=null   : longblob  # (pixels) x motion correction shifts for every frame
        y_std           : float     # (pixels) standard deviation of y shifts across all frames
        x_std           : float     # (pixels) standard deviation of x shifts across all frames
        z_std=null      : float     # (pixels) standard deviation of z shifts across all frames
        """

    class Summary(dj.Part):
        """Summary images for each field and channel after corrections.

        Attributes:
            MotionCorrection (foreign key): Primary key from MotionCorrection.
            scan.ScanInfo.Field (foreign key): Primary key from scan.ScanInfo.Field.
            ref_image (longblob): Image used as alignment template.
            average_image (longblob): Mean of registered frames.
            correlation_image (longblob, optional): Correlation map (computed during
                cell detection).
            max_proj_image (longblob, optional): Max of registered frames.
        """

        definition = """# Summary images for each field and channel after corrections
        -> master
        -> scan.ScanInfo.Field
        ---
        ref_image               : longblob  # image used as alignment template
        average_image           : longblob  # mean of registered frames
        correlation_image=null  : longblob  # correlation map (computed during cell detection)
        max_proj_image=null     : longblob  # max of registered frames
        """

    def make(self, key):
        """Populate MotionCorrection with results parsed from analysis outputs"""

        method, imaging_dataset = get_loader_result(key, Curation)

        field_keys, _ = (scan.ScanInfo.Field & key).fetch(
            "KEY", "field_z", order_by="field_z"
        )

        if method in ["suite2p", "extract"]:
            suite2p_dataset = imaging_dataset

            motion_correct_channel = suite2p_dataset.planes[0].alignment_channel

            # ---- iterate through all s2p plane outputs ----
            rigid_correction, nonrigid_correction, nonrigid_blocks = {}, {}, {}
            summary_images = []
            for idx, (plane, s2p) in enumerate(suite2p_dataset.planes.items()):
                # -- rigid motion correction --
                if idx == 0:
                    rigid_correction = {
                        **key,
                        "y_shifts": s2p.ops["yoff"],
                        "x_shifts": s2p.ops["xoff"],
                        "z_shifts": np.full_like(s2p.ops["xoff"], 0),
                        "y_std": np.nanstd(s2p.ops["yoff"]),
                        "x_std": np.nanstd(s2p.ops["xoff"]),
                        "z_std": np.nan,
                        "outlier_frames": s2p.ops["badframes"],
                    }
                else:
                    rigid_correction["y_shifts"] = np.vstack(
                        [rigid_correction["y_shifts"], s2p.ops["yoff"]]
                    )
                    rigid_correction["y_std"] = np.nanstd(
                        rigid_correction["y_shifts"].flatten()
                    )
                    rigid_correction["x_shifts"] = np.vstack(
                        [rigid_correction["x_shifts"], s2p.ops["xoff"]]
                    )
                    rigid_correction["x_std"] = np.nanstd(
                        rigid_correction["x_shifts"].flatten()
                    )
                    rigid_correction["outlier_frames"] = np.logical_or(
                        rigid_correction["outlier_frames"], s2p.ops["badframes"]
                    )
                # -- non-rigid motion correction --
                if s2p.ops["nonrigid"]:
                    if idx == 0:
                        nonrigid_correction = {
                            **key,
                            "block_height": s2p.ops["block_size"][0],
                            "block_width": s2p.ops["block_size"][1],
                            "block_depth": 1,
                            "block_count_y": s2p.ops["nblocks"][0],
                            "block_count_x": s2p.ops["nblocks"][1],
                            "block_count_z": len(suite2p_dataset.planes),
                            "outlier_frames": s2p.ops["badframes"],
                        }
                    else:
                        nonrigid_correction["outlier_frames"] = np.logical_or(
                            nonrigid_correction["outlier_frames"],
                            s2p.ops["badframes"],
                        )
                    for b_id, (b_y, b_x, bshift_y, bshift_x) in enumerate(
                        zip(
                            s2p.ops["xblock"],
                            s2p.ops["yblock"],
                            s2p.ops["yoff1"].T,
                            s2p.ops["xoff1"].T,
                        )
                    ):
                        if b_id in nonrigid_blocks:
                            nonrigid_blocks[b_id]["y_shifts"] = np.vstack(
                                [nonrigid_blocks[b_id]["y_shifts"], bshift_y]
                            )
                            nonrigid_blocks[b_id]["y_std"] = np.nanstd(
                                nonrigid_blocks[b_id]["y_shifts"].flatten()
                            )
                            nonrigid_blocks[b_id]["x_shifts"] = np.vstack(
                                [nonrigid_blocks[b_id]["x_shifts"], bshift_x]
                            )
                            nonrigid_blocks[b_id]["x_std"] = np.nanstd(
                                nonrigid_blocks[b_id]["x_shifts"].flatten()
                            )
                        else:
                            nonrigid_blocks[b_id] = {
                                **key,
                                "block_id": b_id,
                                "block_y": b_y,
                                "block_x": b_x,
                                "block_z": np.full_like(b_x, plane),
                                "y_shifts": bshift_y,
                                "x_shifts": bshift_x,
                                "z_shifts": np.full(
                                    (
                                        len(suite2p_dataset.planes),
                                        len(bshift_x),
                                    ),
                                    0,
                                ),
                                "y_std": np.nanstd(bshift_y),
                                "x_std": np.nanstd(bshift_x),
                                "z_std": np.nan,
                            }

                # -- summary images --
                motion_correction_key = (
                    scan.ScanInfo.Field * Curation & key & field_keys[plane]
                ).fetch1("KEY")
                summary_images.append(
                    {
                        **motion_correction_key,
                        "ref_image": s2p.ref_image,
                        "average_image": s2p.mean_image,
                        "correlation_image": s2p.correlation_map,
                        "max_proj_image": s2p.max_proj_image,
                    }
                )

            self.insert1({**key, "motion_correct_channel": motion_correct_channel})
            if rigid_correction:
                self.RigidMotionCorrection.insert1(rigid_correction)
            if nonrigid_correction:
                self.NonRigidMotionCorrection.insert1(nonrigid_correction)
                self.Block.insert(nonrigid_blocks.values())
            self.Summary.insert(summary_images)
        elif method == "caiman":
            caiman_dataset = imaging_dataset

            self.insert1(
                {
                    **key,
                    "motion_correct_channel": caiman_dataset.alignment_channel,
                }
            )

            is3D = caiman_dataset.params.motion["is3D"]
            if not caiman_dataset.params.motion["pw_rigid"]:
                # -- rigid motion correction --
                rigid_correction = {
                    **key,
                    "x_shifts": caiman_dataset.motion_correction["shifts_rig"][:, 0],
                    "y_shifts": caiman_dataset.motion_correction["shifts_rig"][:, 1],
                    "z_shifts": (
                        caiman_dataset.motion_correction["shifts_rig"][:, 2]
                        if is3D
                        else np.full_like(
                            caiman_dataset.motion_correction["shifts_rig"][:, 0],
                            0,
                        )
                    ),
                    "x_std": np.nanstd(
                        caiman_dataset.motion_correction["shifts_rig"][:, 0]
                    ),
                    "y_std": np.nanstd(
                        caiman_dataset.motion_correction["shifts_rig"][:, 1]
                    ),
                    "z_std": (
                        np.nanstd(caiman_dataset.motion_correction["shifts_rig"][:, 2])
                        if is3D
                        else np.nan
                    ),
                    "outlier_frames": None,
                }

                self.RigidMotionCorrection.insert1(rigid_correction)
            else:
                # -- non-rigid motion correction --
                nonrigid_correction = {
                    **key,
                    "block_height": (
                        caiman_dataset.params.motion["strides"][0]
                        + caiman_dataset.params.motion["overlaps"][0]
                    ),
                    "block_width": (
                        caiman_dataset.params.motion["strides"][1]
                        + caiman_dataset.params.motion["overlaps"][1]
                    ),
                    "block_depth": (
                        caiman_dataset.params.motion["strides"][2]
                        + caiman_dataset.params.motion["overlaps"][2]
                        if is3D
                        else 1
                    ),
                    "block_count_x": len(
                        set(caiman_dataset.motion_correction["coord_shifts_els"][:, 0])
                    ),
                    "block_count_y": len(
                        set(caiman_dataset.motion_correction["coord_shifts_els"][:, 2])
                    ),
                    "block_count_z": (
                        len(
                            set(
                                caiman_dataset.motion_correction["coord_shifts_els"][
                                    :, 4
                                ]
                            )
                        )
                        if is3D
                        else 1
                    ),
                    "outlier_frames": None,
                }

                nonrigid_blocks = []
                for b_id in range(
                    len(caiman_dataset.motion_correction["x_shifts_els"][0, :])
                ):
                    nonrigid_blocks.append(
                        {
                            **key,
                            "block_id": b_id,
                            "block_x": np.arange(
                                *caiman_dataset.motion_correction["coord_shifts_els"][
                                    b_id, 0:2
                                ]
                            ),
                            "block_y": np.arange(
                                *caiman_dataset.motion_correction["coord_shifts_els"][
                                    b_id, 2:4
                                ]
                            ),
                            "block_z": (
                                np.arange(
                                    *caiman_dataset.motion_correction[
                                        "coord_shifts_els"
                                    ][b_id, 4:6]
                                )
                                if is3D
                                else np.full_like(
                                    np.arange(
                                        *caiman_dataset.motion_correction[
                                            "coord_shifts_els"
                                        ][b_id, 0:2]
                                    ),
                                    0,
                                )
                            ),
                            "x_shifts": caiman_dataset.motion_correction[
                                "x_shifts_els"
                            ][:, b_id],
                            "y_shifts": caiman_dataset.motion_correction[
                                "y_shifts_els"
                            ][:, b_id],
                            "z_shifts": (
                                caiman_dataset.motion_correction["z_shifts_els"][
                                    :, b_id
                                ]
                                if is3D
                                else np.full_like(
                                    caiman_dataset.motion_correction["x_shifts_els"][
                                        :, b_id
                                    ],
                                    0,
                                )
                            ),
                            "x_std": np.nanstd(
                                caiman_dataset.motion_correction["x_shifts_els"][
                                    :, b_id
                                ]
                            ),
                            "y_std": np.nanstd(
                                caiman_dataset.motion_correction["y_shifts_els"][
                                    :, b_id
                                ]
                            ),
                            "z_std": (
                                np.nanstd(
                                    caiman_dataset.motion_correction["z_shifts_els"][
                                        :, b_id
                                    ]
                                )
                                if is3D
                                else np.nan
                            ),
                        }
                    )

                self.NonRigidMotionCorrection.insert1(nonrigid_correction)
                self.Block.insert(nonrigid_blocks)

            # -- summary images --
            summary_images = [
                {
                    **key,
                    **fkey,
                    "ref_image": ref_image,
                    "average_image": ave_img,
                    "correlation_image": corr_img,
                    "max_proj_image": max_img,
                }
                for fkey, ref_image, ave_img, corr_img, max_img in zip(
                    field_keys,
                    caiman_dataset.motion_correction["reference_image"].transpose(
                        2, 0, 1
                    )
                    if is3D
                    else caiman_dataset.motion_correction["reference_image"][...][
                        np.newaxis, ...
                    ],
                    caiman_dataset.motion_correction["average_image"].transpose(2, 0, 1)
                    if is3D
                    else caiman_dataset.motion_correction["average_image"][...][
                        np.newaxis, ...
                    ],
                    caiman_dataset.motion_correction["correlation_image"].transpose(
                        2, 0, 1
                    )
                    if is3D
                    else caiman_dataset.motion_correction["correlation_image"][...][
                        np.newaxis, ...
                    ],
                    caiman_dataset.motion_correction["max_image"].transpose(2, 0, 1)
                    if is3D
                    else caiman_dataset.motion_correction["max_image"][...][
                        np.newaxis, ...
                    ],
                )
            ]
            self.Summary.insert(summary_images)
        else:
            raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

RigidMotionCorrection

Bases: Part

Details of rigid motion correction performed on the imaging data.

Attributes:

Name Type Description
MotionCorrection foreign key

Primary key from MotionCorrection.

outlier_frames longblob

Mask with true for frames with outlier shifts (already corrected).

y_shifts longblob

y motion correction shifts (pixels).

x_shifts longblob

x motion correction shifts (pixels).

z_shifts longblob

z motion correction shifts (z-drift, pixels).

y_std float

standard deviation of y shifts across all frames (pixels).

x_std float

standard deviation of x shifts across all frames (pixels).

z_std float

standard deviation of z shifts across all frames (pixels).

Source code in element_calcium_imaging/imaging_preprocess.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
class RigidMotionCorrection(dj.Part):
    """Details of rigid motion correction performed on the imaging data.

    Attributes:
        MotionCorrection (foreign key): Primary key from MotionCorrection.
        outlier_frames (longblob): Mask with true for frames with outlier shifts
            (already corrected).
        y_shifts (longblob): y motion correction shifts (pixels).
        x_shifts (longblob): x motion correction shifts (pixels).
        z_shifts (longblob, optional): z motion correction shifts (z-drift, pixels).
        y_std (float): standard deviation of y shifts across all frames (pixels).
        x_std (float): standard deviation of x shifts across all frames (pixels).
        z_std (float, optional): standard deviation of z shifts across all frames
            (pixels).
    """

    definition = """# Details of rigid motion correction performed on the imaging data
    -> master
    ---
    outlier_frames=null : longblob  # mask with true for frames with outlier shifts (already corrected)
    y_shifts            : longblob  # (pixels) y motion correction shifts
    x_shifts            : longblob  # (pixels) x motion correction shifts
    z_shifts=null       : longblob  # (pixels) z motion correction shifts (z-drift)
    y_std               : float     # (pixels) standard deviation of y shifts across all frames
    x_std               : float     # (pixels) standard deviation of x shifts across all frames
    z_std=null          : float     # (pixels) standard deviation of z shifts across all frames
    """

NonRigidMotionCorrection

Bases: Part

Piece-wise rigid motion correction - tile the FOV into multiple 3D blocks/patches.

Attributes:

Name Type Description
MotionCorrection foreign key

Primary key from MotionCorrection.

outlier_frames (longblob, null)

Mask with true for frames with outlier shifts (already corrected).

block_height int

Block height in pixels.

block_width int

Block width in pixels.

block_depth int

Block depth in pixels.

block_count_y int

Number of blocks tiled in the y direction.

block_count_x int

Number of blocks tiled in the x direction.

block_count_z int

Number of blocks tiled in the z direction.

Source code in element_calcium_imaging/imaging_preprocess.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
class NonRigidMotionCorrection(dj.Part):
    """Piece-wise rigid motion correction - tile the FOV into multiple 3D
    blocks/patches.

    Attributes:
        MotionCorrection (foreign key): Primary key from MotionCorrection.
        outlier_frames (longblob, null): Mask with true for frames with outlier
            shifts (already corrected).
        block_height (int): Block height in pixels.
        block_width (int): Block width in pixels.
        block_depth (int): Block depth in pixels.
        block_count_y (int): Number of blocks tiled in the y direction.
        block_count_x (int): Number of blocks tiled in the x direction.
        block_count_z (int): Number of blocks tiled in the z direction.
    """

    definition = """# Details of non-rigid motion correction performed on the imaging data
    -> master
    ---
    outlier_frames=null : longblob # mask with true for frames with outlier shifts (already corrected)
    block_height        : int      # (pixels)
    block_width         : int      # (pixels)
    block_depth         : int      # (pixels)
    block_count_y       : int      # number of blocks tiled in the y direction
    block_count_x       : int      # number of blocks tiled in the x direction
    block_count_z       : int      # number of blocks tiled in the z direction
    """

Block

Bases: Part

FOV-tiled blocks used for non-rigid motion correction.

Attributes:

Name Type Description
NonRigidMotionCorrection foreign key

Primary key from NonRigidMotionCorrection.

block_id int

Unique block ID.

block_y longblob

y_start and y_end in pixels for this block

block_x longblob

x_start and x_end in pixels for this block

block_z longblob

z_start and z_end in pixels for this block

y_shifts longblob

y motion correction shifts for every frame in pixels

x_shifts longblob

x motion correction shifts for every frame in pixels

z_shift=null longblob

x motion correction shifts for every frame in pixels

y_std float

standard deviation of y shifts across all frames in pixels

x_std float

standard deviation of x shifts across all frames in pixels

z_std=null float

standard deviation of z shifts across all frames in pixels

Source code in element_calcium_imaging/imaging_preprocess.py
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
class Block(dj.Part):
    """FOV-tiled blocks used for non-rigid motion correction.

    Attributes:
        NonRigidMotionCorrection (foreign key): Primary key from
            NonRigidMotionCorrection.
        block_id (int): Unique block ID.
        block_y (longblob): y_start and y_end in pixels for this block
        block_x (longblob): x_start and x_end in pixels for this block
        block_z (longblob): z_start and z_end in pixels for this block
        y_shifts (longblob): y motion correction shifts for every frame in pixels
        x_shifts (longblob): x motion correction shifts for every frame in pixels
        z_shift=null (longblob, optional): x motion correction shifts for every frame
            in pixels
        y_std (float): standard deviation of y shifts across all frames in pixels
        x_std (float): standard deviation of x shifts across all frames in pixels
        z_std=null (float, optional): standard deviation of z shifts across all frames
            in pixels
    """

    definition = """# FOV-tiled blocks used for non-rigid motion correction
    -> master.NonRigidMotionCorrection
    block_id        : int
    ---
    block_y         : longblob  # (y_start, y_end) in pixel of this block
    block_x         : longblob  # (x_start, x_end) in pixel of this block
    block_z         : longblob  # (z_start, z_end) in pixel of this block
    y_shifts        : longblob  # (pixels) y motion correction shifts for every frame
    x_shifts        : longblob  # (pixels) x motion correction shifts for every frame
    z_shifts=null   : longblob  # (pixels) x motion correction shifts for every frame
    y_std           : float     # (pixels) standard deviation of y shifts across all frames
    x_std           : float     # (pixels) standard deviation of x shifts across all frames
    z_std=null      : float     # (pixels) standard deviation of z shifts across all frames
    """

Summary

Bases: Part

Summary images for each field and channel after corrections.

Attributes:

Name Type Description
MotionCorrection foreign key

Primary key from MotionCorrection.

scan.ScanInfo.Field foreign key

Primary key from scan.ScanInfo.Field.

ref_image longblob

Image used as alignment template.

average_image longblob

Mean of registered frames.

correlation_image longblob

Correlation map (computed during cell detection).

max_proj_image longblob

Max of registered frames.

Source code in element_calcium_imaging/imaging_preprocess.py
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
class Summary(dj.Part):
    """Summary images for each field and channel after corrections.

    Attributes:
        MotionCorrection (foreign key): Primary key from MotionCorrection.
        scan.ScanInfo.Field (foreign key): Primary key from scan.ScanInfo.Field.
        ref_image (longblob): Image used as alignment template.
        average_image (longblob): Mean of registered frames.
        correlation_image (longblob, optional): Correlation map (computed during
            cell detection).
        max_proj_image (longblob, optional): Max of registered frames.
    """

    definition = """# Summary images for each field and channel after corrections
    -> master
    -> scan.ScanInfo.Field
    ---
    ref_image               : longblob  # image used as alignment template
    average_image           : longblob  # mean of registered frames
    correlation_image=null  : longblob  # correlation map (computed during cell detection)
    max_proj_image=null     : longblob  # max of registered frames
    """

make(key)

Populate MotionCorrection with results parsed from analysis outputs

Source code in element_calcium_imaging/imaging_preprocess.py
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
def make(self, key):
    """Populate MotionCorrection with results parsed from analysis outputs"""

    method, imaging_dataset = get_loader_result(key, Curation)

    field_keys, _ = (scan.ScanInfo.Field & key).fetch(
        "KEY", "field_z", order_by="field_z"
    )

    if method in ["suite2p", "extract"]:
        suite2p_dataset = imaging_dataset

        motion_correct_channel = suite2p_dataset.planes[0].alignment_channel

        # ---- iterate through all s2p plane outputs ----
        rigid_correction, nonrigid_correction, nonrigid_blocks = {}, {}, {}
        summary_images = []
        for idx, (plane, s2p) in enumerate(suite2p_dataset.planes.items()):
            # -- rigid motion correction --
            if idx == 0:
                rigid_correction = {
                    **key,
                    "y_shifts": s2p.ops["yoff"],
                    "x_shifts": s2p.ops["xoff"],
                    "z_shifts": np.full_like(s2p.ops["xoff"], 0),
                    "y_std": np.nanstd(s2p.ops["yoff"]),
                    "x_std": np.nanstd(s2p.ops["xoff"]),
                    "z_std": np.nan,
                    "outlier_frames": s2p.ops["badframes"],
                }
            else:
                rigid_correction["y_shifts"] = np.vstack(
                    [rigid_correction["y_shifts"], s2p.ops["yoff"]]
                )
                rigid_correction["y_std"] = np.nanstd(
                    rigid_correction["y_shifts"].flatten()
                )
                rigid_correction["x_shifts"] = np.vstack(
                    [rigid_correction["x_shifts"], s2p.ops["xoff"]]
                )
                rigid_correction["x_std"] = np.nanstd(
                    rigid_correction["x_shifts"].flatten()
                )
                rigid_correction["outlier_frames"] = np.logical_or(
                    rigid_correction["outlier_frames"], s2p.ops["badframes"]
                )
            # -- non-rigid motion correction --
            if s2p.ops["nonrigid"]:
                if idx == 0:
                    nonrigid_correction = {
                        **key,
                        "block_height": s2p.ops["block_size"][0],
                        "block_width": s2p.ops["block_size"][1],
                        "block_depth": 1,
                        "block_count_y": s2p.ops["nblocks"][0],
                        "block_count_x": s2p.ops["nblocks"][1],
                        "block_count_z": len(suite2p_dataset.planes),
                        "outlier_frames": s2p.ops["badframes"],
                    }
                else:
                    nonrigid_correction["outlier_frames"] = np.logical_or(
                        nonrigid_correction["outlier_frames"],
                        s2p.ops["badframes"],
                    )
                for b_id, (b_y, b_x, bshift_y, bshift_x) in enumerate(
                    zip(
                        s2p.ops["xblock"],
                        s2p.ops["yblock"],
                        s2p.ops["yoff1"].T,
                        s2p.ops["xoff1"].T,
                    )
                ):
                    if b_id in nonrigid_blocks:
                        nonrigid_blocks[b_id]["y_shifts"] = np.vstack(
                            [nonrigid_blocks[b_id]["y_shifts"], bshift_y]
                        )
                        nonrigid_blocks[b_id]["y_std"] = np.nanstd(
                            nonrigid_blocks[b_id]["y_shifts"].flatten()
                        )
                        nonrigid_blocks[b_id]["x_shifts"] = np.vstack(
                            [nonrigid_blocks[b_id]["x_shifts"], bshift_x]
                        )
                        nonrigid_blocks[b_id]["x_std"] = np.nanstd(
                            nonrigid_blocks[b_id]["x_shifts"].flatten()
                        )
                    else:
                        nonrigid_blocks[b_id] = {
                            **key,
                            "block_id": b_id,
                            "block_y": b_y,
                            "block_x": b_x,
                            "block_z": np.full_like(b_x, plane),
                            "y_shifts": bshift_y,
                            "x_shifts": bshift_x,
                            "z_shifts": np.full(
                                (
                                    len(suite2p_dataset.planes),
                                    len(bshift_x),
                                ),
                                0,
                            ),
                            "y_std": np.nanstd(bshift_y),
                            "x_std": np.nanstd(bshift_x),
                            "z_std": np.nan,
                        }

            # -- summary images --
            motion_correction_key = (
                scan.ScanInfo.Field * Curation & key & field_keys[plane]
            ).fetch1("KEY")
            summary_images.append(
                {
                    **motion_correction_key,
                    "ref_image": s2p.ref_image,
                    "average_image": s2p.mean_image,
                    "correlation_image": s2p.correlation_map,
                    "max_proj_image": s2p.max_proj_image,
                }
            )

        self.insert1({**key, "motion_correct_channel": motion_correct_channel})
        if rigid_correction:
            self.RigidMotionCorrection.insert1(rigid_correction)
        if nonrigid_correction:
            self.NonRigidMotionCorrection.insert1(nonrigid_correction)
            self.Block.insert(nonrigid_blocks.values())
        self.Summary.insert(summary_images)
    elif method == "caiman":
        caiman_dataset = imaging_dataset

        self.insert1(
            {
                **key,
                "motion_correct_channel": caiman_dataset.alignment_channel,
            }
        )

        is3D = caiman_dataset.params.motion["is3D"]
        if not caiman_dataset.params.motion["pw_rigid"]:
            # -- rigid motion correction --
            rigid_correction = {
                **key,
                "x_shifts": caiman_dataset.motion_correction["shifts_rig"][:, 0],
                "y_shifts": caiman_dataset.motion_correction["shifts_rig"][:, 1],
                "z_shifts": (
                    caiman_dataset.motion_correction["shifts_rig"][:, 2]
                    if is3D
                    else np.full_like(
                        caiman_dataset.motion_correction["shifts_rig"][:, 0],
                        0,
                    )
                ),
                "x_std": np.nanstd(
                    caiman_dataset.motion_correction["shifts_rig"][:, 0]
                ),
                "y_std": np.nanstd(
                    caiman_dataset.motion_correction["shifts_rig"][:, 1]
                ),
                "z_std": (
                    np.nanstd(caiman_dataset.motion_correction["shifts_rig"][:, 2])
                    if is3D
                    else np.nan
                ),
                "outlier_frames": None,
            }

            self.RigidMotionCorrection.insert1(rigid_correction)
        else:
            # -- non-rigid motion correction --
            nonrigid_correction = {
                **key,
                "block_height": (
                    caiman_dataset.params.motion["strides"][0]
                    + caiman_dataset.params.motion["overlaps"][0]
                ),
                "block_width": (
                    caiman_dataset.params.motion["strides"][1]
                    + caiman_dataset.params.motion["overlaps"][1]
                ),
                "block_depth": (
                    caiman_dataset.params.motion["strides"][2]
                    + caiman_dataset.params.motion["overlaps"][2]
                    if is3D
                    else 1
                ),
                "block_count_x": len(
                    set(caiman_dataset.motion_correction["coord_shifts_els"][:, 0])
                ),
                "block_count_y": len(
                    set(caiman_dataset.motion_correction["coord_shifts_els"][:, 2])
                ),
                "block_count_z": (
                    len(
                        set(
                            caiman_dataset.motion_correction["coord_shifts_els"][
                                :, 4
                            ]
                        )
                    )
                    if is3D
                    else 1
                ),
                "outlier_frames": None,
            }

            nonrigid_blocks = []
            for b_id in range(
                len(caiman_dataset.motion_correction["x_shifts_els"][0, :])
            ):
                nonrigid_blocks.append(
                    {
                        **key,
                        "block_id": b_id,
                        "block_x": np.arange(
                            *caiman_dataset.motion_correction["coord_shifts_els"][
                                b_id, 0:2
                            ]
                        ),
                        "block_y": np.arange(
                            *caiman_dataset.motion_correction["coord_shifts_els"][
                                b_id, 2:4
                            ]
                        ),
                        "block_z": (
                            np.arange(
                                *caiman_dataset.motion_correction[
                                    "coord_shifts_els"
                                ][b_id, 4:6]
                            )
                            if is3D
                            else np.full_like(
                                np.arange(
                                    *caiman_dataset.motion_correction[
                                        "coord_shifts_els"
                                    ][b_id, 0:2]
                                ),
                                0,
                            )
                        ),
                        "x_shifts": caiman_dataset.motion_correction[
                            "x_shifts_els"
                        ][:, b_id],
                        "y_shifts": caiman_dataset.motion_correction[
                            "y_shifts_els"
                        ][:, b_id],
                        "z_shifts": (
                            caiman_dataset.motion_correction["z_shifts_els"][
                                :, b_id
                            ]
                            if is3D
                            else np.full_like(
                                caiman_dataset.motion_correction["x_shifts_els"][
                                    :, b_id
                                ],
                                0,
                            )
                        ),
                        "x_std": np.nanstd(
                            caiman_dataset.motion_correction["x_shifts_els"][
                                :, b_id
                            ]
                        ),
                        "y_std": np.nanstd(
                            caiman_dataset.motion_correction["y_shifts_els"][
                                :, b_id
                            ]
                        ),
                        "z_std": (
                            np.nanstd(
                                caiman_dataset.motion_correction["z_shifts_els"][
                                    :, b_id
                                ]
                            )
                            if is3D
                            else np.nan
                        ),
                    }
                )

            self.NonRigidMotionCorrection.insert1(nonrigid_correction)
            self.Block.insert(nonrigid_blocks)

        # -- summary images --
        summary_images = [
            {
                **key,
                **fkey,
                "ref_image": ref_image,
                "average_image": ave_img,
                "correlation_image": corr_img,
                "max_proj_image": max_img,
            }
            for fkey, ref_image, ave_img, corr_img, max_img in zip(
                field_keys,
                caiman_dataset.motion_correction["reference_image"].transpose(
                    2, 0, 1
                )
                if is3D
                else caiman_dataset.motion_correction["reference_image"][...][
                    np.newaxis, ...
                ],
                caiman_dataset.motion_correction["average_image"].transpose(2, 0, 1)
                if is3D
                else caiman_dataset.motion_correction["average_image"][...][
                    np.newaxis, ...
                ],
                caiman_dataset.motion_correction["correlation_image"].transpose(
                    2, 0, 1
                )
                if is3D
                else caiman_dataset.motion_correction["correlation_image"][...][
                    np.newaxis, ...
                ],
                caiman_dataset.motion_correction["max_image"].transpose(2, 0, 1)
                if is3D
                else caiman_dataset.motion_correction["max_image"][...][
                    np.newaxis, ...
                ],
            )
        ]
        self.Summary.insert(summary_images)
    else:
        raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

Segmentation

Bases: Computed

Result of the Segmentation process.

Attributes:

Name Type Description
Curation foreign key

Primary key from Curation.

Source code in element_calcium_imaging/imaging_preprocess.py
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
@schema
class Segmentation(dj.Computed):
    """Result of the Segmentation process.

    Attributes:
        Curation (foreign key): Primary key from Curation.
    """

    definition = """# Different mask segmentations.
    -> Curation
    """

    class Mask(dj.Part):
        """Details of the masks identified from the Segmentation procedure.

        Attributes:
            Segmentation (foreign key): Primary key from Segmentation.
            mask (int): Unique mask ID.
            scan.Channel.proj(segmentation_channel='channel') (foreign key): Channel
                used for segmentation.
            mask_npix (int): Number of pixels in ROIs.
            mask_center_x (int): Center x coordinate in pixel.
            mask_center_y (int): Center y coordinate in pixel.
            mask_center_z (int): Center z coordinate in pixel.
            mask_xpix (longblob): X coordinates in pixels.
            mask_ypix (longblob): Y coordinates in pixels.
            mask_zpix (longblob): Z coordinates in pixels.
            mask_weights (longblob): Weights of the mask at the indices above.
        """

        definition = """ # A mask produced by segmentation.
        -> master
        mask               : smallint
        ---
        -> scan.Channel.proj(segmentation_channel='channel')  # channel used for segmentation
        mask_npix          : int       # number of pixels in ROIs
        mask_center_x      : int       # center x coordinate in pixel
        mask_center_y      : int       # center y coordinate in pixel
        mask_center_z=null : int       # center z coordinate in pixel
        mask_xpix          : longblob  # x coordinates in pixels
        mask_ypix          : longblob  # y coordinates in pixels
        mask_zpix=null     : longblob  # z coordinates in pixels
        mask_weights       : longblob  # weights of the mask at the indices above
        """

    def make(self, key):
        """Populate the Segmentation with the results parsed from analysis outputs."""

        method, imaging_dataset = get_loader_result(key, Curation)

        if method == "suite2p":
            suite2p_dataset = imaging_dataset

            # ---- iterate through all s2p plane outputs ----
            masks, cells = [], []
            for plane, s2p in suite2p_dataset.planes.items():
                mask_count = len(masks)  # increment mask id from all "plane"
                for mask_idx, (is_cell, cell_prob, mask_stat) in enumerate(
                    zip(s2p.iscell, s2p.cell_prob, s2p.stat)
                ):
                    masks.append(
                        {
                            **key,
                            "mask": mask_idx + mask_count,
                            "segmentation_channel": s2p.segmentation_channel,
                            "mask_npix": mask_stat["npix"],
                            "mask_center_x": mask_stat["med"][1],
                            "mask_center_y": mask_stat["med"][0],
                            "mask_center_z": mask_stat.get("iplane", plane),
                            "mask_xpix": mask_stat["xpix"],
                            "mask_ypix": mask_stat["ypix"],
                            "mask_zpix": np.full(
                                mask_stat["npix"],
                                mask_stat.get("iplane", plane),
                            ),
                            "mask_weights": mask_stat["lam"],
                        }
                    )
                    if is_cell:
                        cells.append(
                            {
                                **key,
                                "mask_classification_method": "suite2p_default_classifier",
                                "mask": mask_idx + mask_count,
                                "mask_type": "soma",
                                "confidence": cell_prob,
                            }
                        )

            self.insert1(key)
            self.Mask.insert(masks, ignore_extra_fields=True)

            if cells:
                MaskClassification.insert1(
                    {
                        **key,
                        "mask_classification_method": "suite2p_default_classifier",
                    },
                    allow_direct_insert=True,
                )
                MaskClassification.MaskType.insert(
                    cells, ignore_extra_fields=True, allow_direct_insert=True
                )
        elif method == "caiman":
            caiman_dataset = imaging_dataset

            # infer "segmentation_channel" - from params if available, else from caiman loader
            params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
            segmentation_channel = params.get(
                "segmentation_channel", caiman_dataset.segmentation_channel
            )

            masks, cells = [], []
            for mask in caiman_dataset.masks:
                masks.append(
                    {
                        **key,
                        "segmentation_channel": segmentation_channel,
                        "mask": mask["mask_id"],
                        "mask_npix": mask["mask_npix"],
                        "mask_center_x": mask["mask_center_x"],
                        "mask_center_y": mask["mask_center_y"],
                        "mask_center_z": mask["mask_center_z"],
                        "mask_xpix": mask["mask_xpix"],
                        "mask_ypix": mask["mask_ypix"],
                        "mask_zpix": mask["mask_zpix"],
                        "mask_weights": mask["mask_weights"],
                    }
                )
                if caiman_dataset.cnmf.estimates.idx_components is not None:
                    if mask["mask_id"] in caiman_dataset.cnmf.estimates.idx_components:
                        cells.append(
                            {
                                **key,
                                "mask_classification_method": "caiman_default_classifier",
                                "mask": mask["mask_id"],
                                "mask_type": "soma",
                            }
                        )

            self.insert1(key)
            self.Mask.insert(masks, ignore_extra_fields=True)

            if cells:
                MaskClassification.insert1(
                    {
                        **key,
                        "mask_classification_method": "caiman_default_classifier",
                    },
                    allow_direct_insert=True,
                )
                MaskClassification.MaskType.insert(
                    cells, ignore_extra_fields=True, allow_direct_insert=True
                )
        elif method == "extract":
            extract_dataset = imaging_dataset
            masks = [
                dict(
                    **key,
                    segmentation_channel=0,
                    mask=mask["mask_id"],
                    mask_npix=mask["mask_npix"],
                    mask_center_x=mask["mask_center_x"],
                    mask_center_y=mask["mask_center_y"],
                    mask_center_z=mask["mask_center_z"],
                    mask_xpix=mask["mask_xpix"],
                    mask_ypix=mask["mask_ypix"],
                    mask_zpix=mask["mask_zpix"],
                    mask_weights=mask["mask_weights"],
                )
                for mask in extract_dataset.load_results()
            ]

            self.insert1(key)
            self.Mask.insert(masks, ignore_extra_fields=True)
        else:
            raise NotImplementedError(f"Unknown/unimplemented method: {method}")

Mask

Bases: Part

Details of the masks identified from the Segmentation procedure.

Attributes:

Name Type Description
Segmentation foreign key

Primary key from Segmentation.

mask int

Unique mask ID.

scan.Channel.proj(segmentation_channel='channel') foreign key

Channel used for segmentation.

mask_npix int

Number of pixels in ROIs.

mask_center_x int

Center x coordinate in pixel.

mask_center_y int

Center y coordinate in pixel.

mask_center_z int

Center z coordinate in pixel.

mask_xpix longblob

X coordinates in pixels.

mask_ypix longblob

Y coordinates in pixels.

mask_zpix longblob

Z coordinates in pixels.

mask_weights longblob

Weights of the mask at the indices above.

Source code in element_calcium_imaging/imaging_preprocess.py
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
class Mask(dj.Part):
    """Details of the masks identified from the Segmentation procedure.

    Attributes:
        Segmentation (foreign key): Primary key from Segmentation.
        mask (int): Unique mask ID.
        scan.Channel.proj(segmentation_channel='channel') (foreign key): Channel
            used for segmentation.
        mask_npix (int): Number of pixels in ROIs.
        mask_center_x (int): Center x coordinate in pixel.
        mask_center_y (int): Center y coordinate in pixel.
        mask_center_z (int): Center z coordinate in pixel.
        mask_xpix (longblob): X coordinates in pixels.
        mask_ypix (longblob): Y coordinates in pixels.
        mask_zpix (longblob): Z coordinates in pixels.
        mask_weights (longblob): Weights of the mask at the indices above.
    """

    definition = """ # A mask produced by segmentation.
    -> master
    mask               : smallint
    ---
    -> scan.Channel.proj(segmentation_channel='channel')  # channel used for segmentation
    mask_npix          : int       # number of pixels in ROIs
    mask_center_x      : int       # center x coordinate in pixel
    mask_center_y      : int       # center y coordinate in pixel
    mask_center_z=null : int       # center z coordinate in pixel
    mask_xpix          : longblob  # x coordinates in pixels
    mask_ypix          : longblob  # y coordinates in pixels
    mask_zpix=null     : longblob  # z coordinates in pixels
    mask_weights       : longblob  # weights of the mask at the indices above
    """

make(key)

Populate the Segmentation with the results parsed from analysis outputs.

Source code in element_calcium_imaging/imaging_preprocess.py
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
def make(self, key):
    """Populate the Segmentation with the results parsed from analysis outputs."""

    method, imaging_dataset = get_loader_result(key, Curation)

    if method == "suite2p":
        suite2p_dataset = imaging_dataset

        # ---- iterate through all s2p plane outputs ----
        masks, cells = [], []
        for plane, s2p in suite2p_dataset.planes.items():
            mask_count = len(masks)  # increment mask id from all "plane"
            for mask_idx, (is_cell, cell_prob, mask_stat) in enumerate(
                zip(s2p.iscell, s2p.cell_prob, s2p.stat)
            ):
                masks.append(
                    {
                        **key,
                        "mask": mask_idx + mask_count,
                        "segmentation_channel": s2p.segmentation_channel,
                        "mask_npix": mask_stat["npix"],
                        "mask_center_x": mask_stat["med"][1],
                        "mask_center_y": mask_stat["med"][0],
                        "mask_center_z": mask_stat.get("iplane", plane),
                        "mask_xpix": mask_stat["xpix"],
                        "mask_ypix": mask_stat["ypix"],
                        "mask_zpix": np.full(
                            mask_stat["npix"],
                            mask_stat.get("iplane", plane),
                        ),
                        "mask_weights": mask_stat["lam"],
                    }
                )
                if is_cell:
                    cells.append(
                        {
                            **key,
                            "mask_classification_method": "suite2p_default_classifier",
                            "mask": mask_idx + mask_count,
                            "mask_type": "soma",
                            "confidence": cell_prob,
                        }
                    )

        self.insert1(key)
        self.Mask.insert(masks, ignore_extra_fields=True)

        if cells:
            MaskClassification.insert1(
                {
                    **key,
                    "mask_classification_method": "suite2p_default_classifier",
                },
                allow_direct_insert=True,
            )
            MaskClassification.MaskType.insert(
                cells, ignore_extra_fields=True, allow_direct_insert=True
            )
    elif method == "caiman":
        caiman_dataset = imaging_dataset

        # infer "segmentation_channel" - from params if available, else from caiman loader
        params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
        segmentation_channel = params.get(
            "segmentation_channel", caiman_dataset.segmentation_channel
        )

        masks, cells = [], []
        for mask in caiman_dataset.masks:
            masks.append(
                {
                    **key,
                    "segmentation_channel": segmentation_channel,
                    "mask": mask["mask_id"],
                    "mask_npix": mask["mask_npix"],
                    "mask_center_x": mask["mask_center_x"],
                    "mask_center_y": mask["mask_center_y"],
                    "mask_center_z": mask["mask_center_z"],
                    "mask_xpix": mask["mask_xpix"],
                    "mask_ypix": mask["mask_ypix"],
                    "mask_zpix": mask["mask_zpix"],
                    "mask_weights": mask["mask_weights"],
                }
            )
            if caiman_dataset.cnmf.estimates.idx_components is not None:
                if mask["mask_id"] in caiman_dataset.cnmf.estimates.idx_components:
                    cells.append(
                        {
                            **key,
                            "mask_classification_method": "caiman_default_classifier",
                            "mask": mask["mask_id"],
                            "mask_type": "soma",
                        }
                    )

        self.insert1(key)
        self.Mask.insert(masks, ignore_extra_fields=True)

        if cells:
            MaskClassification.insert1(
                {
                    **key,
                    "mask_classification_method": "caiman_default_classifier",
                },
                allow_direct_insert=True,
            )
            MaskClassification.MaskType.insert(
                cells, ignore_extra_fields=True, allow_direct_insert=True
            )
    elif method == "extract":
        extract_dataset = imaging_dataset
        masks = [
            dict(
                **key,
                segmentation_channel=0,
                mask=mask["mask_id"],
                mask_npix=mask["mask_npix"],
                mask_center_x=mask["mask_center_x"],
                mask_center_y=mask["mask_center_y"],
                mask_center_z=mask["mask_center_z"],
                mask_xpix=mask["mask_xpix"],
                mask_ypix=mask["mask_ypix"],
                mask_zpix=mask["mask_zpix"],
                mask_weights=mask["mask_weights"],
            )
            for mask in extract_dataset.load_results()
        ]

        self.insert1(key)
        self.Mask.insert(masks, ignore_extra_fields=True)
    else:
        raise NotImplementedError(f"Unknown/unimplemented method: {method}")

MaskClassificationMethod

Bases: Lookup

Available mask classification methods.

Attributes:

Name Type Description
mask_classification_method str

Mask classification method.

Source code in element_calcium_imaging/imaging_preprocess.py
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
@schema
class MaskClassificationMethod(dj.Lookup):
    """Available mask classification methods.

    Attributes:
        mask_classification_method (str): Mask classification method.
    """

    definition = """
    mask_classification_method: varchar(48)
    """

    contents = zip(["suite2p_default_classifier", "caiman_default_classifier"])

MaskClassification

Bases: Computed

Classes assigned to each mask.

Attributes:

Name Type Description
Segmentation foreign key

Primary key from Segmentation.

MaskClassificationMethod foreign key

Primary key from MaskClassificationMethod.

Source code in element_calcium_imaging/imaging_preprocess.py
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
@schema
class MaskClassification(dj.Computed):
    """Classes assigned to each mask.

    Attributes:
        Segmentation (foreign key): Primary key from Segmentation.
        MaskClassificationMethod (foreign key): Primary key from
            MaskClassificationMethod.
    """

    definition = """
    -> Segmentation
    -> MaskClassificationMethod
    """

    class MaskType(dj.Part):
        """Type assigned to each mask.

        Attributes:
            MaskClassification (foreign key): Primary key from MaskClassification.
            Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
            MaskType: Primary key from MaskType.
            confidence (float, optional): Confidence level of the mask classification.
        """

        definition = """
        -> master
        -> Segmentation.Mask
        ---
        -> MaskType
        confidence=null: float
        """

    def make(self, key):
        pass

MaskType

Bases: Part

Type assigned to each mask.

Attributes:

Name Type Description
MaskClassification foreign key

Primary key from MaskClassification.

Segmentation.Mask foreign key

Primary key from Segmentation.Mask.

MaskType foreign key

Primary key from MaskType.

confidence float

Confidence level of the mask classification.

Source code in element_calcium_imaging/imaging_preprocess.py
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
class MaskType(dj.Part):
    """Type assigned to each mask.

    Attributes:
        MaskClassification (foreign key): Primary key from MaskClassification.
        Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
        MaskType: Primary key from MaskType.
        confidence (float, optional): Confidence level of the mask classification.
    """

    definition = """
    -> master
    -> Segmentation.Mask
    ---
    -> MaskType
    confidence=null: float
    """

Fluorescence

Bases: Computed

Fluorescence traces.

Attributes:

Name Type Description
Segmentation foreign key

Primary key from Segmentation.

Source code in element_calcium_imaging/imaging_preprocess.py
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
@schema
class Fluorescence(dj.Computed):
    """Fluorescence traces.

    Attributes:
        Segmentation (foreign key): Primary key from Segmentation.
    """

    definition = """# Fluorescence traces before spike extraction or filtering
    -> Segmentation
    """

    class Trace(dj.Part):
        """Traces obtained from segmented region of interests.

        Attributes:
            Fluorescence (foreign key): Primary key from Fluorescence.
            Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
            scan.Channel.proj(fluo_channel='channel') (int): The channel that this trace
                comes from.
            fluorescence (longblob): Fluorescence trace associated with this mask.
            neuropil_fluorescence (longblob, optional): Neuropil fluorescence trace.
        """

        definition = """
        -> master
        -> Segmentation.Mask
        -> scan.Channel.proj(fluo_channel='channel')  # The channel that this trace comes from
        ---
        fluorescence                : longblob  # Fluorescence trace associated with this mask
        neuropil_fluorescence=null  : longblob  # Neuropil fluorescence trace
        """

    def make(self, key):
        """Populate the Fluorescence with the results parsed from analysis outputs."""

        method, imaging_dataset = get_loader_result(key, Curation)

        if method == "suite2p":
            suite2p_dataset = imaging_dataset

            # ---- iterate through all s2p plane outputs ----
            fluo_traces, fluo_chn2_traces = [], []
            for s2p in suite2p_dataset.planes.values():
                mask_count = len(fluo_traces)  # increment mask id from all "plane"
                for mask_idx, (f, fneu) in enumerate(zip(s2p.F, s2p.Fneu)):
                    fluo_traces.append(
                        {
                            **key,
                            "mask": mask_idx + mask_count,
                            "fluo_channel": 0,
                            "fluorescence": f,
                            "neuropil_fluorescence": fneu,
                        }
                    )
                if len(s2p.F_chan2):
                    mask_chn2_count = len(
                        fluo_chn2_traces
                    )  # increment mask id from all planes
                    for mask_idx, (f2, fneu2) in enumerate(
                        zip(s2p.F_chan2, s2p.Fneu_chan2)
                    ):
                        fluo_chn2_traces.append(
                            {
                                **key,
                                "mask": mask_idx + mask_chn2_count,
                                "fluo_channel": 1,
                                "fluorescence": f2,
                                "neuropil_fluorescence": fneu2,
                            }
                        )

            self.insert1(key)
            self.Trace.insert(fluo_traces + fluo_chn2_traces)
        elif method == "caiman":
            caiman_dataset = imaging_dataset

            # infer "segmentation_channel" - from params if available, else from caiman loader
            params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
            segmentation_channel = params.get(
                "segmentation_channel", caiman_dataset.segmentation_channel
            )

            fluo_traces = []
            for mask in caiman_dataset.masks:
                fluo_traces.append(
                    {
                        **key,
                        "mask": mask["mask_id"],
                        "fluo_channel": segmentation_channel,
                        "fluorescence": mask["inferred_trace"],
                    }
                )

            self.insert1(key)
            self.Trace.insert(fluo_traces)
        elif method == "extract":
            extract_dataset = imaging_dataset

            fluo_traces = [
                {
                    **key,
                    "mask": mask_id,
                    "fluo_channel": 0,
                    "fluorescence": fluorescence,
                }
                for mask_id, fluorescence in enumerate(extract_dataset.T)
            ]

            self.insert1(key)
            self.Trace.insert(fluo_traces)

        else:
            raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

Trace

Bases: Part

Traces obtained from segmented region of interests.

Attributes:

Name Type Description
Fluorescence foreign key

Primary key from Fluorescence.

Segmentation.Mask foreign key

Primary key from Segmentation.Mask.

scan.Channel.proj(fluo_channel='channel') int

The channel that this trace comes from.

fluorescence longblob

Fluorescence trace associated with this mask.

neuropil_fluorescence longblob

Neuropil fluorescence trace.

Source code in element_calcium_imaging/imaging_preprocess.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
class Trace(dj.Part):
    """Traces obtained from segmented region of interests.

    Attributes:
        Fluorescence (foreign key): Primary key from Fluorescence.
        Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
        scan.Channel.proj(fluo_channel='channel') (int): The channel that this trace
            comes from.
        fluorescence (longblob): Fluorescence trace associated with this mask.
        neuropil_fluorescence (longblob, optional): Neuropil fluorescence trace.
    """

    definition = """
    -> master
    -> Segmentation.Mask
    -> scan.Channel.proj(fluo_channel='channel')  # The channel that this trace comes from
    ---
    fluorescence                : longblob  # Fluorescence trace associated with this mask
    neuropil_fluorescence=null  : longblob  # Neuropil fluorescence trace
    """

make(key)

Populate the Fluorescence with the results parsed from analysis outputs.

Source code in element_calcium_imaging/imaging_preprocess.py
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
def make(self, key):
    """Populate the Fluorescence with the results parsed from analysis outputs."""

    method, imaging_dataset = get_loader_result(key, Curation)

    if method == "suite2p":
        suite2p_dataset = imaging_dataset

        # ---- iterate through all s2p plane outputs ----
        fluo_traces, fluo_chn2_traces = [], []
        for s2p in suite2p_dataset.planes.values():
            mask_count = len(fluo_traces)  # increment mask id from all "plane"
            for mask_idx, (f, fneu) in enumerate(zip(s2p.F, s2p.Fneu)):
                fluo_traces.append(
                    {
                        **key,
                        "mask": mask_idx + mask_count,
                        "fluo_channel": 0,
                        "fluorescence": f,
                        "neuropil_fluorescence": fneu,
                    }
                )
            if len(s2p.F_chan2):
                mask_chn2_count = len(
                    fluo_chn2_traces
                )  # increment mask id from all planes
                for mask_idx, (f2, fneu2) in enumerate(
                    zip(s2p.F_chan2, s2p.Fneu_chan2)
                ):
                    fluo_chn2_traces.append(
                        {
                            **key,
                            "mask": mask_idx + mask_chn2_count,
                            "fluo_channel": 1,
                            "fluorescence": f2,
                            "neuropil_fluorescence": fneu2,
                        }
                    )

        self.insert1(key)
        self.Trace.insert(fluo_traces + fluo_chn2_traces)
    elif method == "caiman":
        caiman_dataset = imaging_dataset

        # infer "segmentation_channel" - from params if available, else from caiman loader
        params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
        segmentation_channel = params.get(
            "segmentation_channel", caiman_dataset.segmentation_channel
        )

        fluo_traces = []
        for mask in caiman_dataset.masks:
            fluo_traces.append(
                {
                    **key,
                    "mask": mask["mask_id"],
                    "fluo_channel": segmentation_channel,
                    "fluorescence": mask["inferred_trace"],
                }
            )

        self.insert1(key)
        self.Trace.insert(fluo_traces)
    elif method == "extract":
        extract_dataset = imaging_dataset

        fluo_traces = [
            {
                **key,
                "mask": mask_id,
                "fluo_channel": 0,
                "fluorescence": fluorescence,
            }
            for mask_id, fluorescence in enumerate(extract_dataset.T)
        ]

        self.insert1(key)
        self.Trace.insert(fluo_traces)

    else:
        raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

ActivityExtractionMethod

Bases: Lookup

Available activity extraction methods.

Attributes:

Name Type Description
extraction_method str

Extraction method.

Source code in element_calcium_imaging/imaging_preprocess.py
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
@schema
class ActivityExtractionMethod(dj.Lookup):
    """Available activity extraction methods.

    Attributes:
        extraction_method (str): Extraction method.
    """

    definition = """# Activity extraction method
    extraction_method: varchar(32)
    """

    contents = zip(["suite2p_deconvolution", "caiman_deconvolution", "caiman_dff"])

Activity

Bases: Computed

Inferred neural activity from fluorescence trace (e.g. dff, spikes, etc.).

Attributes:

Name Type Description
Fluorescence foreign key

Primary key from Fluorescence.

ActivityExtractionMethod foreign key

Primary key from ActivityExtractionMethod.

Source code in element_calcium_imaging/imaging_preprocess.py
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
@schema
class Activity(dj.Computed):
    """Inferred neural activity from fluorescence trace (e.g. dff, spikes, etc.).

    Attributes:
        Fluorescence (foreign key): Primary key from Fluorescence.
        ActivityExtractionMethod (foreign key): Primary key from
            ActivityExtractionMethod.
    """

    definition = """# Neural Activity
    -> Fluorescence
    -> ActivityExtractionMethod
    """

    class Trace(dj.Part):
        """Trace(s) for each mask.

        Attributes:
            Activity (foreign key): Primary key from Activity.
            Fluorescence.Trace (foreign key): Fluorescence.Trace.
            activity_trace (longblob): Neural activity from fluorescence trace.
        """

        definition = """
        -> master
        -> Fluorescence.Trace
        ---
        activity_trace: longblob
        """

    @property
    def key_source(self):
        suite2p_key_source = (
            Fluorescence
            * ActivityExtractionMethod
            * ProcessingParamSet.proj("processing_method")
            & 'processing_method = "suite2p"'
            & 'extraction_method LIKE "suite2p%"'
        )
        caiman_key_source = (
            Fluorescence
            * ActivityExtractionMethod
            * ProcessingParamSet.proj("processing_method")
            & 'processing_method = "caiman"'
            & 'extraction_method LIKE "caiman%"'
        )
        return suite2p_key_source.proj() + caiman_key_source.proj()

    def make(self, key):
        """Populate the Activity with the results parsed from analysis outputs."""

        method, imaging_dataset = get_loader_result(key, Curation)

        if method == "suite2p":
            if key["extraction_method"] == "suite2p_deconvolution":
                suite2p_dataset = imaging_dataset
                # ---- iterate through all s2p plane outputs ----
                spikes = [
                    dict(
                        key,
                        mask=mask_idx,
                        fluo_channel=0,
                        activity_trace=spks,
                    )
                    for mask_idx, spks in enumerate(
                        s
                        for plane in suite2p_dataset.planes.values()
                        for s in plane.spks
                    )
                ]

                self.insert1(key)
                self.Trace.insert(spikes)
        elif method == "caiman":
            caiman_dataset = imaging_dataset

            if key["extraction_method"] in (
                "caiman_deconvolution",
                "caiman_dff",
            ):
                attr_mapper = {
                    "caiman_deconvolution": "spikes",
                    "caiman_dff": "dff",
                }

                # infer "segmentation_channel" - from params if available, else from caiman loader
                params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
                segmentation_channel = params.get(
                    "segmentation_channel", caiman_dataset.segmentation_channel
                )

                self.insert1(key)
                self.Trace.insert(
                    dict(
                        key,
                        mask=mask["mask_id"],
                        fluo_channel=segmentation_channel,
                        activity_trace=mask[attr_mapper[key["extraction_method"]]],
                    )
                    for mask in caiman_dataset.masks
                )
        else:
            raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

Trace

Bases: Part

Trace(s) for each mask.

Attributes:

Name Type Description
Activity foreign key

Primary key from Activity.

Fluorescence.Trace foreign key

Fluorescence.Trace.

activity_trace longblob

Neural activity from fluorescence trace.

Source code in element_calcium_imaging/imaging_preprocess.py
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
class Trace(dj.Part):
    """Trace(s) for each mask.

    Attributes:
        Activity (foreign key): Primary key from Activity.
        Fluorescence.Trace (foreign key): Fluorescence.Trace.
        activity_trace (longblob): Neural activity from fluorescence trace.
    """

    definition = """
    -> master
    -> Fluorescence.Trace
    ---
    activity_trace: longblob
    """

make(key)

Populate the Activity with the results parsed from analysis outputs.

Source code in element_calcium_imaging/imaging_preprocess.py
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
def make(self, key):
    """Populate the Activity with the results parsed from analysis outputs."""

    method, imaging_dataset = get_loader_result(key, Curation)

    if method == "suite2p":
        if key["extraction_method"] == "suite2p_deconvolution":
            suite2p_dataset = imaging_dataset
            # ---- iterate through all s2p plane outputs ----
            spikes = [
                dict(
                    key,
                    mask=mask_idx,
                    fluo_channel=0,
                    activity_trace=spks,
                )
                for mask_idx, spks in enumerate(
                    s
                    for plane in suite2p_dataset.planes.values()
                    for s in plane.spks
                )
            ]

            self.insert1(key)
            self.Trace.insert(spikes)
    elif method == "caiman":
        caiman_dataset = imaging_dataset

        if key["extraction_method"] in (
            "caiman_deconvolution",
            "caiman_dff",
        ):
            attr_mapper = {
                "caiman_deconvolution": "spikes",
                "caiman_dff": "dff",
            }

            # infer "segmentation_channel" - from params if available, else from caiman loader
            params = (ProcessingParamSet * ProcessingTask & key).fetch1("params")
            segmentation_channel = params.get(
                "segmentation_channel", caiman_dataset.segmentation_channel
            )

            self.insert1(key)
            self.Trace.insert(
                dict(
                    key,
                    mask=mask["mask_id"],
                    fluo_channel=segmentation_channel,
                    activity_trace=mask[attr_mapper[key["extraction_method"]]],
                )
                for mask in caiman_dataset.masks
            )
    else:
        raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

ProcessingQualityMetrics

Bases: Computed

Quality metrics used to evaluate the results of the calcium imaging analysis pipeline.

Attributes:

Name Type Description
Fluorescence foreign key

Primary key from Fluorescence.

Source code in element_calcium_imaging/imaging_preprocess.py
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
@schema
class ProcessingQualityMetrics(dj.Computed):
    """Quality metrics used to evaluate the results of the calcium imaging analysis pipeline.

    Attributes:
        Fluorescence (foreign key): Primary key from Fluorescence.
    """

    definition = """
    -> Fluorescence
    """

    class Mask(dj.Part):
        """Quality metrics used to evaluate the masks.

        Attributes:
            Fluorescence (foreign key): Primary key from Fluorescence.
            Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
            mask_area (float): Mask area in square micrometer.
            roundness (float): Roundness between 0 and 1. Values closer to 1 are rounder.
        """

        definition = """
        -> master
        -> Segmentation.Mask
        ---
        mask_area=null: float  # Mask area in square micrometer.
        roundness: float       # Roundness between 0 and 1. Values closer to 1 are rounder.
        """

    class Trace(dj.Part):
        """Quality metrics used to evaluate the fluorescence traces.

        Attributes:
            Fluorescence (foreign key): Primary key from Fluorescence.
            Fluorescence.Trace (foreign key): Primary key from Fluorescence.Trace.
            skewness (float): Skewness of the fluorescence trace.
            variance (float): Variance of the fluorescence trace.
        """

        definition = """
        -> master
        -> Fluorescence.Trace
        ---
        skewness: float   # Skewness of the fluorescence trace.
        variance: float   # Variance of the fluorescence trace.
        """

    def make(self, key):
        """Populate the ProcessingQualityMetrics table and its part tables."""
        from scipy.stats import skew

        (
            mask_xpixs,
            mask_ypixs,
            mask_weights,
            fluorescence,
            fluo_channels,
            mask_ids,
            mask_npix,
            px_height,
            px_width,
            um_height,
            um_width,
        ) = (Segmentation.Mask * scan.ScanInfo.Field * Fluorescence.Trace & key).fetch(
            "mask_xpix",
            "mask_ypix",
            "mask_weights",
            "fluorescence",
            "fluo_channel",
            "mask",
            "mask_npix",
            "px_height",
            "px_width",
            "um_height",
            "um_width",
        )

        norm_mean = lambda x: x.mean() / x.max()
        roundnesses = [
            norm_mean(np.linalg.eigvals(np.cov(x, y, aweights=w)))
            for x, y, w in zip(mask_xpixs, mask_ypixs, mask_weights)
        ]

        fluorescence = np.stack(fluorescence)

        self.insert1(key)

        self.Mask.insert(
            dict(key, mask=mask_id, mask_area=mask_area, roundness=roundness)
            for mask_id, mask_area, roundness in zip(
                mask_ids,
                mask_npix * (um_height / px_height) * (um_width / px_width),
                roundnesses,
            )
        )

        self.Trace.insert(
            dict(
                key,
                fluo_channel=fluo_channel,
                mask=mask_id,
                skewness=skewness,
                variance=variance,
            )
            for fluo_channel, mask_id, skewness, variance in zip(
                fluo_channels,
                mask_ids,
                skew(fluorescence, axis=1),
                fluorescence.std(axis=1),
            )
        )

Mask

Bases: Part

Quality metrics used to evaluate the masks.

Attributes:

Name Type Description
Fluorescence foreign key

Primary key from Fluorescence.

Segmentation.Mask foreign key

Primary key from Segmentation.Mask.

mask_area float

Mask area in square micrometer.

roundness float

Roundness between 0 and 1. Values closer to 1 are rounder.

Source code in element_calcium_imaging/imaging_preprocess.py
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
class Mask(dj.Part):
    """Quality metrics used to evaluate the masks.

    Attributes:
        Fluorescence (foreign key): Primary key from Fluorescence.
        Segmentation.Mask (foreign key): Primary key from Segmentation.Mask.
        mask_area (float): Mask area in square micrometer.
        roundness (float): Roundness between 0 and 1. Values closer to 1 are rounder.
    """

    definition = """
    -> master
    -> Segmentation.Mask
    ---
    mask_area=null: float  # Mask area in square micrometer.
    roundness: float       # Roundness between 0 and 1. Values closer to 1 are rounder.
    """

Trace

Bases: Part

Quality metrics used to evaluate the fluorescence traces.

Attributes:

Name Type Description
Fluorescence foreign key

Primary key from Fluorescence.

Fluorescence.Trace foreign key

Primary key from Fluorescence.Trace.

skewness float

Skewness of the fluorescence trace.

variance float

Variance of the fluorescence trace.

Source code in element_calcium_imaging/imaging_preprocess.py
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
class Trace(dj.Part):
    """Quality metrics used to evaluate the fluorescence traces.

    Attributes:
        Fluorescence (foreign key): Primary key from Fluorescence.
        Fluorescence.Trace (foreign key): Primary key from Fluorescence.Trace.
        skewness (float): Skewness of the fluorescence trace.
        variance (float): Variance of the fluorescence trace.
    """

    definition = """
    -> master
    -> Fluorescence.Trace
    ---
    skewness: float   # Skewness of the fluorescence trace.
    variance: float   # Variance of the fluorescence trace.
    """

make(key)

Populate the ProcessingQualityMetrics table and its part tables.

Source code in element_calcium_imaging/imaging_preprocess.py
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
def make(self, key):
    """Populate the ProcessingQualityMetrics table and its part tables."""
    from scipy.stats import skew

    (
        mask_xpixs,
        mask_ypixs,
        mask_weights,
        fluorescence,
        fluo_channels,
        mask_ids,
        mask_npix,
        px_height,
        px_width,
        um_height,
        um_width,
    ) = (Segmentation.Mask * scan.ScanInfo.Field * Fluorescence.Trace & key).fetch(
        "mask_xpix",
        "mask_ypix",
        "mask_weights",
        "fluorescence",
        "fluo_channel",
        "mask",
        "mask_npix",
        "px_height",
        "px_width",
        "um_height",
        "um_width",
    )

    norm_mean = lambda x: x.mean() / x.max()
    roundnesses = [
        norm_mean(np.linalg.eigvals(np.cov(x, y, aweights=w)))
        for x, y, w in zip(mask_xpixs, mask_ypixs, mask_weights)
    ]

    fluorescence = np.stack(fluorescence)

    self.insert1(key)

    self.Mask.insert(
        dict(key, mask=mask_id, mask_area=mask_area, roundness=roundness)
        for mask_id, mask_area, roundness in zip(
            mask_ids,
            mask_npix * (um_height / px_height) * (um_width / px_width),
            roundnesses,
        )
    )

    self.Trace.insert(
        dict(
            key,
            fluo_channel=fluo_channel,
            mask=mask_id,
            skewness=skewness,
            variance=variance,
        )
        for fluo_channel, mask_id, skewness, variance in zip(
            fluo_channels,
            mask_ids,
            skew(fluorescence, axis=1),
            fluorescence.std(axis=1),
        )
    )

get_loader_result(key, table)

Retrieve the processed imaging results from a suite2p or caiman loader.

Parameters:

Name Type Description Default
key dict

The key to one entry of ProcessingTask or Curation

required
table Table

A datajoint table to retrieve the loaded results from (e.g. ProcessingTask, Curation)

required

Raises:

Type Description
NotImplementedError

If the processing_method is different than 'suite2p' or 'caiman'.

Returns:

Type Description
Callable

A loader object of the loaded results (e.g. suite2p.Suite2p or caiman.CaImAn,

Callable

see element-interface for more information on the loaders.)

Source code in element_calcium_imaging/imaging_preprocess.py
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
def get_loader_result(key: dict, table: dj.Table) -> Callable:
    """Retrieve the processed imaging results from a suite2p or caiman loader.

    Args:
        key (dict): The `key` to one entry of ProcessingTask or Curation
        table (dj.Table): A datajoint table to retrieve the loaded results from (e.g.
            ProcessingTask, Curation)

    Raises:
        NotImplementedError: If the processing_method is different than 'suite2p' or
            'caiman'.

    Returns:
        A loader object of the loaded results (e.g. suite2p.Suite2p or caiman.CaImAn,
        see element-interface for more information on the loaders.)
    """
    method, output_dir = (ProcessingParamSet * table & key).fetch1(
        "processing_method", _table_attribute_mapper[table.__name__]
    )

    output_path = find_full_path(get_imaging_root_data_dir(), output_dir)

    if method == "suite2p" or (
        method == "extract" and table.__name__ == "MotionCorrection"
    ):
        from element_interface import suite2p_loader

        loaded_dataset = suite2p_loader.Suite2p(output_path)
    elif method == "caiman":
        from element_interface import caiman_loader

        loaded_dataset = caiman_loader.CaImAn(output_path)
    elif method == "extract":
        from element_interface import extract_loader

        loaded_dataset = extract_loader.EXTRACT(output_path)
    else:
        raise NotImplementedError("Unknown/unimplemented method: {}".format(method))

    return method, loaded_dataset