-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
1735 lines (1589 loc) · 61 KB
/
utils.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
# System
import time, os, h5py, re
import logging
import itertools
import graphviz
# Structure
from collections import deque
# Data
import scipy
import numpy as np
import pandas as pd
from scipy.sparse import diags as spdiags
from scipy.sparse import linalg as sp_linalg
from scipy import interpolate, signal
from utils_models import auc_roc_2dist
from utils_signal import std_filter, median_filter
from packages.photometry_functions import get_dFF
from packages.flour_prep.api import fit_reference
# Plotting
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import seaborn as sns
from packages.photometry_functions import (
get_f0_Martianova_jove,
jove_fit_reference,
smooth_signal,
airPLS,
)
# caiman
try:
from caiman.source_extraction.cnmf.deconvolution import GetSn
from caiman.source_extraction.cnmf.utilities import fast_prct_filt
from caiman.utils.stats import df_percentile
except ModuleNotFoundError:
print(
"CaImAn not installed or environment not activated, certain functions might not be usable"
)
RAND_STATE = 230
# TODO: Move project specific portions to pipeline_*.py as things scale
##################################################
#################### Loading #####################
##################################################
def get_probswitch_session_by_condition(
folder, group="all", region="NAc", signal="all"
):
"""Searches through [folder] and find all of probswitch experiment sessions that match the
description; Returns lists of session files of different recording type
:param group: str, expression
:param region: str, region of recording
:param signal: str, signal type (DA or Ca 05/25/21)
:param photometry:
:param choices:
:param processed:
:return:
"""
if group == "all":
groups = ("D1", "A2A")
else:
groups = [group]
if region == "all":
regions = ["NAc", "DMS"]
else:
regions = [region]
if signal == "all":
signals = ["DA", "Ca"]
else:
signals = [signal]
results = {}
for g in groups:
grouppdf = pd.read_csv(os.path.join(folder, f"ProbSwitch_FP_Mice_{g}.csv"))
rsel = grouppdf["Region"].isin(regions)
if signals[0] == "none":
animal_sessions = grouppdf[rsel]
else:
fpsel = grouppdf["FP"] >= 1
sigsel = np.logical_and.reduce(
[grouppdf[f"FP_{s}_zoom"] > 0 for s in signals]
)
animal_sessions = grouppdf[rsel & fpsel & sigsel]
results[g] = {}
for animal in animal_sessions["animal"].unique():
results[g][animal] = sorted(
animal_sessions[animal_sessions["animal"] == animal]["session"]
)
return results
def get_prob_switch_all_sessions(folder, groups):
"""Exhaustively check all folder that contains ProbSwitch task .mat files and encode all sessions.
.mat -> decode -> return group
:param folder:
:return:
"""
only_Ca = []
only_DA = []
results = {g: {a: [] for a in groups[g]} for g in groups}
for d in os.listdir(folder):
if os.path.isdir(os.path.join(folder, d)):
m = re.match(
"^(?P<animal>\w{2,3}-\d{2,}[-\w*]*_[A-Z]{2})_(?P<session>p\d+\w+)", d
)
if m:
animal, day = m.group("animal"), m.group("session")
group_dict = results[animal.split("-")[0]]
if animal in group_dict:
group_dict[animal].append(day)
elif animal not in group_dict and "*" in group_dict:
group_dict[animal] = [day]
for g in results:
del results[g]["*"]
return results
def check_FP_contain_dff_method(fp, methods, sig="DA"):
"""Utility function that helps check whether the <fp> hdf5 file contains <dff> signals preprocessed."""
if fp is None:
return False
if isinstance(methods, str):
methods = [methods]
with h5py.File(fp, "r") as hf:
return np.all([f"{sig}/dff/{m}" in hf for m in methods])
def get_sources_from_csvs(
csvfiles, window=400, delim=None, aux_times=None, tags=None, show=False
):
"""
Extract sources from a list of csvfiles, with csvfile[0] be channels with cleaniest
TODO: potentially use the fact that 415 has the same timestamps to speed up the process
:param csvfiles:
:param window:
:return:
"""
if isinstance(csvfiles, str):
csvfiles = [csvfiles]
if delim is None:
delim = " "
try:
pdf = pd.read_csv(
csvfiles[0], delimiter=delim, names=["time", "calcium"], usecols=[0, 1]
)
FP_times = [None] * len(csvfiles)
FP_signals = [None] * len(csvfiles)
for i in range(len(csvfiles)):
csvfile = csvfiles[i]
# Signal Sorting
pdf = pd.read_csv(
csvfile, delimiter=delim, names=["time", "calcium"], usecols=[0, 1]
)
FP_times[i] = pdf.time.values
FP_signals[i] = pdf.calcium.values
if aux_times:
old_zero = FP_times[0][0]
if old_zero == aux_times[0][0]:
print("WARNING: NO UPDATE, something is up")
assert len(FP_times) == len(aux_times), "MUST BE SAME dim"
FP_times = aux_times
if tags is None:
tags = [f"REC{i}" for i in range(len(csvfiles))]
except:
print("OOPPS")
# TODO: aux_time input potentially needed
FP_times = [None] * len(csvfiles) * 2
FP_signals = [None] * len(csvfiles) * 2
for i in range(len(csvfiles)):
# Signal Sorting
csvfile = csvfiles[i]
pdf = pd.read_csv(csvfile, delimiter=",")
red_sig = pdf["Region1R"].values
green_sig = pdf["Region0G"].values
times = pdf["Timestamp"].values
FP_times[2 * i], FP_times[2 * i + 1] = times, times
FP_signals[2 * i], FP_signals[2 * i + 1] = green_sig, red_sig
if tags is None:
tags = np.concatenate(
[[f"REC{i}_G", f"REC{i}_R"] for i in range(len(csvfiles))]
)
FP_REC_signals = [None] * len(FP_signals)
FP_REC_times = [None] * len(FP_signals)
FP_415_signals = [None] * len(FP_signals)
FP_415_times = [None] * len(FP_signals)
FP_415_sel = None
for i in range(len(FP_signals)):
FP_time, FP_signal = FP_times[i], FP_signals[i]
# # Plain Threshold
# min_signal, max_signal = np.min(FP_signal), np.max(FP_signal)
# intensity_threshold = min_signal+(max_signal - min_signal)*0.4
# Dynamic Threshold
n_win = len(FP_signal) // window
bulk = n_win * window
edge = len(FP_signal) - bulk
first_batch = FP_signal[:bulk].reshape((n_win, window), order="C")
end_batch = FP_signal[-window:]
edge_batch = FP_signal[-edge:]
sigT_sels = np.concatenate(
[
(first_batch > np.mean(first_batch, keepdims=True, axis=1)).reshape(
bulk, order="C"
),
edge_batch > np.mean(end_batch),
]
)
sigD_sels = ~sigT_sels
FP_top_signal, FP_top_time = FP_signal[sigT_sels], FP_time[sigT_sels]
FP_down_signal, FP_down_time = FP_signal[sigD_sels], FP_time[sigD_sels]
topN, downN = len(FP_top_signal) // window, len(FP_down_signal) // window
top_dyn_std = np.std(
FP_top_signal[: topN * window].reshape((topN, window), order="C"), axis=1
).mean()
down_dyn_std = np.std(
FP_down_signal[: downN * window].reshape((downN, window), order="C"), axis=1
).mean()
# TODO: check for consecutives
# TODO: check edge case when only 415 has signal
if top_dyn_std >= down_dyn_std:
sigREC_sel, sig415_sel = sigT_sels, sigD_sels
FP_REC_signals[i], FP_REC_times[i] = FP_top_signal, FP_top_time
FP_415_signals[i], FP_415_times[i] = FP_down_signal, FP_down_time
else:
sigREC_sel, sig415_sel = sigD_sels, sigT_sels
FP_REC_signals[i], FP_REC_times[i] = FP_down_signal, FP_down_time
FP_415_signals[i], FP_415_times[i] = FP_top_signal, FP_top_time
if show:
fig, axes = plt.subplots(nrows=len(FP_REC_signals), ncols=1, sharex=True)
for i in range(len(FP_REC_signals)):
ax = axes[i] if len(FP_REC_signals) > 1 else axes
itag = tags[i]
ax.plot(FP_REC_times[i], FP_REC_signals[i], label=itag)
ax.plot(FP_415_times[i], FP_415_signals[i], label="415")
ax.legend()
# TODO: save as pd.DataFrame
if len(FP_REC_signals) == 1:
return FP_REC_times[0], FP_REC_signals[0], FP_415_times[0], FP_415_signals[0]
# TODO: if shape uniform merge signals
return FP_REC_times, FP_REC_signals, FP_415_times, FP_415_signals
def path_prefix_free(path):
symbol = os.path.sep
if path[-len(symbol) :] == symbol:
return path[path.rfind(symbol, 0, -len(symbol)) + len(symbol) : -len(symbol)]
else:
return path[path.rfind(symbol) + len(symbol) :]
def file_folder_path(f):
symbol = os.path.sep
len_sym = len(symbol)
if f[-len_sym:] == symbol:
return f[: f.rfind(symbol, 0, -len_sym)]
else:
return f[: f.rfind(symbol)]
def summarize_sessions(data_root, implant_csv, save_path, sort_key="aID"):
"""
implant_csv: pd.DataFrame from implant csv file
"""
# add region of implant, session number, signal quality
# input a list of names implant locations
# "/A2A-15B-B_RT_20200229_learning-switch-2_p39.mat" supposed to be 139
# sorting with p notation mess up if p is less 100\
# bug /D1-27H_LT_20200229_ToneSamp_p89.mat read as 022
alles = {
"animal": [],
"aID": [],
"session": [],
"date": [],
"ftype": [],
"age": [],
"FP": [],
"region": [],
"note": [],
}
implant_lookup = {}
for i in range(len(implant_csv)):
animal_name = implant_csv.loc[i, "Name"]
if animal_name and (str(animal_name) != "nan"):
LH_target = implant_csv.loc[i, "LH Target"]
RH_target = implant_csv.loc[i, "RH Target"]
print(animal_name)
name_first, name_sec = animal_name.split(" ")
name_first = "-".join(name_first.split("-")[:2])
implant_lookup[name_first + "_" + name_sec] = {
"LH": LH_target,
"RH": RH_target,
}
for f in os.listdir(data_root):
options = decode_from_filename(f)
if options is None:
pass
# print(f, "ALERT")
elif ("FP_" in f) and ("FP_" not in options["session"]):
print(f, options["session"])
else:
for q in ["animal", "ftype", "session"]:
alles[q].append(options[q])
name_first2, name_sec2 = options["animal"].split("_")
name_first2 = "-".join(name_first2.split("-")[:2])
aID = name_first2 + "_" + name_sec2
alles["aID"].append(aID)
alles["date"].append(options["T"])
opts = options["session"].split("_FP_")
alles["age"].append(opts[0])
if len(opts) > 1:
alles["FP"].append(opts[1])
if aID not in implant_lookup:
print(
"skipping",
options,
)
alles["region"].append("")
else:
alles["region"].append(implant_lookup[aID][opts[1]])
else:
alles["FP"].append("")
alles["region"].append("")
alles["note"].append(options["DN"] + options["SP"])
apdf = pd.DataFrame(alles)
sorted_pdf = apdf.sort_values(["date", "session"], ascending=True)
sorted_pdf["S_no"] = 0
new_pdfs = []
for anim in sorted_pdf[sort_key].unique():
tempslice = sorted_pdf[sorted_pdf[sort_key] == anim]
sorted_pdf.loc[sorted_pdf[sort_key] == anim, "S_no"] = np.arange(
1, len(tempslice) + 1
)
# final_pdf = pd.concat(new_pdfs, axis=0)
final_pdf = sorted_pdf
final_pdf.to_csv(
os.path.join(save_path, f"exper_list_final_{sort_key}.csv"), index=False
)
def encode_to_filename(folder, animal, session, ftypes="processed_all"):
"""
:param folder: str
folder for data storage
:param animal: str
animal name: e.g. A2A-15B-B_RT
:param session: str
session name: e.g. p151_session1_FP_RH
:param ftype: list or str:
list (or a single str) of typed files to return
'exper': .mat files
'bin_mat': binary file
'green': green fluorescence
'red': red FP
'behavior': .mat behavior file
'FP': processed dff hdf5 file
if ftypes=="all"
:return:
returns all 5 files in a dictionary; otherwise return all file types
in a dictionary, None if not found
"""
# TODO: enable aliasing
paths = [
os.path.join(folder, animal, session),
os.path.join(folder, animal + "_" + session),
os.path.join(folder, animal),
folder,
]
if ftypes == "raw all":
ftypes = ["exper", "bin_mat", "green", "red"]
elif ftypes == "processed_all":
ftypes = ["processed", "green", "red", "FP"]
elif isinstance(ftypes, str):
ftypes = [ftypes]
results = {ft: None for ft in ftypes}
registers = 0
for p in paths:
if os.path.exists(p):
for f in os.listdir(p):
opt = decode_from_filename(f)
if opt is not None:
ift = opt["ftype"]
check_mark = opt["animal"] == animal and opt["session"] == session
# print(opt['session'], animal, session)
check_mark_mdl = (opt["animal"] == animal) and (
opt["session"] in session
)
cm_mdl = ift == "modeling" and check_mark_mdl
# TODO: temporary hacky method for modeling
# print(opt['session'], animal, session, check_mark_mdl, ift, cm_mdl)
if (
ift in ftypes
and results[ift] is None
and (check_mark or cm_mdl)
):
results[ift] = os.path.join(p, f)
registers += 1
if registers == len(ftypes):
return results if len(results) > 1 else results[ift]
return results if len(results) > 1 else list(results.values())[0]
def decode_from_filename(filename):
"""
Takes in filenames of the following formats and returns the corresponding file options
`A2A-15B_RT_20200612_ProbSwitch_p243_FP_RH`, `D1-27H_LT_20200314_ProbSwitch_FP_RH_p103`
behavioral: * **Gen-ID_EarPoke_Time_DNAME_Age_special.mat**
FP: **Gen-ID_EarPoke_DNAME2_Hemi_Age_channel_Time(dash)[Otherthing].csv**
binary matrix: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_Binary_Matrix)Time[special].etwas**
timestamps: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_timestamps)Time[special].csv**
GEN: genetic line, ID: animal ID, EP: ear poke, T: time of expr, TD: detailed HMS DN: Data Name, A: Age,
H: hemisphere, S: session, SP: special extension
:param filename:
:return: options: dict
ftype
animal
session
"""
filename = path_prefix_free(filename)
# case exper
mBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<T>\d+)_(?P<DN>[-&\w]+)_("
r"?P<A>p\d+)(?P<SP>[-&\w]*)\.mat",
filename,
)
# case processed behavior
mPBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_processed_data.mat",
filename,
)
mPBOMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_behavior_data.mat",
filename,
)
mFPMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H).hdf5",
filename,
)
mMDMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>(FP_[LR]H)?)_modeling.hdf5",
filename,
)
mTBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)_trialB.csv",
filename,
)
# case binary
mBIN = None
options, ftype = None, None
if mBMat is not None:
# TODO: handle session#
options = mBMat.groupdict()
ftype = "exper"
oS = options["SP"]
options["H"] = ""
dn_match = re.match(".*(FP_[LR]H).*", options["DN"])
sp_match = re.match(".*(FP_[LR]H).*", options["SP"])
if dn_match:
options["H"] = dn_match.group(1)
elif sp_match:
options["H"] = sp_match.group(1)
elif mTBMat is not None:
options = mTBMat.groupdict()
ftype = "trialB"
oS = options["S"]
elif mMDMat is not None:
options = mMDMat.groupdict()
ftype = "modeling"
oS = options["S"]
elif mPBMat is not None:
options = mPBMat.groupdict()
ftype = "processed"
oS = options["S"]
elif mPBOMat is not None:
options = mPBOMat.groupdict()
ftype = "behavior_old"
oS = options["S"]
elif mFPMat is not None:
options = mFPMat.groupdict()
ftype = "FP"
oS = options["S"]
elif mBIN is not None:
# TODO: fill it up
options = mBIN.groupdict()
oS = ""
ftype = "bin_mat"
else:
# TODO: print("Warning! Certain sessions have inconsistent naming! needs more through check")
# case csv
# todo: merge cage id and earpoke
channels = [
"keystrokes",
"MetaData",
"NIDAQ_Ai0_timestamp",
"NIDAQ_Ai0_Binary_Matrix",
"red",
"green",
"FP",
"FPTS",
]
for c in channels:
mCSV = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<DN>[-&\w]+)_(?P<H>([LR]H_)?)(?P<A>p\d+)(?P<SP>[-&\w]*)"
+ f"_{c}(?P<BSC>(_(BSC)\d)?)"
+ r"(?P<S>_session\d+_|_?)(?P<T>\d{4}-?\d{2}-?\d{2})T(?P<TD>[_\d]+)\.[(csv)|\d+]",
filename,
)
if mCSV is not None:
options = mCSV.groupdict()
ftype = c
oS = options["S"]
options["H"] = "FP_" + options["H"]
break
# print(filename)
# print(options)
if ftype is None:
# print("special:", filename)
return None
mS = re.match(r".*(session\d+).*", oS)
fS = ""
if mS:
fS = "_" + mS.group(1)
options["ftype"] = ftype
options["animal"] = options["GEN"] + "-" + options["ID"] + "_" + options["EP"]
options["session"] = (
options["A"] + fS + (("_" + options["H"]) if options["H"] else "")
)
return options
# Figure out rigorous representation; also keep old version intact
def encode_to_filename_new(folder, animal, session, ftypes="processed_all"):
"""
:param folder: str
folder for data storage
:param animal: str
animal name: e.g. A2A-15B-B_RT
:param session: str
session name: e.g. p151_session1_FP_RH
:param ftype: list or str:
list (or a single str) of typed files to return
'exper': .mat files
'bin_mat': binary file
'green': green fluorescence
'red': red FP
'behavior': .mat behavior file
'FP': processed dff hdf5 file
if ftypes=="all"
:return:
returns all 5 files in a dictionary; otherwise return all file types
in a dictionary, None if not found
"""
# TODO: enable aliasing
paths = [
os.path.join(folder, animal, session),
os.path.join(folder, animal + "_" + session),
os.path.join(folder, animal),
folder,
]
if ftypes == "raw all":
ftypes = ["exper", "bin_mat", "green", "red"]
elif ftypes == "processed_all":
ftypes = ["processed", "green", "red", "FP"]
elif isinstance(ftypes, str):
ftypes = [ftypes]
results = {ft: None for ft in ftypes}
registers = 0
for p in paths:
if os.path.exists(p):
for f in os.listdir(p):
for ift in ftypes:
if ift == "FP":
ift_arg = "FP_"
else:
ift_arg = ift
if (ift_arg in f) and (animal in f) and (session in f):
results[ift] = os.path.join(p, f)
registers += 1
if registers == len(ftypes):
return results if len(results) > 1 else results[ift]
# opt = decode_from_filename(f)
# if opt is not None:
# ift = opt['ftype']
# check_mark = opt['animal'] == animal and opt['session'] == session
# #print(opt['session'], animal, session)
# check_mark_mdl = (opt['animal'] == animal) and (opt['session'] in session)
# cm_mdl = (ift == 'modeling' and check_mark_mdl)
# # TODO: temporary hacky method for modeling
# #print(opt['session'], animal, session, check_mark_mdl, ift, cm_mdl)
# if ift in ftypes and results[ift] is None and (check_mark or cm_mdl):
# results[ift] = os.path.join(p, f)
# registers += 1
# if registers == len(ftypes):
# return results if len(results) > 1 else results[ift]
return results if len(results) > 1 else list(results.values())[0]
def decode_from_filename_new(filename):
"""
Takes in filenames of the following formats and returns the corresponding file options
`A2A-15B_RT_20200612_ProbSwitch_p243_FP_RH`, `D1-27H_LT_20200314_ProbSwitch_FP_RH_p103`
behavioral: * **Gen-ID_EarPoke_Time_DNAME_Age_special.mat**
FP: **Gen-ID_EarPoke_DNAME2_Hemi_Age_channel_Time(dash)[Otherthing].csv**
binary matrix: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_Binary_Matrix)Time[special].etwas**
timestamps: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_timestamps)Time[special].csv**
GEN: genetic line, ID: animal ID, EP: ear poke, T: time of expr, TD: detailed HMS DN: Data Name, A: Age,
H: hemisphere, S: session, SP: special extension
:param filename:
:return: options: dict
ftype
animal
session
"""
filename = path_prefix_free(filename)
# case exper
mBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<T>\d+)_(?P<DN>[-&\w]+)_("
r"?P<A>p\d+)(?P<SP>[-&\w]*)\.mat",
filename,
)
# case processed behavior
mPBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_processed_data.mat",
filename,
)
mPBOMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_behavior_data.mat",
filename,
)
mFPMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H).hdf5",
filename,
)
mMDMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>(FP_[LR]H)?)_modeling.hdf5",
filename,
)
mTBMat = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<A>p\d+)(?P<S>(_session\d+)?)_trialB.csv",
filename,
)
# case binary
mBIN = None
options, ftype = None, None
if mBMat is not None:
# TODO: handle session#
options = mBMat.groupdict()
ftype = "exper"
oS = options["SP"]
options["H"] = ""
dn_match = re.match(".*(FP_[LR]H).*", options["DN"])
sp_match = re.match(".*(FP_[LR]H).*", options["SP"])
if dn_match:
options["H"] = dn_match.group(1)
elif sp_match:
options["H"] = sp_match.group(1)
elif mTBMat is not None:
options = mTBMat.groupdict()
ftype = "trialB"
oS = options["S"]
options["H"] = ""
elif mMDMat is not None:
options = mMDMat.groupdict()
ftype = "modeling"
oS = options["S"]
elif mPBMat is not None:
options = mPBMat.groupdict()
ftype = "processed"
oS = options["S"]
elif mPBOMat is not None:
options = mPBOMat.groupdict()
ftype = "behavior_old"
oS = options["S"]
elif mFPMat is not None:
options = mFPMat.groupdict()
ftype = "FP"
oS = options["S"]
elif mBIN is not None:
# TODO: fill it up
options = mBIN.groupdict()
oS = ""
ftype = "bin_mat"
else:
# TODO: print("Warning! Certain sessions have inconsistent naming! needs more through check")
# case csv
# todo: merge cage id and earpoke
"""A2A-16B-1_RT_ChR2_switch_no_cue_LH_p147_red_2020-03-17T15_38_40.csv"""
channels = [
"keystrokes",
"MetaData",
"NIDAQ_Ai0_timestamp",
"red",
"green",
"FP",
"FPTS",
]
for c in channels:
mCSV = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<DN>[-&\w]+)_(?P<H>([LR]H_)?)(?P<A>p\d+)(?P<SP>[-&\w]*)"
+ f"_{c}(?P<BSC>(_(BSC)\d)?)"
+ r"(?P<S>_session\d+_|_?)(?P<T>\d{4}-?\d{2}-?\d{2})T(?P<TD>[_\d]+)\.[(csv)|\d+]",
filename,
)
if mCSV is not None:
options = mCSV.groupdict()
ftype = c
oS = options["S"]
options["H"] = ("FP_" + options["H"]) if options["H"] else ""
break
# print(filename)
# print(options)
if ftype is None:
# print("special:", filename)
return None
mS = re.match(r".*(session\d+).*", oS)
fS = ""
if mS:
fS = "_" + mS.group(1)
options["ftype"] = ftype
options["animal"] = options["GEN"] + "-" + options["ID"] + "_" + options["EP"]
options["session"] = (
options["A"] + fS + (("_" + options["H"]) if options["H"] else "")
)
return options
def access_mat_with_path(mat, p, ravel=False, dtype=None, raw=False):
"""Takes in .mat file or hdf5 file and path like structure p and return the entry
:param mat:
glml matfiles: modified from Belief_State_FP_Analysis.m legacy Chris Hall GLM structure:
glml/
notes/
hemisphere/
region/
time/
center_in/
contra/
contra_rew/
contra_unrew/
execute/
initiate/
ipsi/
ipsi_rew/
ipsi_unrew/
left_in_choice/
right_in_choice/
trial_event_FP_time/
trials/
ITI/
center_in/
center_to_side/
contra/
contra_rew/
contra_unrew/
execute/
initiate/ termination of the trial.
ipsi/
ipsi_rew/
ipsi_unrew/
left_in_choice/
omission/
right_in_choice/
side_to_center/
time_indexs/
value/
center_to_side_times/
contra/
cue_port_side/ 2=left 1=right
execute/
initiate/
ipsi/
port_side/
result/ : 1.2=reward, 1.1 = correct omission, 2 = incorrect, 3 = no choice, 0: undefined
side_to_center_time/
time_to_left/
time_to_right/
:param p:
:return:
"""
result = mat
for ip in p.split("/"):
result = result[ip]
if raw:
return result
result = np.array(result, dtype=dtype)
return result.ravel() if ravel else result
def recursive_mat_dict_view(mat, prefix=""):
"""Recursively print out mat in file structure for visualization, only support pure dataset like"""
for p in mat:
print(prefix + p + "/")
if not isinstance(mat[p], h5py.Dataset) and not isinstance(mat[p], np.ndarray):
recursive_mat_dict_view(mat[p], prefix + " ")
###################################################
#################### Cleaning #####################
###################################################
def flip_back_2_channels(animal, session):
pass
########################################################
#################### Preprocessing #####################
########################################################
def raw_fluor_to_dff(
rec_time,
rec_sig,
iso_time,
iso_sig,
baseline_method="robust",
zscore=False,
**kwargs,
):
"""Takes in 1d signal and convert to dff (zscore dff)
:param rec_sig:
:param rec_time:
:param iso_sig:
:param iso_time:
:param baseline_method:
:param zscore:
:param kwargs:
:return:
"""
# TODO: figure out the best policy for removal currently no removal
# TODO: More in-depth analysis of the best baselining approach with quantitative metrics
bms = baseline_method.split("_")
fast = False
if len(bms) > 1:
fast = bms[-1] == "fast"
baseline_method = bms[0]
if baseline_method == "robust":
f0 = f0_filter_sig(rec_time, rec_sig, buffer=not fast, **kwargs)[:, 0]
elif baseline_method == "mode":
f0 = percentile_filter(rec_time, rec_sig, perc=None, **kwargs)
elif baseline_method.startswith("perc"):
pc = int(baseline_method[4:])
f0 = percentile_filter(rec_time, rec_sig, perc=pc, **kwargs)
elif baseline_method == "isosbestic":
# cite jove paper
reference = interpolate.interp1d(iso_time, iso_sig, fill_value="extrapolate")(
rec_time
)
signal = rec_sig
f0 = get_f0_Martianova_jove(reference, signal)
elif baseline_method == "isosbestic_old":
dc_rec, dc_iso = np.mean(rec_sig), np.mean(iso_sig)
dm_rec_sig, dm_iso_sig = rec_sig - dc_rec, iso_sig - dc_iso
# TODO: implement impulse based optimization
f0_iso = isosbestic_baseline_correct(iso_time, dm_iso_sig, **kwargs) + dc_rec
f0 = f0_iso
if iso_time.shape != rec_time.shape or np.allclose(iso_time, rec_time):
f0 = interpolate.interp1d(iso_time, f0_iso, fill_value="extrapolate")(
rec_time
)
else:
raise NotImplementedError(f"Unknown baseline method {baseline_method}")
dff = (rec_sig - f0) / (
f0 + np.mean(rec_sig) + 1e-16
) # arbitrary DC shift to avoid issue
return (dff - np.mean(dff)) / np.std(dff, ddof=1) if zscore else dff
def sources_get_noise_power(s415, s470):
npower415 = GetSn(s415)
npower470 = GetSn(s470)
return npower415, npower470
def get_sample_interval(times):
return np.around((np.max(times) - np.min(times)) / len(times), 0)
def resample_quasi_uniform(sig, times, method="interpolate"):
if np.sum(np.diff(times) < 0) > 0:
shuffles = np.argsort(times)
sig = sig[shuffles]
times = times[shuffles]
si = get_sample_interval(times)
T0, Tm = np.min(times), np.max(times)
if method == "interpolate":
new_times = np.arange(T0, Tm, si)
new_sig = interpolate.interp1d(times, sig, fill_value="extrapolate")(new_times)
elif method == "fft":
new_sig, new_times = signal.resample(sig, int((Tm - T0) // si), t=times)
else:
raise NotImplementedError(f"unknown method {method}")
return new_sig, new_times
def denoise_quasi_uniform(sig, times, method="wiener"):
new_sig, new_times = resample_quasi_uniform(sig, times)
if method == "wiener":
return signal.wiener(new_sig), new_times
else:
raise NotImplementedError(f"Unknown method {method}")
def robust_filter(ys, method=12, window=200, optimize_window=2, buffer=False):
"""
First 2 * windows re-estimate with mode filter
To avoid edge effects as beginning, it uses mode filter; better solution: specify initial conditions
Return:
dff: np.ndarray (T, 2)
col0: dff
col1: boundary scale for noise level
"""
if method < 10:
mf, mDC = median_filter(window, method)
else:
mf, mDC = std_filter(window, method % 10, buffer=buffer)
opt_w = int(np.rint(optimize_window * window))
# prepend
init_win_ys = ys[:opt_w]
prepend_ys = init_win_ys[opt_w - 1 : 0 : -1]
ys_pp = np.concatenate([prepend_ys, ys])
f0 = np.array([(mf(ys_pp, i), mDC.get_dev()) for i in range(len(ys_pp))])[
opt_w - 1 :
]
return f0
def f0_filter_sig(
xs,
ys,
method=12,
window=200,
optimize_window=2,
edge_method="prepend",
buffer=False,
**kwargs,
):
"""
First 2 * windows re-estimate with mode filter
To avoid edge effects as beginning, it uses mode filter; better solution: specify initial conditions
Return:
dff: np.ndarray (T, 2)
col0: dff
col1: boundary scale for noise level
"""
if method < 10:
mf, mDC = median_filter(window, method)
else:
mf, mDC = std_filter(window, method % 10, buffer=buffer)
opt_w = int(np.rint(optimize_window * window))
# prepend
init_win_ys = ys[:opt_w]
init_win_xs = xs[:opt_w]
if edge_method == "init":
# subpar method so far, use prepend
initial = percentile_filter(init_win_xs, init_win_ys, window)
initial_std = np.sqrt(max(0, np.mean(np.square(init_win_ys - initial))))
m2 = np.mean(
np.square(init_win_ys[init_win_ys - initial < (method % 10) * initial_std])
)
mDC.set_init(np.mean(initial[:window]), np.std(initial, ddof=1))
dff = np.array([(mf(ys, i), mDC.get_dev()) for i in range(len(ys))])
elif edge_method == "prepend":
prepend_xs = init_win_xs[opt_w - 1 : 0 : -1]
prepend_ys = init_win_ys[opt_w - 1 : 0 : -1]
prepend_xs = 2 * np.min(init_win_xs) - prepend_xs
ys_pp = np.concatenate([prepend_ys, ys])
xs_pp = np.concatenate([prepend_xs, xs])
dff = np.array([(mf(ys_pp, i), mDC.get_dev()) for i in range(len(ys_pp))])[
opt_w - 1 :
]
elif edge_method == "mode":
dff = np.array([(mf(ys, i), mDC.get_dev()) for i in range(len(ys))])
dff[:opt_w, 0] = percentile_filter(init_win_xs, init_win_ys, window)