forked from abhishekde95/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Batch_Scanbox.jl
1246 lines (1114 loc) · 62.9 KB
/
Batch_Scanbox.jl
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
using DataFramesMeta,Interact,CSV,MAT,Query,DataStructures,HypothesisTests,StatsFuns,Random,LinearAlgebra
using Statistics,StatsPlots,StatsBase,Mmap,Images,ePPR
function process_2P_dirsf(files,param;uuid="",log=nothing,plot=false)
interpolatedData = haskey(param,:interpolatedData) ? param[:interpolatedData] : true # If you have multiplanes. True: use interpolated data; false: use uniterpolated data. Results are slightly different.
preOffset = haskey(param,:preOffset) ? param[:preOffset] : 0.1
responseOffset = haskey(param,:responseOffset) ? param[:responseOffset] : 0.05 # in sec
α = haskey(param,:α) ? param[:α] : 0.05 # p value
sampnum = haskey(param,:sampnum) ? param[:sampnum] : 100 # random sampling 100 times
fitThres = haskey(param,:fitThres) ? param[:fitThres] : 0.5
# Expt info
dataset = prepare(files)
ex = dataset["ex"]
disk=string(param[:dataexportroot][1:2])
subject=uppercase(ex["Subject_ID"]);recordSession=uppercasefirst(ex["RecordSite"]);testId=ex["TestID"]
## Prepare data & result path
exptId = join(filter(!isempty,[recordSession[2:end], testId]),"_")
dataFolder = joinpath(disk,subject, "2P_data", recordSession, exptId)
## load expt, scanning parameters
envparam = ex["EnvParam"]
sbx = dataset["sbx"]["info"]
## Align Scan frames with stimulus
# Calculate the scan parameters
scanFreq = sbx["resfreq"]
lineNum = sbx["sz"][1]
if haskey(sbx, "recordsPerBuffer_bi")
scanMode = 2 # bidirectional scanning # if process Splitted data, =1
else
scanMode = 1 # unidirectional scanning
end
sbxfs = 1/(lineNum/scanFreq/scanMode) # frame rate
if (sbx["line"][1] == 0.00) | (sbx["frame"][1] == 0.00) # Sometimes there is extra pulse at start, need to remove it
stNum = 2
else
stNum = 1
end
trialOnLine = sbx["line"][stNum:2:end]
trialOnFrame = sbx["frame"][stNum:2:end] + round.(trialOnLine/lineNum) # if process splitted data use frame_split
trialOffLine = sbx["line"][stNum+1:2:end]
trialOffFrame = sbx["frame"][stNum+1:2:end] + round.(trialOffLine/lineNum) # if process splitted data use frame_split
# On/off frame indces of trials
trialEpoch = Int.(hcat(trialOnFrame, trialOffFrame))
# minTrialDur = minimum(trialOffFrame-trialOnFrame)
# histogram(trialOffFrame-trialOnFrame,nbins=20,title="Trial Duration(Set to $minTrialDur)")
# Transform Trials ==> Condition
ctc = DataFrame(ex["CondTestCond"])
trialNum = size(ctc,1)
# Include blank as a condition, marked as Inf
for factor in 1:size(ctc,2)
ctc[factor] = replace(ctc[factor], "blank"=>Inf)
end
condition = condin(ctc)
condNum = size(condition,1) # including blanks
# On/off frame indces of condations/stimuli
preStim = ex["PreICI"]; stim = ex["CondDur"]; postStim = ex["SufICI"]
trialOnTime = fill(0, trialNum)
condOfftime = preStim + stim
preEpoch = [0 preStim-preOffset]
condEpoch = [preStim+responseOffset condOfftime-responseOffset]
preFrame=epoch2sampleindex(preEpoch, sbxfs)
condFrame=epoch2sampleindex(condEpoch, sbxfs)
# preOn = fill(preFrame.start, trialNum)
# preOff = fill(preFrame.stop, trialNum)
# condOn = fill(condFrame.start, trialNum)
# condOff = fill(condFrame.stop, trialNum)
## Load data
if interpolatedData
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.signals"),dir=dataFolder,join=true)[1]
else
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9].signals"),dir=dataFolder,join=true)[1]
end
segment = prepare(segmentFile)
signal = prepare(signalFile)
sig = transpose(signal["sig"]) # 1st dimention is cell roi, 2nd is fluorescence trace
# spks = transpose(signal["spks"]) # 1st dimention is cell roi, 2nd is spike train
planeNum = size(segment["mask"],3) # how many planes
if interpolatedData
planeStart = vcat(1, length.(segment["seg_ot"]["vert"]).+1)
end
## Use for loop process each plane seperately
for pn in 1:planeNum
# pn=1 # for test
# Initialize DataFrame for saving results
recordPlane = string("00",pn-1) # plane/depth, this notation only works for expt has less than 10 planes
siteId = join(filter(!isempty,[recordSession[2:end], testId, recordPlane]),"_")
dataExportFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "DataExport")
resultFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "Plots")
isdir(dataExportFolder) || mkpath(dataExportFolder)
isdir(resultFolder) || mkpath(resultFolder)
result = DataFrame()
if interpolatedData
cellRoi = segment["seg_ot"]["vert"][pn]
else
cellRoi = segment["vert"]
end
cellNum = length(cellRoi)
display("plane: $pn")
display("Cell Number: $cellNum")
cellId = collect(range(1, step=1, stop=cellNum)) # Currently, the cellID is the row index of signal
if interpolatedData
rawF = sig[planeStart[pn]:planeStart[pn]+cellNum-1,:]
# spike = spks[planeStart[pn]:planeStart[pn]+cellNum-1,:]
else
rawF = sig
# spike = spks
end
result.py = 0:cellNum-1
result.ani = fill(subject, cellNum)
result.dataId = fill(siteId, cellNum)
result.cellId = 1:cellNum
## Plot dF/F traces of all trials for all cells
# Cut raw fluorescence traces according to trial on/off time and calculate dF/F
cellTimeTrial = sbxsubrm(rawF,trialEpoch,cellId;fun=dFoF(preFrame)) # cellID x timeCourse x Trials
# Mean response within stim time
cellMeanTrial = dropdims(mean(cellTimeTrial[:,condFrame,:], dims=2), dims=2) # cellID x Trials
# Plot
if plot
@manipulate for cell in 1:cellNum
plotanalog(transpose(cellTimeTrial[cell,:,:]), fs=sbxfs, timeline=condEpoch.-preStim, xunit=:s, ystep=1,cunit=:p, color=:fire,xext=preStim)
end
end
## Average over repeats, and put each cell's response in factor space (dir-sf...), and find the maximal level of each factor
factors = finalfactor(ctc)
fa = OrderedDict(f=>unique(condition[f]) for f in factors) # factor levels, the last one of each factor maybe blank(Inf)
fms=[];fses=[]; # mean ans sem of each condition of each cell
ufm = Dict(k=>[] for k in keys(fa)) # maxi factor level of each cell
for cell in 1:cellNum
mseuc = condresponse(cellMeanTrial[cell,:],condition) # condtion response, averaged over repeats
fm,fse,_ = factorresponse(mseuc) # put condition response into factor space
p = Any[Tuple(argmax(coalesce.(fm,-Inf)))...]
push!(fms,fm.*100);push!(fses,fse.*100) # change to percentage (*100)
for f in collect(keys(fa))
fd = findfirst(f.==keys(fa)) # facotr dimention
push!(ufm[f], fa[f][p[fd]]) # find the maximal level of each factor
end
end
# Plot
if plot
@manipulate for cell in 1:cellNum
heatmap(fms[cell])
end
@manipulate for cell in 1:cellNum
blankResp = cellMeanTrial[cell,condition[end,:i]] # Blank conditions
histogram(abs.(blankResp), nbins=10)
end
end
## Get the responsive cells
uresponsive=[];umodulative=[]
cti = reduce(append!,condition[1:end-1, :i],init=Int[]) # Drop blank, only choose stim conditions
for cell in 1:cellNum
# cell = 1
# display(cell)
condResp = cellMeanTrial[cell,cti]
push!(umodulative,ismodulative([DataFrame(Y=condResp) ctc[cti,:]], alpha=α, interact=true)) # Check molulativeness within stim conditions
blankResp = cellMeanTrial[cell,condition[end,:i]] # Choose blank conditions
# isresp = []
# for i in 1:condNum
# condResp = cellMeanTrial[cell,condition[i, :i]]
# push!(isresp, pvalue(UnequalVarianceTTest(blankResp,condResp))<α) # Check responsiveness between stim condtions and blank conditions
# end
condResp = cellMeanTrial[cell,condition[(condition.Dir .==ufm[:Dir][cell]) .& (condition.SpatialFreq .==ufm[:SpatialFreq][cell]), :i][1]]
push!(uresponsive, pvalue(UnequalVarianceTTest(blankResp,condResp))<α) # Check responsiveness between stim condtions and blank conditions
# push!(uresponsive,any(isresp))
# plotcondresponse(condResp ctc)
# foreach(i->savefig(joinpath(resultdir,"Unit_$(unitid[cell])_CondResponse$i")),[".png",".svg"])
end
visResp = uresponsive .| umodulative # Combine responsivenness and modulativeness as visual responsiveness
display(["uresponsive:", count(uresponsive)])
display(["umodulative:", count(umodulative)])
display(["Responsive cells:", count(visResp)])
result.visResp = visResp
result.responsive = uresponsive
result.modulative = umodulative
## Check which cell is significantly tuning by orientation or direction
oriAUC=[]; dirAUC=[];
for cell in 1:cellNum
# cell=1 # for test
# Get all trial Id of under maximal sf
# mcti = @where(condition, :SpatialFreq .== ufm[:SpatialFreq][cell])
mcti = condition[condition.SpatialFreq.==ufm[:SpatialFreq][cell], :]
blankResp = cellMeanTrial[cell,condition[end,:i]]
oridist=[];dirdist=[];blkoridist=[];blkdirdist=[];
for k =1:2
if k ==1
resp=[cellMeanTrial[cell,mcti.i[r][t]] for r in 1:nrow(mcti), t in 1:mcti.n[1]]
elseif k ==2
resp = Array{Float64}(undef, nrow(mcti), mcti[1,:n])
sample!(blankResp, resp; replace=true, ordered=false)
end
for j = 1:sampnum # Random sampling sampnum times
for i=1:size(resp,1)
shuffle!(@view resp[i,:])
end
resu= [factorresponsefeature(mcti[:Dir],resp[:,t],factor=:Dir,isfit=false) for t in 1:mcti.n[1]]
orivec = reduce(vcat,[resu[t].om for t in 1:mcti.n[1]])
orivecmean = mean(orivec, dims=1)[1] # final mean vec
oridistr = [real(orivec) imag(orivec)] * [real(orivecmean) imag(orivecmean)]' # Project each vector to the final vector, so now it is 1D distribution
# check significance of direction selective
oriorth = angle(mean(-orivec, dims=1)[1]) # angel orthogonal to mean ori vector
orivecdir = exp(im*oriorth/2) # dir axis vector (orthogonal to ori vector) in direction space
dirvec = reduce(vcat,[resu[t].dm for t in 1:mcti.n[1]])
dirdistr = [real(dirvec) imag(dirvec)] * [real(orivecdir) imag(orivecdir)]'
if k ==1
push!(oridist, oridistr);push!(dirdist, dirdistr);
elseif k==2
push!(blkoridist, oridistr); push!(blkdirdist, dirdistr);
end
end
end
blkoridist = reduce(vcat, blkoridist)
blkdirdist = reduce(vcat, blkdirdist)
oridist = reduce(vcat, oridist)
dirdist = reduce(vcat, dirdist)
oriauc=roccurve(blkoridist, oridist)
dirauc=roccurve(blkdirdist, dirdist)
push!(oriAUC,oriauc);push!(dirAUC,dirauc);
end
result.oriauc = oriAUC
result.dirauc = dirAUC
## Get the optimal factor level using Circular Variance for each cell
ufs = Dict(k=>[] for k in keys(fa))
for cell in 1:length(fms), f in collect(keys(fa))
p = Any[Tuple(argmax(coalesce.(fms[cell],-Inf)))...] # Replace missing with -Inf, then find the x-y coordinates of max value.
fd = findfirst(f.==keys(fa)) # facotr dimention
fdn = length(fa[f]) # dimention length/number of factor level
p[fd]=1:fdn # pick up a slice for plotting tuning curve
mseuc=DataFrame(m=fms[cell][p...],se=fses[cell][p...],u=fill(cellId[cell],fdn),ug=fill(parse(Int, recordPlane), fdn)) # make DataFrame for plotting
mseuc[f]=fa[f]
# The optimal dir, ori (based on circular variance) and sf (based on log2 fitting)
push!(ufs[f],factorresponsefeature(dropmissing(mseuc)[f],dropmissing(mseuc)[:m],factor=f, isfit=oriAUC[cell]>fitThres))
# plotcondresponse(dropmissing(mseuc),colors=[:black],projection=[],responseline=[], responsetype=:ResponseF)
# foreach(i->savefig(joinpath(resultdir,"Unit_$(unitid[u])_$(f)_Tuning$i")),[".png"]#,".svg"])
end
tempDF=DataFrame(ufs[:SpatialFreq])
result.osf = tempDF.osf # preferred sf from weighted average
result.maxsf = tempDF.maxsf
result.maxsfr = tempDF.maxr
result.fitsf =map(i->isempty(i) ? NaN : :psf in keys(i) ? i.psf : NaN,tempDF.fit) # preferred sf from fitting
result.sfhw =map(i->isempty(i) ? NaN : :sfhw in keys(i) ? i.sfhw : NaN,tempDF.fit)
result.sftype =map(i->isempty(i) ? NaN : :sftype in keys(i) ? i.sftype : NaN,tempDF.fit)
result.sfbw =map(i->isempty(i) ? NaN : :sfbw in keys(i) ? i.sfbw : NaN,tempDF.fit)
result.dog =map(i->isempty(i) ? NaN : :dog in keys(i) ? i.dog : NaN,tempDF.fit)
tempDF=DataFrame(ufs[:Dir])
result.cvdir = tempDF.od # preferred direction from cv
result.dircv = tempDF.dcv
result.fitdir =map(i->isempty(i) ? NaN : :pd in keys(i) ? i.pd : NaN,tempDF.fit) # preferred direction from fitting
result.dsi1 =map(i->isempty(i) ? NaN : :dsi1 in keys(i) ? i.dsi1 : NaN,tempDF.fit)
result.dsi2 =map(i->isempty(i) ? NaN : :dsi2 in keys(i) ? i.dsi2 : NaN,tempDF.fit)
result.dhw =map(i->isempty(i) ? NaN : :dhw in keys(i) ? i.dhw : NaN,tempDF.fit)
result.gvm =map(i->isempty(i) ? NaN : :gvm in keys(i) ? i.gvm : NaN,tempDF.fit)
result.cvori = tempDF.oo # preferred orientation from cv
result.oricv = tempDF.ocv
result.fitori =map(i->isempty(i) ? NaN : :po in keys(i) ? i.po : NaN,tempDF.fit) # preferred orientation from fitting
result.osi1 =map(i->isempty(i) ? NaN : :osi1 in keys(i) ? i.osi1 : NaN,tempDF.fit)
result.osi2 =map(i->isempty(i) ? NaN : :osi2 in keys(i) ? i.osi2 : NaN,tempDF.fit)
result.ohw =map(i->isempty(i) ? NaN : :ohw in keys(i) ? i.ohw : NaN,tempDF.fit)
result.vmn2 =map(i->isempty(i) ? NaN : :vmn2 in keys(i) ? i.vmn2 : NaN,tempDF.fit)
# Plot tuning curve of each factor of each cell
if plot
@manipulate for u in 1:length(fms), f in collect(keys(fa))
p = Any[Tuple(argmax(coalesce.(fms[u],-Inf)))...] # Replace missing with -Inf, then find the x-y coordinates of max value.
fd = findfirst(f.==keys(fa)) # facotr dimention
fdn = length(fa[f]) # dimention length/number of factor level
p[fd]=1:fdn # pick up a slice for plotting tuning curve
mseuc=DataFrame(m=fms[u][p...],se=fses[u][p...],u=fill(cellId[u],fdn),ug=fill(parse(Int, recordPlane), fdn)) # make DataFrame for plotting
mseuc[f]=fa[f]
plotcondresponse(dropmissing(mseuc),colors=[:black],projection=:polar,responseline=[], responsetype=:ResponseF)
end
end
#Save results
CSV.write(joinpath(resultFolder,join([subject,"_",siteId,"_result.csv"])), result)
save(joinpath(dataExportFolder,join([subject,"_",siteId,"_result.jld2"])), "result",result,"params", param)
end
end
function process_2P_dirsfcolor(files,param;uuid="",log=nothing,plot=false)
interpolatedData = haskey(param,:interpolatedData) ? param[:interpolatedData] : true # If you have multiplanes. True: use interpolated data; false: use uniterpolated data. Results are slightly different.
preOffset = haskey(param,:preOffset) ? param[:preOffset] : 0.1
responseOffset = haskey(param,:responseOffset) ? param[:responseOffset] : 0.05 # in sec
α = haskey(param,:α) ? param[:α] : 0.05 # p value
sampnum = haskey(param,:sampnum) ? param[:sampnum] : 100 # random sampling 100 times
fitThres = haskey(param,:fitThres) ? param[:fitThres] : 0.5
hueSpace = haskey(param,:hueSpace) ? param[:hueSpace] : "DKL" # Color space used? DKL or HSL
diraucThres = haskey(param,:diraucThres) ? param[:diraucThres] : 0.8 # if passed, calculate hue direction, otherwise calculate hue axis
oriaucThres = haskey(param,:oriaucThres) ? param[:oriaucThres] : 0.5
# Respthres = haskey(param,:Respthres) ? param[:Respthres] : 0.1 # Set a response threshold to filter out low response cells?
blankId = haskey(param,:blankId) ? param[:blankId] : 36 # Blank Id
excId = haskey(param,:excId) ? param[:excId] : [27,28] # Exclude some condition?
excId = vcat(excId,blankId)
# Expt info
dataset = prepare(files)
ex = dataset["ex"]
disk=string(param[:dataexportroot][1:2])
subject=uppercase(ex["Subject_ID"]);recordSession=uppercasefirst(ex["RecordSite"]);testId=ex["TestID"]
## Prepare data & result path
exptId = join(filter(!isempty,[recordSession[2:end], testId]),"_")
dataFolder = joinpath(disk,subject, "2P_data", recordSession, exptId)
## load expt, scanning parameters
envparam = ex["EnvParam"]
sbx = dataset["sbx"]["info"]
## Align Scan frames with stimulus
# Calculate the scan parameters
scanFreq = sbx["resfreq"]
lineNum = sbx["sz"][1]
if haskey(sbx, "recordsPerBuffer_bi")
scanMode = 2 # bidirectional scanning # if process Splitted data, =1
else
scanMode = 1 # unidirectional scanning
end
sbxfs = 1/(lineNum/scanFreq/scanMode) # frame rate
if (sbx["line"][1] == 0.00) | (sbx["frame"][1] == 0.00) # Sometimes there is extra pulse at start, need to remove it
stNum = 2
else
stNum = 1
end
trialOnLine = sbx["line"][stNum:2:end]
trialOnFrame = sbx["frame"][stNum:2:end] + round.(trialOnLine/lineNum) # if process splitted data use frame_split
trialOffLine = sbx["line"][stNum+1:2:end]
trialOffFrame = sbx["frame"][stNum+1:2:end] + round.(trialOffLine/lineNum) # if process splitted data use frame_split
# On/off frame indces of trials
trialEpoch = Int.(hcat(trialOnFrame, trialOffFrame))
# minTrialDur = minimum(trialOffFrame-trialOnFrame)
# histogram(trialOffFrame-trialOnFrame,nbins=20,title="Trial Duration(Set to $minTrialDur)")
# Transform Trials ==> Condition
ctc = DataFrame(ex["CondTestCond"])
trialNum = size(ctc,1)
conditionAll = condin(ctc)
# Remove extra conditions (only for AF4), and seperate blanks
others = (:ColorID, excId)
condi = .!in.(conditionAll[!,others[1]],[others[2]])
# factors = finalfactor(conditionAll)
conditionCond = conditionAll[condi,:]
condNum = size(conditionCond,1) # not including blanks
# Extract blank condition
blank = (:ColorID, blankId)
bi = in.(conditionAll[!,blank[1]],[blank[2]])
conditionBlank = conditionAll[bi,:]
# replace!(bctc.ColorID, 36 =>Inf)
# Change ColorID ot HueAngle if needed
# if hueSpace == "DKL"
ucid = sort(unique(conditionCond.ColorID))
hstep = 360/length(ucid)
conditionCond.ColorID = (conditionCond.ColorID.-minimum(ucid)).*hstep
conditionCond=rename(conditionCond, :ColorID => :HueAngle)
# end
# On/off frame indces of condations/stimuli
preStim = ex["PreICI"]; stim = ex["CondDur"]; postStim = ex["SufICI"]
trialOnTime = fill(0, trialNum)
condOfftime = preStim + stim
preEpoch = [0 preStim-preOffset]
condEpoch = [preStim+responseOffset condOfftime-responseOffset]
preFrame=epoch2sampleindex(preEpoch, sbxfs)
condFrame=epoch2sampleindex(condEpoch, sbxfs)
# preOn = fill(preFrame.start, trialNum)
# preOff = fill(preFrame.stop, trialNum)
# condOn = fill(condFrame.start, trialNum)
# condOff = fill(condFrame.stop, trialNum)
## Load data
if interpolatedData
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.signals"),dir=dataFolder,join=true)[1]
else
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9].signals"),dir=dataFolder,join=true)[1]
end
segment = prepare(segmentFile)
signal = prepare(signalFile)
sig = transpose(signal["sig"]) # 1st dimention is cell roi, 2nd is fluorescence trace
# spks = transpose(signal["spks"]) # 1st dimention is cell roi, 2nd is spike train
planeNum = size(segment["mask"],3) # how many planes
# planeNum = 1
if interpolatedData
planeStart = vcat(1, length.(segment["seg_ot"]["vert"]).+1)
end
## Use for loop process each plane seperately
for pn in 1:planeNum
# pn=1 # for test
# Initialize DataFrame for saving results
recordPlane = string("00",pn-1) # plane/depth, this notation only works for expt has less than 10 planes
siteId = join(filter(!isempty,[recordSession[2:end], testId, recordPlane]),"_")
dataExportFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "DataExport")
resultFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "Plots")
isdir(dataExportFolder) || mkpath(dataExportFolder)
isdir(resultFolder) || mkpath(resultFolder)
result = DataFrame()
if interpolatedData
cellRoi = segment["seg_ot"]["vert"][pn]
else
cellRoi = segment["vert"]
end
cellNum = length(cellRoi)
display("plane: $pn")
display("Cell Number: $cellNum")
cellId = collect(range(1, step=1, stop=cellNum)) # Currently, the cellID is the row index of signal
if interpolatedData
rawF = sig[planeStart[pn]:planeStart[pn]+cellNum-1,:]
# spike = spks[planeStart[pn]:planeStart[pn]+cellNum-1,:]
else
rawF = sig
# spike = spks
end
result.py = 0:cellNum-1
result.ani = fill(subject, cellNum)
result.dataId = fill(siteId, cellNum)
result.cellId = 1:cellNum
## Plot dF/F traces of all trials for all cells
# Cut raw fluorescence traces according to trial on/off time and calculate dF/F
cellTimeTrial = sbxsubrm(rawF,trialEpoch,cellId;fun=dFoF(preFrame)) # cellID x timeCourse x Trials
# Mean response within stim time
cellMeanTrial = dropdims(mean(cellTimeTrial[:,condFrame,:], dims=2), dims=2) # cellID x Trials
# Plot
if plot
@manipulate for cell in 1:cellNum
plotanalog(transpose(cellTimeTrial[cell,:,:]), fs=sbxfs, timeline=condEpoch.-preStim, xunit=:s, ystep=1,cunit=:p, color=:fire,xext=preStim)
end
end
## Average over repeats, and put each cell's response in factor space (hue-dir-sf...), and find the maximal level of each factor
factors = finalfactor(conditionCond)
fa = OrderedDict(f=>unique(conditionCond[f]) for f in factors) # factor levels, the last one of each factor maybe blank(Inf)
fms=[];fses=[]; # factor mean spac, factor sem space, mean and sem of each condition of each cell
ufm = Dict(k=>[] for k in keys(fa)) # maxi factor level of each cell
for cell in 1:cellNum
# cell=1
mseuc = condresponse(cellMeanTrial[cell,:],conditionCond) # condtion response, averaged over repeats
fm,fse,_ = factorresponse(mseuc) # put condition response into factor space
p = Any[Tuple(argmax(coalesce.(fm,-Inf)))...]
push!(fms,fm.*100);push!(fses,fse.*100) # change to percentage (*100)
for f in collect(keys(fa))
fd = findfirst(f.==keys(fa)) # facotr dimention
push!(ufm[f], fa[f][p[fd]]) # find the maximal level of each factor
end
end
# Plot
if plot
# @manipulate for cell in 1:cellNum
# heatmap(fms[cell])
# end
@manipulate for cell in 1:cellNum
# blankResp = cellMeanTrial[cell,vcat(conditionBlank[:,:i]...)] # Blank conditions
# histogram(abs.(blankResp), nbins=10)
condResp = cellMeanTrial[cell,vcat(conditionCond[:,:i]...)] # Stim conditions
histogram(abs.(condResp), nbins=10)
end
end
## Get the responsive cells & blank response
mseub=[];uresponsive=[];umodulative=[]; #uhighResp=[];
cti = reduce(append!,conditionCond[:, :i],init=Int[]) # Choose hue condition, exclude blanks and others
for cell in 1:cellNum
# cell=1
condResp = cellMeanTrial[cell,cti] #
push!(umodulative,ismodulative([DataFrame(Y=condResp) ctc[cti,:]], alpha=α, interact=true)) # Check molulativeness within stim conditions
blankResp = cellMeanTrial[cell,vcat(conditionBlank[:,:i]...)] # Choose blank conditions
mseuc = condresponse(cellMeanTrial[cell,:],[vcat(conditionBlank[:,:i]...)]) # Get the mean & sem of blank response for a cell
push!(mseub, mseuc)
# isresp = []
# for i in 1:condNum
# condResp = cellMeanTrial[cell,condition[i, :i]]
# push!(isresp, pvalue(UnequalVarianceTTest(blankResp,condResp))<α)
# end
# condResp = cellMeanTrial[cell,condition[(condition.Dir .==ufm[:Dir][cell]) .& (condition.SpatialFreq .==ufm[:SpatialFreq][cell]), :i][1]]
condResp = cellMeanTrial[cell,conditionCond[(conditionCond.HueAngle .==ufm[:HueAngle][cell]).& (conditionCond.Dir .==ufm[:Dir][cell]) .& (conditionCond.SpatialFreq .==ufm[:SpatialFreq][cell]), :i][1]]
push!(uresponsive, pvalue(UnequalVarianceTTest(blankResp,condResp))<α) # Check responsiveness between stim condtions and blank conditions
# push!(uhighResp, mean(condResp,dims=1)[1]>Respthres)
# plotcondresponse(condResp cctc)
# foreach(i->savefig(joinpath(resultdir,"Unit_$(unitid[cell])_CondResponse$i")),[".png",".svg"])
end
visResp = uresponsive .| umodulative # Combine responsivenness and modulativeness as visual responsiveness
display(["uresponsive:", count(uresponsive)])
# display(["uhighResp:", count(uhighResp)])
display(["umodulative:", count(umodulative)])
display(["Responsive cells:", count(visResp)])
result.visResp = visResp
result.responsive = uresponsive
# result.uhighResp = uhighResp
result.modulative = umodulative
## Check which cell is significantly tuning by orientation or direction
# oripvalue=[];orivec=[];dirpvalue=[];dirvec=[];
# hueaxpvalue=[];huedirpvalue=[];opratioc=[];dpratioc=[];
oriAUC=[]; dirAUC=[]; hueaxAUC=[]; huedirAUC=[];
for cell in 1:cellNum
# cell=1 # for test
# Get all trial Id of under maximal sf
# mcti = @where(condition, :SpatialFreq .== ufm[:SpatialFreq][cell])
mcti = conditionCond[(conditionCond.HueAngle.==ufm[:HueAngle][cell]).&(conditionCond.SpatialFreq.==ufm[:SpatialFreq][cell]), :]
mbti = conditionBlank[conditionBlank.SpatialFreq.==ufm[:SpatialFreq][cell], :]
blankResp = [cellMeanTrial[cell,conditionBlank.i[r][t]] for r in 1:nrow(conditionBlank), t in 1:conditionBlank.n[1]]
# resp = [cellMeanTrial[cell,mcti.i[r][t]] for r in 1:nrow(mcti), t in 1:mcti.n[1]]
# resu= [factorresponsefeature(mcti[:dir],resp[:,t],factor=:dir,isfit=false) for t in 1:mcti.n[1]]
# orivec = reduce(vcat,[resu[t].oov for t in 1:mcti.n[1]])
# pori=[];pdir=[];pbori=[];pbdir=[];
oridist=[];dirdist=[];blkoridist=[];blkdirdist=[];
for k =1:2
if k ==1
resp = [cellMeanTrial[cell,mcti.i[r][t]] for r in 1:nrow(mcti), t in 1:mcti[1,:n]]
elseif k==2
resp = Array{Float64}(undef, nrow(mcti), ncol(mcti))
sample!(blankResp, resp; replace=true, ordered=false)
end
for j = 1:sampnum # Random sampling sampnum times
for i=1:size(resp,1)
shuffle!(@view resp[i,:])
end
resu= [factorresponsefeature(mcti[:Dir],resp[:,t],factor=:Dir, isfit=false) for t in 1:mcti[1,:n]]
orivec = reduce(vcat,[resu[t].om for t in 1:mcti[1,:n]])
orivecmean = mean(orivec, dims=1)[1] # final mean vec
oridistr = [real(orivec) imag(orivec)] * [real(orivecmean) imag(orivecmean)]' # Project each vector to the final vector, so now it is 1D distribution
# orip = hotellingt2test([real(orivec) imag(orivec)],[0 0],0.05)
# push!(orivec, orivectemp)
# check significance of direction selective
oriorth = angle(mean(-orivec, dims=1)[1]) # angel orthogonal to mean ori vector
orivecdir = exp(im*oriorth/2) # dir axis vector (orthogonal to ori vector) in direction space
dirvec = reduce(vcat,[resu[t].dm for t in 1:mcti[1,:n]])
dirdistr = [real(dirvec) imag(dirvec)] * [real(orivecdir) imag(orivecdir)]'
# dirp = dirsigtest(orivecdir, dirvec)
if k ==1
# push!(pori, orip);push!(pdir, dirp);
push!(oridist, oridistr);push!(dirdist, dirdistr);
elseif k==2
# push!(pbori, orip);push!(pbdir, dirp);
push!(blkoridist, oridistr); push!(blkdirdist, dirdistr);
end
end
end
# yso,nso,wso,iso=histrv(float.(pori),0,1,nbins=20)
# ysd,nsd,wsd,isd=histrv(float.(pdir),0,1,nbins=20)
# opfi=mean(yso[findmax(nso)[2]])
# dpfi=mean(ysd[findmax(nsd)[2]])
# ysob,nsob,wsob,isob=histrv(float.(pbori),0,1,nbins=20)
# ysdb,nsdb,wsdb,isdb=histrv(float.(pbdir),0,1,nbins=20)
# opratio=sum(nsob[map(i-> mean(wsob[i])<opfi, range(1,size(wsob,1)))])/sum(nsob)
# dpratio=sum(nsdb[map(i-> mean(wsdb[i])<dpfi, range(1,size(wsdb,1)))])/sum(nsdb)
# push!(oripvalue,opfi); push!(dirpvalue,dpfi);
# push!(opratioc,opratio); push!(dpratioc,dpratio);
blkoridist = reduce(vcat, blkoridist)
blkdirdist = reduce(vcat, blkdirdist)
oridist = reduce(vcat, oridist)
dirdist = reduce(vcat, dirdist)
oriauc=roccurve(blkoridist, oridist)
dirauc=roccurve(blkdirdist, dirdist)
push!(oriAUC,oriauc);push!(dirAUC,dirauc);
if dirauc >= diraucThres #dirpvalue[cell] < α # direction selective
mcti = conditionCond[(conditionCond.Dir.==ufm[:Dir][cell]).&(conditionCond.SpatialFreq.==ufm[:SpatialFreq][cell]), :]
elseif (dirauc < diraucThres) .& (oriauc > oriaucThres) #(dirpvalue[cell] > α) .& (oripvalue[cell] < α) # no direction selective, but has orientation selective
mcti = conditionCond[((conditionCond.Dir.==ufm[:Dir][cell]) .| (conditionCond.Dir.==mod.(ufm[:Dir][cell]+180,360))).&(conditionCond.SpatialFreq.==ufm[:SpatialFreq][cell]), :]
mcti = by(mcti, :HueAngle, n=:n=>sum, i=:i=>d->[reduce(hcat,d')])
else # neither direction nor orientation selective
mcti = conditionCond[conditionCond.SpatialFreq.==ufm[:SpatialFreq][cell], :]
mcti = by(mcti, :HueAngle, n=:n=>sum, i=:i=>d->[reduce(hcat,d')])
end
# phueax=[];phuedir=[];pbdir=[];
hueaxdist=[];huedirdist=[];blkhueaxdist=[];blkhuedirdist=[];
for k =1:2
if k ==1 # hue condition
resp = [cellMeanTrial[cell,mcti.i[r][t]] for r in 1:nrow(mcti), t in 1:mcti[1,:n]]
elseif k==2 # blank condition
resp = Array{Float64}(undef, nrow(mcti), mcti[1,:n])
sample!(blankResp, resp; replace=true, ordered=false)
end
for j = 1:sampnum # Random sampling sampnum times
for i=1:size(resp,1)
shuffle!(@view resp[i,:])
end
resu= [factorresponsefeature(mcti[:HueAngle],resp[:,t],factor=:HueAngle,isfit=false) for t in 1:mcti[1,:n]]
huevec = reduce(vcat,[resu[t].ham for t in 1:mcti.n[1]]) # hue axis
# hueaxp = hotellingt2test([real(huevec) imag(huevec)],[0 0],0.05)
huevecmean = mean(huevec, dims=1)[1] # final mean vec
hueaxdistr = [real(huevec) imag(huevec)] * [real(huevecmean) imag(huevecmean)]' # Project each vector to the final vector, so now it is 1D distribution
huevec = reduce(vcat,[resu[t].hm for t in 1:mcti.n[1]]) # hue direction
# huedirp = hotellingt2test([real(huevec) imag(huevec)],[0 0],0.05)
huevecmean = mean(huevec, dims=1)[1] # final mean vec
huedirdistr = [real(huevec) imag(huevec)] * [real(huevecmean) imag(huevecmean)]' # Project each vector to the final vector, so now it is 1D distribution
# push!(phueax,hueaxp)
# push!(phuedir,huedirp)
if k ==1
push!(hueaxdist, hueaxdistr);push!(huedirdist, huedirdistr);
elseif k==2
push!(blkhueaxdist, hueaxdistr);push!(blkhuedirdist, huedirdistr);
end
end
end
# ysh,nsh,wsh,ish=histrv(float.(phueax),0,1,nbins=20)
# push!(hueaxpvalue,mean(ysh[findmax(nsh)[2]]))
# ysh,nsh,wsh,ish=histrv(float.(phuedir),0,1,nbins=20)
# push!(huedirpvalue,mean(ysh[findmax(nsh)[2]]))
blkhueaxdist = reduce(vcat, blkhueaxdist)
blkhuedirdist = reduce(vcat, blkhuedirdist)
hueaxdist = reduce(vcat, hueaxdist)
huedirdist = reduce(vcat, huedirdist)
hueaxauc=roccurve(blkhueaxdist, hueaxdist)
huedirauc=roccurve(blkhuedirdist, huedirdist)
push!(hueaxAUC,hueaxauc);push!(huedirAUC,huedirauc);
end
# result.orip = oripvalue
# result.opratio=opratioc
# result.dirp = dirpvalue
# result.dpratio=dpratioc
# result.hueaxp = hueaxpvalue
# result.huedirp = huedirpvalue
result.hueoriauc = oriAUC
result.huedirauc = dirAUC
result.hueaxauc = hueaxAUC
result.huediauc = huedirAUC
## Get the optimal factor level using Circular Variance for each cell
ufs = Dict(k=>[] for k in keys(fa))
for cell in 1:length(fms), f in collect(keys(fa))
p = Any[Tuple(argmax(coalesce.(fms[cell],-Inf)))...] # Replace missing with -Inf, then find the x-y coordinates of max value.
fd = findfirst(f.==keys(fa)) # facotr dimention
fdn = length(fa[f]) # dimention length/number of factor level
p[fd]=1:fdn # pick up a slice for plotting tuning curve
mseuc=DataFrame(m=fms[cell][p...],se=fses[cell][p...],u=fill(cellId[cell],fdn),ug=fill(parse(Int, recordPlane), fdn)) # make DataFrame for plotting
mseuc[f]=fa[f]
# The optimal dir, ori (based on circular variance) and sf (based on log2 fitting)
push!(ufs[f],factorresponsefeature(dropmissing(mseuc)[f],dropmissing(mseuc)[:m],factor=f, isfit=max(oriAUC[cell], dirAUC[cell], hueaxAUC[cell], huedirAUC[cell])>fitThres))
# plotcondresponse(dropmissing(mseuc),colors=[:black],projection=[],responseline=[], responsetype=:ResponseF)
# foreach(i->savefig(joinpath(resultdir,"Unit_$(unitid[u])_$(f)_Tuning$i")),[".png"]#,".svg"])
end
tempDF=DataFrame(ufs[:SpatialFreq])
result.hueosf = tempDF.osf # preferred sf from weighted average
result.huemaxsf = tempDF.maxsf
result.huemaxsfr = tempDF.maxr
result.huefitsf =map(i->isempty(i) ? NaN : :psf in keys(i) ? i.psf : NaN,tempDF.fit) # preferred sf from fitting
result.huesfhw =map(i->isempty(i) ? NaN : :sfhw in keys(i) ? i.sfhw : NaN,tempDF.fit)
result.huesftype =map(i->isempty(i) ? NaN : :sftype in keys(i) ? i.sftype : NaN,tempDF.fit)
result.huesfbw =map(i->isempty(i) ? NaN : :sfbw in keys(i) ? i.sfbw : NaN,tempDF.fit)
result.huedog =map(i->isempty(i) ? NaN : :dog in keys(i) ? i.dog : NaN,tempDF.fit)
tempDF=DataFrame(ufs[:Dir])
result.cvhuedir = tempDF.od # preferred direction from cv
result.huedircv = tempDF.dcv
result.fithuedir =map(i->isempty(i) ? NaN : :pd in keys(i) ? i.pd : NaN,tempDF.fit) # preferred direction from fitting
result.huedsi1 =map(i->isempty(i) ? NaN : :dsi1 in keys(i) ? i.dsi1 : NaN,tempDF.fit)
result.huedsi2 =map(i->isempty(i) ? NaN : :dsi2 in keys(i) ? i.dsi2 : NaN,tempDF.fit)
result.huedhw =map(i->isempty(i) ? NaN : :dhw in keys(i) ? i.dhw : NaN,tempDF.fit)
result.huegvm =map(i->isempty(i) ? NaN : :gvm in keys(i) ? i.gvm : NaN,tempDF.fit)
result.cvhueori = tempDF.oo # cv
result.hueoricv = tempDF.ocv
result.fithueori =map(i->isempty(i) ? NaN : :po in keys(i) ? i.po : NaN,tempDF.fit) # preferred orientation from fitting
result.hueosi1 =map(i->isempty(i) ? NaN : :osi1 in keys(i) ? i.osi1 : NaN,tempDF.fit)
result.hueosi2 =map(i->isempty(i) ? NaN : :osi2 in keys(i) ? i.osi2 : NaN,tempDF.fit)
result.hueohw =map(i->isempty(i) ? NaN : :ohw in keys(i) ? i.ohw : NaN,tempDF.fit)
result.huevmn2 =map(i->isempty(i) ? NaN : :vmn2 in keys(i) ? i.vmn2 : NaN,tempDF.fit)
tempDF=DataFrame(ufs[:HueAngle])
result.cvhueax = tempDF.oha # cv
result.hueaxcv = tempDF.hacv
result.fithueax =map(i->isempty(i) ? NaN : :pha in keys(i) ? i.pha : NaN,tempDF.fit) # fitting
result.hueaxsi1 =map(i->isempty(i) ? NaN : :hasi1 in keys(i) ? i.hasi1 : NaN,tempDF.fit)
result.hueaxsi2 =map(i->isempty(i) ? NaN : :hasi2 in keys(i) ? i.hasi2 : NaN,tempDF.fit)
result.hueaxhw =map(i->isempty(i) ? NaN : :hahw in keys(i) ? i.hahw : NaN,tempDF.fit)
result.hueaxvmn2 =map(i->isempty(i) ? NaN : :vmn2 in keys(i) ? i.vmn2 : NaN,tempDF.fit)
result.cvhuedi = tempDF.oh # cv
result.huedicv = tempDF.hcv
result.fithuedi =map(i->isempty(i) ? NaN : :ph in keys(i) ? i.ph : NaN,tempDF.fit) # fitting
result.huedisi1 =map(i->isempty(i) ? NaN : :hsi1 in keys(i) ? i.hsi1 : NaN,tempDF.fit)
result.huedisi2 =map(i->isempty(i) ? NaN : :hsi2 in keys(i) ? i.hsi2 : NaN,tempDF.fit)
result.huedihw =map(i->isempty(i) ? NaN : :hhw in keys(i) ? i.hhw : NaN,tempDF.fit)
result.huedigvm =map(i->isempty(i) ? NaN : :gvm in keys(i) ? i.gvm : NaN,tempDF.fit)
result.maxhue = tempDF.maxh
result.maxhueresp = tempDF.maxr
# Plot tuning curve of each factor of each cell
# plot = true
if plot
@manipulate for u in 1:length(fms), f in collect(keys(fa))
p = Any[Tuple(argmax(coalesce.(fms[u],-Inf)))...] # Replace missing with -Inf, then find the x-y coordinates of max value.
fd = findfirst(f.==keys(fa)) # facotr dimention
fdn = length(fa[f]) # dimention length/number of factor level
p[fd]=1:fdn # pick up a slice for plotting tuning curve
mseuc=DataFrame(m=fms[u][p...],se=fses[u][p...],u=fill(cellId[u],fdn),ug=fill(parse(Int, recordPlane), fdn)) # make DataFrame for plotting
mseuc[f]=fa[f]
plotcondresponse(dropmissing(mseuc),colors=[:black],projection=:polar,responseline=[], responsetype=:ResponseF)
end
end
#Save results
CSV.write(joinpath(resultFolder,join([subject,"_",siteId,"_result.csv"])), result)
save(joinpath(dataExportFolder,join([subject,"_",siteId,"_result.jld2"])), "result",result,"params", param)
save(joinpath(dataExportFolder,join([subject,"_",siteId,"_tuning.jld2"])), "tuning",tempDF)
end
end
function process_2P_hartleySTA(files,param;uuid="",log=nothing,plot=false)
# files=tests.files[3] # for testing
interpolatedData = haskey(param,:interpolatedData) ? param[:interpolatedData] : true # If you have multiplanes. True: use interpolated data; false: use uniterpolated data. Results are slightly different.
hartelyBlkId = haskey(param,:hartelyBlkId) ? param[:hartelyBlkId] : 5641
delays = param[:delays]
stanorm = param[:stanorm]
stawhiten = param[:stawhiten]
hartleyscale = param[:hartleyscale]
print(collect(delays))
# Expt info
dataset = prepare(files)
ex = dataset["ex"];
disk=string(param[:dataexportroot][1:2])
subject=uppercase(ex["Subject_ID"]);recordSession=uppercasefirst(ex["RecordSite"]);testId=ex["TestID"]
## Prepare data & result path
exptId = join(filter(!isempty,[recordSession[2:end], testId]),"_")
dataFolder = joinpath(disk,subject, "2P_data", recordSession, exptId)
## load expt, scanning parameters
envparam = ex["EnvParam"]
coneType = getparam(envparam,"colorspace")
sbx = dataset["sbx"]["info"]
sbxft = ex["frameTimeSer"] # time series of sbx frame in whole recording
# Condition Tests
envparam = ex["EnvParam"];preicidur = ex["PreICI"];conddur = ex["CondDur"];suficidur = ex["SufICI"]
condon = ex["CondTest"]["CondOn"]
condoff = ex["CondTest"]["CondOff"]
condidx = ex["CondTest"]["CondIndex"]
# condtable = DataFrame(ex["Cond"])
condtable = DataFrame(ex["raw"]["log"]["randlog_T1"]["domains"]["Cond"])
rename!(condtable, [:oridom, :kx, :ky,:bwdom,:colordom])
# find out blanks and unique conditions
blkidx = condidx .>= hartelyBlkId # blanks start from 5641
cidx = .!blkidx
condidx2 = condidx.*cidx + blkidx.* hartelyBlkId # all blanks now have the same id 5641
## Load data
if interpolatedData
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*_merged.signals"),dir=dataFolder,join=true)[1]
else
segmentFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9]*.segment"),dir=dataFolder,join=true)[1]
signalFile=matchfile(Regex("[A-Za-z0-9]*[A-Za-z0-9].signals"),dir=dataFolder,join=true)[1]
end
segment = prepare(segmentFile)
signal = prepare(signalFile)
# sig = transpose(signal["sig"]) # 1st dimention is cell roi, 2nd is fluorescence trace
spks = transpose(signal["spks"]) # 1st dimention is cell roi, 2nd is spike train
##
# Prepare Imageset
downsample = haskey(param,:downsample) ? param[:downsample] : 2
sigma = haskey(param,:sigma) ? param[:sigma] : 1.5
# bgRGB = [getparam(envparam,"backgroundR"),getparam(envparam,"backgroundG"),getparam(envparam,"backgroundB")]
bgcolor = RGBA([0.5,0.5,0.5,1]...)
coneType = string(getparam(envparam,"colorspace"))
masktype = getparam(envparam,"mask_type")
maskradius = getparam(envparam,"mask_radius")
masksigma = 1#getparam(envparam,"Sigma")
hartleyscale = haskey(param,:hartleyscale) ? param[:hartleyscale] : 1
hartleynorm = haskey(param, :hartleynorm) ? param[:hartleynorm] : false
xsize = getparam(envparam,"x_size")
ysize = getparam(envparam,"y_size")
stisize = xsize
ppd = haskey(param,:ppd) ? param[:ppd] : 52
ppd = ppd/downsample
imagesetname = "Hartley_stisize$(stisize)_hartleyscalescale$(hartleyscale)_ppd$(ppd)"
maskradius = maskradius /stisize + 0.03
if !haskey(param,imagesetname)
imageset = Dict{Any,Any}(:image =>map(i->GrayA.(hartley(kx=i.kx,ky=i.ky,bw=i.bwdom,stisize=stisize, ppd=ppd,norm=hartleynorm,scale=hartleyscale)),eachrow(condtable)))
# imageset = Dict{Any,Any}(:image =>map(i->GrayA.(grating(θ=deg2rad(i.Ori),sf=i.SpatialFreq,phase=rem(i.SpatialPhase+1,1)+0.02,stisize=stisize,ppd=23)),eachrow(condtable)))
# imageset = Dict{Symbol,Any}(:pyramid => map(i->gaussian_pyramid(i, nscale-1, downsample, sigma),imageset))
imageset[:sizepx] = size(imageset[:image][1])
param[imagesetname] = imageset
end
# Prepare Image Stimuli
imageset = param[imagesetname]
bgcolor = oftype(imageset[:image][1][1],bgcolor)
imagestimuliname = "bgcolor$(bgcolor)_masktype$(masktype)_maskradius$(maskradius)_masksigma$(masksigma)" # bgcolor and mask define a unique masking on an image set
if !haskey(imageset,imagestimuliname)
imagestimuli = Dict{Any,Any}(:stimuli => map(i->alphablend.(alphamask(i,radius=maskradius,sigma=masksigma,masktype=masktype)[1],[bgcolor]),imageset[:image]))
imagestimuli[:unmaskindex] = alphamask(imageset[:image][1],radius=maskradius,sigma=masksigma,masktype=masktype)[2]
imageset[imagestimuliname] = imagestimuli
end
imagestimuli = imageset[imagestimuliname]
## Load data
planeNum = size(segment["mask"],3) # how many planes
if interpolatedData
planeStart = vcat(1, length.(segment["seg_ot"]["vert"]).+1)
end
## Use for loop process each plane seperately
for pn in 1:planeNum
# pn=1 # for test
display("plane: $pn")
# Initialize DataFrame for saving results
recordPlane = string("00",pn-1) # plane/depth, this notation only works for expt has less than 10 planes
siteId = join(filter(!isempty,[recordSession[2:end], testId, recordPlane]),"_")
dataExportFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "DataExport")
resultFolder = joinpath(disk,subject, "2P_analysis", recordSession, siteId, "Plots")
isdir(dataExportFolder) || mkpath(dataExportFolder)
isdir(resultFolder) || mkpath(resultFolder)
if interpolatedData
cellRoi = segment["seg_ot"]["vert"][pn]
else
cellRoi = segment["vert"]
end
cellNum = length(cellRoi)
display("Cell Number: $cellNum")
if interpolatedData
# rawF = sig[planeStart[pn]:planeStart[pn]+cellNum-1,:]
spike = spks[planeStart[pn]:planeStart[pn]+cellNum-1,:]
else
# rawF = sig
spike = spks
end
imagesize = imageset[:sizepx]
xi = imagestimuli[:unmaskindex]
# estimate RF using STA
if :STA in param[:model]
uci = unique(condidx2)
ucii = map(i->findall(condidx2.==i),deleteat!(uci,findall(isequal(hartelyBlkId),uci))) # find the repeats of each unique condition
ubii = map(i->findall(condidx2.==i), [hartelyBlkId])
uy = Array{Float64}(undef,cellNum,length(delays),length(ucii))
ucy = Array{Float64}(undef,cellNum,length(delays),length(ucii))
uby = Array{Float64}(undef,cellNum,length(delays),length(ubii))
usta = Array{Float64}(undef,cellNum,length(delays),length(xi))
cx = Array{Float64}(undef,length(ucii),length(xi))
foreach(i->cx[i,:]=gray.(imagestimuli[:stimuli][uci[i]][xi]),1:size(cx,1))
for d in eachindex(delays)
display("Processing delay: $d")
y,num,wind,idx = epochspiketrain(sbxft,condon.+delays[d], condoff.+delays[d],isminzero=false,ismaxzero=false,shift=0,israte=false)
spk=zeros(size(spike,1),length(idx))
for i =1:length(idx)
spkepo = @view spike[:,idx[i][1]:idx[i][end]]
spk[:,i]= mean(spkepo, dims=2)
end
for cell in 1:cellNum
# display(cell)
cy = map(i->mean(spk[cell,:][i]),ucii) # response to grating
bly = map(i->mean(spk[cell,:][i]),ubii) # response to blank, baseline
ry = cy.-bly # remove baseline
csta = sta(cx,ry,norm=stanorm,whiten=stawhiten) # calculate sta
ucy[cell,d,:]=cy
uby[cell,d,:]=bly
uy[cell,d,:]=ry
usta[cell,d,:]=csta
if plot
r = [extrema(csta)...]
title = "Unit_$(cell)_STA_$(delays[d])"
p = plotsta(csta,sizepx=imagesize,sizedeg=stisize,ppd=ppd,index=xi,title=title,r=r)
foreach(i->save(joinpath(resultFolder,"$title$i"),p),[".png"])
end
end
end
save(joinpath(dataExportFolder,join([subject,"_",siteId,"_",coneType,"_sta.jld2"])),"imagesize",imagesize,"cx",cx,"xi",xi,"xcond",condtable[uci,:],"uy",uy,"ucy",ucy,"usta",usta,"uby",uby,"delays",delays,"maskradius",maskradius,"stisize",stisize,"color",coneType)
end
# estimate RF using ePPR
if :ePPR in param[:model]
ucy = Array{Float64}(undef,cellNum,length(condidx))
ueppr = Dict()
xscale=255
bg = xscale*gray(bgcolor)
# roicenter = Int64.(imagesize./2)
# roiradius = Int64.(floor.(imagesize.*(maskradius)))[1]
# roisize = (roiradius*2+1,roiradius*2+1)
cx = Array{Float64}(undef,length(condidx),prod(imagesize))
# foreach(i->cx[i,:]=gray.(imagestimuli[:stimuli][condidx[i]][map(i->(-roiradius:roiradius).+i,roicenter)...]),1:size(cx,1))
foreach(i->cx[i,:]=gray.(imagestimuli[:stimuli][condidx[i]]),1:size(cx,1))
# for d in eachindex(delays)
d = 10
display("Processing delay: $d")
y,num,wind,idx = epochspiketrain(sbxft,condon.+delays[d], condoff.+delays[d],isminzero=false,ismaxzero=false,shift=0,israte=false)
spk=zeros(size(spike,1),length(idx))
for i =1:length(idx)
spkepo = @view spike[:,idx[i][1]:idx[i][end]]
spk[:,i]= mean(spkepo, dims=2)
end
for cell in 1:cellNum
# cell = 346
display(cell)
cy = spk[cell,:] # response to grating
ucy[cell,:] = cy
# unitresultdir = joinpath(resultFolder,"Unit_$(cell)_ePPR_$(delays[d])")
# rm(unitresultdir,force=true,recursive=true)
log = ePPRLog(debug=false,plot=false,dir=resultFolder)
hp = ePPRHyperParams(imagesize...,xindex=xi,blankcolor=bg,ndelay=param[:eppr_ndelay],nft=param[:eppr_nft],lambda=param[:eppr_lambda])
model,models = epprhypercv(cx.*xscale,cy,hp,log)
ueppr[cell] = Dict()
ueppr[cell]["model"] = model
ueppr[cell]["models"] = models
if plot && !isnothing(model)
log(plotmodel(model,hp,color=:bwr,width=400,height=400),file="Unit_$(cell)_Model_Final (λ=$(hp.lambda)).png")
end
# clean!(model)
end
# end
save(joinpath(dataExportFolder,join([subject,"_",siteId,"_",coneType,"_eppr.jld2"])),"imagesize",imagesize,"cx",cx,"ucy",ucy,
"ueppr",ueppr,"delay",delays[d],"maskradius",maskradius,"stisize",stisize,"color",coneType)
end
end
end
function process_2P_hartleyFourier(files,param;uuid="",log=nothing,plot=false)
interpolatedData = haskey(param,:interpolatedData) ? param[:interpolatedData] : true # If you have multiplanes. True: use interpolated data; false: use uniterpolated data. Results are slightly different.
hartelyBlkId = haskey(param,:hartelyBlkId) ? param[:hartelyBlkId] : 5641
delays = param[:delays]
ntau = length(collect(delays))
print(collect(delays))
# Expt info
dataset = prepare(files)
ex = dataset["ex"]
disk=string(param[:dataexportroot][1:2])
subject=uppercase(ex["Subject_ID"]);recordSession=uppercasefirst(ex["RecordSite"]);testId=ex["TestID"]
## Prepare data & result path
exptId = join(filter(!isempty,[recordSession[2:end], testId]),"_")
dataFolder = joinpath(disk,subject, "2P_data", recordSession, exptId)
## load expt, scanning parameters
envparam = ex["EnvParam"]
coneType = getparam(envparam,"colorspace")
szhtly_visangle = envparam["x_size"] # deg
maxSF = envparam["max_sf"] # cyc/deg
sbx = dataset["sbx"]["info"]