-
Notifications
You must be signed in to change notification settings - Fork 7
/
pipeline2p.py
2667 lines (2310 loc) · 93.5 KB
/
pipeline2p.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
"""
Module for feeding ThorLabs imaging datasets into a 2p imaging analysis
pipeline
(c) 2015 C. Schmidt-Hieber
GPLv3
"""
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import shutil
import time
import pickle
import tempfile
import multiprocessing as mp
import subprocess
from functools import partial
import numpy as np
import scipy.signal as signal
import scipy.stats as stats
from scipy.io import savemat
from scipy.optimize import fminbound
from scipy.optimize import fmin_bfgs
from scipy.ndimage import percentile_filter
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm
import matplotlib.collections as mcoll
import matplotlib.path as mpath
try:
import cv2
except ImportError:
print("cv2 unavailable")
HAS_CV2 = False
import sima
import sima.motion
import sima.segment
import sima.spikes
from sima.ROI import ROIList
import shapely
if sys.version_info.major < 3:
try:
import caiman.source_extraction.cnmf as caiman_cnmf
import caiman.source_extraction.cnmf.temporal as caiman_temporal
import caiman.utils.stats as caiman_stats
except ImportError:
sys.stderr.write("Could not find caiman cnmf module")
try:
from . import utils
from . import haussio
from . import movies
from . import scalebars
from . import spectral
from . import cnmf
from . import motion
from . import decode
except ValueError:
try:
import utils
import haussio
import movies
import scalebars
import spectral
import cnmf
import motion
import decode
except ImportError:
from haussmeister import utils
from haussmeister import haussio
from haussmeister import movies
from haussmeister import scalebars
from haussmeister import spectral
from haussmeister import cnmf
from haussmeister import motion
from haussmeister import decode
try:
import stfio
from stfio import plot as stfio_plot
except ImportError:
sys.stderr.write("stfio module missing\n")
import haussmeister
if not os.name == "nt":
sys.path.append("%s/py2p/tools" % (
os.environ["HOME"]))
bar1_color = 'k' # black
bar2_color = 'w' # white
edge_color = 'k' # black
gap2 = 0.15 # gap between series
bar_width = 0.5
NCPUS = int(mp.cpu_count()/2)
# Maximal number of frames that thunder ICA can deal with before running
# out of memory (128 GB)
MAXFRAMES_ICA = 1600
MIN_SPEED = 1.0
STD_SCALE = 2.0
class ThorExperiment(object):
"""
Helper class to feed ThorLabs imaging datasets into a 2p imaging
analysis pipeline
Attributes
----------
fn2p : str
File path (relative to root_path) leading to directory that contains
tiff series
ch2p : str, optional
Channel. Default: "A"
area2p : str, optional
Brain area code (e.g. "CA1"). Default: None
fnsync : str, optional
Thorsync directory name. Default: None
fnvr : str, optional
VR file name trunk. Default: None
fntrack : str, optional
Open field track file name trunk. Default: None
roi_subset : str, optional
String appended to roi label to distinguish between roi subsets.
Default: ""
mc_method : str, optional
Motion correction method. One of "hmmc", "dft", "hmmcres", "hmmcframe",
"hmmcpx", "calblitz", "normcorr", "suite2p". Default: "hmmc"
detrend : bool, optional
Whether to detrend fluorescence traces. Default: False
subtract_halo : float, optional
Relative size of halo to subtract from each ROI.
No halo subtraction is applied for values <= 1.0. Default: 1.0
nrois_init : int, optional
Estimate of the number of ROIs. Default: 200
roi_translate : 2-tuple of ints, optional
Apply ROI translation in x and y. Default: None
root_path : str, optional
Root directory leading to fn2p. Default: ""
seg_method : str, optional
One of "thunder" (ROIs are identified by thunder's ICA), "sima" (ROIs
are identified by SIMA's stICA), "ij" (an ImageJ RoiSet is used),
"cnmf" (constrained non-negative matrix factorization), "suite2p".
Default: "cnmf"
maxtime : float, optional
Limit data to maxtime. Default: None
ignore_sync_errors : bool, optional
Whether to ignore mismatch between imaging and VR recording file
lengths. Default: False
behav_frame_trigger : bool, optional
Whether behavioural movie frames were triggered by imaging movie
frames. Default: False
conditions : list, optional
List of strings defining experimental conditions for each file
in a series of concatenated files. Default: None
session_number : int, optional
Session number/index. Default: None
"""
def __init__(
self, fn2p, ch2p="A", area2p=None, fnsync=None, fnvr=None,
fntrack=None, roi_subset="", mc_method="hmmc", detrend=False,
subtract_halo=1.0, nrois_init=200, roi_translate=None, root_path="",
ftype="thor", dx=None, dt=None, seg_method="cnmf", maxtime=None,
ignore_sync_errors=False, rois_eliminate=None, mousecal=None,
rotate_track=None, track_sync=False, cmperpx=None, override_sync_mismatch=False,
behav_frame_trigger=False, conditions=None, session_number=None, cut_periods=None):
self.fn2p = fn2p
self.ch2p = ch2p
self.area2p = area2p
self.fnsync = fnsync
self.fnvr = fnvr
self.fntrack = fntrack
self.roi_subset = roi_subset
self.roi_translate = roi_translate
self.root_path = root_path
self.data_path = self.root_path + self.fn2p
self.data_path_comp = self.data_path.replace("?", "n")
self.ftype = ftype
self.dx = dx
self.dt = dt
self.nrois_init = nrois_init
self.maxtime = maxtime
self.ignore_sync_errors = ignore_sync_errors
self.rois_eliminate = rois_eliminate
self.mousecal = mousecal
self.rotate_track = rotate_track
self.track_sync = track_sync
self.cmperpx = cmperpx
self.override_sync_mismatch = override_sync_mismatch
self.behav_frame_trigger = behav_frame_trigger
if self.behav_frame_trigger:
if not self.track_sync:
raise AssertionError(
"behav_frame_trigger == True implies track_sync == True")
self.conditions = conditions
self.session_number = session_number
self.cut_periods = cut_periods
self._as_haussio_mc = None
self._as_haussio = None
self._as_sima_mc = None
self._as_sima = None
assert(seg_method in ["thunder", "sima", "ij", "cnmf", "suite2p"])
self.seg_method = seg_method
if self.ftype == "prairie":
datatrunk = self.data_path
else:
datatrunk = os.path.dirname(self.data_path)
if self.ftype == "doric":
max_displacement = [64, 64]
# print(max_displacement)
else:
max_displacement = [20, 30]
if self.fnsync is not None:
self.sync_path = os.path.join(
datatrunk, self.fnsync)
else:
self.sync_path = None
if self.fnvr is not None:
self.vr_path = os.path.join(
datatrunk, self.fnvr)
self.vr_path_comp = self.vr_path.replace("?", "n")
else:
self.vr_path = None
self.vr_path_comp = None
if self.fntrack is not None:
self.track_path = os.path.join(
datatrunk, self.fntrack)
self.track_path_comp = self.track_path.replace("?", "n")
else:
self.track_path = None
self.track_path_comp = None
self.mc_method = mc_method
self.mc_suffix = "_mc_" + self.mc_method
if self.mc_method == "hmmc":
self.mc_suffix = "_mc" # special case
self.mc_approach = sima.motion.HiddenMarkov2D(
granularity='row', max_displacement=max_displacement,
n_processes=NCPUS, verbose=True)
elif self.mc_method == "dft":
self.mc_approach = sima.motion.DiscreteFourier2D(
max_displacement=max_displacement, n_processes=NCPUS, verbose=True)
elif self.mc_method == "hmmcres":
self.mc_approach = sima.motion.ResonantCorrection(
sima.motion.HiddenMarkov2D(
granularity='row', max_displacement=max_displacement,
n_processes=4, verbose=True))
elif self.mc_method == "hmmcframe":
self.mc_approach = sima.motion.HiddenMarkov2D(
granularity='frame', max_displacement=max_displacement,
n_processes=NCPUS, verbose=True)
elif self.mc_method == "hmmcpx":
self.mc_approach = sima.motion.HiddenMarkov2D(
granularity='column', max_displacement=max_displacement,
n_processes=4, verbose=True)
elif self.mc_method == "calblitz":
self.mc_approach = motion.CalBlitz(
max_displacement=max_displacement, fr=self.to_haussio().fps,
verbose=True)
elif self.mc_method == "normcorr":
self.mc_approach = motion.NormCorr(
max_displacement=max_displacement, fr=self.to_haussio().fps,
verbose=True, savedir=self.data_path_comp + ".sima")
elif self.mc_method == "suite2p":
self.mc_approach = None
elif self.mc_method == "none" or self.mc_method == "doric":
self.mc_suffix = ""
self.mc_approach = None
self.sima_mc_dir = self.data_path_comp + self.mc_suffix + ".sima"
self.mc_tiff_dir = self.data_path_comp + self.mc_suffix
self.movie_mc_fn = self.data_path_comp + self.mc_suffix + ".mp4"
# Do not add translation string to original roi file name
self.roi_path_mc = self.data_path_comp + self.mc_suffix + '/RoiSet' + \
self.roi_subset + '.zip'
if self.roi_translate is not None:
self.roi_subset += "_{0}_{1}".format(
self.roi_translate[0], self.roi_translate[1])
self.spikefn = self.data_path_comp + self.mc_suffix + "_infer" + \
self.roi_subset
self.detrend = detrend
if self.detrend:
self.spikefn += "_detrend.pkl"
else:
self.spikefn += ".pkl"
self.subtract_halo = subtract_halo
self.proj_fn = self.data_path_comp + self.mc_suffix + "_proj.npy"
def to_haussio(self, mc=False):
"""
Convert experiment to haussio.HaussIO
Parameters
----------
mc : bool, optional
Use motion corrected images. Default: False
Returns
-------
dataset : haussio.HaussIO
A haussio.HaussIO instance
"""
if not mc:
if self._as_haussio is not None:
return self._as_haussio
else:
if self._as_haussio_mc is not None:
return self._as_haussio_mc
if self.ftype == "thor":
if not mc:
self._as_haussio = haussio.ThorHaussIO(
self.data_path, chan=self.ch2p,
sync_path=self.sync_path, width_idx=4,
maxtime=self.maxtime)
return self._as_haussio
else:
self._as_haussio_mc = haussio.ThorHaussIO(
self.data_path + self.mc_suffix,
chan=self.ch2p, xml_path=self.data_path+"/Experiment.xml",
sync_path=self.sync_path, width_idx=5,
maxtime=self.maxtime)
return self._as_haussio_mc
elif self.ftype == "movie":
if not mc:
self._as_haussio = haussio.MovieHaussIO(
self.data_path, self.dx, self.dt, chan=self.ch2p,
sync_path=self.sync_path, width_idx=4)
return self._as_haussio
else:
self._as_haussio_mc = haussio.MovieHaussIO(
self.data_path + self.mc_suffix, self.dx, self.dt,
chan=self.ch2p, sync_path=self.sync_path, width_idx=5)
return self._as_haussio_mc
elif self.ftype == "si4":
if not mc:
self._as_haussio = haussio.SI4HaussIO(
self.data_path, chan=self.ch2p,
sync_path=self.sync_path, width_idx=4,
maxtime=self.maxtime)
return self._as_haussio
else:
self._as_haussio_mc = haussio.SI4HaussIO(
self.data_path + self.mc_suffix,
chan=self.ch2p,
sync_path=self.sync_path, width_idx=5,
maxtime=self.maxtime)
return self._as_haussio_mc
elif self.ftype == "doric":
if not mc:
self._as_haussio = haussio.DoricHaussIO(
self.data_path, chan=self.ch2p,
sync_path=self.sync_path, width_idx=4,
maxtime=self.maxtime)
return self._as_haussio
else:
self._as_haussio_mc = haussio.DoricHaussIO(
self.data_path + self.mc_suffix,
chan=self.ch2p,
sync_path=self.sync_path, width_idx=5,
maxtime=self.maxtime)
return self._as_haussio_mc
elif self.ftype == "prairie":
if not mc:
self._as_haussio = haussio.PrairieHaussIO(
self.data_path, chan=self.ch2p,
sync_path=self.sync_path, width_idx=4,
maxtime=self.maxtime)
return self._as_haussio
else:
basename = os.path.basename(self.data_path)
self._as_haussio_mc = haussio.PrairieHaussIO(
self.data_path + self.mc_suffix,
chan=self.ch2p,
xml_path=os.path.join(self.data_path, basename+'.xml'),
sync_path=self.sync_path, width_idx=5,
maxtime=self.maxtime)
return self._as_haussio_mc
def to_sima(self, mc=False, haussio_data=None):
"""
Convert experiment to sima.ImagingDataset
Parameters
----------
mc : bool, optional
Use motion corrected images. Default: False
haussio_data : haussio.HaussIO, optional
A pre-existing HaussIO object to save memory. Default: None
Returns
-------
dataset : sima.ImagingDataset
A sima.ImagingDataset instance
"""
if mc:
if self._as_sima_mc is not None:
return self._as_sima_mc
suffix = self.mc_suffix
else:
if self._as_sima is not None:
return self._as_sima
suffix = ""
sima_dir = self.data_path_comp + suffix + ".sima"
if not os.path.exists(sima_dir):
restore = True
try:
sys.stdout.write("Loading sima dataset {0}... ".format(
sima_dir))
sys.stdout.flush()
t0 = time.time()
dataset = sima.ImagingDataset.load(sima_dir)
sys.stdout.write("done in {0:.1f}s\n".format(time.time()-t0))
restore = False
except (EOFError, IOError, IndexError):
sys.stdout.write("failure, will attempt to restore dataset\n")
restore = True
if not restore:
try:
dataset.channel_names.index(self.ch2p)
dataset.sequences
except (ValueError, IOError, EOFError):
restore = True
if restore:
if haussio_data is None:
haussio_data = self.to_haussio(mc=mc)
sima_bak = haussio_data.sima_dir + ".bak"
if os.path.exists(haussio_data.sima_dir):
if os.path.exists(sima_bak):
shutil.rmtree(sima_bak)
while os.path.exists(sima_bak):
time.wait(1)
shutil.copytree(haussio_data.sima_dir, sima_bak)
shutil.rmtree(haussio_data.sima_dir)
while os.path.exists(haussio_data.sima_dir):
time.wait(1)
dataset = haussio_data.tosima(stopIdx=None)
if mc:
self._as_sima_mc = dataset
else:
self._as_sima = dataset
return dataset
def thor_preprocess(data, ffmpeg=movies.FFMPEG, compress=False):
"""
Read in ThorImage dataset, apply motion correction, export motion-corrected
tiffs, produce movie of corrected and uncorrected data
Parameters
----------
data : ThorExperiment
The ThorExperiment to be processed
ffmpeg : str, optional
Path to ffmpeg binary. Default: movies.FFMPEG global variable
compress : boolean, optional
Compress resulting raw file with xz. Default: False
"""
haussio_data = data.to_haussio(mc=False)
if os.path.exists(haussio_data.movie_fn):
raw_movie = movies.html_movie(haussio_data.movie_fn)
else:
try:
raw_movie = haussio_data.make_movie(norm=14.0, crf=24)
except IOError:
raw_movie = haussio_data.make_movie(norm=False, crf=24)
if not os.path.exists(haussio_data.sima_dir):
dataset = haussio_data.tosima(stopIdx=None)
else:
dataset = data.to_sima(mc=False, haussio_data=haussio_data)
print(dataset.savedir)
assert(dataset.savedir is not None)
if not os.path.exists(data.sima_mc_dir):
t0 = time.time()
dataset_mc = data.mc_approach.correct(dataset, data.sima_mc_dir)
print("Motion correction took {0:.2f} s".format(time.time()-t0))
dataset_mc.save(data.sima_mc_dir)
else:
try:
dataset_mc = sima.ImagingDataset.load(data.sima_mc_dir)
print("Loaded sima dataset from " + data.sima_mc_dir)
except Exception as err:
print("Couldn't load sima dataset: ", err)
dataset_mc = data.to_sima(mc=True)
filenames_mc = ["{0}{1:05d}.tif".format(haussio_data.filetrunk, nf+1)
for nf in range(haussio_data.nframes)]
if data.maxtime is None:
if len(filenames_mc) < dataset_mc.sequences[0].shape[0]:
if dataset_mc.sequences[0].shape[0]-len(filenames_mc) < 5:
dataset_mc.sequences[0] = dataset_mc.sequences[0][
:len(filenames_mc), :, :, :, :]
else:
raise AssertionError(
"File lengths mismatch: {0}, {1}".format(
len(filenames_mc), dataset_mc.sequences[0].shape[0]))
elif len(filenames_mc) != dataset_mc.sequences[0].shape[0]:
raise AssertionError(
"File lengths mismatch: {0}, {1}".format(
len(filenames_mc), dataset_mc.sequences[0].shape[0]))
raw_fn = "Image_0001_0001.raw"
if compress and os.name != 'nt':
raw_fn += ".xz"
del(dataset)
del(haussio_data.raw_array)
if not os.path.exists(os.path.join(data.mc_tiff_dir, os.path.basename(
filenames_mc[-1]))) and not os.path.exists(os.path.join(
data.mc_tiff_dir, raw_fn)):
print("Exporting frames...")
haussio.sima_export_frames(
dataset_mc, data.mc_tiff_dir, filenames_mc, ftype="raw",
compress = (compress and os.name != 'nt'))
if os.path.exists(data.movie_mc_fn):
corr_movie = movies.html_movie(data.movie_mc_fn)
else:
corr_movie = haussio_data.make_movie_extern(
data.mc_tiff_dir, norm=14.0, crf=24, width_idx=5)
return dataset_mc
def activity_level(data, infer_threshold=0.15, roi_subset=""):
"""
Determine the ratio of active over inactive neurons
Parameters
----------
data : ThorExperiment
The ThorExperiment to be processed
infer_threshold : float, optional
Activity threshold of spike inference. Default: 0.15
roi_subset : str
Roi subset to be processed
Returns
-------
level : int, int
Number of active and inactive neurons
"""
if not os.path.exists(data.spikefn):
print("Couldn't find spike inference file", data.spikefn)
return None, None
spikefile = open(data.spikefn, 'rb')
spikes = pickle.load(spikefile)
fits = pickle.load(spikefile)
parameters = pickle.load(spikefile)
spikefile.close()
active = 0
for nroi in range(spikes[0].shape[0]):
sys.stdout.write("\rROI %d/%d" % (nroi+1, spikes[0].shape[0]))
sys.stdout.flush()
spikes_filt = spikes[nroi][1:]
event_ts = stfio.peak_detection(spikes_filt, infer_threshold, 30)
active += (len(event_ts) > 0)
sys.stdout.write("\n%s: %d out of %d cells (%.0f%%) are active\n" % (
data.data_path, active, spikes[0].shape[0],
100.0*active/spikes[0].shape[0]))
return active, spikes[0].shape[0]
def process_data(data, detrend=False, base_fraction=0.2, zscore=True):
"""
Compute \Delta F / F_0 and detrend if required
Parameters
----------
data : numpy.ndarray
Fluorescence trace, shape: (nrois, nframes)
detrend : bool, optional
Detrend fluorescence traces. Default: False
base_fraction : float, optional
Bottom fraction to be used for F_0 computation. If None, F_0 is set to
data.mean(). Default: 0.05
zscore : bool, optional
Use z score instead of mean
Returns
-------
ret_data : numpy.ndarray
Processed data
"""
sortedi = np.ogrid[:data.shape[0], :data.shape[1]]
if base_fraction is not None:
# Sort data by brightness, select lower base_fraction:
sortedi[1] = data.argsort(axis=1)[
:, :int(np.round(base_fraction*data.shape[1]))]
Fmu = data[sortedi].mean(axis=1)
if zscore:
Fsig = data[sortedi].std(axis=1)
else:
Fsig = Fmu
Fsig[Fsig == 0] = 1.0
# Fmu and Fsig should be of shape (nrois)
# data and ret_data should be of shape (nrois, nframes)
ret_data = ((data.T-Fmu)/Fsig).T * 100.0
ret_data[np.isnan(ret_data)] = 0
if detrend:
ret_data = np.array([
signal.detrend(
trace, bp=[0, int(data.shape[0]/4.0),
int(data.shape[0]/2.0),
int(3.0*data.shape[0]/4.0),
int(data.shape[0])])
for trace in ret_data])
ret_data = (ret_data.T-ret_data.min(axis=1)).T
return ret_data
def xcorr(data, chan, roi_subset1="DG", roi_subset2="CA3",
infer_threshold=0.15):
"""
Compute cross correlation between fluorescence extracted from two
roi subsets
Parameters
----------
data : ThorExperiment
The ThorExperiment to be processed
chan : str
Channel character
roi_subset1 : str, optional
Roi subset 1 suffix. Default: "DG"
roi_subset2 : str, optional
Roi subset 2 suffix. Default: "CA3"
infer_threshold: float, optional
Spike inference threshold. Default: 0.15
Returns
-------
high_xcs : list of 2-tuple of ints
List of roi indices with xcorr values > 0.5
"""
rois1, meas1, experiment1, zproj1, spikes1 = \
get_rois_ij(data, infer=True)
rois2, meas2, experiment2, zproj2, spikes2 = \
get_rois_ij(data, infer=True)
meas1_filt = process_data(meas1, detrend=data.detrend)
meas2_filt = process_data(meas2, detrend=data.detrend)
high_xcs = []
for nroi1, m1 in enumerate(meas1_filt):
spikes1_filt = (spikes1[0][nroi1]-spikes1[0][nroi1].min())[1:]
event1_ts = stfio.peak_detection(spikes1_filt, infer_threshold, 30)
if len(event1_ts):
for nroi2, m2 in enumerate(meas2_filt):
spikes2_filt = (spikes2[0][nroi2]-spikes2[0][nroi2].min())[1:]
event2_ts = stfio.peak_detection(spikes2_filt, infer_threshold, 30)
if len(event2_ts):
xc = cv2.matchTemplate(m1, m2, cv2.TM_CCORR_NORMED)
if xc.max() > 0.5:
high_xcs.append((nroi1, nroi2))
return high_xcs
def norm(sig):
"""
Normalize data to have range [0,1]
Parameters
----------
sig : numpy.ndarray
Data to be normalized
Returns
-------
norm : numpy.ndarray
Normalized data
"""
return (sig-sig.min())/(sig.max()-sig.min())
def make_segments(x, y):
"""
Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments
def colorline(
ax, x, y, z=None, cmap=plt.get_cmap('jet'), norm=plt.Normalize(0.0, 1.0),
linewidth=3, alpha=1.0):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and y
Optionally specify colors in the array z
Optionally specify a colormap, a norm function and a line width
"""
# Default colors equally spaced on [0,1]:
if z is None:
zc = np.linspace(0.0, 1.0, len(x))
else:
zc = z.copy()
# Special case if a single number:
if not hasattr(zc, "__iter__"): # to check for numerical input -- this is a hack
zc = np.array([zc])
zc = np.asarray(zc)
segments = make_segments(x, y)
lc = mcoll.LineCollection(segments, array=zc, cmap=cmap, norm=norm,
linewidth=linewidth, alpha=alpha)
ax.add_collection(lc)
return lc
def find_events(norm_meas, track_speed, min_speed, std_scale, fixed_std=None, min_inter_samples=10, min_event_samples=10, max_event_samples=1000):
assert(norm_meas.shape == track_speed.shape)
zsignal = norm_meas.copy()
if fixed_std is None:
zsignal[track_speed >= min_speed] = stats.zscore(norm_meas[track_speed > min_speed])
else:
zsignal[track_speed >= min_speed] = (
norm_meas[track_speed > min_speed]-norm_meas[track_speed > min_speed].mean())/fixed_std
zsignal[track_speed < min_speed] = 0
thresholded = (zsignal > std_scale).astype(int)
start = np.where(np.diff(thresholded) > 0)[0]
if not len(start):
return [], []
stop = np.where(np.diff(thresholded) < 0)[0]
if len(stop) == len(start)-1:
stop = np.concatenate((stop, [len(thresholded)]))
if len(stop)-1 == len(start):
stop = stop[1:]
if not len(start) or not len(stop):
return [], []
if start[0] > stop[0]:
start = start[:-1]
stop = stop[1:]
if not len(start):
return [], []
merged = True
events = np.array([start, stop])
while merged:
merged = False
tmpevents = [events[:, 0].tolist()]
for ir, (r1, r2) in enumerate(zip(events[0, 1:], events[1, :-1])):
if r1-r2 > min_inter_samples:
tmpevents[-1][1] = r2
tmpevents.append([r1, events[1, ir+1]])
elif ir == events.shape[-2]:
tmpevents[-1][1] = events[1][-1]
else:
merged = True
events = np.array(tmpevents).T.copy()
durations = (events[1, :]-events[0, :])
assert(np.all(durations > 0))
events = events[:, durations < max_event_samples]
assert(np.all(durations > 0))
durations = (events[1, :]-events[0, :])
events = events[:, durations >= min_event_samples]
eventmaxs = np.array([np.sum(norm_meas[event[0]:event[1]]) for event in events.T])
# events = events[:, eventmaxs > highThresholdFactor]
eventargmaxs = np.array([np.argmax(norm_meas[event[0]:event[1]])+event[0] for event in events.T])
return events[0, :], eventmaxs
def compute_dff(exp, vrdict, calciumdict_in, config):
calciumdict = calciumdict_in.copy()
# Neuropil subtraction / normalization
if 'dF_F' not in calciumdict:
if config['Fneu_factor'] is None:
calciumdict['dF_F'] = calciumdict['Fraw']/calciumdict['Fneu']
else:
calciumdict['dF_F'] = calciumdict['Fraw']-config['Fneu_factor']*calciumdict['Fneu']
dt = np.median(np.diff(vrdict['framet2p']))*1e-3
if exp.rois_eliminate is None:
rois_eliminate = []
else:
rois_eliminate = exp.rois_eliminate
nrois_total = calciumdict['dF_F'].shape[0]
nrois_total_range = np.arange(nrois_total)
calciumdict['nrois_index_eliminated'] = np.array([
nroi for nroi in nrois_total_range if nroi not in rois_eliminate
])
calciumdict['dF_F'] = np.array([
spectral.lowpass(
spectral.highpass(
spectral.Timeseries(df.astype(np.float), dt), 0.002, verbose=False),
config["F_filter"], verbose=False).data
for nroi, df in enumerate(calciumdict['dF_F']) if nroi not in rois_eliminate])
calciumdict['S'] = np.array([
S for nroi, S in enumerate(calciumdict['S']) if nroi not in rois_eliminate])
# Bootstrap
calciumdict['dF_F_bs'] = np.empty(calciumdict['dF_F'].shape)
calciumdict['dF_F_bs'][:, :int(calciumdict['dF_F_bs'].shape[1]/2)] = \
calciumdict['dF_F'][:, -int(calciumdict['dF_F_bs'].shape[1]/2):]
calciumdict['dF_F_bs'][:, -int(calciumdict['dF_F_bs'].shape[1]/2):] = \
calciumdict['dF_F'][:, :int(calciumdict['dF_F_bs'].shape[1]/2)]
calciumdict['S_bs'] = np.empty(calciumdict['S'].shape)
calciumdict['S_bs'][:, :int(calciumdict['S_bs'].shape[1]/2)] = \
calciumdict['S'][:, -int(calciumdict['S_bs'].shape[1]/2):]
calciumdict['S_bs'][:, -int(calciumdict['S_bs'].shape[1]/2):] = \
calciumdict['S'][:, :int(calciumdict['S_bs'].shape[1]/2)]
return calciumdict
def detect_events(cnmfdict, track_speed, std_scale, dt):
if 'YrA' in cnmfdict.keys():
C_df_f = caiman_cnmf.utilities.detrend_df_f(
cnmfdict['A'],
cnmfdict['bl'].squeeze(),
cnmfdict['C'].squeeze(),
cnmfdict['f'].squeeze(),
cnmfdict['YrA'].squeeze())
elif 'C' in cnmfdict.keys():
C_df_f = cnmfdict['C'].squeeze()
C_df_f = np.array([
spectral.lowpass(spectral.Timeseries(C_df_roi, dt), 1.0, verbose=False).data
for C_df_roi in C_df_f
])
else:
C_df_f = cnmfdict['dF_F']
ievents = [
find_events(C_df_roi, track_speed, -5, std_scale)[0]
for C_df_roi in C_df_f
]
spikes = np.array(cnmfdict['S']).squeeze()
return C_df_f, ievents, spikes
def bin_events(times, ievents, binsize, nroi_eliminate):
binstart = times[0]
binend = times[-1] + times[1]-times[0]
bins = np.arange(binstart, binend, binsize)
binsum = np.zeros((bins.shape[0]-1))
nrois_final = 0
for nroi, ievent_roi in enumerate(ievents):
if nroi_eliminate is None or nroi not in nroi_eliminate:
nrois_final += 1
for ievent in ievent_roi:
try:
binsum[np.where(times[ievent] < bins)[0][0]] += 1.0/binsize
except IndexError:
binsum[-1] += 1.0/binsize
binsum /= nrois_final
return bins, binsum
def bin_spikes(times, spikes, binsize, nroi_eliminate):
binstart = times[0]
binend = times[-1] + times[1]-times[0]
bins = np.arange(binstart, binend, binsize)
binsum = np.zeros((bins.shape[0]-1))
for nroi, spikes_roi in enumerate(spikes):
if nroi_eliminate is None or nroi not in nroi_eliminate:
for nbin, (binstart, binend) in enumerate(
zip(bins[:-1], bins[1:])):
binsum[nbin] += np.mean((spikes_roi/spikes_roi.max())[
(times >= binstart) & (times < binend)])
return bins, binsum
def sum_calcium(C_df_f, nroi_eliminate):
return np.mean([
norm(C_df_f_n) for nroi, C_df_f_n in enumerate(C_df_f)
if nroi_eliminate is None or nroi not in nroi_eliminate], axis=0)
def trackspeed(trackdict, cm_per_px=0.11, lopass=0.1):
track_speed = np.sqrt(
(np.diff(trackdict['posx_frames'].squeeze())**2 +
np.diff(trackdict['posy_frames'].squeeze())**2)
) / np.diff(trackdict['frametimes'].squeeze()) * cm_per_px
track_speed = np.concatenate([[track_speed[0], ], track_speed])
track_speed = spectral.lowpass(
spectral.Timeseries(track_speed, np.mean(np.diff(trackdict['frametimes']))),
lopass, verbose=False).data
return track_speed
def plot_rois(rois, measured, haussio_data, zproj, data_path, pdf_suffix="",
spikes=None, infer_threshold=0.15, region="", mapdict=None,
lopass=1.0, plot_events=False, minimaps=None, dpi=1200,
selected_rois=None, decoded=None, trackdict=None):
"""
Plot ROIs on top of z-projected image, extracted fluorescence, spike
inference, fluorescence and spike inference against position (if available)
Parameters
----------
rois : sima.ROI.ROIList
sima ROIList to be plotted
measured : numpy.ndarray
Processed fluorescence data for each ROI
haussio_data : haussio.HaussIO
haussio.HaussIO instance
zproj : numpy.ndarray
z-projected fluorescence image
data_path : str
Path to data directory
pdf_suffix : str, optional
Suffix appended to pdf. Default: ""
spikes : numpy.ndarray, optional
Spike inference values. Default: None
infer_threshold: float, optional
Spike inference threshold. Default: 0.15
region : str, optional
Brain region. Default: ""
mapdict : dict, optional
Dictionary containing processed VR data. Default: None
lopass : float, optional
Lowpass filter frequency for plotted traces. Default: 1.0
plot_events : bool, optional
Plot events. Default: False
selected_rois : list of ints, optional
Indices of ROIs to be plotted. Default: None (plots all ROIs)
"""
fig = plt.figure(figsize=(18, 24))
colors = ['r', 'g', 'b', 'c', 'm', 'y']
nrows = 8
strow = 2
has_vr = mapdict is not None and 't_vr' in mapdict.keys()
has_track = trackdict is not None
if not has_vr:
stcol = 0
ncols = 2
else:
stcol = 2
ncols = 4
gs = gridspec.GridSpec(nrows, ncols)
ax_nospike = fig.add_subplot(gs[strow:, 1:2])
plt.axis('off')
if not has_track:
ax_blank = fig.add_subplot(gs[:strow, stcol:stcol+1])
ax_blank.imshow(zproj, cmap='gray')
haussio_data.plot_scale_bar(ax_blank)
plt.axis('off')