-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy patherpimage.m
3873 lines (3642 loc) · 155 KB
/
erpimage.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
% ERPIMAGE - Plot a colored image of a collection of single-trial data epochs, optionally
% sorted on and/or aligned to an input sorting variable and smoothed across
% trials with a Gaussian weighted moving-average. (To return event-aligned data
% without plotting, use EEGALIGN). Optionally sort trials on value, amplitude
% or phase within a specified latency window. Optionally plot the ERP mean
% and std. dev.and moving-window spectral amplitude and inter-trial coherence
% at aselected or peak frequency. Optionally 'time warp' the single trial
% time-domain (potential) or power data to align the plotted data to a series
% of events with varying latencies that occur in each trial. Click on
% individual figures parts to examine them separately and zoom (using AXCOPY).
% Usage:
% >> figure; erpimage(data,[],times); % image trials as colored lines in input order
%
% >> figure; [outdata,outvar,outtrials,limits,axhndls, ...
% erp,amps,cohers,cohsig,ampsig,outamps,...
% phsangls,phsamp,sortidx,erpsig] ...
% = erpimage(data,sortvar,times,'title',avewidth,decimate,...
% 'key', 'val', ...); % use options
% Required input:
% data = [vector or matrix] Single-channel input data to image.
% Formats (1,frames*trials) or (frames,trials)
%
% Optional ordered inputs {with defaults}:
%
% sortvar = [vector | []] Variable to sort epochs on (length(sortvar) = nepochs)
% Example: sortvar may by subject response time in each epoch (in ms)
% {default|[]: plot in input order}
% times = [vector | []] vector of latencies (in ms) for each epoch time point.
% Else [startms ntimes srate] = [start latency (ms), time points
% (=frames) per epoch, sampling rate (Hz)]. Else [] -> 0:nframes-1
% {default: []}
% 'title' = ['string'] Plot title {default: none}
% avewidth = [positive scalar (may be non-integer)]. If avg_type is set to 'boxcar'
% (the default), this is the number of trials used to smooth
% (vertically) with a moving-average. If avg_type is set to
% 'Gaussian,' this is the standard deviation (in units of
% trials) of the Gaussian window used to smooth (vertically)
% with a moving-average. Gaussian window extends three
% standard deviations below and three standard deviations above window
% center (trials beyond window are not incorporated into average). {default: no
% smoothing}
% decimate = Factor to decimate|interpolate ntrials by (may be non-integer)
% Else, if this is large (> sqrt(ntrials)), output this many epochs.
% {default|0->1}
%
% Optional unordered 'keyword',argument pairs:
%
% Re-align data epochs:
% 'align' = [latency] Time-lock data to sortvar. Plot sortvar at given latency
% (in ms). Else Inf -> plot sortvar at median sortvar latency
% {default: do not align}
% 'timewarp' = {[events], [warpms], {colors}} Time warp ERP, amplitude and phase
% time-courses before smoothing. 'events' is a matrix whose columns
% specify the latencies (in ms) at which a series of successive events occur
% in each trial. 'warpms' is an optional vector of latencies (in ms) to which
% the series of events should be time locked. (Note: Epoch start and end
% should not be declared as events or warpms}. If 'warpms' is absent or [],
% the median of each 'events' column will be used. {colors} contains a
% list of Matlab linestyles to use for vertical lines marking the occurrence
% of the time warped events. If '', no line will be drawn for this event
% column. If fewer colors than event columns, cycles through the given color
% labels. Note: Not compatible with 'vert' (below).
% 'renorm' = ['yes'|'no'| formula] Normalize sorting variable to epoch
% latency range and plot. 'yes'= autoscale. formula must be a linear
% transformation in the format 'a*x+b'
% Example of formula: '3*x+2'. {default: 'no'}
% If sorting by string values like event type, suggested formulas for:
% letter string: '1000*x', number string: '30000*x-1500'
% 'noplot' = ['on'|'off'] Do not plot sortvar {default: Plot sortvar if in times range}
% 'NoShow' = ['on'|'off'] Do not plot erpimage, simply return outputs {default: 'off'}
%
% Sort data epochs:
% 'nosort' = ['on'|'off'] Do not sort data epochs. {default: Sort data epochs by
% sortvar (see sortvar input above)}
% 'replace_ties' = ['yes'|'no'] Replace trials with the same value of
% sortvar with the mean of those trials. Only works if sorting trials
% by sortvar. {default: 'no'}
% 'valsort' = [startms endms direction] Sort data on (mean) value
% between startms and (optional) endms. Direction is 1 or -1.
% If -1, plot max-value epoch at bottom {default: sort on sortvar}
% 'phasesort' = [ms_center prct freq maxfreq topphase] Sort epochs by phase in
% a 3-cycle window centered at latency ms_center (ms).
% Percentile (prct) in range [0,100] gives percent of trials
% to reject for (too) low amplitude. Else, if in range [-100,0],
% percent of trials to reject for (too) high amplitude;
% freq (Hz) is the phase-sorting frequency. With optional
% maxfreq, sort by phase at freq of max power in the data in
% the range [freq,maxfreq] (Note: 'phasesort' arg freq overrides
% the frequency specified in 'coher'). With optional topphase,
% sort by phase, putting topphase (degrees, in range [-180,180])
% at the top of the image. Note: 'phasesort' now uses circular
% smoothing. Use 'cycles' (below) for wavelet length.
% {default: [0 25 8 13 180]}
% 'ampsort' = [center_ms prcnt freq maxfreq] Sort epochs by amplitude.
% (See 'phasesort' above). If ms_center is 'Inf', then sorting
% is by mean power across the time window specified by 'sortwin'
% below. If third arg, freq, is < 0, sort by mean power in the range
% [ abs(freq) maxfreq ].
% 'sortwin' = [start_ms end_ms] If center_ms == Inf in 'ampsort' arg (above), sorts
% by mean amplitude across window centers shifted from start_ms
% to end_ms by 10 ms.
% 'showwin' = ['on'|'off'] Show sorting window behind ERP trace. {default: 'off'}
%
% Plot time-varying spectral amplitude instead of potential:
% 'plotamps' = ['on'|'off'] Image amplitudes at each trial and latency instead of
% potential values. Note: Currently requires 'coher' (below) with alpha signif.
% Use 'cycles' (see below) > (its default) 3 for better frequency specificity,
% {default: plot potential, not amplitudes, with no minimum}. The average power
% (in log space) before time 0 is automatically removed. Note that the
% 'baseline' parameter has no effect on 'plotamps'. Instead use
% change "baselinedb" or "basedB" in the 'limits' parameter. By default
% the baseline is removed before time 0.
%
% Specify plot parameters:
% 'limits' = [lotime hitime minerp maxerp lodB hidB locoher hicoher basedB]
% Plot axes limits. Can use NaN (or nan, but not Nan) for missing items
% and omit late items. Use last input, basedB, to set the
% baseline dB amplitude in 'plotamps' plots {default: from data}
% 'sortvar_limits' = [min max] minimum and maximum sorting variable
% values to image. This only affects visualization of
% ERPimage and ERPs (not smoothing). Cannot be used
% if sorting by any factor besides sortvar (e.g.,
% phase).
% 'signif' = [lo_dB, hi_dB, coher_signif_level] Use precomputed significance
% thresholds (as from outputs ampsig, cohsig) to save time. {default: none}
% 'caxis' = [lo hi] Set color axis limits. Else [fraction] Set caxis limits at
% (+/-)fraction*max(abs(data)) {default: symmetrical in dB, based on data limits}
%
% Add epoch-mean ERP to plot:
% 'erp' = ['on'|'off'|1|2|3|4] Plot ERP time average of the trials below the
% image. If 'on' or 1, a single ERP (the mean of all trials) is shown. If 2,
% two ERPs (super and sub median trials) are shown. If 3, the trials are split into
% tertiles and their three ERPs are shown. If 4, the trials are split into quartiles
% and four ERPs are shown. Note, if you want negative voltage plotted up, change YDIR
% to -1 in icadefs.m. If 'erpalpha' option is used, any values of 'erp' greater than
% 1 will be reset to 1. {default no ERP plotted}
% 'erpalpha' = [alpha] Visualizes two-sided significance threshold (i.e., a two-tailed test) for the
% null hypothesis of a zero mean, symmetric distribution (range: [.001 0.1]). Thresholds
% are determined via a permutation test. Requires 'erp' to be a value other than 'off'.
% If 'erp' is set to a value greater than 1, it is reset to 1 to increase plot readability.
% {default: no alpha significance thresholds plotted}
% 'erpstd' = ['on'|'off'] Plot ERP +/- stdev. Requires 'erp' {default: no std. dev. plotted}
% 'erp_grid' = If 'erp_grid' is added as an option voltage axis dashed grid lines will be
% added to the ERP plot to facilitate judging ERP amplitude
% 'rmerp' = ['on'|'off'] Subtract the average ERP from each trial before processing {default: no}
%
% Add time/frequency information:
% 'coher' = [freq] Plot ERP average plus mean amplitude & coherence at freq (Hz)
% Else [minfrq maxfrq] = same, but select frequency with max power in
% given range. (Note: the 'phasesort' freq (above) overwrites these
% parameters). Else [minfrq maxfrq alpha] = plot coher. signif. level line
% at probability alpha (range: [0,0.1]) {default: no coher, no alpha level}
% 'srate' = [freq] Specify the data sampling rate in Hz for amp/coher (if not
% implicit in third arg, times) {default: as defined in icadefs.m}
% 'cycles' = [float] Number of cycles in the wavelet time/frequency decomposition {default: 3}
%
% Add plot features:
% 'cbar' = ['on'|'off'] Plot color bar to right of ERP-image {default no}
% 'cbar_title' = [string] The title for the color bar (e.g., '\muV' for
% microvolts).
% 'topo' = {map,chan_locs,eloc_info} Plot a 2-D scalp map at upper left of image.
% map may be a single integer, representing the plotted data channel,
% or a vector of scalp map channel values. chan_locs may be a channel locations
% file or a chanlocs structure (EEG.chanlocs). See '>> topoplot example'
% eloc_info (EEG.chaninfo), if empty ([]) or absent, implies the 'X' direction
% points towards the nose and all channels are plotted {default: no scalp map}
% 'spec' = [loHz,hiHz] Plot the mean data spectrum at upper right of image.
% 'specaxis' = ['log'|'lin] Use 'lin' for linear spectrum frequency scaling,
% else 'log' for log scaling {default: 'log'}
% 'horz' = [epochs_vector] Plot horizontal lines at specified epoch numbers.
% 'vert' = [times_vector] Plot vertical dashed lines at specified latencies
% 'auxvar' = [size(nvars,ntrials) matrix] Plot auxiliary variable(s) for each trial
% as separate traces. Else, 'auxvar',{[matrix],{colorstrings}}
% to specify N trace colors. Ex: colorstrings = {'r','bo-','','k:'}
% (see also: 'vert' and 'timewarp' above). {default: none}
% 'sortvarpercent' = [float vector] Plot percentiles for the sorting variable
% for instance, [0.1 0.5 0.9] plots the 10th percentile, the median
% and the 90th percentile.
% Plot options:
% 'noxlabel' = ['on'|'off'] Do not plot "Time (ms)" on the bottom x-axis
% 'yerplabel' = ['string'] ERP ordinate axis label (default is ERP). Print uV with '\muV'
% 'avg_type' = ['boxcar'|'Gaussian'] The type of moving average used to smooth
% the data. 'Boxcar' smoothes the data by simply taking the mean of
% a certain number of trials above and below each trial.
% 'Gaussian' does the same but first weights the trials
% according to a Gaussian distribution (e.g., nearby trials
% receive greater weight). The Gaussian is better than the
% boxcar in that it rather evenly filters out high frequency
% vertical components in the ERPimage. See 'avewidth' argument
% description for more information. {default: boxcar}
% 'img_trialax_label' = ['string'] The label of the axis corresponding to trials in the ERPimage
% (e.g., 'Reaction Time'). Note, if img_trialax_label is set to something
% besides 'Trials' or [], the tick marks on this axis will be set in units
% of the sorting variable. This is a useful alternative to plotting the
% sorting variable when the sorting variable is not in milliseconds. This
% option is not effective if sorting by amplitude, phase, or EEG value. {default: 'Trials'}
% 'img_trialax_ticks' = Vector of sorting variable values at which tick marks (e.g., [300 350 400 450]
% for reaction time in msec) will appear on the trial axis of the erpimage. Tick mark
% values should be given in units img_trialax_label (e.g., 'Trials' or msec).
% This option is not effective if sorting by amplitude, phase, or EEG value.
% {default: automatic}
% 'baseline' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]) after filtering.
% Useful in conjunction with 'filt' option to re-basline trials after they have been
% filtered. Not necessary if data have already been baselined and erpimage
% processing does not affect baseline amplitude {default: no further baselining
% of data}.
% 'baselinedb' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]). Use basedB in limits
% to remove a fixed value. Default is time before 0. If you do not want to use a
% baseline for amplitude plotting, enter a NaN value.
% 'filt' = [low_boundary high_boundary] a two element vector indicating the frequency
% cut-offs for a 3rd order Butterworth filter that will be applied to each
% trial of data. If low_boundary=0, the filter is a low pass filter. If
% high_boundary=srate/2, then the filter is a high pass filter. If both
% boundaries are between 0 and srate/2, then the filter is a bandpass filter.
% If both boundaries are between 0 and -srate/2, then the filter is a bandstop
% filter (with boundaries equal to the absolute values of low_boundary and
% high_boundary). Note, using this option requires the 'srate' option to be
% specified and the signal processing toolbox function butter.m. You should
% probably use the 'baseline' option as well since the mean prestimulus baseline
% may no longer be 0 after the filter is applied {default: no filtering}
%
% Optional outputs:
% outdata = (times,epochsout) data matrix (after smoothing)
% outvar = (1,epochsout) actual values trials are sorted on (after smoothing).
% if 'sortvarpercent' is used, this variable contains a cell array with
% { sorted_values { sorted_percent1 ... sorted_percentN } }
% outtrials = (1,epochsout) smoothed trial numbers
% limits = (1,10) array, 1-9 as in 'limits' above, then analysis frequency (Hz)
% axhndls = vector of 1-7 plot axes handles (img,cbar,erp,amp,coh,topo,spec)
% erp = plotted ERP average
% amps = mean amplitude time course
% coher = mean inter-trial phase coherence time course
% cohsig = coherence significance level
% ampsig = amplitude significance levels [lo high]
% outamps = matrix of imaged amplitudes (from option 'plotamps')
% phsangls = vector of sorted trial phases at the phase-sorting frequency
% phsamp = vector of sorted trial amplitudes at the phase-sorting frequency
% sortidx = indices of input data epochs in the sorting order
% erpsig = trial average significance levels [2,frames]
%
% Example: >> figure;
% erpimage(data,RTs,[-400 256 256],'Test',1,1,...
% 'erp','cbar','vert',-350);
% Plots an ERP-image of 1-s data epochs sampled at 256 Hz, sorted by RTs, with
% title ('Test'), and sorted epochs not smoothed or decimated (1,1). Overplots
% the (unsmoothed) RT latencies on the colored ERP-image. Also plots the
% epoch-mean (ERP), a color bar, and a dashed vertical line at -350 ms.
%
% Authors: Scott Makeig, Tzyy-Ping Jung & Arnaud Delorme,
% CNL/Salk Institute, La Jolla, 3-2-1998 -
%
% See also: phasecoher, rmbase, cbar, movav
% Copyright (C) Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute, La Jolla 3-2-98
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.
% Uses external toolbox functions: PHASECOHER, RMBASE, CBAR, MOVAV
% Uses included functions: PLOT1TRACE, PHASEDET
% UNIMPLEMENTED - 'allcohers',[data2] -> image the coherences at each latency & epoch.
% Requires arg 'coher' with alpha significance.
% Shows projection on grand mean coherence vector at each latency
% and trial. {default: no}
%% LOG COMMENTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data,outsort,outtrials,limits,axhndls,erp,amps,cohers,cohsig,ampsig,allamps,phaseangles,phsamp,sortidx,erpsig] = erpimage(data,sortvar,times,titl,avewidth,decfactor,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14,arg15,arg16,arg17,arg18,arg19,arg20,arg21,arg22,arg23,arg24,arg25,arg26,arg27,arg28,arg29,arg30,arg31,arg32,arg33,arg34,arg35,arg36,arg37,arg38,arg39,arg40,arg41,arg42,arg43,arg44,arg45,arg46,arg47,arg48,arg49,arg50,arg51,arg52,arg53,arg54,arg55,arg56,arg57,arg58,arg59,arg60,arg61,arg62,arg63,arg64,arg65,arg66)
%
%% %%%%%%%%%%%%%%%%% Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Initialize optional output variables:
warning off;
erp = []; amps = []; cohers = []; cohsig = []; ampsig = [];
allamps = []; phaseangles = []; phsamp = []; sortidx = [];
auxvar = []; erpsig = []; winloc = [];winlocs = [];
timeStretchColors = {};
YES = 1; % logical variables
NO = 0;
DEFAULT_BASELINE_END = 0; % ms
TIMEX = 1; % 1 -> plot time on x-axis;
% 0 -> plot trials on x-axis
BACKCOLOR = [0.8 0.8 0.8]; % grey background
try, icadefs; catch, end
% read BACKCOLOR for plot from defs file (edit this)
% read DEFAULT_SRATE for coher,phase,allamps, etc.
% read YDIR for plotting ERP
% Fix plotting text and line style parameters
SORTWIDTH = 2.5; % Linewidth of plotted sortvar
ZEROWIDTH = 3.0; % Linewidth of vertical 0 line
VERTWIDTH = 2.5; % Linewidth of optional vertical lines
HORZWIDTH = 2.1; % Linewidth of optional vertical lines
SIGNIFWIDTH = 1.9; % Linewidth of red significance lines for amp, coher
DOTSTYLE = 'k--'; % line style to use for vertical dotted/dashed lines
LINESTYLE = '-'; % solid line
LABELFONT = 10; % font sizes for axis labels, tick labels
TICKFONT = 10;
PLOT_HEIGHT = 0.2; % fraction of y dim taken up by each time series axes
YGAP = 0.03; % fraction gap between time axes
YEXPAND = 1.3; % expansion factor for y-axis about erp, amp data limits
DEFAULT_SDEV = 1/7; % smooth trials with this window size by default if Gaussian window
DEFAULT_AVEWIDTH = 1; % smooth trials with this window size by default
DEFAULT_DECFACTOR = 1; % decimate by this factor by default
DEFAULT_CYCLES = 3; % use this many cycles in amp,coher computation window
cycles = DEFAULT_CYCLES;
DEFAULT_CBAR = NO;% do not plot color bar by default
DEFAULT_PHARGS = [0 25 8 13]; % Default arguments for phase sorting
DEFAULT_ALPHA = 0.01;
alpha = 0; % default alpha level for coherence significance
MIN_ERPALPHA = 0.001; % significance bounds for ERP
MAX_ERPALPHA = 0.1;
NoShowVar = NO; % show sortvar by default
Nosort = NO; % sort on sortvar by default
Caxflag = NO; % use default caxis by default
timestretchflag = NO; % Added -JH
mvavg_type='boxcar'; % use the original rectangular moving average -DG
erp_grid = NO; % add y-tick grids to ERP plot -DG
cbar_title = []; % title to add above ERPimage color bar (e.g., '\muV') -DG
img_ylab = 'Trials'; % make the ERPimage y-axis in units of the sorting variable -DG
img_ytick_lab = []; % the values at which tick marks will appear on the trial axis of the ERPimage (the y-axis by default).
%Note, this is in units of the sorting variable if img_ylab~='Trials', otherwise it is in units of trials -DG
baseline = []; %time window of each trial whose mean amp will be used to baseline the trial -DG
baselinedb = []; %time window of each trial whose mean power will be used to baseline the trial
flt=[]; %frequency domain filter parameters -DG
sortvar_limits=[]; %plotting limits for sorting variable/trials; limits only affect visualization, not smoothing -DG
replace_ties = NO; %if YES, trials with the exact same value of a sorting variable will be replaced by their average -DG
erp_vltg_ticks=[]; %if non-empty, these are the voltage axis ticks for the ERP plot
Caxis = [];
caxfraction = [];
Coherflag = NO; % don't compute or show amp,coher by default
Cohsigflag= NO; % default: do not compute coherence significance
Allampsflag=NO; % don't image the amplitudes by default
Allcohersflag=NO; % don't image the coherence amplitudes by default
Topoflag = NO; % don't plot a topoplot in upper left
Specflag = NO; % don't plot a spectrum in upper right
SpecAxisflag = NO; % don't change the default spectrum axis type from default
SpecAxis = 'log'; % default log frequency spectrum axis (if Specflag)
Erpflag = NO; % don't show erp average by default
Erpstdflag= NO;
Erpalphaflag= NO;
Alignflag = NO; % don't align data to sortvar by default
Colorbar = NO; % if YES, plot a colorbar to right of erp image
Limitflag = NO; % plot whole times range by default
Phaseflag = NO; % don't sort by phase
Ampflag = NO; % don't sort by amplitude
Sortwinflag = NO; % sort by amplitude over a window
Valflag = NO; % don't sort by value
Srateflag = NO; % srate not given
Vertflag = NO;
Horzflag = NO;
titleflag = NO;
NoShowflag = NO;
Renormflag = NO;
Showwin = NO;
yerplabel = 'ERP';
yerplabelflag = NO;
verttimes = [];
horzepochs = [];
NoTimeflag= NO; % by default DO print "Time (ms)" below bottom axis
Signifflag= NO; % compute significance instead of receiving it
Auxvarflag= NO;
plotmodeflag= NO;
plotmode = 'normal';
Cycleflag = NO;
signifs = NaN;
coherfreq = nan; % amp/coher-calculating frequency
freq = 0; % phase-sorting frequency
srate = DEFAULT_SRATE; % from icadefs.m
aligntime = nan;
timelimits= nan;
topomap = []; % topo map vector
lospecHz = []; % spec lo frequency
topphase = 180; % default top phase for 'phase' option
renorm = 'no';
NoShow = 'no';
Rmerp = 'no';
percentiles = [];
percentileflag = NO;
erp_ptiles = 1;
minerp = NaN; % default limits
maxerp = NaN;
minamp = NaN;
maxamp = NaN;
mincoh = NaN;
maxcoh = NaN;
baseamp =NaN;
allamps = []; % default return
ax1 = NaN; % default axes handles
axcb = NaN;
ax2 = NaN;
ax3 = NaN;
ax4 = NaN;
timeStretchRef = [];
timeStretchMarks = [];
tsurdata = []; % time-stretched data before smoothing (for timestretched-erp computation)
% If time-stretching is off, this variable remains empty
%
%% %%%%%%%%%%%%%%%%% Test, fill in commandline args %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin < 1
help erpimage
return
end
data = squeeze(data);
if nargin < 3 || isempty(times)
if size(data,1)==1 || size(data,2)==1
fprintf('\nerpimage(): either input a times vector or make data size = (frames,trials).\n')
return
end
times = 1:size(data,1);
NoTimesPassed= 1;
end
if nargin < 2 || isempty(sortvar)
sortvar = 1:size(data,2);
NoShowVar = 1; % don't plot the dummy sortvar
end
framestot = size(data,1)*size(data,2);
ntrials = length(sortvar);
if ntrials < 2
help erpimage
fprintf('\nerpimage(): too few trials.\n');
return
end
frames = floor(framestot/ntrials);
if frames*ntrials ~= framestot
help erpimage
fprintf(...
'\nerpimage(); length of sortvar doesn''t divide number of data elements??\n')
return
end
if nargin < 6
decfactor = 0;
end
if nargin < 5
avewidth = DEFAULT_AVEWIDTH;
end
if nargin<4
titl = ''; % default no title
end
if nargin<3
times = NO;
end
if (length(times) == 1) || (length(times) == 1 && times(1) == NO) % make default times
times = 0:frames-1;
srate = 1000*(length(times)-1)/(times(length(times))-times(1));
fprintf('Using sampling rate %g Hz.\n',srate);
elseif length(times) == 3
mintime = times(1);
frames = times(2);
srate = times(3);
times = mintime:1000/srate:mintime+(frames-1)*1000/srate;
fprintf('Using sampling rate %g Hz.\n',srate);
else
% Note: might use default srate read from icadefs here...
srate = 1000*(length(times)-1)/(times(end)-times(1));
end
if length(times) ~= frames
fprintf(...
'\nerpimage(): length(data)(%d) ~= length(sortvar)(%d) * length(times)(%d).\n\n',...
framestot, length(sortvar), length(times));
return
end
if decfactor == 0
decfactor = DEFAULT_DECFACTOR;
elseif decfactor > ntrials
fprintf('Setting variable decfactor to max %d.\n',ntrials)
decfactor = ntrials;
end
%
%% %%%%%%%%%%%%%%% Collect optional args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin > 6
flagargs = [];
a = 6;
while a < nargin % for each remaining Arg
a = a + 1;
Arg = eval(['arg' int2str(a-6)]);
if Caxflag == YES
if size(Arg,1) ~= 1 || size(Arg,2) > 2
help erpimage
fprintf('\nerpimage(): caxis arg must be a scalar or (1,2) vector.\n');
return
end
if size(Arg,2) == 2
Caxis = Arg;
else
caxfraction = Arg;
end
Caxflag = NO;
elseif timestretchflag == YES % Added -JH
timeStretchMarks = Arg{1};
timeStretchMarks = round(1+(timeStretchMarks-times(1))*srate/1000); % convert from ms to frames -sm
[smc, smr] = find(diff(timeStretchMarks') < 0);
if ~isempty(smr)
fprintf('\nerpimage(): Timewarp event latencies not in ascending order in trial %d.\n',smr)
return
end
timeStretchMarks = [ ...
repmat(1, [size(timeStretchMarks,1), 1]), ...% Epoch begins
timeStretchMarks, ...
repmat(length(times), [size(timeStretchMarks,1), 1])]; % Epoch ends
if length(Arg) < 2 || isempty(Arg{2})
timeStretchRef = median(timeStretchMarks);
else
timeStretchRef = Arg{2};
timeStretchRef = round(1+(timeStretchRef-times(1))*srate/1000); % convert from ms to frames -sm
timeStretchRef = [1 timeStretchRef length(times)]; % add epoch beginning, end
end
if length(Arg) < 3 || isempty(Arg{3})
timeStretchColors = {};
else
timeStretchColors = Arg{3};
end
fprintf('The %d events specified in each trial will be time warped to latencies:',length(timeStretchRef)-2);
fprintf(' %.0f', times(1)+1000*(timeStretchRef(2:end-1)-1)/srate); % converted from frames to ms -sm
fprintf(' ms\n');
timestretchflag = NO;
elseif Coherflag == YES
if length(Arg) > 3 || length(Arg) < 1
help erpimage
fprintf('\nerpimage(): coher arg must be size <= 3.\n');
return
end
coherfreq = Arg(1);
if size(Arg,2) == 1
coherfreq = Arg(1);
else
coherfreq = Arg(1:2);
end
if size(Arg,2) == 3
Cohsigflag = YES;
alpha = Arg(3);
if alpha < 0 || alpha > 0.1
fprintf('\nerpimage(): alpha value %g out of bounds.\n',alpha);
return
end
end
Coherflag = NO;
Erpflag = YES; % plot amp, coher below erp time series
elseif Topoflag == YES
if length(Arg) < 2
help erpimage
fprintf('\nerpimage(): topo arg must be a list of length 2 or 3.\n');
return
end
topomap = Arg{1};
eloc_file = Arg{2};
if length(Arg) > 2, eloc_info = Arg{3};
else eloc_info = [];
end
Topoflag = NO;
elseif Specflag == YES
if length(Arg) ~= 2
error('\nerpimage(): ''spec'' flag argument must be a numeric array of length 2.\n');
return
end
lospecHz = Arg(1);
hispecHz = Arg(2);
Specflag = NO;
elseif SpecAxisflag == YES
SpecAxis = Arg;
if ~strcmpi(SpecAxis,'lin') && ~strcmpi(SpecAxis,'log')
error('\nerpimage(): spectrum axis type must be ''lin'' or ''log''.\n');
return
end
if strcmpi(SpecAxis,'lin')
SpecAxis = 'linear'; % convert to MATLAB Xscale keyword
end
SpecAxisflag = NO;
elseif Renormflag == YES
renorm = Arg;
Renormflag = NO;
elseif NoShowflag == YES
NoShow = Arg;
if strcmpi(NoShow, 'off'), NoShow = 'no'; end
NoShowflag = NO;
elseif Alignflag == YES
aligntime = Arg;
Alignflag = NO;
elseif percentileflag == YES
percentiles = Arg;
percentileflag = NO;
elseif Limitflag == YES
% [lotime hitime loerp hierp loamp hiamp locoher hicoher]
if size(Arg,1) ~= 1 || size(Arg,2) < 2 || size(Arg,2) > 9
help erpimage
fprintf('\nerpimage(): limits arg must be a vector sized (1,2<->9).\n');
return
end
if ~isnan(Arg(1)) && (Arg(2) <= Arg(1))
help erpimage
fprintf('\nerpimage(): time limits out of order or out of range.\n');
return
end
if Arg(1) < min(times)
Arg(1) = min(times);
fprintf('Adjusting mintime limit to first data value %g\n',min(times));
end
if Arg(2) > max(times)
Arg(2) = max(times);
fprintf('Adjusting maxtime limit to last data value %g\n',max(times));
end
timelimits = Arg(1:2);
if length(Arg)> 2
minerp = Arg(3);
end
if length(Arg)> 3
maxerp = Arg(4);
end
if ~isnan(maxerp) && maxerp <= minerp
help erpimage
fprintf('\nerpimage(): erp limits args out of order.\n');
return
end
if length(Arg)> 4
minamp = Arg(5);
end
if length(Arg)> 5
maxamp = Arg(6);
end
if maxamp <= minamp
help erpimage
fprintf('\nerpimage(): amp limits args out of order.\n');
return
end
if length(Arg)> 6
mincoh = Arg(7);
end
if length(Arg)> 7
maxcoh = Arg(8);
end
if maxcoh <= mincoh
help erpimage
fprintf('\nerpimage(): coh limits args out of order.\n');
return
end
if length(Arg)>8
baseamp = Arg(9); % for 'allamps'
end
Limitflag = NO;
elseif Srateflag == YES
srate = Arg(1);
Srateflag = NO;
elseif Cycleflag == YES
cycles = Arg;
Cycleflag = NO;
elseif Auxvarflag == YES
if isa(Arg,'cell')==YES && length(Arg)==2
auxvar = Arg{1};
auxcolors = Arg{2};
elseif isa(Arg,'cell')==YES
fprintf('\nerpimage(): auxvars argument must be a matrix or length-2 cell array.\n');
return
else
auxvar = Arg; % no auxcolors specified
end
[xr,xc] = size(auxvar);
lns = length(sortvar);
if xr ~= lns && xc ~= lns
error('\nerpimage(): auxvar columns different from the number of epochs in data');
elseif xr == lns && xc ~= lns
auxvar = auxvar'; % exchange rows/cols
end
Auxvarflag = NO;
elseif Vertflag == YES
verttimes = Arg;
Vertflag = NO;
elseif Horzflag == YES
horzepochs = Arg;
Horzflag = NO;
elseif yerplabelflag == YES
yerplabel = Arg;
yerplabelflag = NO;
elseif Signifflag == YES
signifs = Arg; % [low_amp hi_amp coher]
if length(signifs) ~= 3
fprintf('\nerpimage(): signif arg [%g] must have 3 values\n',Arg);
return
end
Signifflag = NO;
elseif Allcohersflag == YES
data2=Arg;
if size(data2) ~= size(data)
fprintf('\nerpimage(): allcohers data matrix must be the same size as data.\n');
return
end
Allcohersflag = NO;
elseif Phaseflag == YES
n = length(Arg);
if n > 5
error('\nerpimage(): Too many arguments for keyword ''phasesort''');
end
phargs = Arg;
if phargs(3) < 0
error('\nerpimage(): Invalid negative frequency argument for keyword ''phasesort''');
end
if n>=4
if phargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''phasesort''');
end
end
if min(phargs(1)) < times(1) || max(phargs(1)) > times(end)
error('\nerpimage(): time for phase sorting filter out of bound.');
end
if phargs(2) >= 100 || phargs(2) < -100
error('\nerpimage(): %-argument for keyword ''phasesort'' must be (-100;100)');
end
if length(phargs) >= 4 && phargs(3) > phargs(4)
error('\nerpimage(): Phase sorting frequency range must be increasing.');
end
if length(phargs) == 5
topphase = phargs(5);
end
Phaseflag = NO;
elseif Sortwinflag == YES % 'ampsort' mean amplitude over a time window
n = length(Arg);
sortwinarg = Arg;
if n > 2
error('\nerpimage(): Too many arguments for keyword ''sortwin''');
end
if min(sortwinarg(1)) < times(1) || max(sortwinarg(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(sortwinarg(2)) < times(1) || max(sortwinarg(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 && sortwinarg(1) > sortwinarg(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
Sortwinflag = NO;
elseif Ampflag == YES % 'ampsort',[center_time,prcnt_reject,minfreq,maxfreq]
n = length(Arg);
if n > 4
error('\nerpimage(): Too many arguments for keyword ''ampsort''');
end
ampargs = Arg;
% if ampargs(3) < 0
% error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
% end
if n>=4
if ampargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
end
end
if ~isinf(ampargs(1))
if min(ampargs(1)) < times(1) || max(ampargs(1)) > times(end)
error('\nerpimage(): time for amplitude sorting filter out of bounds.');
end
end
if ampargs(2) >= 100 || ampargs(2) < -100
error('\nerpimage(): percentile argument for keyword ''ampsort'' must be (-100;100)');
end
if length(ampargs) == 4 && abs(ampargs(3)) > abs(ampargs(4))
error('\nerpimage(): Amplitude sorting frequency range must be increasing.');
end
Ampflag = NO;
elseif Valflag == YES % sort by potential value in a given window
% Usage: 'valsort',[mintime,maxtime,direction]
n = length(Arg);
if n > 3
error('\nerpimage(): Too many arguments for keyword ''valsort''');
end
valargs = Arg;
if min(valargs(1)) < times(1) || max(valargs(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(valargs(2)) < times(1) || max(valargs(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 && valargs(1) > valargs(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
if n==3 && (~isnumeric(valargs(3)) || valargs(3)==0)
error('\nerpimage(): Value sorting direction must be +1 or -1.');
end
Valflag = NO;
elseif plotmodeflag == YES
plotmode = Arg; plotmodeflag = NO;
elseif titleflag == YES
titl = Arg; titleflag = NO;
elseif Erpalphaflag == YES
erpalpha = Arg(1);
if erpalpha < MIN_ERPALPHA || erpalpha > MAX_ERPALPHA
fprintf('\nerpimage(): erpalpha value is out of bounds [%g, %g]\n',...
MIN_ERPALPHA,MAX_ERPALPHA);
return
end
Erpalphaflag = NO;
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
elseif strcmpi(Arg,'avg_type')
if a < nargin
a=a+1;
Arg = eval(['arg' int2str(a-6)]);
if strcmpi(Arg, 'Gaussian'), mvavg_type='gaussian';
elseif strcmpi(Arg, 'Boxcar'), mvavg_type='boxcar';
else error('\nerpimage(): Invalid value for optional argument ''avg_type''.');
end
else
error('\nerpimage(): Optional argument ''avg_type'' needs to be assigned a value.');
end
elseif strcmp(Arg,'nosort')
Nosort = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Nosort = YES;
a = a + 1;
elseif strcmpi(Arg, 'off')
Nosort = NO;
a = a + 1;
end
end
elseif strcmp(Arg,'showwin')
Showwin = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Showwin = YES; a = a+1;
elseif strcmpi(Arg, 'off')
Showwin = NO; a = a+1;
end
end
elseif strcmp(Arg,'noplot') % elseif strcmp(Arg,'NoShow') % by Luca && Ramon
NoShow = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), NoShow = YES; a = a+1;
elseif strcmpi(Arg, 'off'), NoShow = NO; a = a+1;
end
end
elseif strcmpi(Arg,'replace_ties')
if a < nargin
a = a+1;
temp = eval(['arg' int2str(a-6)]);
if strcmpi(temp,'on')
replace_ties = YES;
elseif strcmpi(temp,'off')
replace_ties = NO;
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
elseif strcmpi(Arg,'sortvar_limits')
if a < nargin
a = a+1;
sortvar_limits = eval(['arg' int2str(a-6)]);
if ischar(sortvar_limits) || length(sortvar_limits)~=2
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
else
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'erp')
Erpflag = YES;
erp_ptiles=1;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Erpflag = YES; erp_ptiles=1; a = a+1;
elseif strcmpi(Arg, 'off'), Erpflag = NO; a = a+1;
elseif strcmpi(Arg,'1') || (Arg(1)==1), Erplag = YES; erp_ptiles=1; a=a+1;
elseif strcmpi(Arg,'2') || (Arg(1)==2), Erplag = YES; erp_ptiles=2; a=a+1;
elseif strcmpi(Arg,'3') || (Arg(1)==3), Erplag = YES; erp_ptiles=3; a=a+1;
elseif strcmpi(Arg,'4') || (Arg(1)==4), Erplag = YES; erp_ptiles=4; a=a+1;
end
end
elseif strcmpi(Arg,'rmerp')
Rmerp = 'yes';
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Rmerp = 'yes'; a = a+1;
elseif strcmpi(Arg, 'off')
Rmerp = 'no'; a = a+1;
end
end
elseif strcmp(Arg,'cbar') || strcmp(Arg,'colorbar')
Colorbar = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Colorbar = YES; a = a+1;
elseif strcmpi(Arg, 'off')
Colorbar = NO; a = a+1;
end
end
elseif (strcmp(Arg,'allamps') || strcmp(Arg,'plotamps'))
Allampsflag = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Allampsflag = YES; a = a+1;
elseif strcmpi(Arg, 'off')
Allampsflag = NO; a = a+1;
end
end
elseif strcmpi(Arg,'erpstd')
Erpstdflag = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
Erpstdflag = YES; a = a+1;
elseif strcmpi(Arg, 'off')
Erpstdflag = NO; a = a+1;
end
end
elseif strcmp(Arg,'noxlabel') || strcmp(Arg,'noxlabels') || strcmp(Arg,'nox')
NoTimeflag = YES;
if a < nargin
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on')
NoTimeflag = YES; a = a+1;
elseif strcmpi(Arg, 'off')
NoTimeflag = NO; a = a+1;
end
end
elseif strcmp(Arg,'plotmode')
plotmodeflag = YES;
elseif strcmp(Arg,'sortvarpercent')
percentileflag = YES;
elseif strcmp(Arg,'renorm')
Renormflag = YES;
elseif strcmp(Arg,'NoShow')
NoShowflag = YES;
elseif strcmp(Arg,'caxis')
Caxflag = YES;
elseif strcmp(Arg,'title')
titleflag = YES;
elseif strcmp(Arg,'coher')
Coherflag = YES;
elseif strcmp(Arg,'timestretch') || strcmp(Arg,'timewarp') % Added -JH
timestretchflag = YES;
elseif strcmp(Arg,'allcohers')
Allcohersflag = YES;
elseif strcmp(Arg,'topo') || strcmp(Arg,'topoplot')
Topoflag = YES;