-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathMEApipeline.m
More file actions
1552 lines (1295 loc) · 68.7 KB
/
MEApipeline.m
File metadata and controls
1552 lines (1295 loc) · 68.7 KB
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
function MEApipeline(InputParamsFilePath)
% Process data from MEA recordings of 2D and 3D neuronal cultures
% Created: RC Feord, May 2021
% Authors: T Sit, RC Feord, AWE Dunn, J Chabros and other members of the Synaptic and Network Development (SAND) Group
%% USER INPUT REQUIRED FOR THIS SECTION
% In this section all modifiable parameters of the analysis are defined.
% No subsequent section requires user input.
% Please refer to the documentation for guidance on parameter choice here:
% https://analysis-pipeline.readthedocs.io/en/latest/pipeline-steps.html#pipeline-settings
clearvars -except InputParamsFilePath
close all
% Change to MEANAP folder
MEANAPscriptPath = which('MEApipeline.m');
MEANAPfolder = fileparts(MEANAPscriptPath);
cd(MEANAPfolder)
restoredefaultpath
% Directories
HomeDir = '[INPUT_REQUIRED]'; % Where the MEA-NAP (MEA Network Analysis Pipeline) code is located
Params.outputDataFolder = ''; % Where to save the output data, leave as '' if same as HomeDir
Params.outputDataFolderName = ''; % Name of the folder to save the output data
rawData = '[INPUT_REQUIRED]'; % path to raw data .mat files
Params.priorAnalysisPath = ['']; % path to prev analysis, leave as [''] if no prior anlaysis
spikeDetectedData = ''; % path to spike-detected data, leave as '' if no previously detected spike data
% Input and output filetype
spreadsheet_file_type = 'csv'; % 'csv' or 'excel'
spreadsheet_filename = '[INPUT_REQUIRED].csv';
sheet = 1; % specify excel sheet
xlRange = 'A2:C7'; % specify range on the sheet (e.g., 'A2:C7' would analyse the first 6 files)
csvRange = [2, Inf]; % read the data in the range [StartRow EndRow], e.g. [2 Inf] means start reading data from row 2
Params.output_spreadsheet_file_type = 'csv'; % .xlsx or .csv
% Analysis step settings
Params.priorAnalysisDate = ''; % prior analysis date in format given in output data folder e.g., '27Sep2021'
Params.priorAnalysis = 0; % use previously analysed data? 1 = yes, 0 = no
Params.startAnalysisStep = 1; % if Params.priorAnalysis=0, default is to start with spike detection
Params.optionalStepsToRun = {''}; % include 'generateCSV' to generate csv for rawData folder
% include 'Stats' to look at feature
% correlation and classification across groups
% include 'combineDIVplots' to combine plots across DIVs
% Spike detection settings
detectSpikes = 0; % run spike detection? % 1 = yes, 0 = no
Params.runSpikeCheckOnPrevSpikeData = 0; % whether to run spike detection check without spike detection
Params.fs = 25000; % Sampling frequency you selected when acquiring data, e.g., MCS: 25000, Axion: 12500;
Params.dSampF = 25000; % down sampling factor for spike detection check, e.g., can set the same as the sampling frequency
Params.potentialDifferenceUnit = 'uV'; % Unit for voltage signal, e.g., MCS: uV, Axion: V
Params.channelLayout = 'MCS60'; % 'MCS60' (for MEA2100), 'Axion64' (for 6-well plates), or 'MCS60old' (for MEA6100)
Params.thresholds = {'3', '4', '5'}; % standard deviation multiplier threshold(s), eg. {'2.5', '3.5', '4.5'}
Params.wnameList = {'bior1.5', 'bior1.3', 'db2'}; % wavelet methods to use e.g., {'bior1.5', 'bior1.3', 'mea'};
Params.costList = -0.12;
Params.SpikesMethod = 'bior1p5'; % wavelet methods, e.g., 'bior1p5', or 'mergedAll', or 'mergedWavelet'
% Functional connectivity inference settings
Params.FuncConLagval = [10, 25, 50]; % set the different lag values (in ms), default to [10, 15, 25]
Params.TruncRec = 0; % truncate recording? 1 = yes, 0 = no
Params.TruncLength = 120; % length of truncated recordings (in seconds)
Params.adjMtype = 'weighted'; % 'weighted' or 'binary'
% Connectivity matrix thresholding settings
Params.ProbThreshRepNum = 200; % probabilistic thresholding number of repeats (recommend at least 180)
Params.ProbThreshTail = 0.05; % probabilistic thresholding percentile threshold
Params.ProbThreshPlotChecks = 1; % randomly sample recordings to plot probabilistic thresholding check, 1 = yes, 0 = no
Params.ProbThreshPlotChecksN = 5; % number of random checks to plot
% Node cartography settings
Params.autoSetCartographyBoudariesPerLag = 1; % whether to fit separate boundaries per lag value
Params.cartographyLagVal = [10, 25, 50]; % lag value (ms) to use to calculate PC-Z distribution (only applies if Params.autoSetCartographyBoudariesPerLag = 0)
Params.autoSetCartographyBoundaries = 1; % whether to automatically determine bounds for hubs or use custom ones
% Statistics and machine learning settings
Params.classificationTarget = 'AgeDiv'; % which property of the recordings to classify
Params.classification_models = {'linearSVM', 'kNN', 'fforwardNN', 'decisionTree', 'LDA'};
Params.regression_models = {'svmRegressor', 'regressionTree', 'ridgeRegression', 'fforwardNN'};
% Plot settings
Params.figExt = {'.png', '.svg'}; % supported options are '.fig', '.png', and '.svg'
Params.fullSVG = 1; % whether to insist svg even with plots with large number of elements
Params.showOneFig = 1; % otherwise, 0 = pipeline shows plots as it runs, 1: supress plots
% Re-computation of metrics
Params.recomputeMetrics = 0;
Params.metricsToRecompute = {}; % {} or {'all'} or {'metricNames'}
%% GUI / Tutorial mode settings
Params.guiMode = 1; % GUI mode? 1 = on, 0 = off
if (Params.guiMode == 1) && ~exist('InputParamsFilePath', 'var')
runPipelineApp
if isvalid(app)
spikeDetectedData = Params.spikeDetectedData;
else
return
end
else
Params.spreadSheetFileName = spreadsheet_filename;
end
%% Check if ParamsFilePath is specified
if exist('InputParamsFilePath', 'var')
ParamDataFile = load(InputParamsFilePath);
Params = ParamDataFile.Params;
Params.guiMode = 1;
HomeDir = Params.HomeDir;
spreadsheet_filename = Params.spreadSheetFileName;
rawData = Params.rawData;
detectSpikes = Params.detectSpikes;
option = 'list';
Params.spikeMethodColors = ...
[ 0 0.4470 0.7410; ...
0.8500 0.3250 0.0980; ...
0.9290 0.6940 0.1250; ...
0.4940 0.1840 0.5560; ...
0.4660 0.6740 0.1880; ...
0.3010 0.7450 0.9330; ...
0.6350 0.0780 0.1840];
end
%% Paths
% add all relevant folders to path
cd(HomeDir)
addpath(genpath('Functions'))
addpath('Images')
%% END OF USER REQUIRED INPUT SECTION
% The rest of the MEApipeline.m runs automatically. Do not change after this line
% unless you are an expert user.
% Define output folder names
formatOut = 'ddmmmyyyy';
Params.Date = datestr(now,formatOut);
clear formatOut
if Params.guiMode ~= 1
AdvancedSettings
end
if Params.runSpikeCheckOnPrevSpikeData
fprintf(['You specified to run spike detection check on previously extracted spikes, \n', ...
'so I will skip over the spike detection step \n'])
detectSpikes = 0;
end
Params.detectSpikes = detectSpikes; % As a record of option selection
% Allow starting from a subset of steps
if length(Params.startAnalysisStep) > 1
Params.startAnalysisSubStep = Params.startAnalysisStep(2);
Params.startAnalysisStep = str2num(Params.startAnalysisStep(1));
else
if isstr(Params.startAnalysisStep)
Params.startAnalysisStep = str2num(Params.startAnalysisStep);
end
Params.startAnalysisSubStep = 'ALL';
end
%% Optional step : generate csv
if any(strcmp(Params.optionalStepsToRun,'generateCSV'))
fprintf('Generating CSV with given rawData folder \n')
mat_file_list = dir(fullfile(rawData, '*mat'));
name_list = {mat_file_list.name}';
name_without_ext = {};
div = {};
for filenum = 1:length(name_list)
name_without_ext{filenum} = name_list{filenum}(1:end-4);
div{filenum} = name_list{filenum}((end-5):end-4);
end
name = name_without_ext';
div = div';
name_table = table([name, div]);
writetable(name_table, spreadsheet_filename)
end
%% setup - additional setup
setUpSpreadSheet % import metadata from spreadsheet
[~,Params.GrpNm] = findgroups(ExpGrp);
[~,Params.DivNm] = findgroups(ExpDIV);
% create output data folder if doesn't exist
CreateOutputFolders(Params.outputDataFolder, Params.GrpNm, Params)
% Set up one figure handle to save all the figures
oneFigureHandle = NaN;
oneFigureHandle = checkOneFigureHandle(Params, oneFigureHandle);
% plot electrode layout
plotElectrodeLayout(Params.outputDataFolder, Params, oneFigureHandle)
% export parameters to .mat and .csv file
outputDataWDatePath = fullfile(Params.outputDataFolder, Params.outputDataFolderName);
ParamsTableSavePath = fullfile(outputDataWDatePath, strcat('Parameters_',Params.outputDataFolderName,'.csv'));
writetable(struct2table(Params,'AsArray',true), ParamsTableSavePath)
ParamsMatSavePath = fullfile(outputDataWDatePath, strcat('Parameters_',Params.outputDataFolderName,'.mat'));
save(ParamsMatSavePath, 'Params');
% save metadata to ExperimentMatFiles
metaDataSaveFolder = fullfile(outputDataWDatePath, 'ExperimentMatFiles');
for ExN = 1:length(ExpName)
Info.FN = ExpName(ExN);
Info.DIV = num2cell(ExpDIV(ExN));
Info.Grp = ExpGrp(ExN);
InfoSavePath = fullfile(metaDataSaveFolder, strcat(char(Info.FN),'_',Params.outputDataFolderName,'.mat'));
% Append cell type information, currently assumes to be contained
% in folder where the 'suite2p' folder is located
if Params.suite2pMode == 1
fileFolder = fullfile(Params.rawData, Info.FN{1});
folderCsvFiles = dir(fullfile(fileFolder, '*csv'));
if length(folderCsvFiles) == 1
cellTypeTable = readtable(fullfile(fileFolder, folderCsvFiles(1).name));
Info.CellTypes = cellTypeTable;
end
end
if ~isfile(InfoSavePath)
save(InfoSavePath,'Info')
else
save(InfoSavePath,'Info', '-append')
end
end
% create a random sample for checking the probabilistic thresholding
if Params.ProbThreshPlotChecks == 1
Params.randRepCheckExN = randi([1 length(ExpName)],1,Params.ProbThreshPlotChecksN);
Params.randRepCheckLag = Params.FuncConLagval(randi([1 length(Params.FuncConLagval)],1,Params.ProbThreshPlotChecksN));
Params.randRepCheckP = [Params.randRepCheckExN;Params.randRepCheckLag];
Params.randRepCheckExN2p = zeros(1, length(ExpName));
Params.randRepCheckExN2p(1:Params.ProbThreshPlotChecksN) = 1;
Params.randRepCheckExN2p = Params.randRepCheckExN2p(randperm(length(Params.randRepCheckExN2p)));
Params.randRepCheckLag2p = Params.FuncConLagval(randi([1 length(Params.FuncConLagval)],1,length(ExpName)));
end
% Copy spreadsheet to output folder
copyfile(Params.spreadSheetFileName, outputDataWDatePath);
%% Step 1 - spike detection
if ((Params.priorAnalysis == 0) || (Params.runSpikeCheckOnPrevSpikeData)) && (Params.startAnalysisStep == 1)
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; ...
'Running step 1 of MEA-NAP: spike detection'];
end
if Params.timeProcesses
step1Start = tic;
end
if (detectSpikes == 1) || (Params.runSpikeCheckOnPrevSpikeData)
if iscell(rawData)
for pathIdx = 1:length(rawData)
addpath(rawData{pathIdx});
end
else
addpath(rawData)
end
else
addpath(spikeDetectedData)
end
savePath = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, ...
'1_SpikeDetection', '1A_SpikeDetectedData');
% Run spike detection
if detectSpikes == 1
if Params.guiMode == 1
batchDetectSpikes(rawData, savePath, option, ExpName, Params, app);
else
batchDetectSpikes(rawData, savePath, option, ExpName, Params);
end
end
% Stimulus detection
if Params.stimulationMode == 1
batchDetectStim(ExpName, Params, app);
% Edit spike data based on the stimulation time
batchProcessSpikesFromStim(ExpName, Params);
end
% Specify where ExperimentMatFiles are stored
experimentMatFileFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
% Plot spike detection results
for ExN = 1:length(ExpName)
if Params.runSpikeCheckOnPrevSpikeData
spikeDetectedDataOutputFolder = spikeDetectedData;
else
spikeDetectedDataOutputFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '1_SpikeDetection', '1A_SpikeDetectedData');
end
spikeFilePath = fullfile(spikeDetectedDataOutputFolder, strcat(char(ExpName(ExN)),'_spikes.mat'));
load(spikeFilePath,'spikeTimes','spikeDetectionResult', 'channels', 'spikeWaveforms')
experimentMatFilePath = fullfile(experimentMatFileFolder, ...
strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat'));
load(experimentMatFilePath,'Info')
spikeDetectionCheckGrpFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '1_SpikeDetection', '1B_SpikeDetectionChecks', char(Info.Grp));
FN = char(Info.FN);
spikeDetectionCheckFNFolder = fullfile(spikeDetectionCheckGrpFolder, FN);
if ~isfolder(spikeDetectionCheckFNFolder)
mkdir(spikeDetectionCheckFNFolder)
end
plotSpikeDetectionChecks(spikeTimes, spikeDetectionResult, ...
spikeWaveforms, Info, Params, spikeDetectionCheckFNFolder, oneFigureHandle)
% Check whether there are no spikes at all in the recording
checkIfAnySpikes(spikeTimes, ExpName{ExN});
end
if Params.timeProcesses
step1Duration = toc(step1Start);
end
end
%% Step 2 - neuronal activity
if Params.startAnalysisStep < 3
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; ...
'Running step 2 of MEA-NAP: neuronal activity'];
else
fprintf('Running step 2 of MEA-NAP: neuronal activity \n')
end
if Params.timeProcesses
step2Start = tic;
end
% Suite2p data processing
if Params.suite2pMode == 1
spikeFreqMax2p = 0;
experimentMatFolderPath = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
for ExN = 1:length(ExpName)
experimentMatFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
experimentMatFpath = fullfile(experimentMatFolderPath, experimentMatFname);
load(experimentMatFpath, 'Info')
suite2pFolder = fullfile(Params.rawData, char(ExpName(ExN)), 'suite2p', 'plane0');
Params.ExN = ExN;
[adjMs, coords, channels, F, denoisedF, spks, spikeTimes, fs, Params, activityProperties] = ...
suite2pToAdjm(suite2pFolder, Params, Info, oneFigureHandle);
% Plot original and denoised traces
stepFolder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, ...
'2_NeuronalActivity', '2A_IndividualNeuronalAnalysis');
groupFolder = fullfile(stepFolder, Info.Grp{1});
if ~isfolder(groupFolder)
mkdir(groupFolder)
end
figFolder = fullfile(groupFolder, Info.FN{1});
if ~isfolder(figFolder)
mkdir(figFolder)
end
Info.duration_s = size(spks, 1) / fs;
plot2ptraces(suite2pFolder, Params, Info.FN{1}, fs, figFolder, oneFigureHandle);
resamplingRate = 1; % resample spike matrix for raster plotting
twopActivityMatrix = get2pActivityMatrix(F, denoisedF, spks, spikeTimes, resamplingRate, Info, Params);
spikeFreqMax2p = max([spikeFreqMax2p, max(twopActivityMatrix)]);
ExpMatFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
infoFnFname = strcat(char(Info.FN),'_',Params.outputDataFolderName,'.mat');
infoFnFilePath = fullfile(ExpMatFolder, infoFnFname);
Info.channels = channels;
varsToSave = {'Info', 'Params', 'coords', 'channels', ...
'adjMs', 'spikeTimes', 'F', 'denoisedF', 'spks', 'fs', ...
'activityProperties'};
save(infoFnFilePath, varsToSave{:}, '-append')
end
end
% NEURONAL ACTIVITY: INITIALISE MAX VALUES FOR PLOTTING
maxValStruct = struct(); % get the maximum value of various metrics for scaling
valsTogetMax = {'FR', ...
'channelBurstRate', ...
'channelBurstDur', ...
'channelFracSpikesInBursts', ...
'channelISIwithinBurst', ...
'channeISIoutsideBurst', ...
};
for fieldNameIdx = 1:length(valsTogetMax)
fieldName = valsTogetMax{fieldNameIdx};
maxValStruct.(fieldName) = [];
end
% NEURONAL ACTIVITY: ANALYSIS STEP
for ExN = 1:length(ExpName)
experimentMatFolderPath = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
experimentMatFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
experimentMatFpath = fullfile(experimentMatFolderPath, experimentMatFname);
load(experimentMatFpath, 'Info')
if Params.suite2pMode == 0
if Params.priorAnalysis==1 && Params.startAnalysisStep==2
spikeDetectedDataFolder = spikeDetectedData;
else
if detectSpikes == 1
spikeDetectedDataFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '1_SpikeDetection', ...
'1A_SpikeDetectedData');
else
spikeDetectedDataFolder = spikeDetectedData;
end
end
channelLayout = Params.channelLayoutPerRecording{ExN};
electrodesToGround = Params.electrodesToGroundPerRecording{ExN};
[spikeMatrix,spikeTimes,Params,Info] = formatSpikeTimes(...
char(Info.FN), Params, Info, spikeDetectedDataFolder, channelLayout, electrodesToGround);
% load(experimentMatFpath,'Info','Params','spikeTimes','spikeMatrix');
% get firing rates and burst characterisation
Ephys = firingRatesBursts(spikeMatrix,Params,Info);
for fieldNameIdx = 1:length(valsTogetMax)
fieldName = valsTogetMax{fieldNameIdx};
maxValStruct.(fieldName) = [maxValStruct.(fieldName) Ephys.(fieldName)];
end
infoFnFilePath = fullfile(experimentMatFolderPath, ...
strcat(char(Info.FN),'_',Params.outputDataFolderName,'.mat'));
save(infoFnFilePath,'Info','Params','spikeTimes', 'spikeMatrix', 'Ephys', '-v7.3')
else
expData = load(experimentMatFpath);
activityStats = calTwopActivityStats(expData, Params);
infoFnFilePath = fullfile(experimentMatFolderPath, ...
strcat(char(expData.Info.FN),'_',Params.outputDataFolderName,'.mat'));
save(infoFnFilePath, 'Params', 'activityStats', '-append')
end
end
% Get max value from struct
for fieldNameIdx = 1:length(valsTogetMax)
fieldName = valsTogetMax{fieldNameIdx};
maxVal = max(maxValStruct.(fieldName));
if isnan(maxVal)
maxVal = 0;
end
maxValStruct.(fieldName) = maxVal;
end
% NEURONAL ACTIVITY : PLOTTING STEP
% Set up one figure handle to save all the figures
if ~exist('oneFigureHandle', 'var')
oneFigureHandle = NaN;
end
oneFigureHandle = checkOneFigureHandle(Params, oneFigureHandle);
for ExN = 1:length(ExpName)
experimentMatFolderPath = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
experimentMatFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
experimentMatFpath = fullfile(experimentMatFolderPath, experimentMatFname);
load(experimentMatFpath,'Info','Params', 'spikeTimes', 'spikeMatrix', 'Ephys');
idvNeuronalAnalysisGrpFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '2_NeuronalActivity', ...
'2A_IndividualNeuronalAnalysis', char(Info.Grp));
if ~isfolder(idvNeuronalAnalysisGrpFolder)
mkdir(idvNeuronalAnalysisGrpFolder)
end
idvNeuronalAnalysisFNFolder = fullfile(idvNeuronalAnalysisGrpFolder, char(Info.FN));
if ~isfolder(idvNeuronalAnalysisFNFolder)
mkdir(idvNeuronalAnalysisFNFolder)
end
if Params.suite2pMode == 0
% generate and save raster plot
rasterPlot(char(Info.FN),spikeMatrix,Params, maxValStruct.FR, ...
idvNeuronalAnalysisFNFolder, oneFigureHandle);
% electrode heat maps
coords = Params.coords{ExN};
electrodeHeatMaps(char(Info.FN), spikeMatrix, Info.channels, ...
maxValStruct.FR, Params, coords, idvNeuronalAnalysisFNFolder, oneFigureHandle, Params.electrodesToGroundPerRecording(ExN))
% Plot bursts metrics
metricVarsToPlot = {'channelBurstRate', ...
'channelBurstDur', ...
'channelFracSpikesInBursts', ...
'channelISIwithinBurst', ...
'channeISIoutsideBurst', ...
};
metricLabels = {'Average burst rate (per minute)', ...
'Average burst duration (ms)', ...
'Fraction spikes in bursts', ...
'ISI within bursts (ms)', ...
'ISI outside bursts (ms)'};
figNames = {'3_BurstRate_heatmap', ...
'4_BurstDur_heatmap', ...
'5_FractSpikesInBursts_heatmap',...
'6_ISIwithinBurst_heatmap', ...
'7_ISIoutsideBurst_heatmap'};
cmapToUse = {viridis, ...
flip(viridis), ...
viridis, ...
flip(viridis), ...
flip(viridis), ...
};
useLogScale = [0, 1, 0, 0, 1];
for metricIdx = 1:length(metricVarsToPlot)
metricVarname = metricVarsToPlot{metricIdx};
% plot burst heatmap
plotNodeHeatmap(char(Info.FN), Ephys, Info.channels, ...
maxValStruct.(metricVarname), Params, coords, metricVarname, metricLabels{metricIdx}, ...
cmapToUse{metricIdx}, useLogScale(metricIdx), idvNeuronalAnalysisFNFolder, figNames{metricIdx}, ...
oneFigureHandle, []);
end
% Plot network burst detection
plotNetworkBursts(spikeTimes, Ephys, Info, Params, idvNeuronalAnalysisFNFolder, oneFigureHandle)
% half violin plots
firingRateElectrodeDistribution(char(Info.FN), Ephys, Params, ...
Info, idvNeuronalAnalysisFNFolder, oneFigureHandle)
clear spikeTimes spikeMatrix
else
expData = load(experimentMatFpath);
% half violin plots
firingRateElectrodeDistribution(char(expData.Info.FN), activityStats, Params, ...
expData.Info, idvNeuronalAnalysisFNFolder, oneFigureHandle)
end
end
% Raster plot for suite2p data
if Params.suite2pMode == 1
for ExN = 1:length(ExpName)
expData = loadExpData(char(ExpName(ExN)), Params, 0);
resamplingRate = 1; % resample spike matrix for raster plotting
twopActivityMatrix = get2pActivityMatrix(expData.F, expData.denoisedF, ...
expData.spks, expData.spikeTimes, resamplingRate, expData.Info, Params);
stepFolder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, ...
'2_NeuronalActivity', '2A_IndividualNeuronalAnalysis');
groupFolder = fullfile(stepFolder, expData.Info.Grp{1});
figFolder = fullfile(groupFolder, expData.Info.FN{1});
Params.fs = fs;
rasterPlot(expData.Info.FN{1}, twopActivityMatrix, Params, spikeFreqMax2p, figFolder, oneFigureHandle)
end
end
% create combined plots across groups/ages
PlotEphysStats(ExpName,Params,HomeDir, oneFigureHandle)
saveEphysStats(ExpName, Params)
cd(HomeDir)
% Stimulation neuronal activity analysis
if Params.stimulationMode == 1
for ExN = 1:length(ExpName)
% spike data
spikeDataFname = strcat(char(ExpName(ExN)),'_spikes','.mat');
spikeDataFpath = fullfile(spikeDetectedDataFolder, spikeDataFname);
% experiment mat file
experimentMatFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
experimentMatFpath = fullfile(experimentMatFolderPath, experimentMatFname);
expData = load(experimentMatFpath);
% get fig folder
stepFolder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, ...
'2_NeuronalActivity', '2A_IndividualNeuronalAnalysis');
groupFolder = fullfile(stepFolder, expData.Info.Grp{1});
figFolder = fullfile(groupFolder, expData.Info.FN{1});
spikeData = load(spikeDataFpath);
if strcmp(Params.SpikesMethod,'merged') || strcmp(Params.SpikesMethod,'mergedAll')
spikeTimes = spikeData.spikeTimes;
for uu = 1:length(spikeTimes)
[spikeTimes{uu}.('mergedAll'),~, ~] = mergeSpikes(spikeTimes{uu}, 'all');
end
for channel = 1:length(spikeData.channels)
channelAmpData = spikeData.spikeAmps{channel};
channelSpikeTimes = spikeData.spikeTimes{channel};
detectionMethods = fieldnames(channelAmpData);
channelAllSpikeAmps = [];
channelAllSpikeTimes = [];
for methodIdx = 1:length(detectionMethods)
method = detectionMethods{methodIdx};
channelAllSpikeAmps = [channelAllSpikeAmps; ...
channelAmpData.(method)];
channelAllSpikeTimes = [channelAllSpikeTimes; ...
channelSpikeTimes.(method)];
end
[~, originalLocations] = ismember(spikeTimes{channel}.mergedAll, channelAllSpikeTimes);
mergedSpikeAmps = channelAllSpikeAmps(originalLocations);
spikeData.spikeAmps{channel}.mergedAll = mergedSpikeAmps;
end
spikeData.spikeTimes = spikeTimes;
end
stimActivityAnalysis(spikeData, Params, expData.Info, ...
figFolder, oneFigureHandle);
end
end
if Params.stimulationMode == 1
% Save stimulation analysis data to CSV files
saveEphysStatsStim(ExpName, Params);
end
if Params.timeProcesses
step2Duration = toc(step2Start);
end
end
%% Step 3 - functional connectivity, generate adjacency matrices
if Params.priorAnalysis==0 || Params.priorAnalysis==1 && Params.startAnalysisStep<4
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; ...
'Running step 3 of MEA-NAP: generating adjacency matrices'];
else
fprintf('Running step 3 of MEA-NAP: generating adjacency matrices \n')
end
if Params.timeProcesses
step3Start = tic;
end
% Set up one figure handle to save all the figures
if ~exist('oneFigureHandle', 'var')
oneFigureHandle = NaN;
end
oneFigureHandle = checkOneFigureHandle(Params, oneFigureHandle);
if Params.suite2pMode == 0 % suite2p adjM is created in step 2
for ExN = 1:length(ExpName)
% Load spike / previous data
if Params.priorAnalysis==1 && Params.startAnalysisStep==3
priorAnalysisExpMatFolder = fullfile(Params.priorAnalysisPath, 'ExperimentMatFiles');
spikeDataFname = strcat(char(ExpName(ExN)),'_',Params.priorAnalysisSubFolderName, '.mat');
spikeDataFpath = fullfile(priorAnalysisExpMatFolder, spikeDataFname);
if isfile(spikeDataFpath)
load(spikeDataFpath, 'spikeTimes', 'Ephys', 'Info')
else
% look for spike data in spike data folder
spikeDataFpath = fullfile(Params.spikeDetectedData, ...
strcat([char(ExpName(ExN)) '_spikes.mat']));
load(spikeDataFpath, 'spikeTimes', 'Info')
end
else
ExpMatFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
spikeDataFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
spikeDataFpath = fullfile(ExpMatFolder, spikeDataFname);
load(spikeDataFpath, 'Info', 'Params', 'spikeTimes', 'Ephys')
end
if strcmp(Params.verboseLevel, 'High')
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; ...
sprintf('Generating adjacency matrix for: %s', char(Info.FN))];
else
fprintf(sprintf('Generating adjacency matrix for: %s \n', char(Info.FN)))
end
end
% ground electrodes
electrodesToGround = Params.electrodesToGroundPerRecording{ExN};
spikeTimes = groundSpikeTimes(spikeTimes, Info.channels, ...
electrodesToGround, Params.electrodesToGroundPerRecordingUseName);
% calculate adjacecny matrix from spike times
adjMs = generateAdjMs(spikeTimes, ExN, Params, Info, oneFigureHandle);
ExpMatFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
infoFnFname = strcat(char(Info.FN),'_',Params.outputDataFolderName,'.mat');
infoFnFilePath = fullfile(ExpMatFolder, infoFnFname);
varsToSave = {'Info', 'Params', 'spikeTimes', 'Ephys', 'adjMs'};
save(infoFnFilePath, varsToSave{:}, '-append')
end
end
if Params.timeProcesses
step3Duration = toc(step3Start);
end
end
%% Step 4 - network activity
if Params.priorAnalysis==0 || Params.priorAnalysis==1 && Params.startAnalysisStep<=4
step4startMessage = 'Running step 4 of MEA-NAP: Analyzing network activity';
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; step4startMessage];
else
fprintf([step4startMessage '\n'])
end
if Params.timeProcesses
step4Start = tic;
end
% Set up one figure handle to save all the figures
if ~exist('oneFigureHandle', 'var')
oneFigureHandle = NaN;
end
oneFigureHandle = checkOneFigureHandle(Params, oneFigureHandle);
% Set up node cartography metrics
nodeCartographyMetrics = {'NCpn1', 'NCpn2', 'NCpn3', 'NCpn4', 'NCpn5','NCpn6'};
% Step 4 Analysis step
if strcmp(Params.startAnalysisSubStep, 'ALL')
for ExN = 1:length(ExpName)
if Params.priorAnalysis==1 && Params.startAnalysisStep==4
priorAnalysisExpMatFolder = fullfile(Params.priorAnalysisPath, 'ExperimentMatFiles');
spikeDataFname = strcat(char(ExpName(ExN)),'_',Params.priorAnalysisSubFolderName,'.mat');
spikeDataFpath = fullfile(priorAnalysisExpMatFolder, spikeDataFname);
expMatData = load(spikeDataFpath);
if Params.suite2pMode == 0
load(spikeDataFpath, 'spikeTimes', 'Ephys','adjMs','Info')
else
load(spikeDataFpath, 'spks', 'fs', 'adjMs','Info')
end
else
ExpMatFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
spikeDataFname = strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat');
spikeDataFpath = fullfile(ExpMatFolder, spikeDataFname);
expMatData = load(spikeDataFpath);
if Params.suite2pMode == 0
load(spikeDataFpath, 'Info', 'Params', 'spikeTimes', 'Ephys','adjMs')
else
load(spikeDataFpath, 'Info', 'Params', 'spks', 'fs', 'adjMs')
end
end
if strcmp(Params.verboseLevel, 'High')
if Params.guiMode == 1
app.MEANAPStatusTextArea.Value = [app.MEANAPStatusTextArea.Value; ...
sprintf('Running network analysis on: %s', char(Info.FN))];
else
fprintf(sprintf('Running network analysis on: %s', char(Info.FN)))
end
end
idvNetworkAnalysisGrpFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '4_NetworkActivity', ...
'4A_IndividualNetworkAnalysis', char(Info.Grp));
idvNetworkAnalysisFNFolder = fullfile(idvNetworkAnalysisGrpFolder, char(Info.FN));
if ~isfolder(idvNetworkAnalysisFNFolder)
mkdir(idvNetworkAnalysisFNFolder)
end
if Params.priorAnalysis == 1
if isempty(spikeDetectedData)
spikeDetectedDataFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '1_SpikeDetection', ...
'1A_SpikeDetectedData');
else
spikeDetectedDataFolder = spikeDetectedData;
end
else
spikeDetectedDataFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, '1_SpikeDetection', ...
'1A_SpikeDetectedData');
end
channelLayout = Params.channelLayoutPerRecording{ExN};
electrodesToGround = Params.electrodesToGroundPerRecording{ExN};
if Params.suite2pMode
if strcmp(Params.twopActivity, 'denoised F')
activityMatrix = expMatData.denoisedF;
Params.fs = expMatData.fs;
spikeTimes = [];
elseif strcmp(Params.twopActivity, 'spks')
activityMatrix = expMatData.spks;
Params.fs = expMatData.fs;
spikeTimes = [];
elseif strcmp(Params.twopActivity, 'peaks')
Params.fs = expMatData.fs;
[activityMatrix, spikeTimes, Params, Info] = formatSpikeTimes(char(Info.FN), ...
Params, Info, spikeDetectedDataFolder, expMatData, electrodesToGround);
end
else
[activityMatrix, spikeTimes, Params, Info] = formatSpikeTimes(char(Info.FN), ...
Params, Info, spikeDetectedDataFolder, channelLayout, electrodesToGround);
end
Params.networkActivityFolder = idvNetworkAnalysisFNFolder;
if isfield(expMatData, 'coords')
coords = expMatData.coords;
channels = expMatData.channels;
else
coords = Params.coords{ExN};
channels = Params.channels{ExN};
end
NetMet = ExtractNetMet(adjMs, activityMatrix, ...
Params.FuncConLagval, Info, Params, coords, channels, oneFigureHandle);
ExpMatFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
infoFnFname = strcat(char(Info.FN),'_',Params.outputDataFolderName,'.mat');
infoFnFilePath = fullfile(ExpMatFolder, infoFnFname);
varsToSave = {'Info', 'Params', 'adjMs', 'NetMet', 'coords', 'channels'};
if Params.suite2pMode == 1
varsToSave{end+1} = 'fs';
end
if exist('spikeTimes', 'var')
varsToSave{end+1} = 'spikeTimes';
end
if exist('Ephys', 'var')
varsToSave{end+1} = 'Ephys';
end
save(infoFnFilePath, varsToSave{:}, '-append')
clear adjMs
end
% save and export network data to spreadsheet
saveNetMet(ExpName, Params)
% Set up one figure handle to save all the figures
if ~exist('oneFigureHandle', 'var')
oneFigureHandle = NaN;
end
oneFigureHandle = checkOneFigureHandle(Params, oneFigureHandle);
% Aggregate all files and run density analysis to determine boundaries
% for node cartography
usePriorNetMet = 0; % set to 0 by default
if length(intersect(Params.netMetToCal, nodeCartographyMetrics)) >= 1
if Params.autoSetCartographyBoundaries
if Params.priorAnalysis==1 && usePriorNetMet
experimentMatFileFolder = fullfile(Params.priorAnalysisPath, 'ExperimentMatFiles');
% cd(fullfile(Params.priorAnalysisPath, 'ExperimentMatFiles'));
fig_folder = fullfile(Params.priorAnalysisPath, ...
'4_NetworkActivity', '4B_GroupComparisons', '7_DensityLandscape');
else
experimentMatFileFolder = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
% cd(fullfile(strcat('OutputData', Params.Date), 'ExperimentMatFiles'));
fig_folder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, ...
'4_NetworkActivity', '4B_GroupComparisons', '7_DensityLandscape');
end
if ~isfolder(fig_folder)
mkdir(fig_folder)
end
add_fig_info = '';
if Params.autoSetCartographyBoudariesPerLag
for lag_val = Params.FuncConLagval
[hubBoundaryWMdDeg, periPartCoef, proHubpartCoef, nonHubconnectorPartCoef, connectorHubPartCoef] = ...
TrialLandscapeDensity(Params, ExpName, experimentMatFileFolder, fig_folder, add_fig_info, lag_val, oneFigureHandle);
if isnan(hubBoundaryWMdDeg)
hubBoundaryWMdDeg = Params.hubBoundaryWMdDeg;
periPartCoef = Params.periPartCoef;
proHubpartCoef = Params.proHubpartCoef;
nonHubconnectorPartCoef = Params.nonHubconnectorPartCoef;
connectorHubPartCoef = Params.connectorHubPartCoef;
end
Params.(strcat('hubBoundaryWMdDeg', sprintf('_%.fmsLag', lag_val))) = hubBoundaryWMdDeg;
Params.(strcat('periPartCoef', sprintf('_%.fmsLag', lag_val))) = periPartCoef;
Params.(strcat('proHubpartCoef', sprintf('_%.fmsLag', lag_val))) = proHubpartCoef;
Params.(strcat('nonHubconnectorPartCoef', sprintf('_%.fmsLag', lag_val))) = nonHubconnectorPartCoef;
Params.(strcat('connectorHubPartCoef', sprintf('_%.fmsLag', lag_val))) = connectorHubPartCoef;
end
else
lagValIdx = 1;
lag_val = Params.FuncConLagval;
[hubBoundaryWMdDeg, periPartCoef, proHubpartCoef, nonHubconnectorPartCoef, connectorHubPartCoef] = ...
TrialLandscapeDensity(Params, ExpName, experimentMatFileFolder, fig_folder, add_fig_info, lag_val(lagValIdx), oneFigureHandle);
Params.hubBoundaryWMdDeg = hubBoundaryWMdDeg;
Params.periPartCoef = periPartCoef;
Params.proHubpartCoef = proHubpartCoef;
Params.nonHubconnectorPartCoef = nonHubconnectorPartCoef;
Params.connectorHubPartCoef = connectorHubPartCoef;
end
% save the newly set boundaries to the Params struct
experimentMatFileFolderToSaveTo = fullfile(Params.outputDataFolder, ...
Params.outputDataFolderName, 'ExperimentMatFiles');
for nFile = 1:length(ExpName)
FN = ExpName{nFile};
FNPath = fullfile(experimentMatFileFolderToSaveTo, [FN '_' Params.outputDataFolderName '.mat']);
save(FNPath, 'Params', '-append')
end
end
% Run through each file to do node cartography analysis
for ExN = 1:length(ExpName)
if Params.priorAnalysis==1 && Params.startAnalysisStep==4 && usePriorNetMet
experimentMatFileFolder = fullfile(Params.priorAnalysisPath, 'ExperimentMatFiles');
experimentMatFilePath = fullfile(experimentMatFileFolder, strcat(char(ExpName(ExN)),'_',Params.priorAnalysisSubFolderName,'.mat'));
expData = load(experimentMatFilePath);
else
experimentMatFileFolder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, 'ExperimentMatFiles');
experimentMatFilePath = fullfile(experimentMatFileFolder, strcat(char(ExpName(ExN)),'_',Params.outputDataFolderName,'.mat'));
expData = load(experimentMatFilePath);
end
fileNameFolder = fullfile(Params.outputDataFolder, Params.outputDataFolderName, ...
'4_NetworkActivity', '4A_IndividualNetworkAnalysis', ...
char(expData.Info.Grp), char(expData.Info.FN));
if isfield(expData, 'coords')
coords = expData.coords; % to be saved
channels = expData.channels; % to be saved
originalCoords = expData.coords;
originalChannels = expData.channels;
else
originalCoords = Params.coords{ExN};
originalChannels = Params.channels{ExN};
end
Params.ExpNameGroupUseCoord = 1;
NetMet = calNodeCartography(expData.adjMs, Params, expData.NetMet, expData.Info, originalCoords, originalChannels, ...
HomeDir, fileNameFolder, oneFigureHandle);
% save NetMet now that we have node cartography data as well
experimentMatFileFolderToSaveTo = fullfile(Params.outputDataFolder, Params.outputDataFolderName, 'ExperimentMatFiles');
experimentMatFilePathToSaveTo = fullfile(experimentMatFileFolderToSaveTo, strcat(char(expData.Info.FN),'_',Params.outputDataFolderName,'.mat'));
if isfield(expData, 'spikeTimes')
spikeTimes = expData.spikeTimes;
else
spikeTimes = [];
end
if isfield(expData, 'Ephys')
Ephys = expData.Ephys;
else
Ephys = [];
end
varsToSave = {'Info', 'Params', 'spikeTimes', 'adjMs', 'NetMet', 'coords', 'channels', 'Ephys'};
adjMs = expData.adjMs; % evaluated here for saving purpose
Info = expData.Info;
save(experimentMatFilePathToSaveTo, varsToSave{:}, '-append')
end
end