-
Notifications
You must be signed in to change notification settings - Fork 1
/
TestingToolboxes.m
1650 lines (1529 loc) · 57 KB
/
TestingToolboxes.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
clear; close all; clc; % clean and close everything
%{
Notes:
% 1 before proceeding to the next sections make sure that the paths to
% all the corresponding toolboxes are set (as well as path to the Data folder).
% Toolboxes used in each section are specified in brackets after the section name
% 2 each section of code is independent and can be run separately
% 3 PerichReachData.mat contains same data as MM_S1_raw.mat but
% 1ms bin size 1ms instead of 10 ms: PerichReachData.mat data was
% generated by running clean_data.m from
% https://crcns.org/data-sets/motor-cortex/pmd-1/about-pmd-1 (data and scripts)
% for dt = 0.001 instead of dt = 0.01 (line 24)
%}
%% 2.1.1 PSTH and raster plot for same neurons (FieldTrip, gramm, Chronux)
clear
nRuns = 1; % increase nRuns to average plotting times over more runs
load( 'PerichReachData.mat' );
binSize = 0.05; % bin size is 50 ms=0.05s
timeSegment = [ 0.0 1.0 ]; % analyze the first second
unitsSelection = [ 6 14 42 ]; % selection of M1 units to analyze
nUnits = length( unitsSelection );
nTrials = 498; % number of trials
fontSize = 24;
% we select trials longer than 1 second
[ spikeData, newNumbers ] = ...
convertToFieldTrip( Data, 'M1', unitsSelection, nTrials, timeSegment );
% 2.1 FieldTrip and gramm: PSTH and raster plot (Figure 1)
cfg = [];
cfg.binsize = binSize; % in seconds
cfg.latency = timeSegment;
cfg.outputunit = 'rate';
cfg.trials = find( newNumbers == 2 ); % consider every second reach
psthFieldTrip = ft_spike_psth( cfg, spikeData );
cfg = [];
cfg.cmapneurons = [ 0.1725 0.6275 0.1725; 0.1216 0.4667 0.7059; ...
1.0000 0.4980 0.0549 ]; % set colormap
cfg.latency = timeSegment; % in seconds
cfg.linewidth = 2;
cfg.topplotfunc = 'line'; % plot as a line
cfg.trials = find( newNumbers == 2 ); % consider every second reach
compTime = zeros( 1, 2 );
figure;
subplot( 1, 2, 1 );
tic;
for iRuns = 1:nRuns
ft_spike_plot_raster( cfg, spikeData, psthFieldTrip );
set( gca, 'fontSize', 24 );
legend( 'Unit6', 'Unit14', 'Unit42' );
end
compTime( 1 ) = toc/nRuns;
title( [ '(A) FieldTrip, plotting time ' num2str( compTime( 1 ), '%.2f') ' s' ] );
% data conversion for gramm
trialCnt = 1; % counter of trials longer than 1 second
minTrialLength = 1000;
for iUnit = 1:nUnits
% we take only trials corresponding to movement to the second trial
for iTrial = 2:4:nTrials
% take only trials longer than 1s
if ( size( Data.neural_data_M1{ iTrial }( unitsSelection( iUnit ), : ), 2 ) > minTrialLength )
spikeTimes = find( Data.neural_data_M1{ iTrial }( unitsSelection( iUnit ), 1:minTrialLength ) > 0 )/1000;
grammSpikeData{ trialCnt } = spikeTimes;
temp = histc( spikeTimes, 0:binSize:1.0 );
binned{ trialCnt } = temp( 1:end-1 )/binSize;
% we set here bin centers
bins{ trialCnt } = 0.025:binSize:0.975;
colorValues{ trialCnt } = [ 'Unit' num2str( unitsSelection( iUnit ) ) ];
trialCnt = trialCnt + 1;
end
end
end
columnNumber = 2;
firstIndex = 1;
secondIndex = 2;
verticalLine = 0.325;
for iRuns = 1:nRuns
clear g
tic;
g( firstIndex, columnNumber ) = gramm( 'x', bins, 'y', binned, 'color', colorValues );
g( firstIndex, columnNumber ).stat_summary( 'setylim', true, 'type', 'sem' );
g( firstIndex, columnNumber ).geom_vline( 'xintercept', verticalLine );
g( firstIndex, columnNumber ).set_line_options( 'base_size', 4 );
g( firstIndex, columnNumber ).set_names( 'x', '', 'y', 'Rate [Hz]' );
g( secondIndex, columnNumber ) = gramm( 'x', grammSpikeData, 'color', colorValues );
g( secondIndex, columnNumber ).geom_raster( 'geom', 'point' );
g( secondIndex, columnNumber ).geom_vline( 'xintercept', verticalLine );
g( secondIndex, columnNumber ).set_line_options( 'base_size', 4 );
g( secondIndex, columnNumber ).set_names( 'x', 'Time [s]', 'y', 'Trials' );
g( secondIndex, columnNumber ).set_layout_options( 'legend', 'false' );
g.set_text_options( 'base_size', fontSize );
g.set_color_options( 'map', 'd3_20' );
g.set_point_options( 'base_size', 4 );
g.set_line_options( 'base_size', 4 );
% as actual drawing happens after setting the title, the computing time
% is set as constant here, but it follows from theexperiments
g.set_title( '(B) gramm, plotting time 0.54s' );
g.draw();
compTime( 2 ) = compTime( 2 ) + toc;
end
compTime( 2 ) = compTime( 2 )/nRuns;
% PSTH by Chronux
figure;
unitNumber = 6;
trialCnt = 1;
for iTrial = 2:4:nTrials
% spike times in seconds
if ( size( Data.neural_data_M1{ iTrial }( unitNumber, : ), 2 ) > minTrialLength )
chrSpikes( trialCnt ).times = ...
find( Data.neural_data_M1{ iTrial }( unitNumber, 1:minTrialLength ) > 0 )/minTrialLength;
trialCnt = trialCnt + 1;
end
end
clear psth % clear variable with the same name as Chronux function
[ firingRate, spikeTimes, statErrors ] = ...
psth( chrSpikes, binSize, 'r', timeSegment, 1 );
legend( 'Unit 6' );
set( gca, 'FontSize', fontSize );
title( 'Chronux: PSTH' );
%% 2.1.2 ISI (inter-spike-interval) distribution (FieldTrip)
clear
load( 'PerichReachData.mat' );
timeSegment = [ 0 1.0 ];
unitsSelection = 14;
nTrials = 489;
spikeData = convertToFieldTrip( Data, 'M1', unitsSelection, nTrials, timeSegment );
nTrials = size( spikeData.trialtime, 1 );
cfg = [];
cfg.bins = 0:0.005:0.1; % use bins of 0.5 milliseconds
cfg.param = 'coeffvar'; % compute the coefficient of variation (sd/mn of isis)
cfg.trials = 1:4:nTrials;
isih = ft_spike_isi( cfg, spikeData );
figure;
cfg = [];
cfg.spikechannel = isih.label{ 1 };
cfg.interpolate = 5; % interpolate at 5 times the original density
cfg.window = 'gausswin'; % use a gaussian window to smooth
cfg.winlen = 0.004; % the smoothing window has size 4 by 4 ms
cfg.colormap = jet; % colormap
cfg.scatter = 'no'; % do not plot the individual isis per spike as scatters
ft_spike_plot_isireturn( cfg, isih );
title( '(A) FieldTrip' );
caxis( [ 0 4 ] );
set( gca, 'FontSize', 24 );
% for Spike Viewer ISIH, use SpikeViewer GUI for test dataset:
% from https://spyke-viewer.readthedocs.io/en/latest/usage.html#loading-data
% Tetrode 1(A-a), all channels selected, all segments selected, unit 2 (A-a-1)
%% 2.2.1 Unique tools: locfit (Chronux)
clear
load( 'MM_S1_raw.mat' );
nTrials = 140;
% compute PSTH with Chronux
figure;
binSize = 0.05; % in seconds
timeInterval = [ 0.0 4.0 ];
unitNumber = 6;
for iTrial = 1:nTrials
spikeTimes = ( M1.units( unitNumber ).ts > trial_table( iTrial, 3 ) & ...
M1.units( unitNumber ).ts < trial_table( iTrial, 22 ) );
% spike times in seconds
spikeData( iTrial ).times = ...
( M1.units( unitNumber ).ts( spikeTimes ) - trial_table( iTrial, 1 ) );
spikeData( iTrial ).times = ...
spikeData( iTrial ).times( spikeData( iTrial ).times < timeInterval( 2 ) );
end
[ firingRate, spikeTimes, statErrors ] = ...
psth( spikeData, binSize, 'r', timeInterval, 1 );
set( gca, 'FontSize', 24 );
title( 'Chronux: PSTH' );
trialNumber = 1;
figure;
subplot( 1, 2, 1 );
h = histogram( spikeData( trialNumber ).times );
h.BinWidth = 0.2;
set( gca, 'FontSize', 24 );
ylabel( 'Counts' );
title( 'Frequency histogram' );
subplot( 1, 2, 2 );
fit = locfit( spikeData( trialNumber ).times', 'family', 'rate', 'nn', 0.7 );
lfplot( fit );
lfband( fit );
set( gca, 'FontSize', 24 );
xlabel( 'Time [s]' );
ylabel( 'Rate [Hz]' );
title( 'Smoothed spike rate for 1 trial ');
%% 2.2.2.1 Unique tools: spectrum and spectogram for point-processes (Chronux)
% spectrogram averaged across trials
clear
load( 'MM_S1_raw.mat' );
figure;
params.tapers = [ 5 9 ]; % 10 - time-bandwidth product, 19 - number of tapers
params.err = 0; % no error computation
params.fpass = [ 0 100 ]; % interval of frequencies of interest
params.Fs = 1000; % sampling rate
params.trialave = 1;
movingWin = [ 0.5 0.05 ]; % moving windows in seconds [ size step ]
iTrial = 49;
cnt = 1;
for iUnit = [ 39 44 ]
% from movement onset till the end of trial
clear spikeData
% spike times in seconds
trialCnt = 1;
minTrialLength = 2.8;
for iTrial = 1:140
if ( trial_table( iTrial, 22 ) - trial_table( iTrial, 3 ) > minTrialLength )
spikeTimes = ( M1.units( iUnit ).ts > trial_table( iTrial, 3 ) & ...
M1.units( iUnit ).ts < trial_table( iTrial, 3 ) + minTrialLength );
spikeData( trialCnt ).times = ( M1.units( iUnit ).ts( spikeTimes ) - trial_table( iTrial, 3 ) )';
trialCnt = trialCnt + 1;
end
end
subplot( 1, 2, cnt );
cnt = cnt + 1;
[ spectrumValues, cTimeValues, freqValues, rateValues ] = ...
mtspecgrampt( spikeData, movingWin, params );
spectrumValues = spectrumValues/max( max( spectrumValues ) );
colormap parula;
imagesc( cTimeValues', freqValues', 10*log10( spectrumValues' ) );
hc = colorbar;
title( hc, 'dB/Hz' );
caxis( [ -4 0 ] );
axis xy; % flip axis
set( gca, 'FontSize', 24 );
xlabel( 'Time [s]' );
if ( iUnit == 14 )
ylabel( 'Freq [Hz]' );
end
title( [ 'Spectogram, ' num2str( iTrial ) ' trial, M1 unit ' ...
num2str( iUnit ) ] );
end
%% 2.2.2.2 Unique tools: spectrum and spectogram for point-processes (Chronux)
% spectrogram for 1 trial
clear
load( 'MM_S1_raw.mat' );
figure;
params.tapers = [ 10 19 ]; % 10: time-bandwidth product, 19: number of tapers
params.err = 0; % no error computation
params.fpass = [ 0 100 ]; % interval of frequencies of interest
params.Fs = 1000; % sampling rate
params.trialave = 1;
movingWin = [ 0.8 0.05 ]; % moving windows in seconds [ size step ]
iTrial = 3;
cnt = 1;
for iUnit = [ 14 17 ]
% from movement onset till the end of trial
clear spikeData
spikeTimes = ( M1.units( iUnit ).ts > trial_table( iTrial, 3 ) & ...
M1.units( iUnit ).ts < trial_table( iTrial, 22 ) );
% spike times in seconds
spikeData( 1 ).times = ...
( M1.units( iUnit ).ts( spikeTimes ) - trial_table( iTrial, 1 ) );
subplot( 1, 2, cnt );
cnt = cnt + 1;
[ spectrumValues, cTimeValues, freqValues, rateValues ] = ...
mtspecgrampt( spikeData, movingWin, params );
colormap parula;
imagesc( cTimeValues', freqValues', 10*log10( spectrumValues' ) );
hc = colorbar;
title( hc, 'dB/Hz' );
caxis( [ 0 20 ] );
axis xy; % flip axis
set( gca, 'FontSize', 24 );
xlabel( 'Time [s]' );
if ( iUnit == 14 )
ylabel( 'Freq [Hz]' );
else
set( gca, 'YTickLabel', [] );
end
title( [ 'Spectogram, ' num2str( iTrial ) ' trial, M1 unit ' ...
num2str( iUnit ) ] );
end
%% 3.1.1 Line Noise Removal (MATLAB, Brainstorm, Chronux, FieldTrip)
% ! to run this section, exclude from the MATLAB path the folder
% fieldtrip/external/signal (due to the name conflict) !
clear
load openloop60hertz
noisyData = openLoopVoltage;
nRuns = 1; % increase nRuns to average computing times for more runs
Fs = 1000;
timeValues = ( 0:length( noisyData ) - 1 )/Fs;
filterDesigned = designfilt( 'bandstopiir', 'FilterOrder', 2, ...
'HalfPowerFrequency1', 59, 'HalfPowerFrequency2', 61, ...
'DesignMethod', 'butter', 'SampleRate', Fs );
% MATLAB filtering
tic;
for iRun = 1:nRuns
matlabFilt = filtfilt( filterDesigned, noisyData );
end
filtTime( 1 ) = toc/nRuns;
% Chronux filtering
params.tapers = [ 3 5 ];
params.Fs = Fs;
tic;
for iRun = 1:nRuns
chronuxFilt = rmlinesc( noisyData, params, 0.05, 'n', 60 );
end
filtTime( 2 ) = toc/nRuns;
% FieldTrip filtering with dft
tic;
for iRun = 1:nRuns
fieldtripFilt = ft_preproc_dftfilter( noisyData', 1000, 60, ...
'Flreplace', 'zero' );
end
filtTime( 3 ) = toc/nRuns;
% Brainstorm filtering (this code has been copied from
% process_notch function, lines 104-139, Brainstorm toolbox v3.4)
tic;
for iRun = 1:nRuns
x = noisyData';
FreqList = 60.0;
FreqWidth = 1;
sfreq = Fs;
UseSigProcToolbox = 1;
% Remove the mean of the data before filtering
xmean = mean(x,2);
x = bst_bsxfun(@minus, x, xmean);
% Remove all the frequencies sequencially
for ifreq = 1:length(FreqList)
% Define coefficients of an IIR notch filter
delta = FreqWidth/2;
% Pole radius
r = 1 - (delta * pi / sfreq);
theta = 2 * pi * FreqList(ifreq) / sfreq;
% Gain factor
B0 = abs(1 - 2*r*cos(theta) + r^2) / (2*abs(1-cos(theta)));
% Numerator coefficients
B = B0 * [1, -2*cos(theta), 1];
% Denominator coefficients
A = [1, -2*r*cos(theta), r^2];
% Filter signal
if UseSigProcToolbox
x = filtfilt( B,A,x')';
else
x = filter( B,A,x')';
x(:,end:-1:1) = filter(B,A,x(:,end:-1:1)')';
end
end
% Restore the mean of the signal
brainstormFilt = bst_bsxfun(@plus, x, xmean);
end
filtTime( 4 ) = toc/nRuns;
filtTime = filtTime*1000;
timeInt = 1:800;
figure;
fontSize = 24;
subplot( 5, 2, 1 );
plot( timeValues( timeInt ), noisyData( timeInt ), ...
timeValues( timeInt ), matlabFilt( timeInt ), 'LineWidth', 2 );
set( gca, 'XTick', [] );
%xlabel( 'Time (s)' );
ylabel( 'Voltage (V)' );
legend( 'Unfiltered', 'MATLAB filtered' );
title( '(A) Open-Loop Voltage' );
axis tight
grid on
set( gca, 'FontSize', fontSize );
subplot( 5, 2, 3 );
plot( timeValues( timeInt ), noisyData( timeInt ), ...
timeValues( timeInt ), chronuxFilt( timeInt ), 'LineWidth', 2 );
set( gca, 'XTick', [] );
%xlabel( 'Time (s)' );
legend( 'Unfiltered', 'Chronux filtered' );
axis tight
grid on
set( gca, 'FontSize', fontSize );
subplot( 5, 2, 5 );
plot( timeValues( timeInt ), noisyData( timeInt ), ...
timeValues( timeInt ), fieldtripFilt( timeInt ), 'LineWidth', 2 );
set( gca, 'XTick', [] );
%xlabel( 'Time (s)' );
legend( 'Unfiltered', 'FieldTrip filtered' );
axis tight
grid on
set( gca, 'FontSize', fontSize );
subplot( 5, 2, 7 );
plot( timeValues( timeInt ), noisyData( timeInt ), ...
timeValues( timeInt ), brainstormFilt( timeInt ), 'LineWidth', 2 );
legend( 'Unfiltered', 'Brainstorm filtered' );
xlabel( 'Time (s)' );
axis tight
grid on
set( gca, 'FontSize', fontSize );
[ pOriginal, fOriginal ] = periodogram( noisyData, [], [], Fs );
[ pMATLAB, fMATLAB ] = periodogram( matlabFilt, [], [], Fs );
[ pChronux, fChronux ] = periodogram( chronuxFilt, [], [], Fs );
[ pFieldTrip, fFieldTrip ] = periodogram( fieldtripFilt, [], [], Fs );
[ pBrainstorm, fBrainstorm ] = periodogram( brainstormFilt, [], [], Fs );
subplot( 5, 2, 2 );
% *20 because of power transfer, P = UxI=U^2/R, T = 10log(P_out/P_in)=10log()
%https://www.physicsforums.com/threads/confusion-with-db-equation-10-or-20.641850/
freqToPlot = 50:206; % indices for frequencies to plot
plot( fOriginal( freqToPlot ), 20*log10( abs( pOriginal( freqToPlot ) ) ), ...
fOriginal( freqToPlot ), 20*log10( abs( pMATLAB( freqToPlot ) ) ), ...
'--', 'LineWidth', 2 );
set( gca, 'XTick', [] );
legend( 'Unfiltered', [ 'MATLAB filtered, ' num2str( filtTime( 1 ), '%.2f' ) 'ms' ] );
title( '(B) Power Spectrum' );
%xlabel( 'Frequency (Hz)' );
set( gca, 'FontSize', fontSize );
ylabel( 'Power/frequency (dB/Hz)' );
axis tight
grid on
ylim( [ -120 20 ] );
subplot( 5, 2, 4 );
plot( fOriginal( freqToPlot ), 20*log10( abs( pOriginal( freqToPlot ) ) ), ...
fOriginal( freqToPlot ), 20*log10( abs( pChronux( freqToPlot ) ) ), ...
'--', 'LineWidth', 2 );
set( gca, 'XTick', [] );
legend( 'Unfiltered', ['Chronux filtered, ' num2str( filtTime( 2 ), '%.2f') 'ms' ] );
set( gca, 'FontSize', fontSize );
%xlabel( 'Frequency (Hz)' );
axis tight
grid on
ylim( [ -120 20 ] );
subplot( 5, 2, 6 );
plot( fOriginal( freqToPlot ), 20*log10( abs( pOriginal( freqToPlot ) ) ), ...
fOriginal( freqToPlot ), 20*log10( abs( pFieldTrip( freqToPlot ) ) ), ...
'--', 'LineWidth', 2 );
set( gca, 'XTick', [] );
legend( 'Unfiltered', [ 'FieldTrip filtered, ' num2str( filtTime( 3 ), '%.2f') 'ms' ] );
set( gca, 'FontSize', fontSize );
%xlabel( 'Frequency (Hz)' );
axis tight
grid on
ylim( [ -120 20 ] );
subplot( 5, 2, 8 );
plot( fOriginal( freqToPlot ), 20*log10( abs( pOriginal( freqToPlot ) ) ), ...
fOriginal( freqToPlot ), 20*log10( abs( pBrainstorm( freqToPlot ) ) ), ...
'--', 'LineWidth', 2 );
legend( 'Unfiltered', [ 'Brainstorm filtered, ' num2str( filtTime( 4 ), '%.2f' ) 'ms' ] );
xlabel( 'Frequency (Hz)' );
set( gca, 'FontSize', fontSize );
axis tight
grid on
ylim( [ -120 20 ] );
pOriginal = 20*log10( abs( pOriginal ) );
pMATLAB = 20*log10( abs( pMATLAB ) );
pChronux = 20*log10( abs( pChronux ) );
pFieldTrip = 20*log10( abs( pFieldTrip ) );
pBrainstorm = 20*log10( abs( pBrainstorm ) );
MSE = zeros( 1, 4 );
% we exclude point in the 0.2 vicinity of 60Hz
for iFreq = [ 1:123 125:length( fOriginal ) ]
MSE( 1 ) = MSE( 1 ) + ( pMATLAB( iFreq ) - pOriginal( iFreq ) )^2;
MSE( 2 ) = MSE( 2 ) + ( pChronux( iFreq ) - pOriginal( iFreq ) )^2;
MSE( 3 ) = MSE( 3 ) + ( pFieldTrip( iFreq ) - pOriginal( iFreq ) )^2;
MSE( 4 ) = MSE( 4 ) + ( pBrainstorm( iFreq ) - pOriginal( iFreq ) )^2;
end
MSE( : ) = MSE( : )/( length( fOriginal ) - 2 );
subplot( 5, 1, 5 );
hBar = bar( MSE );
hBar.FaceColor = [ 0 0.4470 0.7410 ];
set( gca, 'XTickLabel', {'MATLAB', 'Chronux', 'FieldTrip', 'Brainstorm' } );
ylabel( 'MSE' );
grid on;
title( '(C) Mean-squared error' );
set( gca, 'FontSize', 24 );
%% 3.1.2 detrending (Brainstorm, Chronux, FieldTrip)
clear
nRuns = 1; % increase nRuns to average detrending times for more runs
timeValues = 0:300;
dailyFluct = gallery( 'normaldata', size( timeValues ), 2 );
originalData = cumsum( dailyFluct ) + 20 + timeValues/100;
figure;
plot( timeValues, originalData, 'LineWidth', 2 );
legend( 'Original Data', 'Location', 'northwest' );
xlabel( 'Time (days)' );
ylabel( 'Stock Price (dollars)' );
tic
for iRun = 1:nRuns
matlabDetrend = detrend( originalData );
end
compTime( 1 ) = toc/nRuns;
tic
for iRun = 1:nRuns
chronuxDetrend = locdetrend( originalData );
end
compTime( 2 ) = toc/nRuns;
tic
for iRun = 1:nRuns
fieldtripDetrend = ft_preproc_detrend( originalData, 1, length( originalData ) );
end
compTime( 3 ) = toc/nRuns;
% Brainstorm v3.4 detrend from process_detrend function, lines 116-128
iTime = [];
tic
for iRun = 1:nRuns
% Number of samples
nTime = size( originalData, 2 );
% Parse inputs
if isempty(iTime)
iTime = 1:nTime;
end
% Basis functions
x = [ones(1,nTime); 0:nTime-1];
invxcov = inv(x(:,iTime) * x(:,iTime)');
beta = originalData(:,iTime) * x(:,iTime)' * invxcov;
% Remove the estimated basis functions
brainstormDetrend = originalData - beta*x;
end
compTime( 4 ) = toc/nRuns;
hold on
plot( timeValues, originalData - matlabDetrend, ':', 'LineWidth', 2 );
plot( timeValues, originalData - chronuxDetrend', ':', 'LineWidth', 2 );
plot( timeValues, originalData - fieldtripDetrend, ':', 'LineWidth', 2 );
plot( timeValues, originalData - brainstormDetrend, ':', 'LineWidth', 2 );
plot( timeValues, matlabDetrend, 'LineWidth', 2 );
plot( timeValues, chronuxDetrend, 'LineWidth', 2 );
plot( timeValues, fieldtripDetrend, 'LineWidth', 2 );
plot( timeValues, brainstormDetrend, 'LineWidth', 2 );
plot( timeValues, zeros( size( timeValues ) ), ':k', 'LineWidth', 2 );
legend( 'Original Data', 'Trend MATLAB', 'Trend Chronux', ...
'Trend FieldTrip', 'Trend Brainstorm', 'Detrended data MATLAB', ...
'Detrended data Chronux', 'Detrended data FieldTrip', ...
'Detrended data Brainstorm', 'Mean of Detrended Data', 'Location', 'northwest' );
xlabel( 'Time (days)' );
ylabel( 'Stock Price (dollars)' );
set( gca, 'FontSize', 24 );
%% 3.1.3 spectogram of 1 trial (MATLAB, Brainstorm, Chronux, Elephant, FieldTrip)
clear
freqOfInterest = 1.9531:1.9531:80.0;
fSample = 1000; % sampling frequency
nRuns = 1; % increase nRuns to average spectra estimating times over more runs
plotXlim = [ 0.5 3.5 ]; % plot spectra values from 0.5 to 3.5 seconds
timeSegment = [ 0.0 4.0 ]; % time segment in seconds
nPoints = 4001;
lfpTimeSegment = 1:nPoints; % in time points from -1 to 1 seconds
movingWindow = 512; % 512ms = 512 points
windowStep = 1; % in points: 50ms = 50 points
winOverlap = 511; % maximal overlap for windows
minDb = -40;
colorbarLim = [ minDb 0 ];
timeValues = timeSegment( 1 ):0.001:timeSegment( end );
modFreq = [ 40 60 8 20 ];
fm = 2.0;
fc = 40.0;
mi = 6.0;
% prepare FieldTrip structure
lfpData.fSample = fSample;
lfpData.trial = cell( 1, 1 );
lfpData.time = cell( 1, 1 );
lfpData.label{ 1 } = 'simulated_data';
% data in additiveNoise.mat were generated as additiveNoise = randn( 1, 2001 );
% and saved in mat file for repeatability of the results
load( 'additiveNoise.mat' );
plotIndices = [ 1 3 5 7 9 11 13 15 2 4 6 8 10 12 14 16 17 18 ];
figure;
nPlot = 1;
chronuxTapers = 1;
estFreq = cell( 1, 16 );
estSpectra = cell( 1, 16 );
for iPlot = 1:2
if ( iPlot == 1 )
ftMorletWidth = 20; % width of wavelet in number of cycles
ftSpectralSmoothing = 2; % amount of spectral smoothing +-2Hz
% sliding window in seconds for each frequency
ftSlidingWindow = repmat( movingWindow/fSample, length( freqOfInterest ) );
chronuxTbwProduct = 2; % time band-width product
brainstromCentralFreq = 4.0;
dataValues( 1:4001 ) = ...
sin( 2*pi*modFreq( 1 )*timeValues ) + sin( 2*pi*modFreq( 2 )*timeValues ) + ...
sin( 2*pi*modFreq( 3 )*timeValues ) + sin( 2*pi*modFreq( 4 )*timeValues );
else
ftMorletWidth = 10; % width of wavelet in number of cycles
% amount of spectral smoothing +-0.1F at each frequency F
ftSpectralSmoothing = 0.1*freqOfInterest;
% sliding window in seconds for each frequency: 8/F at each F
ftSlidingWindow = 8./freqOfInterest;
chronuxTbwProduct = 8; % time bandwidth product in Chronux
brainstromCentralFreq = 1.5;
dataValues( 1:4001 ) = cos( 2*pi*fc*timeValues + ( mi*sin( 2*pi*fm*timeValues ) ) );
end
% compute signal to noise ratio
SNR( iPlot ) = snr( dataValues( 2001:end ), additiveNoise );
dataValues( 2001:end ) = dataValues( 2001:end ) + additiveNoise;
lfpData.trial{ 1 }( lfpTimeSegment ) = dataValues;
lfpData.time{ 1 }( lfpTimeSegment ) = timeValues;
% save data for Elephant
save( [ 'sines' num2str( iPlot ) '.mat' ], 'dataValues' );
% Brainstorm Morlet wavelet transform (with default central frequency)
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
tic; % loop to measure computing time
for iRun = 1:nRuns
coefsBrainstorm = morlet_transform( dataValues, timeValues, ...
freqOfInterest, brainstromCentralFreq, [], 'y' );
end
specTime( 5 ) = toc;
coefsBrainstorm = coefsBrainstorm/max( max( coefsBrainstorm ) );
coefsBrainstorm = 10*log10( squeeze( coefsBrainstorm )' );
coefsBrainstorm( coefsBrainstorm < minDb ) = minDb;
estSpectra{ nPlot - 1 } = coefsBrainstorm;
imagesc( timeValues, 2:2:80, coefsBrainstorm );
colormap jet
axis xy; % flip axis
caxis( colorbarLim );
xlim( plotXlim );
set( gca, 'XTick', [] );
if ( iPlot == 1 )
ylabel( 'Freq [Hz]' );
title( [ '(A) Brainstorm: Morlet wavelet ' ...
num2str( specTime( 5 )/nRuns, '%.2f' ) 's' ] );
else
set( gca, 'YTick', [] );
end
set( gca, 'FontSize', 24 );
% Chronux multi-taper time-frequency transform
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
params.tapers = [ chronuxTbwProduct chronuxTapers ]; % taper parameters
params.fpass = [ freqOfInterest( 1 ) - 0.5 freqOfInterest( end ) + 0.5 ];
params.Fs = fSample; % sampling Rate
params.pad = 0; % padding type
tic; % loop to measure computing time
for iRun = 1:nRuns
[ spectrumValues, cTimeValues, freqValues ] = ...
mtspecgramc( dataValues', [ movingWindow windowStep ]/fSample, params );
end
specTime( 2 ) = toc;
spectrumValues = spectrumValues/( max( max( spectrumValues ) ) );
spectrumValues = 10*log10( spectrumValues );
spectrumValues( spectrumValues < minDb ) = minDb;
estFreq{ nPlot - 1 } = freqValues;
estSpectra{ nPlot - 1 } = spectrumValues';
imagesc( ( cTimeValues )', freqValues', spectrumValues' );
colormap jet
xlim( plotXlim );
set( gca, 'XTick', [] );
caxis( colorbarLim );
set( gca, 'FontSize', 24 );
set( gca, 'YTick', [] );
set( gca, 'YDir', 'normal' );
if ( iPlot == 1 )
title( [ '(B) Chronux: multitapers dpss ' num2str( specTime( 2 )/nRuns, '%.2f' ) 's' ] );
end
% Elephant Morlet wavelets
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
if ( iPlot == 1 )
load( 'spectrSine1' );
else
load( 'spectrSine2' );
end
powerValues = squeeze( abs( data ).^2 );
powerValues = powerValues/max( max( powerValues ) );
powerValues = 10*log10( powerValues );
powerValues( powerValues < minDb ) = minDb;
estSpectra{ nPlot - 1 } = powerValues;
imagesc( timeValues, freqOfInterest, powerValues );
colormap jet
axis xy; % flip axis
caxis( colorbarLim );
xlim( plotXlim );
set( gca, 'XTick', [] );
if ( iPlot == 1 )
title( '(C) Elephant: Morlet wavelet 0.02s' );
ylabel( 'Freq [Hz]' );
else
set( gca, 'YTick', [] );
end
set( gca, 'FontSize', 24 );
% Fieldtrip multi-taper time-frequency transform with Slepian seuqences
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
cfg = [];
cfg.foi = freqOfInterest; % frequencies of interest
cfg.method = 'mtmconvol'; % multitaper time-frequency transformation
cfg.output = 'pow';
cfg.taper = 'dpss'; % with Slepian sequences
cfg.tapsmofrq = ftSpectralSmoothing; % amount of spectral smoothing
cfg.t_ftimwin = ftSlidingWindow; % sliding window in seconds
cfg.pad = 512;
% times (in seconds) on which analysis windows should be centered
cfg.toi = timeSegment( 1 ):windowStep/fSample:timeSegment( 2 );
cfg.trials = 1;
tic; % loop to measure computing time
for iRun = 1:nRuns
spectrumValues = ft_freqanalysis( cfg, lfpData );
end
specTime( 4 ) = toc;
temp = spectrumValues.powspctrm/max( max( spectrumValues.powspctrm ) );
spectrumValues.powspctrm = 10*log10(temp);
spectrumValues.powspctrm( spectrumValues.powspctrm < minDb ) = minDb;
estFreq{ nPlot - 1 } = spectrumValues.freq;
estSpectra{ nPlot - 1 } = squeeze( spectrumValues.powspctrm );
cfg = [];
cfg.colorbar = 'no';
cfg.title = [];
ft_singleplotTFR( cfg, spectrumValues );
set( gca, 'XTick', [] );
set( gca, 'YTick', [] );
caxis( colorbarLim );
colormap jet
xlim( plotXlim );
if ( iPlot == 1 )
title( [ '(D) FieldTrip: multitapers dpss ' num2str( specTime( 4 )/nRuns, '%.2f' ) 's' ] );
else
title( '' );
end
set( gca, 'FontSize', 24 );
% FieldTrip multitaper time-frequency transform with a Hanning window
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
cfg = [];
cfg.foi = freqOfInterest; % Freq Of Interest - analysis in steps of 2 Hz
cfg.method = 'mtmconvol'; % time-frequency analysis using Morlet waveforms
cfg.output = 'pow';
cfg.taper = 'hanning';
% length of sliding time window in seconds
cfg.t_ftimwin = ftSlidingWindow;
cfg.pad = 512;
% times on which analysis windows should be centered
cfg.toi = timeSegment( 1 ):windowStep/fSample:timeSegment( 2 );
cfg.trials = 1;
tic; % loop to measure computing time
for iRun = 1:nRuns
spectrumValues = ft_freqanalysis( cfg, lfpData );
end
specTime( 3 ) = toc;
temp = spectrumValues.powspctrm/max( max( spectrumValues.powspctrm ) );
spectrumValues.powspctrm = 10*log10( temp );
spectrumValues.powspctrm( spectrumValues.powspctrm < minDb ) = minDb;
estFreq{ nPlot - 1 } = spectrumValues.freq;
estSpectra{ nPlot - 1 } = squeeze( spectrumValues.powspctrm );
cfg = [];
cfg.colorbar = 'no';
ft_singleplotTFR( cfg, spectrumValues );
caxis( colorbarLim );
xlim( plotXlim );
set( gca, 'XTick', [] );
if ( iPlot == 1 )
ylabel( 'Freq [Hz]' );
title( [ '(E) FieldTrip: multitapers Hanning ' ...
num2str( specTime( 3 )/nRuns, '%.2f' ) 's'] );
else
title( '' );
set( gca, 'YTick', [] );
end
set( gca, 'FontSize', 24 );
% FieldTrip Morlet wavelet transform
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
cfg = [];
cfg.foi = freqOfInterest; % frequencies of interest
cfg.method = 'wavelet'; % time-frequency analysis using Morlet waveforms
cfg.output = 'pow';
% times on which analysis windows should be centered
cfg.toi = timeSegment( 1 ):windowStep/fSample:timeSegment( 2 );
cfg.trials = 1;
% standard parameters
cfg.width = ftMorletWidth;
cfg.pad = 512;
%cfg.gwidth = 3; % wavelet length in standard deviations of the implicit Gaussian kernel
% loop to measure computing time
tic;
for iRun = 1:nRuns
spectrumValues = ft_freqanalysis( cfg, lfpData );
end
specTime( 7 ) = toc;
temp = spectrumValues.powspctrm/max( max( spectrumValues.powspctrm ) );
spectrumValues.powspctrm = 10*log10( temp );
spectrumValues.powspctrm( spectrumValues.powspctrm < minDb ) = minDb;
estFreq{ nPlot - 1 } = spectrumValues.freq;
estSpectra{ nPlot - 1 } = squeeze( spectrumValues.powspctrm );
cfg = [];
cfg.colorbar = 'no';
ft_singleplotTFR( cfg, spectrumValues );
caxis( colorbarLim );
set( gca, 'XTick', [] );
%xlabel( 'Time [s]' );
xlim( plotXlim );
set( gca, 'YTick', [] );
if ( iPlot == 1 )
title( [ '(F) FieldTrip: Morlet wavelet ' num2str( specTime( 7 )/nRuns, '%.2f' ) 's' ] );
else
title( '' );
end
set( gca, 'FontSize', 24 );
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
tic; % loop to measure computing time
for iRun = 1:nRuns
[ spectrumValues, freqValues, mTimeValues, powerValues ] = ...
spectrogram( dataValues, movingWindow, winOverlap, freqOfInterest, fSample, 'yaxis' );
end
specTime( 1 ) = toc;
powerValues = powerValues/( max( max( powerValues ) ) );
powerValues = 10*log10( powerValues );
powerValues( powerValues < minDb ) = minDb;
estFreq{ nPlot - 1 } = freqValues;
estSpectra{ nPlot - 1 } = powerValues;
imagesc( mTimeValues, freqValues, powerValues );
set( gca, 'XTick', [] );
xlim( plotXlim );
colormap jet
axis xy; % flip axis
caxis( colorbarLim );
if ( iPlot == 1 )
ylabel( 'Freq [Hz]' );
title( [ '(G) MATLAB: short time FFT ' ...
num2str( specTime( 1 )/nRuns, '%.2f' ) 's' ] );
else
set( gca, 'YTick', [] );
end
set( gca, 'FontSize', 24 );
% Morlet wavelet with MATLAB
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
tic; % loop to measure computing time
for iRun = 1:nRuns
% Convert the scales to approximate frequencies in hertz for the Morlet wavelet
convertedFrq = brainstromCentralFreq./freqOfInterest;
scales = 6./( 2*pi*freqOfInterest );
[ coefMatlab, freqMatlab ] = cwt( dataValues, scales, 'cmor1-1.5', 1/fSample );
end
specTime( 6 ) = toc;
coefMatlab = abs( coefMatlab ).^2;
coefMatlab = coefMatlab/max( coefMatlab );
powerVaules = 10*log10( coefMatlab );
powerValues( powerValues < minDb ) = minDb;
estFreq{ nPlot - 1 } = freqMatlab;
estSpectra{ nPlot - 1 } = powerValues;
imagesc( mTimeValues, freqMatlab, powerValues );
axis xy
xlabel( 'Time [s]' );
caxis( colorbarLim );
xlim( plotXlim );
set( gca, 'YTick', [] );
if ( iPlot == 1 )
title( [ '(H) MATLAB: Morlet wavelet ', num2str( specTime( 6 )/nRuns, '%.2f' ) 's' ] );
end
set( gca, 'FontSize', 24 );
end
% now compare quantitatevly estimated with ideal spectra
idealSpectrumX1 = zeros( 80, nPoints ) - 40;
% we allow bandwidth +-1 Hz
idealSpectrumX1( [ 7:9 19:21 39:41 59:61 ], : ) = 0;
% at first we take all frequencies from 1 to 80
idealSpectrumX2 = zeros( 80, nPoints ) - 40;
freqPoint = zeros( 1, nPoints ) + 40;
for iPoint = 2:4001
freqPoint( iPoint ) = round( 40 + 12*cos( 4*pi*timeValues( iPoint ) ) );
% we allow bandwidth +-1
idealSpectrumX2( freqPoint( iPoint ) - 1:freqPoint( iPoint ) + 1, iPoint ) = 0;
end
realFreq = round( estFreq{ 2 } );
idealSpectrumX1 = idealSpectrumX1( realFreq, : );
idealSpectrumX2 = idealSpectrumX2( realFreq, : );
subplot( 5, 4, plotIndices( nPlot ) );
nPlot = nPlot + 1;
imagesc( timeValues, realFreq, idealSpectrumX1 );
colormap jet
axis xy; % flip axis
xlim( plotXlim );
xlabel( 'Time [s]' );
ylabel( 'Freq [Hz]' );
title( '(I) Ideal spectrum' );
set( gca, 'FontSize', 24 );
caxis( colorbarLim );
subplot( 5, 4, plotIndices( nPlot ) );
imagesc( timeValues, realFreq, idealSpectrumX2 );
axis xy; % flip axis
caxis( colorbarLim );
xlim( plotXlim );
xlabel( 'Time [s]' );
set( gca, 'YTickLabel', [] );
set( gca, 'FontSize', 24 );
hc = colorbar;
title( hc, 'dB/Hz' );
% test how spectra differences from the ideal spectrum look like
figure;
tlbxLabels = {'Brainstorm','Chronux', 'Elephant', ...
'\begin{tabular}{c} FieldTrip \\ dpss \end{tabular}', ...
'\begin{tabular}{c} FieldTrip \\ Hanning \end{tabular}', ...
'\begin{tabular}{c} FieldTrip \\ Morlet \end{tabular}', ...
'\begin{tabular}{c} MATLAB \\ FFT \end{tabular}', ...
'\begin{tabular}{c} MATLAB \\ Morlet \end{tabular}' };
for iSpectrum = 1:16
subplot( 4, 4, iSpectrum );
phaseShift = 0;
if ( iSpectrum == 2 || iSpectrum == 7 || iSpectrum == 8 || ...
iSpectrum == 10 || iSpectrum == 15 || iSpectrum == 16 )
phaseShift = 256;
end
if ( iSpectrum < 9 )
temp = estSpectra{ iSpectrum }( 3:35, 1000 - phaseShift:3000 - phaseShift ) - ...
idealSpectrumX1( 3:35, 1000:3000 );
else
temp = estSpectra{ iSpectrum }( 3:35, 1000 - phaseShift:3000 - phaseShift ) - ...
idealSpectrumX2( 3:35, 1000:3000 );
end
imagesc( abs( temp ) );
axis xy; % flip axis
colormap jet
caxis( [ 0 40 ] );
if ( iSpectrum < 9 )
title( tlbxLabels{ iSpectrum }, 'Interpreter', 'Latex' );
else
title( tlbxLabels{ iSpectrum - 8 }, 'Interpreter', 'Latex' );
end
set( gca, 'FontSize', 24 );
end
colorbar;
% compare quantitatevly estimated spectra with ideal one
MSE = zeros( 2, 16 );
corr2D = zeros( 2, 16 );
% 1 - without noise; 2 - with noise
for iSpectrum = 1:16
pntsInt = { 1000:2000, 2001:3000 };
phaseShift = 0;
% for MATLAB and Chronux there is phase shift 256 points due to no
% zero-padding
if ( iSpectrum == 2 || iSpectrum == 7 || iSpectrum == 8 || iSpectrum == 10 )
phaseShift = 256;
end
if ( iSpectrum < 9 )
idealSpectrum = idealSpectrumX1;
else
idealSpectrum = idealSpectrumX2;
end
cnt = [ 0 0 ];
% iInt for the first (stable) and the second (modulated) half of the signal
for iInt = 1:2
for iPoint = pntsInt{ iInt }
cnt( iInt ) = 1;
for iFreq = 4:39
temp = ( estSpectra{ iSpectrum }( iFreq, iPoint - phaseShift ) - ...
idealSpectrum( iFreq, iPoint ) ).^2;