forked from cab79/Matlab_files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewtimef_singletrial.m
2219 lines (2029 loc) · 95.2 KB
/
newtimef_singletrial.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
% newtimef() - Return estimates and plots of mean event-related (log) spectral
% perturbation (ERSP) and inter-trial coherence (ITC) events across
% event-related trials (epochs) of a single input channel time series.
%
% * Also can compute and statistically compare transforms for two time
% series. Use this to compare ERSP and ITC means in two conditions.
%
% * Uses either fixed-window, zero-padded FFTs (fastest), or wavelet
% 0-padded DFTs. FFT uses Hanning tapers; wavelets use (similar) Morlet
% tapers.
%
% * For the wavelet and FFT methods, output frequency spacing
% is the lowest frequency ('srate'/'winsize') divided by 'padratio'.
% NaN input values (such as returned by eventlock()) are ignored.
%
% * If 'alpha' is given (see below), permutation statistics are computed
% (from a distribution of 'naccu' surrogate data trials) and
% non-significant features of the output plots are zeroed out
% and plotted in green.
%
% * Given a 'topovec' topo vector and 'elocs' electrode location file,
% the figure also shows a topoplot() view of the specified scalp map.
%
% * Note: Left-click on subplots to view and zoom in separate windows.
%
% Usage with single dataset:
% >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ...
% newtimef(data, frames, epochlim, srate, cycles,...
% 'key1',value1, 'key2',value2, ... );
%
% Example to compare two condition (channel 1 EEG versus ALLEEG(2)):
% >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ...
% newtimef({EEG.data(1,:,:) ALLEEG(2).data(1,:,:)},
% EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, cycles);
% NOTE:
% >> timef details % presents more detailed argument information
% % Note: version timef() also computes multitaper transforms
%
% Required inputs: Value {default}
% data = Single-channel data vector (1,frames*ntrials), else
% 2-D array (frames,trials) or 3-D array (1,frames,trials).
% To compare two conditions (data1 versus data2), in place of
% a single data matrix enter a cell array {data1 data2}
% frames = Frames per trial. Ignored if data are 2-D or 3-D. {750}
% tlimits = [mintime maxtime] (ms). Note that these are the time limits
% of the data epochs themselves, NOT A SUB-WINDOW TO EXTRACT
% FROM THE EPOCHS as is the case for pop_newtimef(). {[-1000 2000]}
% Fs = data sampling rate (Hz) {default: read from icadefs.m or 250}
% varwin = [real] indicates the number of cycles for the time-frequency
% decomposition {default: 0}
% If 0, use FFTs and Hanning window tapering.
% If [real positive scalar], the number of cycles in each Morlet
% wavelet, held constant across frequencies.
% If [cycles cycles(2)] wavelet cycles increase with
% frequency beginning at cycles(1) and, if cycles(2) > 1,
% increasing to cycles(2) at the upper frequency,
% If cycles(2) = 0, use same window size for all frequencies
% (similar to FFT when cycles(1) = 1)
% If cycles(2) = 1, cycles do not increase (same as giving
% only one value for 'cycles'). This corresponds to a pure
% wavelet decomposition, same number of cycles at each frequency.
% If 0 < cycles(2) < 1, cycles increase linearly with frequency:
% from 0 --> FFT (same window width at all frequencies)
% to 1 --> wavelet (same number of cycles at all frequencies).
% The exact number of cycles in the highest frequency window is
% indicated in the command line output. Typical value: 'cycles', [3 0.5]
%
% Optional inter-trial coherence (ITC) Type:
% 'itctype' = ['coher'|'phasecoher'|'phasecoher2'] Compute either linear
% coherence ('coher') or phase coherence ('phasecoher').
% Originall called 'phase-locking factor' {default: 'phasecoher'}
%
% Optional detrending:
% 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'}
% 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'}
%
% Optional FFT/DFT parameters:
% 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames);
% If cycles >0: The *longest* window length to use. This
% determines the lowest output frequency. Note: this parameter
% is overwritten when the minimum frequency requires
% a longer time window {default: ~frames/8}
% 'timesout' = Number of output times (int<frames-winframes). Enter a
% negative value [-S] to subsample original times by S.
% Enter an array to obtain spectral decomposition at
% specific times (Note: The algorithm finds the closest time
% point in data; this could give a slightly unevenly spaced
% time array {default: 200}
% 'padratio' = FFT-length/winframes (2^k) {default: 2}
% Multiplies the number of output frequencies by dividing
% their spacing (standard FFT padding). When cycles~=0,
% frequency spacing is divided by padratio.
% 'maxfreq' = Maximum frequency (Hz) to plot (& to output, if cycles>0)
% If cycles==0, all FFT frequencies are output. {default: 50}
% DEPRECATED, use 'freqs' instead,and never both.
% 'freqs' = [min max] frequency limits. {default [minfreq 50],
% minfreq being determined by the number of data points,
% cycles and sampling frequency.
% 'nfreqs' = number of output frequencies. For FFT, closest computed
% frequency will be returned. Overwrite 'padratio' effects
% for wavelets. {default: use 'padratio'}
% 'freqscale' = ['log'|'linear'] frequency scale. {default: 'linear'}
% Note that for obtaining 'log' spaced freqs using FFT,
% closest correspondant frequencies in the 'linear' space
% are returned.
% 'verbose' = ['on'|'off'] print text {'on'}
% 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence
% (ITC) from x and y. This computes an 'intrinsic' coherence
% of x and y not arising directly from common phase locking
% to experimental events. See notes. {default: 'off'}
% 'wletmethod' = ['dftfilt'|'dftfilt2'|'dftfilt3'] Wavelet type to use.
% 'dftfilt2' -> Morlet-variant wavelets, or Hanning DFT.
% 'dftfilt3' -> Morlet wavelets. See the timefreq() function
% for more detials {default: 'dftfilt3'}
% 'cycleinc' ['linear'|'log'] mode of cycles increase when [min max] cycles
% are provided in 'cycle' parameter. Applies only to
% 'wletmethod','dftfilt' {default: 'linear'}
%
% Optional baseline parameters:
% 'baseline' = Spectral baseline end-time (in ms). NaN --> no baseline is used.
% A [min max] range may also be entered
% You may also enter one row per region for baseline
% e.g. [0 100; 300 400] considers the window 0 to 100 ms and
% 300 to 400 ms This parameter validly defines all baseline types
% below. Again, [NaN] Prevent baseline subtraction.
% {default: 0 -> all negative time values}.
% 'powbase' = Baseline spectrum to log-subtract {default|NaN -> from data}
% 'commonbase' = ['on'|'off'] use common baseline when comparing two
% conditions {default: 'on'}.
% 'basenorm' = ['on'|'off'] 'on' normalize baseline in the power spectral
% average; else 'off', divide by the average power across
% trials at each frequency (gain model). {default: 'off'}
% 'trialbase' = ['on'|'off'|'full'] perform baseline (normalization or division
% above in single trial instead of the trial average. Default
% if 'off'. 'full' is an option that perform single
% trial normalization (or simple division based on the
% 'basenorm' input over the full trial length before
% performing standard baseline removal. It has been
% shown to be less sensitive to noisy trials in Grandchamp R,
% Delorme A. (2011) Single-trial normalization for event-related
% spectral decomposition reduces sensitivity to noisy trials.
% Front Psychol. 2:236.
%
% Optional time warping parameter:
% 'timewarp' = [eventms matrix] Time-warp amplitude and phase time-
% courses(following time/freq transform but before
% smoothing across trials). 'eventms' is a matrix
% of size (all_trials,epoch_events) whose columns
% specify the epoch times (latencies) (in ms) at which
% the same series of successive events occur in each
% trial. If two data conditions, eventms should be
% [eventms1;eventms2] --> all trials stacked vertically.
% 'timewarpms' = [warpms] optional vector of event times (latencies) (in ms)
% to which the series of events should be warped.
% (Note: Epoch start and end should not be declared
% as eventms or warpms}. If 'warpms' is absent or [],
% the median of each 'eventms' column will be used;
% If two datasets, the grand medians of the two are used.
% 'timewarpidx' = [plotidx] is an vector of indices telling which of
% the time-warped 'eventms' columns (above) to show with
% vertical lines. If undefined, all columns are plotted.
% Overwrites the 'vert' argument (below) if any.
%
% Optional permutation parameters:
% 'alpha' = If non-0, compute two-tailed permutation significance
% probability level. Show non-signif. output values
% as green. {default: 0}
% 'mcorrect' = ['none'|'fdr'] correction for multiple comparison
% 'fdr' uses false detection rate (see function fdr()).
% Not available for condition comparisons. {default:'none'}
% 'pcontour' = ['on'|'off'] draw contour around significant regions
% instead of masking them. Not available for condition
% comparisons. {default:'off'}
% 'naccu' = Number of permutation replications to accumulate {200}
% 'baseboot' = permutation baseline subtract (1 -> use 'baseline';
% 0 -> use whole trial
% [min max] -> use time range)
% You may also enter one row per region for baseline,
% e.g. [0 100; 300 400] considers the window 0 to 100 ms
% and 300 to 400 ms. {default: 1}
% 'boottype' = ['shuffle'|'rand'|'randall'] 'shuffle' -> shuffle times
% and trials; 'rand' -> invert polarity of spectral data
% (for ERSP) or randomize phase (for ITC); 'randall' ->
% compute significances by accumulating random-polarity
% inversions for each time/frequency point (slow!). Note
% that in the previous revision of this function, this
% method was called 'bootstrap' though it is actually
% permutation {default: 'shuffle'}
% 'condboot' = ['abs'|'angle'|'complex'] to compare two conditions,
% either subtract ITC absolute values ('abs'), angles
% ('angles'), or complex values ('complex'). {default: 'abs'}
% 'pboot' = permutation power limits (e.g., from newtimef()) {def: from data}
% 'rboot' = permutation ITC limits (e.g., from newtimef()).
% Note: Both 'pboot' and 'rboot' must be provided to avoid
% recomputing the surrogate data! {default: from data}
%
% Optional Scalp Map:
% 'topovec' = Scalp topography (map) to plot {none}
% 'elocs' = Electrode location file for scalp map {none}
% Value should be a string array containing the path
% and name of the file. For file format, see
% >> topoplot example
% 'chaninfo' Passed to topoplot, if called.
% [struct] optional structure containing fields
% 'nosedir', 'plotrad', and/or 'chantype'. See these
% field definitions above, below.
% {default: nosedir +X, plotrad 0.5, all channels}
%
% Optional Plotting Parameters:
% 'scale' = ['log'|'abs'] visualize power in log scale (dB) or absolute
% scale. {default: 'log'}
% 'plottype' = ['image'|'curve'] plot time/frequency images or traces
% (curves, one curve per frequency). {default: 'image'}
% 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all
% frequencies given as input. {default: 'on'}
% 'highlightmode' = ['background'|'bottom'] For 'curve' plots only,
% display significant time regions either in the plot background
% or under the curve.
% 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'}
% 'plotitc' = ['on'|'off'] Plot inter-trial coherence {'on'}
% 'plotphasesign' = ['on'|'off'] Plot phase sign in the inter trial coherence {'on'}
% 'plotphaseonly' = ['on'|'off'] Plot ITC phase instead of ITC amplitude {'off'}
% 'erspmax' = [real] set the ERSP max. For the color scale (min= -max) {auto}
% 'itcmax' = [real] set the ITC image maximum for the color scale {auto}
% 'hzdir' = ['up' or 'normal'|'down' or 'reverse'] Direction of
% the frequency axes {default: as in icadefs.m, or 'up'}
% 'ydir' = ['up' or 'normal'|'down' or 'reverse'] Direction of
% the ERP axis plotted below the ITC {as in icadefs.m, or 'up'}
% 'erplim' = [min max] ERP limits for ITC (below ITC image) {auto}
% 'itcavglim' = [min max] average ITC limits for all freq. (left of ITC) {auto}
% 'speclim' = [min max] average spectrum limits (left of ERSP image) {auto}
% 'erspmarglim' = [min max] average marginal ERSP limits (below ERSP image) {auto}
% 'title' = Optional figure or (brief) title {none}. For multiple conditions
% this must contain a cell array of 2 or 3 title strings.
% 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none}
% 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2}
% 'axesfont' = Axes text font size {10}
% 'titlefont' = Title text font size {8}
% 'vert' = [times_vector] -> plot vertical dashed lines at specified times
% in ms. {default: none}
% 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'}
% 'caption' = Caption of the figure {none}
% 'outputformat' = ['old'|'plot'] for compatibility with script that used the
% old output format, set to 'old' (mbase in absolute amplitude (not
% dB) and real itc instead of complex itc). 'plot' returns
% the plotted result {default: 'plot'}
% Outputs:
% ersp = (nfreqs,timesout) matrix of log spectral diffs from baseline
% (in dB log scale or absolute scale). Use the 'plot' output format
% above to output the ERSP as shown on the plot.
% itc = (nfreqs,timesout) matrix of complex inter-trial coherencies.
% itc is complex -- ITC magnitude is abs(itc); ITC phase in radians
% is angle(itc), or in deg phase(itc)*180/pi.
% powbase = baseline power spectrum. Note that even, when selecting the
% the 'trialbase' option, the average power spectrum is
% returned (not trial based). To obtain the baseline of
% each trial, recompute it manually using the tfdata
% output described below.
% times = vector of output times (spectral time window centers) (in ms).
% freqs = vector of frequency bin centers (in Hz).
% erspboot = (nfreqs,2) matrix of [lower upper] ERSP significance.
% itcboot = (nfreqs) matrix of [upper] abs(itc) threshold.
% tfdata = optional (nfreqs,timesout,trials) time/frequency decomposition
% of the single data trials. Values are complex.
%
% Plot description:
% Assuming both 'plotersp' and 'plotitc' options are 'on' (= default).
% The upper panel presents the data ERSP (Event-Related Spectral Perturbation)
% in dB, with mean baseline spectral activity (in dB) subtracted. Use
% "'baseline', NaN" to prevent timef() from removing the baseline.
% The lower panel presents the data ITC (Inter-Trial Coherence).
% Click on any plot axes to pop up a new window (using 'axcopy()')
% -- Upper left marginal panel presents the mean spectrum during the baseline
% period (blue), and when significance is set, the significance threshold
% at each frequency (dotted green-black trace).
% -- The marginal panel under the ERSP image shows the maximum (green) and
% minimum (blue) ERSP values relative to baseline power at each frequency.
% -- The lower left marginal panel shows mean ITC across the imaged time range
% (blue), and when significance is set, the significance threshold (dotted
% green-black).
% -- The marginal panel under the ITC image shows the ERP (which is produced by
% ITC across the data spectral pass band).
%
% Authors: Arnaud Delorme, Jean Hausser from timef() by Sigurd Enghoff, Scott Makeig
% CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002-
%
% See also: timefreq(), condstat(), newcrossf(), tftopo()
% Deprecated Multitaper Parameters: [not included here]
% 'mtaper' = If [N W], performs multitaper decomposition.
% (N is the time resolution and W the frequency resolution;
% maximum taper number is 2NW-1). Overwrites 'winsize' and 'padratio'.
% If [N W K], forces the use of K Slepian tapers (if possible).
% Phase is calculated using standard methods.
% The use of mutitaper with wavelets (cycles>0) is not
% recommended (as multiwavelets are not implemented).
% Uses Matlab functions DPSS, PMTM. {no multitaper}
% Deprecated time warp keywords (working?)
% 'timewarpfr' = {{[events], [warpfr], [plotidx]}} Time warp amplitude and phase
% time-courses (after time/freq transform but before smoothingtimefreqfunc
% across trials). 'events' is a matrix whose columns specify the
% epoch frames [1 ... end] at which a series of successive events
% occur in each trial. 'warpfr' is an optional vector of event
% frames to which the series of events should be time locked.
% (Note: Epoch start and end should not be declared as events or
% warpfr}. If 'warpfr' is absent or [], the median of each 'events'
% column will be used. [plotidx] is an optional vector of indices
% telling which of the warpfr to plot with vertical lines. If
% undefined, all marks are plotted. Overwrites 'vert' argument,
% if any. [Note: In future releases, 'timewarpfr' will be deprecated
% in favor of 'timewarp' using latencies in ms instead of frames].
% Deprecated original time warp keywords (working?)
% 'timeStretchMarks' = [(marks,trials) matrix] Each trial data will be
% linearly warped (after time/freq. transform) so that the
% event marks are time locked to the reference frames
% (see timeStretchRefs). Marks must be specified in frames
% 'timeStretchRefs' = [1 x marks] Common reference frames to all trials.
% If empty or undefined, median latency for each mark will be used.boottype
% 'timeStretchPlot' = [vector] Indicates the indices of the reference frames
% (in StretchRefs) should be overplotted on the ERSP and ITC.
%
%
% Copyright (C) University of California San Diego, La Jolla, CA
%
% First built as timef.m at CNL / Salk Institute 8/1/98-8/28/01 by
% Sigurd Enghoff and Scott Makeig, edited by Arnaud Delorme
% SCCN/INC/UCSD/ reprogrammed as newtimef -Arnaud Delorme 2002-
% SCCN/INC/UCSD/ added time warping capabilities -Jean Hausser 2005
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 10-19-98 avoided division by zero (using MIN_ABS) -sm
% 10-19-98 improved usage message and commandline info printing -sm
% 10-19-98 made valid [] values for tvec and g.elocs -sm
% 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se && -tpj
% 06-29-99 fixed frequency indexing for constant-Q -se
% 08-24-99 reworked to handle NaN input values -sm
% 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm
% 12-22-99 debugged ERPtimes, added BASE_BOOT -sm
% 01-10-00 debugged BASE_BOOT=0 -sm
% 02-28-00 added NOTE on formula derivation below -sm
% 03-16-00 added axcopy() feature -sm && tpj
% 04-16-00 added multiple marktimes loop -sm
% 04-20-00 fixed ITC cbar limits when spcified in input -sm
% 07-29-00 changed frequencies displayed msg -sm
% 10-12-00 fixed bug in freqs when cycles>0 -sm
% 02-07-01 fixed inconsistency in BASE_BOOT use -sm
% 08-28-01 matlab 'key' value arguments -ad
% 08-28-01 multitaper decomposition -ad
% 01-25-02 reformated help && license -ad
% 03-08-02 debug && compare to old timef function -ad
% 03-16-02 timeout automatically adjusted if too high -ad
% 04-02-02 added 'coher' option -ad
function [P,PS,R,mbase,timesout,freqs,Pboot,Rboot,alltfX,PA] = newtimef_singletrial( data, frames, tlimits, Fs, varwin, varargin);
% Note: Above, PA is output of 'phsamp','on'
% For future 'timewarp' keyword help: 'timewarp' 3rd element {colors} contains a
% list of Matlab linestyles to use for vertical lines marking the occurence
% 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).
%varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot)
% ITC: Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is coherence.
% But here, we consider Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx
% Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC)
% Also called 'phase-locking factor' by Tallon-Baudry et al. (1996)
if nargin < 1
help newtimef;
return;
end;
% Read system (or directory) constants and preferences:
% ------------------------------------------------------
icadefs % read local EEGLAB constants: HZDIR, YDIR, DEFAULT_SRATE, DEFAULT_TIMLIM
if ~exist('HZDIR'), HZDIR = 'up'; end; % ascending freqs
if ~exist('YDIR'), YDIR = 'up'; end; % positive up
if YDIR == 1, YDIR = 'up'; end; % convert from [-1|1] as set in icadefs.m
if YDIR == -1, YDIR = 'down'; end; % and read by other plotting functions
if ~exist('DEFAULT_SRATE'), DEFAULT_SRATE = 250; end; % 250 Hz
if ~exist('DEFAULT_TIMLIM'), DEFAULT_TIMLIM = [-1000 2000]; end; % [-1 2] s epochs
% Constants set here:
% ------------------
ERSP_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value
% giving symmetric +/- caxis limits.
ITC_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value
% giving symmetric +/- caxis limits.
MIN_ABS = 1e-8; % avoid division by ~zero
% Command line argument defaults:
% ------------------------------
DEFAULT_NWIN = 200; % Number of windows = horizontal resolution
DEFAULT_VARWIN = 0; % Fixed window length or fixed number of cycles.
% =0: fix window length to that determined by nwin
% >0: set window length equal to varwin cycles
% Bounded above by winsize, which determines
% the min. freq. to be computed.
DEFAULT_OVERSMP = 2; % Number of times to oversample frequencies
DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz)
DEFAULT_TITLE = ''; % Figure title (no default)
DEFAULT_ELOC = 'chan.locs'; % Channel location file
DEFAULT_ALPHA = NaN; % Percentile of bins to keep
DEFAULT_MARKTIME= NaN;
% Font sizes:
AXES_FONT = 10; % axes text FontSize
TITLE_FONT = 8;
if (nargin < 2)
frames = floor((DEFAULT_TIMLIN(2)-DEFAULT_TIMLIM(1))/DEFAULT_SRATE);
elseif (~isnumeric(frames) | length(frames)~=1 | frames~=round(frames))
error('Value of frames must be an integer.');
elseif (frames <= 0)
error('Value of frames must be positive.');
end;
DEFAULT_WINSIZE = max(pow2(nextpow2(frames)-3),4);
DEFAULT_PAD = max(pow2(nextpow2(DEFAULT_WINSIZE)),4);
if (nargin < 1)
help newtimef
return
end
if isstr(data) && strcmp(data,'details')
more on
help timefdetails
more off
return
end
if ~iscell(data)
data = reshape_data(data, frames);
trials = size(data,ndims(data));
else
if ndims(data) == 3 && size(data,1) == 1
error('Cannot process multiple channel component in compare mode');
end;
[data{1}, frames] = reshape_data(data{1}, frames);
[data{2}, frames] = reshape_data(data{2}, frames);
trials = size(data{1},2);
end;
if (nargin < 3)
tlimits = DEFAULT_TIMLIM;
elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3)
error('Value of tlimits must be a vector containing two numbers.');
elseif (tlimits(1) >= tlimits(2))
error('tlimits interval must be ascending.');
end
if (nargin < 4)
Fs = DEFAULT_SRATE;
elseif (~isnumeric(Fs) | length(Fs)~=1)
error('Value of srate must be a number.');
elseif (Fs <= 0)
error('Value of srate must be positive.');
end
if (nargin < 5)
varwin = DEFAULT_VARWIN;
elseif ~isnumeric(varwin) && strcmpi(varwin, 'cycles')
varwin = varargin{1};
varargin(1) = [];
elseif (varwin < 0)
error('Value of cycles must be zero or positive.');
end
% build a structure for keyword arguments
% --------------------------------------
if ~isempty(varargin)
[tmp indices] = unique_bc(varargin(1:2:end));
varargin = varargin(sort(union(indices*2-1, indices*2))); % these 2 lines remove duplicate arguments
try, g = struct(varargin{:});
catch, error('Argument error in the {''param'', value} sequence'); end;
end
%}
[ g timefreqopts ] = finputcheck(varargin, ...
{'boottype' 'string' {'shuffle','rand','randall'} 'shuffle'; ...
'condboot' 'string' {'abs','angle','complex'} 'abs'; ...
'title' { 'string','cell' } { [] [] } DEFAULT_TITLE; ...
'title2' 'string' [] DEFAULT_TITLE; ...
'winsize' 'integer' [0 Inf] DEFAULT_WINSIZE; ...
'pad' 'real' [] DEFAULT_PAD; ...
'timesout' 'integer' [] DEFAULT_NWIN; ...
'padratio' 'integer' [0 Inf] DEFAULT_OVERSMP; ...
'topovec' 'real' [] []; ...
'elocs' {'string','struct'} [] DEFAULT_ELOC; ...
'alpha' 'real' [0 0.5] DEFAULT_ALPHA; ...
'marktimes' 'real' [] DEFAULT_MARKTIME; ...
'powbase' 'real' [] NaN; ...
'pboot' 'real' [] NaN; ...
'rboot' 'real' [] NaN; ...
'plotersp' 'string' {'on','off'} 'on'; ...
'plotamp' 'string' {'on','off'} 'on'; ...
'plotitc' 'string' {'on','off'} 'on'; ...
'detrend' 'string' {'on','off'} 'off'; ...
'rmerp' 'string' {'on','off'} 'off'; ...
'basenorm' 'string' {'on','off'} 'off'; ...
'commonbase' 'string' {'on','off'} 'on'; ...
'baseline' 'real' [] 0; ...
'baseboot' 'real' [] 1; ...
'linewidth' 'integer' [1 2] 2; ...
'naccu' 'integer' [1 Inf] 200; ...
'mtaper' 'real' [] []; ...
'maxfreq' 'real' [0 Inf] DEFAULT_MAXFREQ; ...
'freqs' 'real' [0 Inf] [0 DEFAULT_MAXFREQ]; ...
'cycles' 'integer' [] []; ...
'nfreqs' 'integer' [] []; ...
'freqscale' 'string' [] 'linear'; ...
'vert' 'real' [] []; ...
'newfig' 'string' {'on','off'} 'on'; ...
'type' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ...
'itctype' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ...
'phsamp' 'string' {'on','off'} 'off'; ... % phsamp not completed - Toby 9.28.2006
'plotphaseonly' 'string' {'on','off'} 'off'; ...
'plotphasesign' 'string' {'on','off'} 'on'; ...
'plotphase' 'string' {'on','off'} 'on'; ... % same as above for backward compatibility
'pcontour' 'string' {'on','off'} 'off'; ...
'outputformat' 'string' {'old','new','plot' } 'plot'; ...
'itcmax' 'real' [] []; ...
'erspmax' 'real' [] []; ...
'lowmem' 'string' {'on','off'} 'off'; ...
'verbose' 'string' {'on','off'} 'on'; ...
'plottype' 'string' {'image','curve'} 'image'; ...
'mcorrect' 'string' {'fdr','none'} 'none'; ...
'plotmean' 'string' {'on','off'} 'on'; ...
'plotmode' 'string' {} ''; ... % for metaplottopo
'highlightmode' 'string' {'background','bottom'} 'background'; ...
'chaninfo' 'struct' [] struct([]); ...
'erspmarglim' 'real' [] []; ...
'itcavglim' 'real' [] []; ...
'erplim' 'real' [] []; ...
'speclim' 'real' [] []; ...
'ntimesout' 'real' [] []; ...
'scale' 'string' { 'log','abs'} 'log'; ...
'timewarp' 'real' [] []; ...
'precomputed' 'struct' [] struct([]); ...
'timewarpms' 'real' [] []; ...
'timewarpfr' 'real' [] []; ...
'timewarpidx' 'real' [] []; ...
'timewarpidx' 'real' [] []; ...
'timeStretchMarks' 'real' [] []; ...
'timeStretchRefs' 'real' [] []; ...
'timeStretchPlot' 'real' [] []; ...
'trialbase' 'string' {'on','off','full'} 'off';
'caption' 'string' [] ''; ...
'hzdir' 'string' {'up','down','normal','reverse'} HZDIR; ...
'ydir' 'string' {'up','down','normal','reverse'} YDIR; ...
'cycleinc' 'string' {'linear','log'} 'linear'
}, 'newtimef', 'ignore');
if isstr(g), error(g); end;
if strcmpi(g.plotamp, 'off'), g.plotersp = 'off'; end;
if strcmpi(g.basenorm, 'on'), g.scale = 'abs'; end;
if ~strcmpi(g.itctype , 'phasecoher'), g.type = g.itctype; end;
g.tlimits = tlimits;
g.frames = frames;
g.srate = Fs;
if isempty(g.cycles)
g.cycles = varwin;
end;
g.AXES_FONT = AXES_FONT; % axes text FontSize
g.TITLE_FONT = TITLE_FONT;
g.ERSP_CAXIS_LIMIT = ERSP_CAXIS_LIMIT;
g.ITC_CAXIS_LIMIT = ITC_CAXIS_LIMIT;
if ~strcmpi(g.plotphase, 'on'), g.plotphasesign = g.plotphase; end;
% unpack 'timewarp' (and undocumented 'timewarpfr') arguments
%------------------------------------------------------------
if isfield(g,'timewarpfr')
if iscell(g.timewarpfr) && length(g.timewarpfr) > 3
error('undocumented ''timewarpfr'' cell array may have at most 3 elements');
end
end
if ~isempty(g.nfreqs)
verboseprintf(g.verbose, 'Warning: ''nfreqs'' input overwrite ''padratio''\n');
end;
if strcmpi(g.basenorm, 'on')
verboseprintf(g.verbose, 'Baseline normalization is on (results will be shown as z-scores)\n');
end;
if isfield(g,'timewarp') && ~isempty(g.timewarp)
if ndims(data) == 3
error('Cannot perform time warping on 3-D data input');
end;
if ~isempty(g.timewarp) % convert timewarp ms to timewarpfr frames -sm
fprintf('\n')
if iscell(g.timewarp)
error('timewarp argument must be a (total_trials,epoch_events) matrix');
end
evntms = g.timewarp;
warpfr = round((evntms - g.tlimits(1))/1000*g.srate)+1;
g.timewarpfr{1} = warpfr';
if isfield(g,'timewarpms')
refms = g.timewarpms;
reffr = round((refms - g.tlimits(1))/1000*g.srate)+1;
g.timewarpfr{2} = reffr';
end
if isfield(g,'timewarpidx')
g.timewarpfr{3} = g.timewarpidx;
end
end
% convert again to timeStretch parameters
% ---------------------------------------
if ~isempty(g.timewarpfr)
g.timeStretchMarks = g.timewarpfr{1};
if length(g.timewarpfr) > 1
g.timeStretchRefs = g.timewarpfr{2};
end
if length(g.timewarpfr) > 2
if isempty(g.timewarpfr{3})
stretchevents = size(g.timeStretchMarks,1);
g.timeStretchPlot = [1:stretchevents]; % default to plotting all lines
else
g.timeStretchPlot = g.timewarpfr{3};
end
end
if max(max(g.timeStretchMarks)) > frames-2 | min(min(g.timeStretchMarks)) < 3
error('Time warping events must be inside the epochs.');
end
if ~isempty(g.timeStretchRefs)
if max(g.timeStretchRefs) > frames-2 | min(g.timeStretchRefs) < 3
error('Time warping reference latencies must be within the epochs.');
end
end
end
end
% Determining source of the call
% --------------------------------------% 'guicall'= 1 if newtimef is called
callerstr = dbstack(1); % from EEGLAB GUI, otherwise 'guicall'= 0
if isempty(callerstr) % 7/3/2014, Ramon
guicall = 0;
elseif strcmp(callerstr(end).name,'pop_newtimef')
guicall = 1;
else
guicall = 0;
end
% test argument consistency
% --------------------------
if g.tlimits(2)-g.tlimits(1) < 30
verboseprintf(g.verbose, 'newtimef(): WARNING: Specified time range is very small (< 30 ms)???\n');
verboseprintf(g.verbose, ' Epoch time limits should be in msec, not seconds!\n');
end
if (g.winsize > g.frames)
error('Value of winsize must be smaller than epoch frames.');
end
if length(g.timesout) == 1 && g.timesout > 0
if g.timesout > g.frames-g.winsize
g.timesout = g.frames-g.winsize;
disp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]);
end
end;
if (pow2(nextpow2(g.padratio)) ~= g.padratio)
error('Value of padratio must be an integer power of two [1,2,4,8,16,...]');
end
if (g.maxfreq > Fs/2)
verboseprintf(g.verbose, ['Warning: value of maxfreq reduced to Nyquist rate' ...
' (%3.2f)\n\n'], Fs/2);
g.maxfreq = Fs/2;
end
if g.maxfreq ~= DEFAULT_MAXFREQ, g.freqs(2) = g.maxfreq; end;
if isempty(g.topovec)
g.topovec = [];
if isempty(g.elocs)
error('Channel location file must be specified.');
end;
end
if (round(g.naccu*g.alpha) < 2)
verboseprintf(g.verbose, 'Value of alpha is outside its normal range [%g,0.5]\n',2/g.naccu);
g.naccu = round(2/g.alpha);
verboseprintf(g.verbose, ' Increasing the number of iterations to %d\n',g.naccu);
end
if ~isnan(g.alpha)
if length(g.baseboot) == 2
verboseprintf(g.verbose, 'Permutation analysis will use data from %3.2g to %3.2g ms.\n', ...
g.baseboot(1), g.baseboot(2))
elseif g.baseboot > 0
verboseprintf(g.verbose, 'Permutation analysis will use data in (pre-0) baseline subwindows only.\n')
else
verboseprintf(g.verbose, 'Permutation analysis will use data in all subwindows.\n')
end
end
if ~isempty(g.timeStretchMarks) % timeStretch code by Jean Hauser
if isempty(g.timeStretchRefs)
verboseprintf(g.verbose, ['Using median event latencies as reference event times for time warping.\n']);
g.timeStretchRefs = median(g.timeStretchMarks,2);
% Note: Uses (grand) median latencies for two conditions
else
verboseprintf(g.verbose, ['Using supplied latencies as reference event times for time warping.\n']);
end
if isempty(g.timeStretchPlot)
verboseprintf(g.verbose, 'Will not overplot the reference event times on the ERSP.\n');
elseif length(g.timeStretchPlot) > 0
g.vert = ((g.timeStretchRefs(g.timeStretchPlot)-1) ...
/g.srate+g.tlimits(1)/1000)*1000;
fprintf('Plotting timewarp markers at ')
for li = 1:length(g.vert), fprintf('%d ',g.vert(li)); end
fprintf(' ms.\n')
end
end
if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2)
error('vertical line (''vert'') latency outside of epoch boundaries');
end
if strcmp(g.hzdir,'up')| strcmp(g.hzdir,'normal')
g.hzdir = 'normal'; % convert to Matlab graphics constants
elseif strcmp(g.hzdir,'down') | strcmp(g.hzdir,'reverse')| g.hzdir==-1
g.hzdir = 'reverse';
else
error('unknown ''hzdir'' argument');
end
if strcmp(g.ydir,'up')| strcmp(g.ydir,'normal')
g.ydir = 'normal'; % convert to Matlab graphics constants
elseif strcmp(g.ydir,'down') | strcmp(g.ydir,'reverse')
g.ydir = 'reverse';
else
error('unknown ''ydir'' argument');
end
% -----------------
% ERSP scaling unit
% -----------------
if strcmpi(g.scale, 'log')
if strcmpi(g.basenorm, 'on')
g.unitpower = '10*log(std.)'; % impossible
elseif isnan(g.baseline)
g.unitpower = '10*log10(\muV^{2}/Hz)';
else
g.unitpower = 'dB';
end;
else
if strcmpi(g.basenorm, 'on')
g.unitpower = 'std.';
elseif isnan(g.baseline)
g.unitpower = '\muV^{2}/Hz';
else
g.unitpower = '% of baseline';
end;
end;
% Multitaper - used in timef
% --------------------------
if ~isempty(g.mtaper) % multitaper, inspired from a Bijan Pesaran matlab function
if length(g.mtaper) < 3
%error('mtaper arguement must be [N W] or [N W K]');
if g.mtaper(1) * g.mtaper(2) < 1
error('mtaper 2 first arguments'' product must be larger than 1');
end;
if length(g.mtaper) == 2
g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1);
end
if length(g.mtaper) == 3
if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1
error('mtaper number too high (maximum (2*N*W-1))');
end;
end
disp(['Using ' num2str(g.mtaper(3)) ' tapers.']);
NW = g.mtaper(1)*g.mtaper(2); % product NW
N = g.mtaper(1)*g.srate;
[e,v] = dpss(N, NW, 'calc');
e=e(:,1:g.mtaper(3));
g.alltapers = e;
else
g.alltapers = g.mtaper;
disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix');
end;
g.winsize = size(g.alltapers, 1);
g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow
nfk = floor([0 g.maxfreq]./g.srate.*g.pad);
g.padratio = 2*nfk(2)/g.winsize;
%compute number of frequencies
%nf = max(256, g.pad*2^nextpow2(g.winsize+1));
%nfk = floor([0 g.maxfreq]./g.srate.*nf);
%freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also works in the case of a FFT
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute frequency by frequency if low memory
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmpi(g.lowmem, 'on') && numel(data) ~= g.frames && isempty(g.nfreqs) && ~iscell(data)
disp('Lowmem is a deprecated option that is not functional any more');
return;
% NOTE: the code below is functional but the graphical output is
% different when the 'lowmem' option is used compared to when it is not
% used - AD, 29 April 2011
% compute for first 2 trials to get freqsout
XX = reshape(data, 1, frames, prod(size(data))/g.frames);
[P,PS,R,mbase,timesout,freqsout] = newtimef_singletrial(XX(1,:,1), frames, tlimits, Fs, g.cycles, 'plotitc', 'off', 'plotamp', 'off',varargin{:}, 'lowmem', 'off');
% scan all frequencies
for index = 1:length(freqsout)
if nargout < 8
[P(index,:),PS(index,:,:), R(index,:),mbase(index),timesout,tmpfreqs(index),Pboottmp,Rboottmp] = ...
newtimef_singletrial(data, frames, tlimits, Fs, g.cycles, ...
'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ...
'plotamp', 'off', 'plotitc', 'off', 'plotphasesign', 'off',varargin{:}, ...
'lowmem', 'off', 'timesout', timesout);
if ~isempty(Pboottmp)
Pboot(index,:) = Pboottmp;
Rboot(index,:) = Rboottmp;
else
Pboot = [];
Rboot = [];
end;
else
[P(index,:),PS(index,:,:),R(index,:),mbase(index),timesout,tmpfreqs(index),Pboot(index,:),Rboot(index,:), ...
alltfX(index,:,:)] = ...
newtimef_singletrial(data, frames, tlimits, Fs, g.cycles, ...
'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ...
'plotamp', 'off', 'plotphasesign', 'off',varargin{:}, ...
'lowmem', 'off', 'timesout', timesout);
end;
end;
% compute trial-average ERP
% -------------------------
ERP = mean(data,2);
% plot results
%-------------
plottimef(P, R, Pboot, Rboot, ERP, freqsout, timesout, mbase, [], [], g);
return; % finished
end;
%%%%%%%%%%%%%%%%%%%%%%%
% compare 2 conditions
%%%%%%%%%%%%%%%%%%%%%%%
if iscell(data)
if ~guicall && (strcmp(g.basenorm, 'on') || strcmp(g.trialbase, 'on')) % ------------------------------------- Temporary fix for error when using
error('EEGLAB error: basenorm and/or trialbase options cannot be used when processing 2 conditions'); % basenorm or trialbase with two conditions
end;
Pboot = [];
Rboot = [];
if ~strcmpi(g.mcorrect, 'none')
error('Correction for multiple comparison not implemented for comparing conditions');
end;
vararginori = varargin;
if length(data) ~= 2
error('newtimef: to compare two conditions, data must be a length-2 cell array');
end;
% deal with titles
% ----------------
for index = 1:2:length(vararginori)
if index<=length(vararginori) % needed if elements are deleted
% if strcmp(vararginori{index}, 'title') | ... % Added by Jean Hauser
% strcmp(vararginori{index}, 'title2') | ...
if strcmp(vararginori{index}, 'timeStretchMarks') | ...
strcmp(vararginori{index}, 'timeStretchRefs') | ...
strcmp(vararginori{index}, 'timeStretchPlots')
vararginori(index:index+1) = [];
end;
end;
end;
if iscell(g.title) && length(g.title) >= 2 % Changed that part because providing titles
% as cells caused the function to crash (why?)
% at line 704 (g.tlimits = tlimits) -Jean
if length(g.title) == 2,
g.title{3} = [ g.title{1} ' - ' g.title{2} ];
end;
else
disp('Warning: title must be a cell array');
g.title = { 'Condition 1' 'Condition 2' 'Condition 1 minus Condition 2' };
end;
verboseprintf(g.verbose, '\nRunning newtimef() on Condition 1 **********************\n\n');
verboseprintf(g.verbose, 'Note: If an out-of-memory error occurs, try reducing the\n');
verboseprintf(g.verbose, ' the number of time points or number of frequencies\n');
verboseprintf(g.verbose, '(''coher'' options take 3 times the memory of other options)\n\n');
cond_1_epochs = size(data{1},2);
if ~isempty(g.timeStretchMarks)
[P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ...
newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ...
'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ...
'timeStretchMarks', g.timeStretchMarks(:,1:cond_1_epochs), ...
'timeStretchRefs', g.timeStretchRefs);
else
[P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ...
newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ...
'plotersp', 'off', vararginori{:}, 'lowmem', 'off');
end
verboseprintf(g.verbose,'\nRunning newtimef() on Condition 2 **********************\n\n');
[P2,R2,mbase2,timesout,freqs,Pboot2,Rboot2,alltfX2] = ...
newtimef( data{2}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ...
'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ...
'timeStretchMarks', g.timeStretchMarks(:,cond_1_epochs+1:end), ...
'timeStretchRefs', g.timeStretchRefs);
verboseprintf(g.verbose,'\nComputing difference **********************\n\n');
% recompute power baselines
% -------------------------
if ~isnan( g.baseline(1) ) && ~isnan( mbase1(1) ) && isnan(g.powbase(1)) && strcmpi(g.commonbase, 'on')
disp('Recomputing baseline power: using the grand mean of both conditions ...');
mbase = (mbase1 + mbase2)/2;
P1 = P1 + repmat(mbase1(1:size(P1,1))',[1 size(P1,2)]);
P2 = P2 + repmat(mbase2(1:size(P1,1))',[1 size(P1,2)]);
P1 = P1 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]);
P2 = P2 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]);
if ~isnan(g.alpha)
Pboot1 = Pboot1 + repmat(mbase1(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]);
Pboot2 = Pboot2 + repmat(mbase2(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]);
Pboot1 = Pboot1 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]);
Pboot2 = Pboot2 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]);
end;
verboseprintf(g.verbose, '\nSubtracting the common power baseline ...\n');
meanmbase = mbase;
mbase = { mbase mbase };
elseif strcmpi(g.commonbase, 'on')
mbase = { NaN NaN };
meanmbase = mbase{1}; %Ramon :for bug 1657
else
meanmbase = (mbase1 + mbase2)/2;
mbase = { mbase1 mbase2 };
end;
% plotting
% --------
if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on')
g.titleall = g.title;
if strcmpi(g.newfig, 'on'), figure; end; % declare a new figure
% using same color scale
% ----------------------
if ~isfield(g, 'erspmax')
g.erspmax = max( max(max(abs(Pboot1))), max(max(abs(Pboot2))) );
end;
if ~isfield(g, 'itcmax')
g.itcmax = max( max(max(abs(Rboot1))), max(max(abs(Rboot2))) );
end;
subplot(1,3,1); % plot Condition 1
g.title = g.titleall{1};
g = plottimef(P1, R1, Pboot1, Rboot1, mean(data{1},2), freqs, timesout, mbase{1}, [], [], g);
g.itcavglim = [];
subplot(1,3,2); % plot Condition 2
g.title = g.titleall{2};
plottimef(P2, R2, Pboot2, Rboot2, mean(data{2},2), freqs, timesout, mbase{2}, [], [], g);
subplot(1,3,3); % plot Condition 1 - Condition 2
g.title = g.titleall{3};
end;
if isnan(g.alpha)
switch(g.condboot)