-
Notifications
You must be signed in to change notification settings - Fork 26
/
core.py
1980 lines (1717 loc) · 71.5 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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
527
528
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
745
746
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
818
819
820
821
822
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
# -*- coding: utf-8 -*-
"""
Main FISSA user interface.
Authors:
- Sander W Keemink <swkeemink@scimail.eu>
- Scott C Lowe <scott.code.lowe@gmail.com>
"""
from __future__ import print_function
import collections
import datetime
import functools
import glob
import itertools
import os.path
import sys
import time
import warnings
try:
from collections import abc
except ImportError:
import collections as abc
import numpy as np
from joblib import Parallel, delayed
from past.builtins import basestring
from scipy.io import savemat
from tqdm.auto import tqdm
from . import deltaf, extraction
from . import neuropil as npil
from . import roitools
def _pretty_timedelta(td=None, **kwargs):
"""
Represent a difference in time as a human-readable string.
Parameters
----------
td : datetime.timedelta, optional
The amount of time elapsed.
**kwargs
Additional arguments as per :class:`datetime.timedelta` constructor.
Returns
-------
str
Representation of the amount of time elapsed.
"""
if td is None:
td = datetime.timedelta(**kwargs)
elif not isinstance(td, datetime.timedelta):
raise ValueError(
"First argument should be a datetime.timedelta instance,"
" but {} was given.".format(type(td))
)
elif kwargs:
raise ValueError(
"Either a timedelta object or its arguments should be given, not both."
)
if td.total_seconds() < 2:
return "{:.3f} seconds".format(td.total_seconds())
if td.total_seconds() < 10:
return "{:.2f} seconds".format(td.total_seconds())
if td.total_seconds() < 60:
return "{:.1f} seconds".format(td.total_seconds())
if td.total_seconds() < 3600:
s = td.total_seconds()
m = int(s // 60)
s -= m * 60
return "{:d} min, {:.0f} sec".format(m, s)
# For durations longer than one hour, we use the default string
# representation for a datetime.timedelta, H:MM:SS.microseconds
return str(td)
def extract(
image,
rois,
nRegions=4,
expansion=1,
datahandler=None,
verbosity=1,
label=None,
total=None,
):
r"""
Extract data for all ROIs in a single 3d array or TIFF file.
.. versionadded:: 1.0.0
Parameters
----------
image : str or :term:`array_like` shaped ``(time, height, width)``
The imaging data.
Either a path to a multipage TIFF file, or 3d :term:`array_like` data.
rois : str or :term:`list` of :term:`array_like`
The regions-of-interest, specified by
either a string containing a path to an ImageJ roi zip file,
or a list of arrays encoding polygons, or list of binary arrays
representing masks.
nRegions : int, default=4
Number of neuropil regions to draw. Use a higher number for
densely labelled tissue. Default is ``4``.
expansion : float, default=1
Expansion factor for the neuropil region, relative to the
ROI area. Default is ``1``. The total neuropil area will be
``nRegions * expansion * area(ROI)``.
datahandler : fissa.extraction.DataHandlerAbstract, optional
A datahandler object for handling ROIs and calcium data.
The default is :class:`~fissa.extraction.DataHandlerTifffile`.
verbosity : int, default=1
Level of verbosity. The options are:
- ``0``: No outputs.
- ``1``: Print extraction start.
- ``2``: Print extraction end.
- ``3``: Print start of each step within the extraction process.
label : str or int, optional
The label for the current trial. Only used for reporting progress.
total : int, optional
Total number of trials. Only used for reporting progress.
Returns
-------
traces : :class:`numpy.ndarray` shaped ``(n_rois, nRegions + 1, n_frames)``
The raw signal, determined as the average fluorence trace extracted
from each ROI and neuropil region.
Each vector ``traces[i_roi, 0, :]`` contains the traces for the
``i_roi``-th ROI.
The following `nRegions` arrays in ``traces[i_roi, 1 : nRegions + 1, :]``
contain the traces from the `nRegions` grown neuropil regions
surrounding the ``i_roi``-th ROI.
polys : list of list of list of :class:`numpy.ndarray` shaped ``(n_nodes, 2)``
Polygon contours describing the outline of each region.
For contiguous ROIs, the outline of the ``i_roi``-th ROI is described
by the array at ``polys[i_roi][0][0]``. This array is ``n_nodes``
rows, each representing the coordinate of a node in ``(y, x)`` format.
For non-contiguous ROIs, a contour is needed for each disconnected
polygon making up the total aggregate ROI. These contours are found at
``polys[i_roi][0][i_contour]``.
Similarly, the `nRegions` neuropil regions are each described by the
polygons ``polys[i_roi][i_neurpil + 1][i_contour]`` respectively.
mean : :class:`numpy.ndarray` shaped (height, width)
Mean image.
"""
# Get the timestamp for program start
t0 = time.time()
mheader = ""
if verbosity >= 1:
# Set up message header
# Use the label, if this was provided
if label is None:
header = ""
elif isinstance(label, int) and isinstance(total, int):
# Pad left based on the total number of jobs, so it is [ 1/10] etc
fmtstr = "{:" + str(int(np.maximum(1, np.ceil(np.log10(total))))) + "d}"
header = fmtstr.format(label + 1)
else:
header = str(label)
# Try to label with [1/5] to indicate progess, if possible
if header and total is not None:
header += "/{}".format(total)
if header:
header = "[Extraction " + header + "] "
# Try to include the path to the image as a footer
footer = ""
if isinstance(image, basestring):
# Include the image path as a footer
footer = " ({})".format(image)
# Done with header and footer
# Inner header is indented further
mheader = " " + header
# Build intro message
message = header + "Extraction starting" + footer
# Wait briefly to prevent messages colliding when using multiprocessing
if isinstance(label, int) and label < 12:
time.sleep(label / 50.0)
print(message)
sys.stdout.flush()
if datahandler is None:
datahandler = extraction.DataHandlerTifffile()
# get data as arrays and rois as masks
if verbosity >= 3:
print("{}Loading imagery".format(mheader))
curdata = datahandler.image2array(image)
if verbosity >= 3:
print("{}Converting ROIs to masks".format(mheader))
base_masks = datahandler.rois2masks(rois, curdata)
# get the mean image
mean = datahandler.getmean(curdata)
if verbosity == 3:
print("{}Growing neuropil regions and extracting traces".format(mheader))
# Initialise output variables
traces = []
polys = []
# get neuropil masks and extract signals
for base_mask in tqdm(
base_masks,
total=len(base_masks),
desc="{}Neuropil extraction".format(mheader),
disable=verbosity < 4,
):
# neuropil masks
npil_masks = roitools.getmasks_npil(
base_mask, nNpil=nRegions, expansion=expansion
)
# add all current masks together
masks = [base_mask] + npil_masks
# extract traces
traces.append(datahandler.extracttraces(curdata, masks))
# store ROI outlines
polys.append([roitools.find_roi_edge(mask) for mask in masks])
# Convert traces from a list to a single numpy array
traces = np.stack(traces, axis=0)
if verbosity >= 2:
# Build end message
message = header + "Extraction finished" + footer
message += " in {}".format(_pretty_timedelta(seconds=time.time() - t0))
print(message)
sys.stdout.flush()
return traces, polys, mean
def separate_trials(
raw,
alpha=0.1,
max_iter=20000,
tol=1e-4,
max_tries=1,
method="nmf",
verbosity=1,
label=None,
total=None,
):
r"""
Separate signals within a set of 2d arrays.
.. versionadded:: 1.0.0
Parameters
----------
raw : list of n_trials :term:`array_like`, each shaped ``(nRegions + 1, observations)``
Raw signals.
A list of 2-d arrays, each of which contains observations of mixed
signals, mixed in the same way across all trials.
The `nRegions` signals must be the same for each trial, and the 0-th
region, ``raw[trial][0]``, should be from the region of interest for
which a matching source signal should be identified.
alpha : float, default=0.1
Sparsity regularizaton weight for NMF algorithm. Set to zero to
remove regularization. Default is ``0.1``.
(Only used for ``method="nmf"``.)
max_iter : int, default=20000
Maximum number of iterations before timing out on an attempt.
tol : float, default=1e-4
Tolerance of the stopping condition.
max_tries : int, default=1
Maximum number of random initial states to try. Each random state will
be optimized for `max_iter` iterations before timing out.
method : {"nmf", "ica"}, default="nmf"
Which blind source-separation method to use. Either ``"nmf"``
for non-negative matrix factorization, or ``"ica"`` for
independent component analysis. Default is ``"nmf"``.
verbosity : int, default=1
Level of verbosity. The options are:
- ``0``: No outputs.
- ``1``: Print separation start.
- ``2``: Print separation end.
- ``3``: Print progress details during separation.
label : str or int, optional
Label/name or index of the ROI currently being processed.
Only used for progress messages.
total : int, optional
Total number of ROIs. Only used for reporting progress.
Returns
-------
Xsep : list of n_trials :class:`numpy.ndarray`, each shaped ``(nRegions + 1, observations)``
The separated signals, unordered.
Xmatch : list of n_trials :class:`numpy.ndarray`, each shaped ``(nRegions + 1, observations)``
The separated traces, ordered by matching score against the raw ROI
signal.
Xmixmat : :class:`numpy.ndarray`, shaped ``(nRegions + 1, nRegions + 1)``
Mixing matrix.
convergence : dict
Metadata for the convergence result, with the following keys and
values:
converged : bool
Whether the separation model converged, or if it ended due to
reaching the maximum number of iterations.
iterations : int
The number of iterations which were needed for the separation model
to converge.
max_iterations : int
Maximum number of iterations to use when fitting the
separation model.
random_state : int or None
Random seed used to initialise the separation model.
"""
# Get the timestamp for program start
t0 = time.time()
header = ""
if verbosity >= 1:
# Set up message header
# Use the label, if this was provided
if label is None:
header = ""
elif isinstance(label, int) and isinstance(total, int):
# Pad left based on the total number of jobs, so it is [ 1/10] etc
fmtstr = "{:" + str(int(np.maximum(1, np.ceil(np.log10(total))))) + "d}"
header = fmtstr.format(label + 1)
else:
header = str(label)
# Try to label with [1/5] to indicate progess, if possible
if header and total is not None:
header += "/{}".format(total)
if header:
header = "[Separation " + header + "] "
# Include the ROI label as a footer
footer = ""
if isinstance(label, int) and isinstance(total, int):
# Include the ROI label as a footer
footer = " (ROI {})".format(label)
# Done with header and footer
# Build intro message
message = header + "Signal separation starting" + footer
# Wait briefly to prevent messages colliding when using multiprocessing
if isinstance(label, int) and label < 12:
time.sleep(label / 50.0)
print(message)
sys.stdout.flush()
# Join together the raw data across trials, collapsing down the trials
X = np.concatenate(raw, axis=1)
# Check for values below 0
if X.min() < 0:
message_extra = ""
if label is not None:
message_extra = " for ROI {}".format(label)
warnings.warn(
"{}Found values below zero in raw signal{}. Offsetting so minimum is 0."
"".format(header, message_extra)
)
X -= X.min()
# Separate the signals
Xsep, Xmatch, Xmixmat, convergence = npil.separate(
X,
method,
max_iter=max_iter,
tol=tol,
max_tries=max_tries,
alpha=alpha,
verbosity=verbosity - 2,
prefix=" " + header,
)
# Unravel observations from multiple trials into a list of arrays
trial_lengths = [r.shape[1] for r in raw]
indices = np.cumsum(trial_lengths[:-1])
Xsep = np.split(Xsep, indices, axis=1)
Xmatch = np.split(Xmatch, indices, axis=1)
# Report status
if verbosity >= 2:
# Build end message
message = header + "Signal separation finished" + footer
message += " in {}".format(_pretty_timedelta(seconds=time.time() - t0))
print(message)
sys.stdout.flush()
return Xsep, Xmatch, Xmixmat, convergence
class Experiment:
r"""
FISSA Experiment.
Uses the methodology described in
`FISSA: A neuropil decontamination toolbox for calcium imaging signals <doi_>`_.
.. _doi: https://www.doi.org/10.1038/s41598-018-21640-2
Parameters
----------
images : str or list
The raw imaging data.
Should be one of:
- the path to a directory containing TIFF files (string),
- a list of paths to TIFF files (list of strings),
- a list of :term:`array_like` data already loaded into memory,
each shaped ``(n_frames, height, width)``.
Note that each TIFF or array is considered a single trial.
rois : str or list
The region of interest (ROI) definitions.
Should be one of:
- the path to a directory containing ImageJ ZIP files (string),
- the path of a single ImageJ ZIP file (string),
- a list of ImageJ ZIP files (list of strings),
- a list of arrays, each encoding a ROI polygons,
- a list of lists of binary arrays, each representing a ROI mask.
This can either be a single roiset for all trials, or a different
roiset for each trial.
folder : str, optional
Path to a cache directory from which pre-extracted data will
be loaded if present, and saved to otherwise. If `folder` is
unset, the experiment data will not be saved.
nRegions : int, default=4
Number of neuropil regions and signals to use. Default is ``4``.
Use a higher number for densely labelled tissue.
expansion : float, default=1
Expansion factor for each neuropil region, relative to the
ROI area. Default is ``1``. The total neuropil area will be
``nRegions * expansion * area(ROI)``.
method : "nmf" or "ica", default="nmf"
Which blind source-separation method to use. Either ``"nmf"``
for non-negative matrix factorization, or ``"ica"`` for
independent component analysis. Default is ``"nmf"`` (recommended).
alpha : float, default=0.1
Sparsity regularizaton weight for NMF algorithm. Set to zero to
remove regularization. Default is ``0.1``.
max_iter : int, default=20000
Maximum number of iterations before timing out on an attempt.
.. versionadded:: 1.0.0
tol : float, default=1e-4
Tolerance of the stopping condition.
.. versionadded:: 1.0.0
max_tries : int, default=1
Maximum number of random initial states to try. Each random state will
be optimized for `max_iter` iterations before timing out.
.. versionadded:: 1.0.0
ncores_preparation : int or None, default=-1
The number of parallel subprocesses to use during the data
preparation steps of :meth:`separation_prep`.
These steps are ROI and neuropil subregion definitions, and extracting
raw signals from TIFFs.
If set to ``None`` or ``-1`` (default), the number of processes used
will equal the number of threads on the machine.
If this is set to ``-2``, the number of processes used will be one less
than the number of threads on the machine; etc.
Note that the preparation process can be quite memory-intensive and it
may be necessary to reduce the number of processes from the default.
ncores_separation : int or None, default=-1
The number of parallel subprocesses to use during the signal
separation steps of :meth:`separate`.
If set to ``None`` or ``-1`` (default), the number of processes used
will equal the number of threads on the machine.
If this is set to ``-2``, the number of processes used will be one less
than the number of threads on the machine; etc.
The separation routine requires less memory per process than
the preparation routine, and so `ncores_separation` be often be set
higher than `ncores_preparation`.
lowmemory_mode : bool, optional
If ``True``, FISSA will load TIFF files into memory frame-by-frame
instead of holding the entire TIFF in memory at once. This
option reduces the memory load, and may be necessary for very
large inputs. Default is ``False``.
datahandler : :class:`fissa.extraction.DataHandlerAbstract`, optional
A custom datahandler object for handling ROIs and calcium data can
be given here. See :mod:`fissa.extraction` for example datahandler
classes. The default datahandler is
:class:`~fissa.extraction.DataHandlerTifffile`.
If `datahandler` is set, the `lowmemory_mode` parameter is
ignored.
verbosity : int, default=1
How verbose the processing will be. Increase for more output messages.
Processing is silent if ``verbosity=0``.
.. versionadded:: 1.0.0
Attributes
----------
result : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped
``(n_signals, n_timepoints)``.
The final output of FISSA, with separated signals ranked in order of
their weighting toward the raw cell ROI signal relative to their
weighting toward other mixed raw signals.
The ordering is such that ``experiment.result[roi, trial][0, :]``
is the signal with highest score in its contribution to the raw
neuronal signal.
Subsequent signals are sorted in order of diminishing score.
The units are same as `raw` (candelas per unit area).
This field is only populated after :meth:`separate` has been run; until
then, it is set to ``None``.
roi_polys : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a list of length ``nRegions + 1``, each element of
which is a list of length ``n_contour`` containing a :class:`numpy.ndarray`
of shape ``(n_nodes, 2)``.
Polygon contours describing the outline of each region.
For contiguous ROIs, the outline of the ``i_roi``-th ROI used in the
``i_trial``-th trial is described by the array at
``experiment.roi_polys[i_roi, i_trial][0][0]``.
This array consists of ``n_nodes`` rows, each representing the
coordinate of a node in ``(y, x)`` format.
For non-contiguous ROIs, a contour is needed for each disconnected
polygon making up the total aggregate ROI. These contours are found at
``experiment.roi_polys[i_roi, i_trial][0][i_contour]``.
Similarly, the `nRegions` neuropil regions are each described by the
polygons
``experiment.roi_polys[i_roi, i_trial][i_neurpil + 1][i_contour]``,
respectively.
means : list of `n_trials` :class:`numpy.ndarray`, each shaped ``(height, width)``
The temporal-mean image for each trial (i.e. for each TIFF file,
the average image over all of its frames).
raw : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped
``(n_signals, n_timepoints)``.
For each ROI and trial (``raw[i_roi, i_trial]``) we extract a temporal
trace of the average value within the spatial area of each of the
``nRegions + 1`` regions.
The 0-th region is the ``i_roi``-th ROI (``raw[i_roi, i_trial][0]``).
The subsequent ``nRegions`` vectors are the traces for each of the
neuropil regions.
The units are the same as the supplied imagery (candelas per unit
area).
sep : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped
``(n_signals, n_timepoints)``.
The separated signals, before output signals are ranked according to
their matching against the raw signal from within the ROI.
Separated signal ``i`` for a specific ROI and trial can be found at
``experiment.sep[roi, trial][i, :]``.
This field is only populated after :meth:`separate` has been run; until
then, it is set to ``None``.
mixmat : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped
``(n_rois, n_signals)``.
The mixing matrix, which maps from ``experiment.raw`` to
``experiment.sep``.
Because we use the collate the traces from all trials to determine
separate the signals, the mixing matrices for a given ROI are the
same across all trials.
This means all ``n_trials`` elements in ``mixmat[i_roi, :]`` are
identical.
This field is only populated after :meth:`separate` has been run; until
then, it is set to ``None``.
info : :class:`numpy.ndarray` shaped ``(n_rois, n_trials)`` of dicts
Information about the separation routine.
Each dictionary in the array has the following fields:
converged : bool
Whether the separation model converged, or if it ended due to
reaching the maximum number of iterations.
iterations : int
The number of iterations which were needed for the separation model
to converge.
max_iterations : int
Maximum number of iterations to use when fitting the
separation model.
random_state : int or None
Random seed used to initialise the separation model.
This field is only populated after :meth:`separate` has been run; until
then, it is set to ``None``.
deltaf_raw : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped ``(1, n_timepoint)``.
The amount of change in fluorence relative to the baseline fluorence
(Δf/f\ :sub:`0`).
This field is only populated after :meth:`calc_deltaf` has been run;
until then, it is set to ``None``.
.. versionchanged:: 1.0.0
The shape of the interior arrays changed from ``(n_timepoint, )``
to ``(1, n_timepoint)``.
deltaf_result : :class:`numpy.ndarray`
A :class:`numpy.ndarray` of shape ``(n_rois, n_trials)``, each element
of which is itself a :class:`numpy.ndarray` shaped
``(n_signals, n_timepoints)``.
The amount of change in fluorence relative to the baseline fluorence
(Δf/f\ :sub:`0`).
By default, the baseline is taken from :attr:`raw` because the
minimum values in :attr:`result` are typically zero.
See :meth:`calc_deltaf` for details.
This field is only populated after :meth:`calc_deltaf` has been run;
until then, it is set to ``None``.
"""
_defaults = {
"nRegions": 4,
"expansion": 1,
"method": "nmf",
"alpha": 0.1,
"max_iter": 20000,
"tol": 1e-4,
"max_tries": 1,
}
def __init__(
self,
images,
rois,
folder=None,
nRegions=None,
expansion=None,
method=None,
alpha=None,
max_iter=None,
tol=None,
max_tries=None,
ncores_preparation=-1,
ncores_separation=-1,
lowmemory_mode=False,
datahandler=None,
verbosity=1,
):
# Initialise internal variables
self.clear(verbosity=0)
if isinstance(images, basestring):
self.images = sorted(glob.glob(os.path.join(images, "*.tif*")))
elif isinstance(images, abc.Sequence):
self.images = images
else:
raise ValueError("images should either be string or list")
if isinstance(rois, basestring):
if rois[-3:] == "zip":
self.rois = [rois] * len(self.images)
else:
self.rois = sorted(glob.glob(os.path.join(rois, "*.zip")))
elif isinstance(rois, abc.Sequence):
self.rois = rois
if len(rois) == 1: # if only one roiset is specified
self.rois *= len(self.images)
else:
raise ValueError("rois should either be string or list")
if datahandler is not None and lowmemory_mode:
raise ValueError(
"Only one of lowmemory_mode and datahandler should be set."
)
elif lowmemory_mode:
self.datahandler = extraction.DataHandlerTifffileLazy()
else:
self.datahandler = datahandler
# define class variables
self.folder = folder
self.nRegions = nRegions
self.expansion = expansion
self.method = method
self.alpha = alpha
self.max_iter = max_iter
self.tol = tol
self.max_tries = max_tries
self.ncores_preparation = ncores_preparation
self.ncores_separation = ncores_separation
self.verbosity = verbosity
# check if any data already exists
if folder is None:
pass
elif folder and not os.path.exists(folder):
os.makedirs(folder)
else:
self.load()
@property
def nCell(self):
if getattr(self, "result", None) is not None:
return self.result.shape[0]
if getattr(self, "raw", None) is not None:
return self.raw.shape[0]
return None
@property
def nTrials(self):
return len(self.images)
def __str__(self):
if isinstance(self.images, basestring):
str_images = repr(self.images)
elif isinstance(self.images, abc.Sequence):
str_images = "<{} of length {}>".format(
self.images.__class__.__name__, len(self.images)
)
else:
str_images = repr(self.images)
if isinstance(self.rois, basestring):
str_rois = repr(self.rois)
elif isinstance(self.rois, abc.Sequence):
str_rois = "<{} of length {}>".format(
self.rois.__class__.__name__, len(self.rois)
)
else:
str_images = repr(self.rois)
fields = [
"folder",
"nRegions",
"expansion",
"method",
"alpha",
"max_iter",
"tol",
"max_tries",
"ncores_preparation",
"ncores_separation",
"datahandler",
"verbosity",
]
str_parts = [
"{}={}".format(field, repr(getattr(self, field))) for field in fields
]
return "{}.{}(images={}, rois={}, {})".format(
__name__,
self.__class__.__name__,
str_images,
str_rois,
", ".join(str_parts),
)
def __repr__(self):
fields = [
"images",
"rois",
"folder",
"nRegions",
"expansion",
"method",
"alpha",
"max_iter",
"tol",
"max_tries",
"ncores_preparation",
"ncores_separation",
"datahandler",
"verbosity",
]
repr_parts = [
"{}={}".format(field, repr(getattr(self, field))) for field in fields
]
return "{}.{}({})".format(
__name__, self.__class__.__name__, ", ".join(repr_parts)
)
def clear(self, verbosity=None):
r"""
Clear prepared data, and all data downstream of prepared data.
.. versionadded:: 1.0.0
Parameters
----------
verbosity : int, optional
Whether to show the data fields which were cleared.
By default, the object's :attr:`verbosity` attribute is used.
"""
if verbosity is None:
verbosity = self.verbosity - 1
keys = ["means", "raw", "roi_polys", "deltaf_raw"]
# Wipe outputs
keys_cleared = []
for key in keys:
if getattr(self, key, None) is not None:
keys_cleared.append(key)
setattr(self, key, None)
if verbosity >= 1 and keys_cleared:
print("Cleared {}".format(", ".join(repr(k) for k in keys_cleared)))
# Wipe outputs of separate(), as they no longer match self.raw
self.clear_separated(verbosity=verbosity)
def clear_separated(self, verbosity=None):
r"""
Clear separated data, and all data downstream of separated data.
.. versionadded:: 1.0.0
Parameters
----------
verbosity : int, optional
Whether to show the data fields which were cleared.
By default, the object's :attr:`verbosity` attribute is used.
"""
if verbosity is None:
verbosity = self.verbosity - 1
keys = ["info", "mixmat", "sep", "result", "deltaf_result"]
# Wipe outputs
keys_cleared = []
for key in keys:
if getattr(self, key, None) is not None:
keys_cleared.append(key)
setattr(self, key, None)
if verbosity >= 1 and keys_cleared:
print("Cleared {}".format(", ".join(repr(k) for k in keys_cleared)))
def _adopt_default_parameters(self, only_preparation=False, force=False):
r"""
Adopt default values for unset analysis parameters.
.. versionadded:: 1.0.0
Parameters
----------
only_preparation : bool, optional
Whether to restrict the parameters to only those used for data
extraction during the preparation step. Default is ``False``.
force : bool, optional
If `True`, all parameters will be overridden with default values
even if they had already been set. Default is ``False``.
"""
defaults = self._defaults
if only_preparation:
# Prune down to only the preparation parameters
preparation_fields = ["expansion", "nRegions"]
defaults = {k: v for k, v in defaults.items() if k in preparation_fields}
# Check through each parameter and set unset values from defaults
keys_adopted = []
for key, value in defaults.items():
if getattr(self, key, None) is not None and not force:
continue
setattr(self, key, value)
keys_adopted.append(key)
if self.verbosity >= 5 and keys_adopted:
print(
"Adopted default values for {}".format(
", ".join(repr(k) for k in keys_adopted)
)
)
def load(self, path=None, force=False, skip_clear=False):
r"""
Load data from cache file in npz format.
.. versionadded:: 1.0.0
Parameters
----------
path : str, optional
Path to cache file (.npz format) or a directory containing
``"prepared.npz"`` and/or ``"separated.npz"`` files.
Default behaviour is to use the :attr:`folder` parameter which was
provided when the object was initialised is used
(``experiment.folder``).
force : bool, optional
Whether to load the cache even if its experiment parameters differ
from the properties of this experiment. Default is ``False``.
skip_clear : bool, optional
Whether to skip clearing values before loading. Default is ``False``.
"""
dynamic_properties = ["nCell", "nTrials"]
ValGroup = collections.namedtuple(
"ValGroup",
["category", "validators", "fields", "clearif", "clearfn"],
)
validation_groups = [
ValGroup(
"prepared",
["expansion", "nRegions"],
["deltaf_raw", "means", "raw", "roi_polys"],
["raw"],
self.clear,
),
ValGroup(
"separated",
[
"alpha",
"nRegions",
"expansion",
"max_iter",
"max_tries",
"method",
"tol",
],
["deltaf_result", "info", "mixmat", "sep", "result"],
["result"],
self.clear_separated,
),
]
if path is None:
if self.folder is None:
raise ValueError(
"path must be provided if experiment folder is not defined"
)
path = self.folder
if os.path.isdir(path) or path == "":
for fname in ("prepared.npz", "separated.npz"):
fullfname = os.path.join(path, fname)
if not os.path.exists(fullfname):
continue
self.load(fullfname)
return
if self.verbosity >= 1:
print("Loading data from cache {}".format(path))
cache = np.load(path, allow_pickle=True)
def _unpack_scalar(x):
if np.array_equal(x, None):
return None
if x.ndim == 0:
# Handle loading scalars
return x.item()
return x