-
Notifications
You must be signed in to change notification settings - Fork 16
/
perceive.m
1666 lines (1513 loc) · 89.8 KB
/
perceive.m
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 perceive(files, sub, sesMedOffOn01, extended)
% https://github.com/neuromodulation/perceive
% Toolbox by Wolf-Julian Neumann
% v1.0 update by J Vanhoecke
% Merge requests from Jennifer Behnke and Mansoureh Fahimi
% Contributors Wolf-Julian Neumann, Tomas Sieger, Gerd Tinkhauser
% This is an open research tool that is not intended for clinical purposes.
%
% INPUT:
% file ["", 'Report_Json_Session_Report_20200115T123657.json', {'Report_Json_Session_Report_20200115T123657.json','Report_Json_Session_Report_20200115T123658.json'}, ...]
% sub ["", 7, 21 , "021", ... ]
% sesMedOffOn01 ["","MedOff01","MedOn01","MedOff02","MedOn02","MedOff03","MedOn03","MedOffOn01"]
% extended ["","yes"] %% gives an extensive output of chronic, calibration, lastsignalcheck, diagnostic, impedance and snapshot data
%% INPUT
arguments
files {mustBeA(files,["char","cell"])} = '';
% files:
% All input is optional, you can specify files as cell or character array
% (e.g. files = 'Report_Json_Session_Report_20200115T123657.json')
% if files isn't specified or remains empty, it will automatically include
% all files in the current working directory
% if no files in the current working directory are found, a you can choose
% files via the MATLAB uigetdir window.
sub {mustBeA(sub,["char","cell","numeric"])} = '';
% sub:
% you can specify a subject ID for each file in case you want to follow an
% IRB approved naming scheme for file export
% (e.g. run perceive('Report_Json_Session_Report_20200115T123657.json','Charite_sub-001')
% if unspecified or left empy, the subjectID will be created from:
% ImplantDate, first letter of disease type and target (e.g. sub-2020110DGpi)
sesMedOffOn01 {mustBeMember(sesMedOffOn01,["","MedOff01","MedOn01","MedOff02","MedOn02","MedOff03","MedOn03","MedOffOn01"])} = '';
%task = 'TASK'; %All types of tasks: Rest, RestTap, FingerTapL, FingerTapR, UPDRS, MovArtArms,MovArtStand,MovArtHead,MovArtWalk
%acq = ''; %StimOff, StimOnL, StimOnR, StimOnB, Burst
%mod = ''; %BrainSense, IS, LMTD, Chronic + Bip Ring RingL RingR SegmIntraL SegmInterL SegmIntraR SegmInterR
%run = ''; %numeric
extended {mustBeMember(extended,["","yes"])} = '';
end
%% OUTPUT
% The script generates BIDS inspired subject and session folders with the
% ieeg format specifier. All time series data are being exported as
% FieldTrip .mat files, as these require no additional dependencies for creation.
% You can reformat with FieldTrip and SPM to MNE
% python and other formats (e.g. using fieldtrip2fiff([fullname '.fif'],data))
%% Recording type output naming
% Each of the FieldTrip data files correspond to a specific aspect of the Recording session:
% LMTD = LFP Montage Time Domain - BrainSenseSurvey
% IS = Indefinite Streaming - BrainSenseStreaming
% CT = Calibration Testing - Calibration Tests
% BSL = BrainSense LFP (2 Hz power average + stimulation settings)
% BSTD = BrainSense Time Domain (250 Hz raw data corresponding to the BSL file)
% BrainSenseBip = combination of BSL and BSTD into Brainsense with LFP signal/stim settings.
% for modalities see white paper: https://www.medtronic.com/content/dam/medtronic-wide/public/western-europe/products/neurological/percept-pc-neurostimulator-whitepaper.pdf
% Jimenez-Shahed, J. (2021). Expert Review of Medical Devices, 18(4), 319–332. https://doi.org/10.1080/17434440.2021.1909471
% Yohann Thenaisie et al (2021) J. Neural Eng. 18 042002 DOI https://doi.org/10.1088/1741-2552/ac1d5b
%% TODO:
% ADD DEIDENTIFICATION OF COPIED JSON -> remove copied json, OK
% BUG FIX UTC? -> yes
% ADD BATTERY DRAIN
% ADD BSL data to BSTD ephys file
% ADD PATIENT SNAPSHOT EVENT READINGS
% IMPROVE CHRONIC DIAGNOSTIC READINGS
% ADD Lead DBS Integration for electrode location
if exist('datafields') && ischar(datafields)
datafields = {datafields};
end
if ~exist('files','var') || isempty(files)
try
files=perceive_ffind('*.json');
catch
files = [];
end
if isempty(files)
[files,path] = uigetfile('*.json','Select .json file','MultiSelect','on');
if isempty(files)
return
end
files = strcat(path,files);
end
end
if ischar(files)
files = {files};
end
%% create subject
if exist('sub','var')
if isnumeric(sub)
sub=num2str(sub);
end
if ischar(sub) && ~isempty(sub)
if length(sub) == sum(isstrprop(sub,'digit'))
sub=pad(sub,3,'left','0');
sub=['sub-' sub];
end
sub={sub};
end
end
%% create task
task = 'task-Rest';
%% create run / mod / acq
run = 0;
mod = '';
acq = 'acq-StimOff';
%% iterate over files
for a = 1:length(files)
filename = files{a};
disp(['RUNNING ' filename])
js = jsondecode(fileread(filename));
try
js.PatientInformation.Initial.PatientFirstName ='';
js.PatientInformation.Initial.PatientLastName ='';
js.PatientInformation.Initial.PatientDateOfBirth ='';
js.PatientInformation.Final.PatientFirstName ='';
js.PatientInformation.Final.PatientLastName ='';
js.PatientInformation.Final.PatientDateOfBirth ='';
catch
js = rmfield(js,'PatientInformation');
js.PatientInformation.Initial.PatientFirstName ='';
js.PatientInformation.Initial.PatientLastName ='';
js.PatientInformation.Initial.PatientDateOfBirth ='';
js.PatientInformation.Initial.Diagnosis ='';
js.PatientInformation.Final.PatientFirstName ='';
js.PatientInformation.Final.PatientLastName ='';
js.PatientInformation.Final.PatientDateOfBirth ='';
js.PatientInformation.Final.Diagnosis = '';
end
infofields = {'SessionDate','SessionEndDate','PatientInformation','DeviceInformation','BatteryInformation','LeadConfiguration','Stimulation','Groups','Stimulation','Impedance','PatientEvents','EventSummary','DiagnosticData'};
for b = 1:length(infofields)
if isfield(js,infofields{b})
hdr.(infofields{b})=js.(infofields{b});
end
end
hdr.SessionEndDate = datetime(strrep(js.SessionEndDate(1:end-1),'T',' ')); %To Do
hdr.SessionEndDate = datetime(strrep(js.SessionDate(1:end-1),'T',' ')); %To Do
if ~isempty(js.PatientInformation.Final.Diagnosis)
hdr.Diagnosis = strsplit(js.PatientInformation.Final.Diagnosis,'.');hdr.Diagnosis=hdr.Diagnosis{2};
else
hdr.Diagnosis = '';
end
hdr.OriginalFile = filename;
hdr.ImplantDate = strrep(strrep(js.DeviceInformation.Final.ImplantDate(1:end-1),'T','_'),':','-'); %To Do
hdr.BatteryPercentage = js.BatteryInformation.BatteryPercentage;
hdr.LeadLocation = strsplit(hdr.LeadConfiguration.Final(1).LeadLocation,'.');hdr.LeadLocation=hdr.LeadLocation{2};
%% preset subject
if isempty(sub)
if ~isempty(hdr.ImplantDate) && ~isnan(str2double(hdr.ImplantDate(1)))
hdr.subject = ['sub-' strrep(strtok(hdr.ImplantDate,'_'),'-','') hdr.Diagnosis(1) hdr.LeadLocation];
else
hdr.subject = ['sub-000' hdr.Diagnosis(1) hdr.LeadLocation];
end
sub = {hdr.subject};
elseif iscell(sub) && length(sub) == length(files)
hdr.subject = sub{a};
elseif length(sub) == 1
hdr.subject = sub{1};
end
% determine session
if isempty(sesMedOffOn01)
ses = ['ses-' char(datetime(hdr.SessionEndDate,'format','yyyyMMddhhmmss')) num2str(hdr.BatteryPercentage)];
hdr.session = ses;
else
%% preset session
if ~ischar(sesMedOffOn01)
sesMedOffOn01=char(sesMedOffOn01);
end
diffmonths=between(datetime(hdr.SessionEndDate,'format','yyyyMMdd') , datetime(strrep(strtok(hdr.ImplantDate,'_'),'-',''),'format','yyyyMMdd'));
diffmonths=abs(calmonths(diffmonths));
presetmonths=[0,1,2,3,6,12,18,24,30,36,42,48,60,72,84,96,108,120];
diffmonths = interp1(presetmonths,presetmonths,diffmonths,'nearest');
diffmonths=num2str(diffmonths);
%% create session
ses = ['ses-', 'Fu' pad(diffmonths,2,'left','0'), 'm' , sesMedOffOn01];
hdr.session = ses;
end
%% create metatable %determine
MetaT = cell2table(cell(0,10),'VariableNames', {'report','perceiveFilename','session','condition','task','contacts','run','part','acq','remove'});
%% create dirs and path
if ~exist(fullfile(hdr.subject,hdr.session,'ieeg'),'dir')
mkdir(fullfile(hdr.subject,hdr.session,'ieeg'));
end
hdr.fpath = fullfile(hdr.subject,hdr.session,'ieeg');
hdr.fname = [hdr.subject '_' hdr.session '_' task '_' acq mod]; % do not add extra '_'
hdr.chan = ['LFP_' hdr.LeadLocation];
AbnormalEnd = js.AbnormalEnd;
if ~AbnormalEnd
hdr.d0 = datetime(js.SessionEndDate(1:10));
else
warning('This recording had an abnormal end')
hdr.d0 = datetime(js.DeviceInformation.Final.DeviceDateTime(1:10));
end
hdr.js = js;
if ~exist('datafields','var')
datafields = sort({'EventSummary','Impedance','MostRecentInSessionSignalCheck','BrainSenseLfp','BrainSenseTimeDomain','LfpMontageTimeDomain','IndefiniteStreaming','BrainSenseSurvey','CalibrationTests','PatientEvents','DiagnosticData'});
end
alldata = {};
disp(['SUBJECT ' hdr.subject])
for b = 1:length(datafields)
if isfield(js,datafields{b})
data = js.(datafields{b});
if isempty(data)
continue
end
mod='';
run=1;
switch datafields{b}
%% add csv files by default
case 'Impedance'
if extended
mod = 'mod-Impedance';
T=table;
save_impedance=1;
for c = 1:length(data.Hemisphere)
tmp=strsplit(data.Hemisphere(c).Hemisphere,'.');
side = tmp{2}(1);
electrodes = unique([{data.Hemisphere(c).SessionImpedance.Monopolar.Electrode2} {data.Hemisphere(c).SessionImpedance.Monopolar.Electrode1}]);
e1 = strrep([{data.Hemisphere(c).SessionImpedance.Monopolar.Electrode1} {data.Hemisphere(c).SessionImpedance.Bipolar.Electrode1}],'ElectrodeDef.','') ;
e2 = [{data.Hemisphere(c).SessionImpedance.Monopolar.Electrode2} {data.Hemisphere(c).SessionImpedance.Bipolar.Electrode2}];
if ~ischar([data.Hemisphere(c).SessionImpedance.Monopolar.ResultValue]) && ~ischar([data.Hemisphere(c).SessionImpedance.Bipolar.ResultValue])
imp = [[data.Hemisphere(c).SessionImpedance.Monopolar.ResultValue] [data.Hemisphere(c).SessionImpedance.Bipolar.ResultValue]];
for e = 1:length(imp)
if strcmp(e1{e},'Case')
T.([hdr.chan '_' side e2{e}(end)]) = imp(e);
else
T.([hdr.chan '_' side e2{e}(end) e1{e}(end)]) = imp(e);
end
end
else
warning('impedance values too high, not being saved...')
save_impedance=0;
end
end
if save_impedance
figure
barh(table2array(T(1,:))')
set(gca,'YTick',1:length(T.Properties.VariableNames),'YTickLabel',strrep(T.Properties.VariableNames,'_',' '))
xlabel('Impedance')
title(strrep({hdr.subject, hdr.session,'Impedances'},'_',' '))
perceive_print(fullfile(hdr.fpath,[hdr.fname '_' mod]))
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod '.csv']));
end
end
case 'PatientEvents'
disp(fieldnames(data));
case 'MostRecentInSessionSignalCheck'
if extended
mod = 'mod-MostRecentSignalCheck';
if ~isempty(data)
channels={};
pow=[];rpow=[];lfit=[];bad=[];peaks=[];
for c = 1:length(data)
cdata = data(c);
if iscell(cdata)
cdata=cdata{1};
end
tmp=strsplit(cdata.Channel,'_');
side=tmp{3}(1);
tmp=strsplit(cdata.Channel,'.');tmp=strrep(tmp{2},'_AND_','');tmp=strsplit(tmp,'_');
ch = strrep(strrep(strrep(strrep(strcat(tmp{1},tmp{2}),'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
channels{c} = [hdr.chan '_' side '_' ch];
freq = cdata.SignalFrequencies;
pow(c,:) = cdata.SignalPsdValues;
rpow(c,:) = perceive_power_normalization(pow(c,:),freq);
lfit(c,:) = perceive_fftlogfitter(freq,pow(c,:));
bad(c,1) = strcmp('IFACT_PRESENT',cdata.ArtifactStatus(end-12:end));
try
peaks(c,1) = cdata.PeakFrequencyInHertz;
peaks(c,2) = cdata.PeakMagnitudeInMicroVolt;
catch
peaks(c,:)=zeros(1,2);
end
end
T=array2table([freq';pow;rpow;lfit]','VariableNames',[{'Frequency'};strcat({'POW'},channels');strcat({'RPOW'},channels');strcat({'LFIT'},channels')]);
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod 'PowerSpectra.csv']));
T=array2table(peaks','VariableNames',channels,'RowNames',{'PeakFrequency','PeakPower'});
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod 'Peaks.csv']));
figure('Units','centimeters','PaperUnits','centimeters','Position',[1 1 40 20])
ir = perceive_ci([hdr.chan '_R'],channels);
subplot(1,2,2)
p=plot(freq,pow(ir,:));
set(p(find(bad(ir))),'linestyle','--')
hold on
plot(freq,nanmean(pow(ir,:)),'color','k','linewidth',2)
xlim([1 35])
plot(peaks(ir,1),peaks(ir,2),'LineStyle','none','Marker','.','MarkerSize',12)
for c = 1:length(ir)
if peaks(ir(c),1)>0
text(peaks(ir(c),1),peaks(ir(c),2),[' ' num2str(peaks(ir(c),1),3) ' Hz'])
end
end
xlabel('Frequency [Hz]')
ylabel('Power spectral density [uV^2/Hz]')
title(strrep({hdr.subject,char(hdr.SessionEndDate),'RIGHT'},'_',' '))
legend(strrep(channels(ir),'_',' '))
il = perceive_ci([hdr.chan '_L'],channels);
subplot(1,2,1)
p=plot(freq,pow(il,:));
set(p(find(bad(il))),'linestyle','--')
hold on
plot(freq,nanmean(pow(il,:)),'color','k','linewidth',2)
xlim([1 35])
title(strrep({'MostRecentSignalCheck',hdr.subject,char(hdr.SessionEndDate),'LEFT'},'_',' '))
plot(peaks(il,1),peaks(il,2),'LineStyle','none','Marker','.','MarkerSize',12)
xlabel('Frequency [Hz]')
ylabel('Power spectral density [uV^2/Hz]')
for c = 1:length(il)
if peaks(il(c),1)>0
text(peaks(il(c),1),peaks(il(c),2),[' ' num2str(peaks(il(c),1),3) ' Hz'])
end
end
legend(strrep(channels(il),'_',' '))
%savefig(fullfile(hdr.fpath,[hdr.fname '_run-MostRecentSignalCheck.fig']))
perceive_print(fullfile(hdr.fpath,[hdr.fname '_' mod]))
end
end
case 'DiagnosticData'
if extended
hdr.fname = strrep(hdr.fname,'StimOff','StimX');
if isfield(data,'LFPTrendLogs')
LFPL=[];STIML=[];DTL=datetime([],[],[]);
LFPR=[];STIMR=[];DTR=datetime([],[],[]);
if isfield(data.LFPTrendLogs,'HemisphereLocationDef_Left')
data.left=data.LFPTrendLogs.HemisphereLocationDef_Left;
runs = fieldnames(data.left);
for c=1:length(runs)
clfp = [data.left.(runs{c}).LFP];
cstim = [data.left.(runs{c}).AmplitudeInMilliAmps];
cdt = datetime({data.left.(runs{c}).DateTime},'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z''');
[cdt,i] = sort(cdt);
LFPL=[LFPL,clfp(i)];
STIML=[STIML,cstim(i)];
DTL=[DTL,cdt];
d=[];
d.hdr = hdr;d.datatype = 'DiagnosticData.LFPTrends';
d.fsample = 0.00166666666;
d.trial{1} = [clfp(i);cstim(i)];
d.label = {'LFP_LEFT','STIM_LEFT'};
d.time{1} = linspace(seconds(cdt(1)-hdr.d0),seconds(cdt(end)-hdr.d0),size(d.trial{1},2));
d.realtime{1} = cdt;
if length(d.time{1})>1
d.fsample = abs(1/diff(d.time{1}(1:2)));
else
warning('Only one data point recorded, assuming a sampling frequency of 1 / 10 minutes ~ 0.0017 Hz');
d.fsample = 1/600; % 10*60 sec = 10 minutes
end
d.hdr.Fs = d.fsample; d.hdr.label = d.label;
firstsample = d.time{1}(1); lastsample = d.time{1}(end);d.sampleinfo(1,:) = [firstsample lastsample];
mod= 'mod-ChronicLeft';
hdr.fname = strrep(hdr.fname, 'task-Rest', 'task-None');
d.fname = [hdr.fname '_' mod];
d.fnamedate = [char(datetime(cdt(1),'format','yyyyMMddhhmmss'))];
d.keepfig = false; % do not keep figure with this signal open (the number of LFPTrendLogs can be high)
alldata{length(alldata)+1} = d;
end
end
if isfield(data.LFPTrendLogs,'HemisphereLocationDef_Right')
data.right=data.LFPTrendLogs.HemisphereLocationDef_Right;
runs = fieldnames(data.right);
for c=1:length(runs)
clfp = [data.right.(runs{c}).LFP];
cstim = [data.right.(runs{c}).AmplitudeInMilliAmps];
cdt = datetime({data.right.(runs{c}).DateTime},'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z''');
[cdt,i] = sort(cdt);
LFPR=[LFPR,clfp(i)];
STIMR=[STIMR,cstim(i)];
DTR=[DTR,cdt];
d=[];
d.hdr = hdr;d.datatype = 'DiagnosticData.LFPTrends';
d.trial{1} = [clfp;cstim];
d.label = {'LFP_RIGHT','STIM_RIGHT'};
d.time{1} = linspace(seconds(cdt(1)-hdr.d0),seconds(cdt(end)-hdr.d0),size(d.trial{1},2));
d.realtime{1} = cdt;
if length(d.time{1})>1
d.fsample = abs(1/diff(d.time{1}(1:2)))
else
warning('Only one data point recorded, assuming a sampling frequency of 1 / 10 minutes ~ 0.0017 Hz');
d.fsample = 1/600; % 10*60 sec = 10 minutes
end
d.hdr.Fs = d.fsample; d.hdr.label = d.label;
firstsample = d.time{1}(1); lastsample = d.time{1}(end);d.sampleinfo(1,:) = [firstsample lastsample];
mod = 'mod-ChronicRight';
hdr.fname = strrep(hdr.fname, 'task-Rest', 'task-None');
d.fname = [hdr.fname '_' mod];
d.fnamedate = [char(datetime(cdt(1),'format','yyyyMMddhhmmss'))];
d.keepfig = false; % do not keep figure with this signal open (the number of LFPTrendLogs can be high)
alldata{length(alldata)+1} = d;
end
end
LFP=[];
STIM=[];
if isempty(DTL)
DT = sort(DTR);
elseif isempty(DTR)
DT = sort(DTL);
else
DT=sort([DTL,setdiff(DTR,DTL)]);
end
for c = 1:length(DT)
if ismember(DT(c),DTL)
i = find(DTL==DT(c));
LFP(1,c) = LFPL(i);
STIM(1,c) = STIML(i);
else
LFP(1,c) = nan;
STIM(1,c) = nan;
end
if ismember(DT(c),DTR)
i = find(DTR==DT(c));
LFP(2,c) = LFPR(i);
STIM(2,c) = STIMR(i);
else
LFP(2,c) = nan;
STIM(2,c) = nan;
end
end
d=[];
d.hdr = hdr;
d.datatype = 'DiagnosticData.LFPTrends';
d.trial{1} = [LFP;STIM];
d.label = {'LFP_LEFT','LFP_RIGHT','STIM_LEFT','STIM_RIGHT'};
d.time{1} = DT;
d.fsample = diff(DT);
firstsample = d.time{1}(1);
lastsample = d.time{1}(end);
d.sampleinfo(1,:) = [firstsample lastsample];
mod = 'mod-Chronic';
hdr.fname = strrep(hdr.fname, 'task-Rest', 'task-None');
d.fname = [hdr.fname '_' mod];
d.fnamedate = [char(datetime(DT(1),'format','yyyyMMddhhmmss'))];
% TODO: set if needed::
%d.keepfig = false; % do not keep figure with this signal open
alldata{length(alldata)+1} = d;
figure('Units','centimeters','PaperUnits','centimeters','Position',[1 1 40 20])
subplot(2,1,1)
title({strrep(hdr.fname,'_',' '),'CHRONIC LEFT'})
yyaxis left
scatter(DT,LFP(1,:),20,'filled','Marker','o')
ylabel('LFP Amplitude')
yyaxis right
scatter(DT,STIM(1,:),20,'filled','Marker','s')
ylabel('STIM Amplitude')
xlabel('Time')
subplot(2,1,2)
yyaxis left
scatter(DT,LFP(2,:),20,'filled','Marker','o')
ylabel('LFP Amplitude')
yyaxis right
scatter(DT,STIM(2,:),20,'filled','Marker','s')
title('RIGHT')
xlabel('Time')
ylabel('STIM Amplitude')
%savefig(fullfile(hdr.fpath,[hdr.fname '_CHRONIC.fig']))
perceive_print(fullfile(hdr.fpath,[hdr.fname '_CHRONIC']))
end
if isfield(data,'LfpFrequencySnapshotEvents')
cdata= data.LfpFrequencySnapshotEvents;
Tpow=table;Trpow=table;Tlfit=table;pow=[];rpow=[];lfit=[];lfp=struct;
for c = 1:length(cdata)
try
lfp=cdata{c};
catch
lfp=cdata(c);
end
if lfp.LFP && isfield(lfp,'LfpFrequencySnapshotEvents')
ids(c) = lfp.EventID;
DT(c) = datetime(lfp.DateTime(1:end-1),'InputFormat','yyyy-MM-dd''T''HH:mm:ss');
events{c} = lfp.EventName;
if isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Left')
tmp = strsplit(strrep(lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Left.SenseID,'_AND',''),'.');
if isempty(tmp{1}) || length(tmp) == 1
tmp = {'','unknown'};
end
ch1 = strcat(hdr.chan,'_L_',strrep(strrep(strrep(strrep(strrep(tmp{2},'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3'),'_',''));
else
ch1 = 'n/a';
end
if isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Right')
tmp = strsplit(strrep(lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Right.SenseID,'_AND',''),'.');
if isempty(tmp{1}) || length(tmp) == 1
tmp = {'','unknown'};
end
ch2 = strcat(hdr.chan,'_R_',strrep(strrep(strrep(strrep(strrep(tmp{2},'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3'),'_',''));
else
ch2 = 'n/a';
end
chanlabels{c} = {ch1 ch2};
if ~isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Left') && ~isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Right')
error('none of HemisphereLocationDef_Left / HemisphereLocationDef_Right appear in LfpFrequencySnapshotEvents');
end
if isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Left')
stimgroups{c} = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Left.GroupId(end);
freq = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Left.Frequency;
else
stimgroups{c} = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Right.GroupId(end);
freq = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Right.Frequency;
end
if isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Left') && isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Right')
pow(:,1) = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Left.FFTBinData;
pow(:,2) = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Right.FFTBinData;
else
if isfield(lfp.LfpFrequencySnapshotEvents,'HemisphereLocationDef_Left')
pow(:,1) = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Left.FFTBinData;
pow(:,2) = 0*pow(:,1);
else
pow(:,2) = lfp.LfpFrequencySnapshotEvents.HemisphereLocationDef_Right.FFTBinData;
pow(:,1) = 0*pow(:,2);
end
end
Tpow.Frequency = freq;
Tpow.(strrep([events{c} '_' num2str(c) '_' ch1 '_' char(datetime(DT(c),'Format','yyyMMddHHmmss'))],' ','')) = pow(:,1);
Tpow.(strrep([events{c} '_' num2str(c) '_' ch2 '_' char(datetime(DT(c),'Format','yyyMMddHHmmss'))],' ','')) = pow(:,2);
figure
plot(freq,pow,'linewidth',2)
legend(strrep(chanlabels{c},'_',' '))
title({strrep(hdr.fname,'_',' ');char(DT(c));events{c};['STIM GROUP ' stimgroups{c}]})
xlabel('Frequency [Hz]')
ylabel('Power spectral density [uV^2/Hz]')
%savefig(fullfile(hdr.fpath,[hdr.fname '_LFPSnapshot_' events{c} '-' num2str(c) '.fig']))
perceive_print(fullfile(hdr.fpath,[hdr.fname '_LFPSnapshot_' events{c} '-' num2str(c)]))
else
% keyboard
warning('LFP Snapshot Event without LFP data present.')
end
end
writetable(Tpow,fullfile(hdr.fpath,[hdr.fname '_LFPSnapshotEvents.csv']))
end
end
case 'BrainSenseTimeDomain'
FirstPacketDateTime = strrep(strrep({data(:).FirstPacketDateTime},'T',' '),'Z','');
runs = unique(FirstPacketDateTime);
fsample = data.SampleRateInHz;
Pass = {data(:).Pass};
tmp = {data(:).GlobalSequences};
for c = 1:length(tmp)
GlobalSequences{c,:} = str2num(tmp{c});
missingPackages{c,:} = (diff(str2num(tmp{c}))==2);
nummissinPackages(c) = numel(find(diff(str2num(tmp{c}))==2));
end
tmp = {data(:).TicksInMses};
for c = 1:length(tmp)
TicksInMses{c,:}= str2num(tmp{c});
TicksInS{c,:} = (TicksInMses{c,:} - TicksInMses{c,:}(1))/1000;
end
tmp = {data(:).GlobalPacketSizes};
for c = 1:length(tmp)
GlobalPacketSizes{c,:} = str2num(tmp{c});
isDataMissing(c)= logical(TicksInS{c,:}(end) >= sum(GlobalPacketSizes{c,:})/fsample);
time_real{c,:} = TicksInS{c,:}(1):1/fsample:TicksInS{c,:}(end)+(GlobalPacketSizes{c,:}(end)-1)/fsample;
time_real{c,:} = round(time_real{c,:},3);
end
gain=[data(:).Gain]';
[tmp1,tmp2] = strtok(strrep({data(:).Channel}','_AND',''),'_');
ch1 = strrep(strrep(strrep(strrep(tmp1,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
[tmp1,tmp2] = strtok(tmp2,'_');
ch2 = strrep(strrep(strrep(strrep(tmp1,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
side = strrep(strrep(strtok(tmp2,'_'),'LEFT','L'),'RIGHT','R');
Channel = strcat(hdr.chan,'_',side,'_', ch1, ch2);
d=[];
for c = 1:length(runs)
i=perceive_ci(runs{c},FirstPacketDateTime);
try
x=find(ismember(i, find(isDataMissing)));
if ~isempty(x)
warning('missing packages detected, will interpolate to replace missing data')
for k=1:numel(x)
isReceived = zeros(size(time_real{i(k),:}, 2), 1);
nPackets = numel(GlobalPacketSizes{i(k),:});
for packetId = 1:nPackets
timeTicksDistance = abs(time_real{i(k),:} - TicksInS{i(k),:}(packetId));
[~, packetIdx] = min(timeTicksDistance);
if isReceived(packetIdx) == 1
packetIdx = packetIdx +1;
end
isReceived(packetIdx:packetIdx+GlobalPacketSizes{i(k),:}(packetId)-1) = isReceived(packetIdx:packetIdx+GlobalPacketSizes{i(k),:}(packetId)-1)+1;
% figure; plot(isReceived, '.'); yticks([0 1]); yticklabels({'not received', 'received'}); ylim([-1 10])
end
data_temp = NaN(size(time_real{i(k),:}, 2), 1);
data_temp(logical(isReceived), :) = data(i(k)).TimeDomainData;
ind_interp=find(diff(isReceived));
if isReceived(ind_interp(1)+1)==1
ind_interp=[1 ind_interp];
data_temp(1)=0;
end
if isReceived(ind_interp(end)+1)==0
ind_interp=[ind_interp size(data_temp,1)-1];
data_temp(end)=0;
end
for mm=1:2:numel(ind_interp/2)
data_temp(ind_interp(mm)+1:ind_interp(mm+1))=...
linspace(data_temp(ind_interp(mm)), data_temp(ind_interp(mm+1)+1), ind_interp(mm+1)-ind_interp(mm));
end
raw_temp(x(k),:)=data_temp';
end
raw=raw_temp;
else
raw=[data(i).TimeDomainData]';
end
catch unmatched_samples
for xi=1:length(i)
sl(xi)=length(data(i(xi)).TimeDomainData);
end
smin=min(sl);
raw=[];
for xi = 1:length(xi)
raw(xi,:) = data(i(xi)).TimeDomainData(1:smin);
end
warning('Sample size differed between channels. Check session affiliation.')
end
d.hdr = hdr;
d.datatype = datafields{b};
d.hdr.CT.Pass=strrep(strrep(unique(strtok(Pass(i),'_')),'FIRST','1'),'SECOND','2');
d.hdr.CT.GlobalSequences=GlobalSequences(i,:);
d.hdr.CT.GlobalPacketSizes=GlobalPacketSizes(i,:);
d.hdr.CT.FirstPacketDateTime = runs{c};
d.label=Channel(i);
d.trial{1} = raw;
d.time{1} = linspace(seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0),seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0)+size(d.trial{1},2)/fsample,size(d.trial{1},2));
d.fsample = fsample;
firstsample = 1+round(fsample*seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0));
lastsample = firstsample+size(d.trial{1},2);
d.sampleinfo(1,:) = [firstsample lastsample];
if firstsample<0
keyboard
end
d.BrainSenseDateTime = [datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','Format','yyyy-MM-dd HH:mm:ss.SSS'), datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','Format','yyyy-MM-dd HH:mm:ss.SSS') + seconds(size(d.trial{1},2)/fsample)];
d.trialinfo(1) = c;
mod = 'mod-BSTD';
d.fname = [hdr.fname '_' mod];
d.fnamedate = [char(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','format','yyyyMMddhhmmss'))];
d.hdr.Fs = d.fsample;
d.hdr.label = d.label;
d=call_ecg_cleaning(d,hdr,raw);
% TODO: set if needed:
%d.keepfig = false; % do not keep figure with this signal open
alldata{length(alldata)+1} = d;
end
case 'BrainSenseLfp'
counterBSL= 0;
FirstPacketDateTime = strrep(strrep({data(:).FirstPacketDateTime},'T',' '),'Z','');
runs = unique(FirstPacketDateTime);
bsldata=[];bsltime=[];bslchannels=[];
figure('Units','centimeters','PaperUnits','centimeters','Position',[1 1 40 20])
for c=1:length(runs)
cdata = data(c);
tmp = strrep(cdata.Channel,'_AND','');
tmp = strsplit(strrep(strrep(strrep(strrep(strrep(tmp,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3'),'_',''),',');
if length(tmp)==2
lfpchannels = {[hdr.chan '_' tmp{1}(3) '_' tmp{1}(1:2) ], ...
[hdr.chan '_' tmp{2}(3) '_' tmp{2}(1:2)]};
else
if length(tmp)==1
lfpchannels = {[hdr.chan '_' tmp{1}(3) '_' tmp{1}(1:2) ]};
else
error(['unsupported number of ' num2str(length(tmp)) 'sides in BrainSenseLfp']);
end
end
d=[];
d.hdr = hdr;
d.hdr.BSL.TherapySnapshot = cdata.TherapySnapshot;
if isfield(d.hdr.BSL.TherapySnapshot,'Left')
tmp = d.hdr.BSL.TherapySnapshot.Left;
lfpsettings{1,1} = ['PEAK' num2str(round(tmp.FrequencyInHertz)) 'Hz_THR' num2str(tmp.LowerLfpThreshold) '-' num2str(tmp.UpperLfpThreshold) '_AVG' num2str(round(tmp.AveragingDurationInMilliSeconds)) 'ms'];
stimchannels = ['STIM_L_' num2str(tmp.RateInHertz) 'Hz_' num2str(tmp.PulseWidthInMicroSecond) 'us'];
else
lfpsettings{1,1}='LFP n/a';
stimchannels = 'STIM n/a';
end
if isfield(d.hdr.BSL.TherapySnapshot,'Right')
tmp = d.hdr.BSL.TherapySnapshot.Right;
lfpsettings{2,1} = ['PEAK' num2str(round(tmp.FrequencyInHertz)) 'Hz_THR' num2str(tmp.LowerLfpThreshold) '-' num2str(tmp.UpperLfpThreshold) '_AVG' num2str(round(tmp.AveragingDurationInMilliSeconds)) 'ms'];
stimchannels = {stimchannels,['STIM_R_' num2str(tmp.RateInHertz) 'Hz_' num2str(tmp.PulseWidthInMicroSecond) 'us']};
else
lfpsettings{2,1} = 'LFP n/a';
stimchannels = {stimchannels,'STIM n/a'};
end
d.label = [strcat(lfpchannels','_',lfpsettings)' stimchannels];
d.hdr.label = d.label;
d.fsample = cdata.SampleRateInHz;
d.hdr.Fs = d.fsample;
tstart = cdata.LfpData(1).TicksInMs/1000;
for e =1:length(cdata.LfpData)
d.trial{1}(1:2,e) = [cdata.LfpData(e).Left.LFP;cdata.LfpData(e).Right.LFP];
d.trial{1}(3:4,e) = [cdata.LfpData(e).Left.mA;cdata.LfpData(e).Right.mA];
d.time{1}(e) = seconds(datetime(runs{c},'InputFormat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0)+((cdata.LfpData(e).TicksInMs/1000)-tstart);
d.realtime(e) = datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','Format','yyyy-MM-dd HH:mm:ss.SSS')+seconds((d.time{1}(e)-d.time{1}(1)));
d.hdr.BSL.seq(e)= cdata.LfpData(e).Seq;
end
d.trialinfo(1) = c;
d.hdr.realtime = d.realtime;
%% set the name for BSL and STIM
counterBSL= counterBSL+1;
mod = 'mod-BSL';
d.fname = [hdr.fname '_' mod ];
d.fname = strrep(d.fname,'task-Rest',['task-TASK' num2str(counterBSL)]);
if contains(d.label(3),'STIM_L')
LAmp=d.trial{1}(3,:);
elseif contains(d.label(4),'STIM_L')
LAmp=d.trial{1}(4,:);
else
LAmp=0;
end
if contains(d.label(3),'STIM_R')
RAmp=d.trial{1}(3,:);
elseif contains(d.label(4),'STIM_R')
RAmp=d.trial{1}(4,:);
else
RAmp=0;
end
% d.hdr.SessionDate
% d.hdr.Groups
% d.hdr.Groups.Initial(1).GroupSettings.Cycling
% d.hdr.Groups.Initial(2).GroupSettings.Cycling
% d.hdr.Groups.Initial(3).GroupSettings.Cycling
% d.hdr.Groups.Initial(4).GroupSettings.Cycling
% %d.hdr.Groups.Initial(5).GroupSettings.Cycling
acq=check_stim(LAmp, RAmp, d.hdr);
d.fname = strrep(d.fname,'StimOff',acq);
d.fnamedate = [char(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','format','yyyyMMddhhmmss'))];
%% plot integrated BrainSense plot
subplot(2,1,1)
yyaxis left
lp=plot(d.realtime,d.trial{1}(1,:),'linewidth',2);
ylabel('LFP Amplitude')
yyaxis right
sp=plot(d.realtime,d.trial{1}(3,:),'linewidth',2,'linestyle','--');
sgtitle(strrep(strrep(strrep(d.fname,'_','-'),'_',' '),'BSL','BrainSenseBIP'))
title('LEFT')
ylabel('Stimulation Amplitude')
legend([lp sp],strrep(d.label([1 3]),'_',' '),'location','northoutside')
xlabel('Time')
xlim([d.realtime(1) d.realtime(end)])
subplot(2,1,2)
yyaxis left
lp=plot(d.realtime,d.trial{1}(2,:),'linewidth',2);
ylabel('LFP Amplitude')
yyaxis right
title('RIGHT')
sp=plot(d.realtime,d.trial{1}(4,:),'linewidth',2,'linestyle','--');
ylabel('Stimulation Amplitude')
legend([lp sp],strrep(d.label([2 4]),'_',' '),'location','northoutside')
xlabel('Time')
xlim([d.realtime(1) d.realtime(end)])
bsldata = [bsldata,d.trial{1}];
bsltime = [bsltime,d.realtime];
bslchannels = d.label;
% TODO: set if needed:
%d.keepfig = false; % do not keep figure with this signal open
alldata{length(alldata)+1} = d;
%savefig(fullfile(hdr.fpath,[d.fname '.fig']))
perceive_print(fullfile(hdr.fpath,[strrep(d.fname, 'BSL','BrainSenseBip')]))
end
T=table;
T.Time = bsltime';
for c = 1:length(bslchannels)
try
T.(bslchannels{c}) = bsldata(c,:)';
catch
T.(strrep(bslchannels{c},'-','_')) = bsldata(c,:)';
end
end
mod = 'mod-BrainsenseLFP';
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod '.csv']))
case 'LfpMontageTimeDomain'
%% add perceive ecg add figures cleaning
FirstPacketDateTime = strrep(strrep({data(:).FirstPacketDateTime},'T',' '),'Z','');
runs = unique(FirstPacketDateTime);
Pass = {data(:).Pass};
tmp = {data(:).GlobalSequences};
for c = 1:length(tmp)
GlobalSequences{c,:} = str2num(tmp{c});
end
tmp = {data(:).GlobalPacketSizes};
for c = 1:length(tmp)
GlobalPacketSizes{c,:} = str2num(tmp{c});
end
fsample = data.SampleRateInHz;
gain=[data(:).Gain]';
%if contains()
[tmp1]=split({data(:).Channel}', regexpPattern("(_AND_)|((?<!.*_.*)_(?!.*_AND_.*))"));
%[tmp1,tmp2] = strtok(strrep({data(:).Channel}','_AND',''),'_');
%[tmp1] = split({data(:).Channel}','_AND_'); % tmp1 is a tuple of first str part before AND and second str part after AND
% ch1 = strrep(strrep(strrep(strrep(tmp1,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
ch1 = strrep(strrep(strrep(strrep(tmp1(:,1),'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3'); % ch1 replaces ZERO to int 0 etc of first part before AND (tmp1(:,1))
% [tmp1,tmp2] = strtok(tmp2,'_');
% ch2 = strrep(strrep(strrep(strrep(tmp1,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
ch2 = strrep(strrep(strrep(strrep(tmp1(:,2),'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3'); % ch2 replaces ZERO to int 0 etc of second part after AND (tmp1(:,1))
% side = strrep(strrep(strtok(tmp2,'_'),'LEFT','L'),'RIGHT','R');
% Channel = strcat(hdr.chan,'_',side,'_', ch1, ch2);
Channel = strcat(hdr.chan,'_', ch1,'_', ch2); % taken out "side" so RIGHT and LEFT will stay the same, no transformation to R and L
d=[];
for c = 1:length(runs)
i=perceive_ci(runs{c},FirstPacketDateTime);
d=[];
d.hdr = hdr;
d.datatype = datafields{b};
d.hdr.IS.Pass=strrep(strrep(unique(strtok(Pass(i),'_')),'FIRST','1'),'SECOND','2');
d.hdr.IS.GlobalSequences=GlobalSequences(i,:);
d.hdr.IS.GlobalPacketSizes=GlobalPacketSizes(i,:);
d.hdr.IS.FirstPacketDateTime = runs{c};
tmp = [data(i).TimeDomainData]';
d.trial{1} = [tmp];
d.label=Channel(i);
d.time{1} = linspace(seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0),seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-hdr.d0)+size(d.trial{1},2)/fsample,size(d.trial{1},2));
d.fsample = fsample;
firstsample = 1+round(fsample*seconds(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')-datetime(FirstPacketDateTime{1},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS')));
lastsample = firstsample+size(d.trial{1},2);
d.sampleinfo(1,:) = [firstsample lastsample];
d.trialinfo(1) = c;
d.hdr.label = d.label;
d.hdr.Fs = d.fsample;
mod = 'mod-LMTD';
d.fname = [hdr.fname '_' mod];
d.fnamedate = [char(datetime(runs{c},'Inputformat','yyyy-MM-dd HH:mm:ss.SSS','format','yyyyMMddhhmmss')), '_',num2str(c)];
% TODO: set if needed:
%d.keepfig = false; % do not keep figure with this signal open
d=call_ecg_cleaning(d,hdr,d.trial{1});
alldata{length(alldata)+1} = d;
end
case 'BrainSenseSurvey'
channels={};
pow=[];rpow=[];lfit=[];bad=[];
for c = 1:length(data)
cdata = data(c);
if iscell(cdata)
cdata=cdata{1};
end
tmp=strsplit(cdata.Hemisphere,'.');
side=tmp{2}(1);
tmp=strsplit(cdata.SensingElectrodes,'.');tmp=strrep(tmp{2},'_AND_','');
ch = strrep(strrep(strrep(strrep(tmp,'ZERO','0'),'ONE','1'),'TWO','2'),'THREE','3');
channels{c} = [hdr.chan '_' side '_' ch];
freq = cdata.LFPFrequency;
pow(c,:) = cdata.LFPMagnitude;
rpow(c,:) = perceive_power_normalization(pow(c,:),freq);
lfit(c,:) = perceive_fftlogfitter(freq,pow(c,:));
bad(c,1) = strcmp('IFACT_PRESENT',cdata.ArtifactStatus(end-12:end));
try
peaks(c,1) = cdata.PeakFrequencyInHertz;
peaks(c,2) = cdata.PeakMagnitudeInMicroVolt;
catch
peaks(c,:)=nan(1,2);
end
end
T=array2table([freq';pow;rpow;lfit]','VariableNames',[{'Frequency'};strcat({'POW'},channels');strcat({'RPOW'},channels');strcat({'LFIT'},channels')]);
mod = 'mod-BrainSenseSurveyBip';
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod 'PowerSpectra.csv']));
T=array2table(peaks','VariableNames',channels,'RowNames',{'PeakFrequency','PeakPower'});
writetable(T,fullfile(hdr.fpath,[hdr.fname '_' mod 'Peaks.csv']));
figure('Units','centimeters','PaperUnits','centimeters','Position',[1 1 40 20])
ir = perceive_ci([hdr.chan '_R'],channels);
subplot(1,2,2)
p=plot(freq,pow(ir,:));
set(p(find(bad(ir))),'linestyle','--')
hold on
plot(freq,nanmean(pow(ir,:)),'color','k','linewidth',2)
xlim([1 35])
plot(peaks(ir,1),peaks(ir,2),'LineStyle','none','Marker','.','MarkerSize',12)
for c = 1:length(ir)
if peaks(ir(c),1)>0
text(peaks(ir(c),1),peaks(ir(c),2),[' ' num2str(peaks(ir(c),1),3) ' Hz'])
end
end
xlabel('Frequency [Hz]')
ylabel('Power spectral density [uV^2/Hz]')
title(strrep({hdr.subject,char(hdr.SessionEndDate),'RIGHT'},'_',' '))
legend(strrep(channels(ir),'_',' '))
il = perceive_ci([hdr.chan '_L'],channels);
subplot(1,2,1)
p=plot(freq,pow(il,:));
set(p(find(bad(il))),'linestyle','--')
hold on
plot(freq,nanmean(pow(il,:)),'color','k','linewidth',2)
xlim([1 35])
title(strrep({hdr.subject,char(hdr.SessionEndDate),'LEFT'},'_',' '))
plot(peaks(il,1),peaks(il,2),'LineStyle','none','Marker','.','MarkerSize',12)
xlabel('Frequency [Hz]')
ylabel('Power spectral density [uV^2/Hz]')
for c = 1:length(il)
if peaks(il(c),1)>0
text(peaks(il(c),1),peaks(il(c),2),[' ' num2str(peaks(il(c),1),3) ' Hz'])
end
end
legend(strrep(channels(il),'_',' '))
%savefig(fullfile(hdr.fpath,[hdr.fname '_run-BrainSenseSurvey.fig']))
%pause(2)
perceive_print(fullfile(hdr.fpath,[hdr.fname '_' mod]))
case 'IndefiniteStreaming'
FirstPacketDateTime = strrep(strrep({data(:).FirstPacketDateTime},'T',' '),'Z','');
runs = unique(FirstPacketDateTime);
fsample = data.SampleRateInHz;
Pass = {data(:).Pass};
tmp = {data(:).GlobalSequences};
for c = 1:length(tmp)
GlobalSequences{c,:} = str2num(tmp{c});
missingPackages{c,:} = (diff(str2num(tmp{c}))==2);
nummissinPackages(c) = numel(find(diff(str2num(tmp{c}))==2));
end
tmp = {data(:).TicksInMses};
for c = 1:length(tmp)
TicksInMses{c,:} = str2num(tmp{c});
TicksInS_temp = (TicksInMses{c,:} - TicksInMses{c,:}(1))/1000;
[TicksInS_temp,~,ci_temp] = unique(TicksInS_temp);
TicksInS{c,:} = TicksInS_temp;
ci{c,:} = ci_temp;
end