-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstimMakeSpatiotemporalExperiment.m
900 lines (748 loc) · 37.7 KB
/
stimMakeSpatiotemporalExperiment.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
function stimMakeSpatiotemporalExperiment(stimParams, runNumber, stimulusType, onsetTimeMultiple, TR)
%% SPATIO TEMPORAL
% For visual experiments, we use band-pass, gray-scale images, spanning
% many stimulus dimensions. Runs are divided up into 3 STIMULUS TYPES:
% Spatial : Patterns (varying in contrast and density; gratings)
% Spatial : Objects (letters, faces, houses)
% Temporal: Patterns (differing in duration and ISI)
% The spatial stimuli were used in a prior publication (Kay et al., 2013,
% PLoS Comp Biol) but are recreated at higher resolution here. The spatial
% patterns vary in contrast, number of component orientations (1, 2 or 16
% superimposed gratings), or spacing between contrast elements (from very
% sparse to very dense). The objects are natural images of faces, letters,
% and houses (also gray-scale, band-pass). These stimuli are presented for
% 0.5 seconds each. The 'temporal patterns' are noise patterns shown with
% different temporal profiles (single pulses with variable duration; or
% multiple pulses with variable interstimulus interval).
% 24 unique exemplars are divided across two unique RUNS for each STIMULUS
% TYPE. Per RUN we have 36 stimulus presentations in total:
% CRF - noise patterns at 5 contrast levels (5*3)
% Orient - gratings at 3 complexity levels (single grating, plaid, circular) (3*3)
% Sparsity - noise patterns at 4 density levels (5th level included in CRF) (4*3)
% Faces - faces regenerated from database used in Kay et al., 2013 (1*12)
% Letters - letters regenerated from database used in Kay et al., 2013 (1*12)
% Houses - houses regenerated from database used in Kay et al., 2013 (1*12)
% 1 Pulse - noise patterns at 6 durations each (6*3)
% 2 Pulses - noise patterns at 6 ISIs (fixed duration) (6*3)
% Other details:
% The order of exemplars is fixed between EcoG, fMRI, MEG.
% Each category of stimuli is generated by specific subfunction (e.g.
% createPatternStimulus.m), but all parameters are set in this script.
% Running this script for site 'master' (maximum 2 runs) will generate the
% stimuli at high resolution and set the stimulus order for each run.
% Timing parameters, ITIs and fixation sequencies are only specified when
% the stimuli are generated for a specific site (e.g. NYU-3T). Multiple
% runs can be generated for sites other than master: odd run numbers will
% take master stimulus 1 and even numbers master stimulus 2 as input.
% IG & JW, BAIR 2018
%% Make the images
% Determine if we're creating the master or loading & resizing for a specific display
site = stimParams.experimentSpecs.sites{1};
imageSizeInPixels = size(stimParams.stimulus.images);
switch site
case 'master'
switch stimulusType
case 'SPATIALPATTERN'
fprintf('[%s]: Creating master stimuli for stimulusType: SPATIALPATTERN, runID: %d.\n',mfilename, runNumber);
categories = {...
'CRF-1' ...
'CRF-2' ...
'CRF-3' ...
'CRF-4' ...
'CRF-5' ...
'GRATING' ...
'PLAID' ...
'CIRCULAR' ...
'SPARSITY-1' ...
'SPARSITY-2' ...
'SPARSITY-3' ...
'SPARSITY-4' ...
};
categoryNumberToAdd = 106; % to make sure we have UNIQUE category number across all BAIR tasks
numberOfImagesPerCat = 3;
% Pre-allocate arrays to store images
images = zeros([imageSizeInPixels length(categories) * numberOfImagesPerCat], 'uint8');
im_cell = cell([1 length(categories)]);
catindex = zeros(1, length(categories) * numberOfImagesPerCat);
imCount = 1;
% Create CRF stimuli
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: CRF.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
% From Kay et al, 2013 PLOS CB
% These stimuli were constructed by varying the contrast
% of the noise patterns used in SPACE. Ten different
% contrast levels were used: 1%, 2%, 3%, 4%, 6%, 9%, 14%,
% 21%, 32%, and 50%. These contrast levels are relative
% to the contrast of the patterns used in SPACE, which is
% taken to be 100%.
% Category-specific settings
categoryIndex = find(contains(categories, {'CRF'}));
numberOfCategories = length(categoryIndex);
contrastLevels = [0.0625 0.125 0.25 0.5 1]; % or should we use log/linear?
densityLevel = 20; % middle density stimulus for SPARSITY
% Create the stimuli
for cc = 1:numberOfCategories
for ii = 1:numberOfImagesPerCat
imageForThisTrial = createPatternStimulus(stimParams, densityLevel, contrastLevels(cc));
% Double to unsigned 8 bit integer, needed for vistadisp
% Note: luminance values need to range between -0.5 and 0.5
% prior to 8Bit conversion to avoid clipping
image8Bit = uint8((imageForThisTrial+.5)*255);
images(:,:,imCount) = image8Bit;
im_cell{categoryIndex(cc)}(:,:,ii) = image8Bit;
catindex(imCount) = categoryIndex(cc)+categoryNumberToAdd;
imCount = imCount + 1;
end
end
% Create GRATING / PLAID / CIRCULAR
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: GRATING PLAID CIRCULAR.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
% From Kay et al, 2013 PLOS CB
% GRATING (4 stimuli). These stimuli consisted of horizontal
% sinusoidal gratings at 2%, 4%, 9%, and 20% Michelson contrast.
% The spatial frequency of the gratings was fixed at 3 cycles per
% degree. Each stimulus consisted of gratings with the same
% contrast but nine different phases (equally spaced from 0 to 2p).
% PLAID (4 stimuli). These stimuli consisted of plaids at 2%, 4%,
% 9%, and 20% contrast (defined below). Each condition comprised
% nine plaids, and each plaid was constructed as the sum of a
% horizontal and a vertical sinusoidal grating (spatial frequency 3
% cycles per degree, random phase). The plaids were scaled in
% contrast to match the root-mean-square (RMS) contrast of the
% GRATING stimuli. For example, the plaids in the 9% condition were
% scaled such that the average RMS contrast of the plaids is
% identical to the average RMS contrast of the gratings in the 9%
% GRATING stimulus.
% CIRCULAR (4 stimuli). These stimuli were identical to the
% PLAID stimuli except that sixteen different orientations
% were used instead of two.
% Category-specific settings
categoryIndex = find(contains(categories, {'GRATING', 'PLAID', 'CIRCULAR'}));
numberOfCategories = length(categoryIndex);
cyclesPerDegree = 3; % cycles per degree
peak2peakContrast = 50; % percentage Michelson contrast
% Create the stimuli
for cc = 1:numberOfCategories
switch categories{categoryIndex(cc)}
case 'GRATING'
gratingOrientation = pi/2; % horizontal
case 'PLAID'
gratingOrientation = [pi/2 pi]; % horizontal + vertical
case 'CIRCULAR'
gratingOrientation = (1:16)/pi; % 16 superimposed
end
for ii = 1:numberOfImagesPerCat
imageForThisTrial = createGratingStimulus(stimParams,cyclesPerDegree,gratingOrientation, peak2peakContrast);
% Double to unsigned 8 bit integer, needed for vistadisp
image8Bit = uint8((imageForThisTrial+.5)*255);
images(:,:,imCount) = image8Bit;
im_cell{categoryIndex(cc)}(:,:,ii) = image8Bit;
catindex(imCount) = categoryIndex(cc)+categoryNumberToAdd;
imCount = imCount + 1;
end
end
% Create SPARSITY
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: SPARSITY.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
% From Kay et al, 2013 PLOS CB
% We generated noise patterns using cutoff frequencies of
% 2.8, 1.6, 0.9, 0.5, and 0.3 cycles per degree, and
% numbered these from 1 (smallest separation) to 5
% (largest separation). The noise patterns used in SPACE
% correspond to separation 4; thus, we only constructed
% stimuli for the remaining separations 1, 2, 3, and 5.
% The noise patterns occupied the full stimulus extent
% (no aperture masking).
% Category-specific settings
categoryIndex = find(contains(categories, {'SPARSITY'}));
numberOfCategories = length(categoryIndex);
contrastLevel = 1; % fixed to max
densityLevels = [10 15 25 30]; % middle density is CRF full contrast stim
% Create the stimuli
for cc = 1:numberOfCategories
for ii = 1:numberOfImagesPerCat
imageForThisTrial = createPatternStimulus(stimParams, densityLevels(cc), contrastLevel);
% Double to unsigned 8 bit integer, needed for vistadisp
image8Bit = uint8((imageForThisTrial+.5)*255);
images(:,:,imCount) = image8Bit;
im_cell{categoryIndex(cc)}(:,:,ii) = image8Bit;
catindex(imCount) = categoryIndex(cc)+categoryNumberToAdd;
imCount = imCount + 1;
end
end
% Set durations and ISI
durations = ones(1,size(images,3))*0.5;
ISI = zeros(1,size(images,3));
% Generate a number specific for this stimulusType and use
% this to set seed for stimulus sequency generator below
% (so we don't use the same sequence for each stimulusType)
taskID = 10;
case 'SPATIALOBJECT'
categories = {...
'FACES' ...
'LETTERS' ...
'HOUSES' ...
};
categoryNumberToAdd = 130; % to make sure we have UNIQUE category number across all BAIR tasks
numberOfImagesPerCat = 12;
% Pre-allocate arrays to store images
images = zeros([imageSizeInPixels length(categories) * numberOfImagesPerCat], 'uint8');
im_cell = cell([1 length(categories)]);
catindex = zeros(1, length(categories) * numberOfImagesPerCat);
imCount = 1;
% Create FACES / LETTERS / HOUSES
fprintf('[%s]: Creating master stimuli for stimulusType: SPATIALOBJECT.\n',mfilename);
% From Kay et al, 2013 PLOS CB
% Each image was whitened (to remove low-frequency bias)
% and then filtered with the custom band-pass filter
% (described previously). Finally, the contrast of each
% image was scaled to fill the full luminance range.
% Download original, unfiltered face, house, letter stimuli
fprintf('[%s]: Loading original, unfiltered stimuli...\n',mfilename);
stimDir = fullfile(BAIRRootPath, 'stimuli');
fname = 'Kay2013unfilteredstim.mat';
writePth = fullfile(stimDir, fname);
if ~exist(writePth, 'file')
readPth = 'https://wikis.nyu.ed*u/download/attachments/85394548/Kay2013unfilteredstim.mat?api=v2';
websave(writePth,readPth);
end
load(writePth);
% Category-specific settings
categoryIndex = find(contains(categories, {'FACES', 'LETTERS', 'HOUSES'}));
numberOfCategories = length(categoryIndex);
imageProcessingParams.imageScaleFactor = 0.4; % size of FHL stimuli relative to the pattern stimuli
imageProcessingParams.maskScaleFactor = 0.85; % size of mask relative to filtered image
imageProcessingParams.maskSoftEdge = 1.1; % size of 'second radius' of mask (determines smoothness of mask edge)
imageProcessingParams.contrastRange = 1.5; % range to scale the contrast prior to 8Bit conversion (a range of 1 results in no clipping)
% Create the stimuli
for cc = 1:numberOfCategories
switch categories{categoryIndex(cc)}
case 'FACES'
imageArray = faces;
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: FACES.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
case 'LETTERS'
imageArray = letters;
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: LETTERS.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
% For LETTERS ONLY: Crop and resize letter
% array prior to filtering to get thicker lines
origSizeinPixels = size(letters);
cropOrigin = [(origSizeinPixels(1)+1)./2 (origSizeinPixels(1)+1)./2];
cropRadius = [-0.3*origSizeinPixels(1)/2 0.3*origSizeinPixels(1)/2]; % optimal crop radius determined empirically REDO
cropIndex = round(cropOrigin+cropRadius);
imageArray = imageArray(cropIndex(1):cropIndex(2), cropIndex(1):cropIndex(2),:);
imageArray = imresize(imageArray,origSizeinPixels([1 2]));
case 'HOUSES'
imageArray = houses;
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: HOUSES.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
end
% Pick which stimuli to select from original set
% ODD for runNum == 1, EVEN for runNum == 2;
imageIndex = runNumber:2:numberOfImagesPerCat*2+runNumber-1;
for ii = 1:numberOfImagesPerCat
inputImage = imageArray(:,:,imageIndex(ii));
imageForThisTrial = createFilteredStimulus(stimParams,inputImage,imageProcessingParams);
% Double to unsigned 8 bit integer, needed for vistadisp
image8Bit = uint8((imageForThisTrial+.5)*255);
images(:,:,imCount) = image8Bit;
im_cell{categoryIndex(cc)}(:,:,ii) = image8Bit;
catindex(imCount) = categoryIndex(cc)+categoryNumberToAdd;
imCount = imCount + 1;
end
end
% Set durations and ISI
durations = ones(1,size(images,3))*0.5;
ISI = zeros(1,size(images,3));
% Generate a number specific for this stimulusType and use
% this to set seed for stimulus sequency generator below
% (so we don't use the same sequence for each stimulusType)
taskID = 11;
case 'TEMPORALPATTERN'
fprintf('[%s]: Creating master stimuli for stimulusType: TEMPORALPATTERN.\n',mfilename);
categories = {...
'ONEPULSE-1' ...
'ONEPULSE-2' ...
'ONEPULSE-3' ...
'ONEPULSE-4' ...
'ONEPULSE-5' ...
'ONEPULSE-6' ...
'TWOPULSE-1' ...
'TWOPULSE-2' ...
'TWOPULSE-3' ...
'TWOPULSE-4' ...
'TWOPULSE-5' ...
'TWOPULSE-6' ...
};
categoryNumberToAdd = 118; % to make sure we have UNIQUE category number across all BAIR tasks
numberOfImagesPerCat = 3;
% Pre-allocate arrays to store images
images = zeros([imageSizeInPixels length(categories) * numberOfImagesPerCat], 'uint8');
im_cell = cell([1 length(categories)]);
catindex = zeros(1, length(categories) * numberOfImagesPerCat);
imCount = 1;
% Create TEMPORAL stimuli
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: ONE PULSE.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
% Category-specific settings
numberOfCategories = length(categories);
categoryIndex = 1:length(categories);
contrastLevel = 1; % max contrast
densityLevel = 20; % middle density
% Create the stimuli
for cc = 1:numberOfCategories
if cc == (numberOfCategories/2)+1
fprintf('[%s]: Creating master stimuli at %d x %d pixels resolution: TWO PULSE.\n',mfilename,imageSizeInPixels(1),imageSizeInPixels(2));
end
for ii = 1:numberOfImagesPerCat
imageForThisTrial = createPatternStimulus(stimParams, densityLevel, contrastLevel);
% Double to unsigned 8 bit integer, needed for vistadisp
image8Bit = uint8((imageForThisTrial+.5)*255);
images(:,:,imCount) = image8Bit;
im_cell{categoryIndex(cc)}(:,:,ii) = image8Bit;
catindex(imCount) = categoryIndex(cc)+categoryNumberToAdd;
imCount = imCount + 1;
end
end
% Set durations and ISIs
tempIndex = [1 2 4 8 16 32]/stimParams.display.frameRate;
durations = [];
% One pulse durations:
for ii = 1:length(tempIndex)
durations = [durations ones(1,numberOfImagesPerCat)*tempIndex(ii)];
end
% Append two pulse durations:
durations = [durations ones(1,length(tempIndex)*numberOfImagesPerCat)*8/stimParams.display.frameRate];
% One pulse ISI:
ISI = zeros(1,18);
% Append two pulse ISI:
for ii = 1:length(tempIndex)
ISI = [ISI ones(1,numberOfImagesPerCat)*tempIndex(ii)];
end
% Generate a number specific for this stimulusType and use
% this to set seed for stimulus sequency generator below
% (so we don't use the same sequence for each stimulusType)
taskID = 12;
end
% % DEBUG: plot generated images
% figure;hold on
% for ii = 1:size(images,3)
% subplot(ceil(sqrt(size(images,3))),ceil(sqrt(size(images,3))),ii);
% imshow(images(:,:,ii));
% end
% Make individual trial sequences
numberOfStimuli = size(images,3);
% Fix the seed for the random generator such that the same sequence
% will be generated based on the run Number
rng(runNumber+taskID,'twister');
stim_seq = randperm(numberOfStimuli);
% Add blank
images(:,:,end+1) = mode(images(:));
BLANK = size(images,3);
% This is the stimulus structure used by vistadisp
stimulus = [];
stimulus.cmap = stimParams.stimulus.cmap;
stimulus.srcRect = stimParams.stimulus.srcRect;
stimulus.dstRect = stimParams.stimulus.destRect;
stimulus.display = stimParams.display;
% Put everything into stimulus struct
stimulus.categories = categories;
stimulus.images = images;
stimulus.im_cell = im_cell;
stimulus.cat = catindex;
stimulus.duration = durations;
stimulus.ISI = ISI;
stimulus.trialindex = stim_seq;
% Update durations for temporal stimuli
for ii = 1:numberOfStimuli
idx = stimulus.trialindex(ii);
if stimulus.ISI(idx)>0
stimulus.trial(ii).seqtiming = [...
[0 stimulus.duration(idx)] ... pulse one
[0 stimulus.duration(idx)] + stimulus.ISI(idx) + stimulus.duration(idx)... ... pulse two
];
stimulus.trial(ii).seq = [idx BLANK idx BLANK];
else
stimulus.trial(ii).seqtiming = [0 stimulus.duration(idx)];
stimulus.trial(ii).seq = [idx BLANK];
end
end
% Generate a save name
fname = sprintf('%s_%s_%d.mat', site, lower(stimulusType), runNumber);
otherwise
% Resize the master stimuli to the required stimulus size for this
% modality and display
% Decide which of the two master runs to take:
runID = 1;
if mod(runNumber,2) == 0
runID = 2;
end
fprintf('[%s]: Loading master stimuli for stimulusType: %s, runID: %d \n',mfilename, stimulusType, runID);
% Load the master stimuli
stimulus = loadBAIRStimulus(stimulusType, 'master', runID);
% Resize
fprintf('[%s]: Resizing master stimuli for: %s\n', mfilename, site);
imageSizeInPixels = size(stimParams.stimulus.images);
images = imresize(stimulus.images, imageSizeInPixels);
% Soft circular mask (1 pixel of blurring per 250 pixels in the image)
supportDiameter = imageSizeInPixels(1);
maskRadius = (stimParams.stimulus.srcRect(3) - stimParams.stimulus.srcRect(1))/2;
circularMask = mkDisc(supportDiameter, maskRadius, (imageSizeInPixels+1)./2, 1/250 * imageSizeInPixels(1));
imagesDouble = double(images)/255-.5;
imagesMasked = bsxfun(@times,imagesDouble,circularMask);
images = uint8((imagesMasked+.5)*255);
% Do the same for the im_cell exemplars
im_cell = cell(size(stimulus.im_cell));
for ii = 1:size(stimulus.im_cell,2)
im_cell{ii} = imresize(stimulus.im_cell{ii}, imageSizeInPixels);
imagesDouble = double(im_cell{ii})/255-.5;
imagesMasked = bsxfun(@times,imagesDouble,circularMask);
im_cell{ii} = uint8((imagesMasked+.5)*255);
end
% % DEBUG: plot generated images
% figure;hold on
% for ii = 1:size(images,3)-1
% subplot(ceil(sqrt(size(images,3)-1)),ceil(sqrt(size(images,3)-1)),ii);
% imshow(images(:,:,ii));
% end
% Overwrite master stimuli with resized images
stimulus.im_cell = im_cell;
stimulus.images = images;
% Overwrite display parameters
stimulus.cmap = stimParams.stimulus.cmap;
stimulus.srcRect = stimParams.stimulus.srcRect;
stimulus.dstRect = stimParams.stimulus.destRect;
stimulus.display = stimParams.display;
frameRate = stimParams.display.frameRate;
% Experiment timing
fprintf('[%s]: Calculating stimulus timing for: %s\n', mfilename, site);
% Generate ITIs
numberOfStimuli = size(stimulus.images,3)-1;
switch(lower(stimParams.modality))
case 'fmri'
ITI_min = 3;
ITI_max = 6;
prescan = round(12/TR)*TR; % seconds
postscan = prescan; % seconds
% Jitter ITIs
ITIs = linspace(ITI_min,ITI_max,numberOfStimuli-1);
% Round off to onsetMultiple
ITIs = round(ITIs/onsetTimeMultiple)*onsetTimeMultiple;
case {'ecog' 'eeg' 'meg'}
ITI_min = 1.25;
ITI_max = 1.75;
prescan = 3; % seconds
postscan = 3; % seconds
% Jitter ITIs
ITIs = linspace(ITI_min,ITI_max,numberOfStimuli-1);
otherwise
error('Unknown modality')
end
stimulus.ITI = ITIs;
stimulus.prescan = prescan; % seconds
stimulus.postscan = postscan; % seconds
% Generate random ITI order
rng('shuffle');
iti_seq = randperm(numberOfStimuli-1);
% Compute onsets based on modality-specific ITIs
onsets = cumsum([stimulus.prescan stimulus.ITI(iti_seq)]);
% Match the stimulus presentation to the frame rate
onsets = round(onsets*frameRate)/frameRate;
stimulus.onsets = onsets;
% Put trials together for whole sequence in 'sparse' format: add
% blank at beginning and end, add offsets
BLANK = size(stimulus.images,3);
seq_sparse = BLANK; % initialize with blank at time 0
seqtiming_sparse = 0; % initialize with blank at time 0
for ii = 1:numberOfStimuli
this_trial_seq = stimulus.trial(ii).seq;
this_trial_seqtiming = stimulus.trial(ii).seqtiming + onsets(ii);
seq_sparse = [seq_sparse this_trial_seq];
seqtiming_sparse = [seqtiming_sparse this_trial_seqtiming];
end
seq_sparse(end+1) = BLANK;
seqtiming_sparse(end+1) = seqtiming_sparse(end);
% Put sparse stimulus timing sequences in struct
stimulus.seq_sparse = seq_sparse;
stimulus.seqtiming_sparse = seqtiming_sparse;
% Generate whole sequence at frame Rate resolution
% Add post-scan stimulus period
%seqtiming = 0:1/frameRate:seqtiming_sparse(end)+max(stimulus.duration)+stimulus.postscan;
seqtiming = 0:1/frameRate:seqtiming_sparse(end)+stimulus.postscan;
seq = zeros(size(seqtiming))+BLANK;
for ii = length(stimulus.seqtiming_sparse):-1:2
idx = round(seqtiming,4) < round(stimulus.seqtiming_sparse(ii),4);
seq(idx) = stimulus.seq_sparse(ii-1);
end
seq(end) = stimulus.seq_sparse(end);
% Put interpolated timing sequences in struct
stimulus.seq = seq;
stimulus.seqtiming = seqtiming;
% Add fixation sequence
minDurationInSeconds = 1;
maxDurationInSeconds = 5;
fixSeq = createFixationSequence(stimulus, 1/frameRate, minDurationInSeconds, maxDurationInSeconds);
stimulus.fixSeq = fixSeq;
% Add triggers for non-fMRI modalities
switch lower(stimParams.modality)
case 'fmri'
% no triggers for fMRI
otherwise
% create an empty trigger sequence
trigSeq = zeros(size(stimulus.seq));
% find the onsets of the stimuli in the sequence
[~,onsetIndices] = intersect(round(stimulus.seqtiming,4),round(stimulus.onsets,4));
assert(length(onsetIndices) == length(stimulus.onsets));
% use the CATEGORICAL labels as trigger codes
trigSeq(onsetIndices) = stimulus.cat(stimulus.seq(onsetIndices));
% add task ONSET and OFFSET trigger
trigSeq(1) = 256;
trigSeq(end) = 256;
stimulus.trigSeq = trigSeq;
end
% Sparsify the stimulus sequence
maxUpdateInterval = 0.25;
stimulus = sparsifyStimulusStruct(stimulus, maxUpdateInterval);
stimulus.modality = stimParams.modality;
% Generate a save name
fname = sprintf('%s_%s_%d.mat', site, lower(stimulusType), runNumber);
% Add table with elements to write to tsv file for BIDS
onset = round(stimulus.onsets,3)';
duration = round(stimulus.duration(stimulus.trialindex),3)';
ISI = round(stimulus.ISI(stimulus.trialindex),3)';
trial_type = stimulus.cat(stimulus.trialindex)';
trial_name = stimulus.categories(trial_type - min(stimulus.cat)+1)';
stim_file = repmat(fname, numberOfStimuli ,1);
stim_file_index = stimulus.trialindex';
stimulus.tsv = table(onset, duration, ISI, trial_type, trial_name, stim_file, stim_file_index);
end
stimulus.site = site;
% save
fprintf('[%s]: Saving stimuli in: %s\n', mfilename, fullfile(vistadispRootPath, 'StimFiles', fname));
save(fullfile(vistadispRootPath, 'StimFiles', fname), 'stimulus', '-v7.3')
return
%% DEBUG
%% Plot individual stimuli ('images')
figure;hold on
for ii = 1:size(stimulus.images,3)
subplot(ceil(sqrt(size(stimulus.images,3))),ceil(sqrt(size(stimulus.images,3))),ii);
imshow(images(:,:,ii));
end
%% Plot one exemplar for all categories ('im_cell')
figure('Name', 'NEW STIM');hold on
for ii = 1:length(stimulus.im_cell)
subplot(2,6,ii);
imshow(stimulus.im_cell{ii}(:,:,1));
title(stimulus.categories{ii});
end
% Compute power spectra for all categories ('im_cell')
D = stimulus.display;
figure('Name', 'NEW STIM SF');hold on
peaks = [];
for ii = 1:length(stimulus.im_cell)
im = stimulus.im_cell{ii}(:,:,1);
[frequencies, amplitudes, binnedFrequencies, binnedAmplitudes] = ...
compute2DamplitudeSpectrum(im, D);
[y,x] = max(binnedAmplitudes);
peaks(ii) = binnedFrequencies(x);
% Plot spectrum per category
subplot(2,6,ii);
plot(binnedFrequencies, binnedAmplitudes/max(binnedAmplitudes), 'LineWidth', 2);
xlabel('Cycles per degree')
xlim([0 7.5])
set(gca, 'XGrid', 'on', 'XTick', 0:1.5:7.5)
title(stimulus.categories{ii});
end
% Plot distribution of peaks
figure('Name', 'NEW STIM SF PEAKS');
subplot(1,2,1);histogram(peaks); xlabel('max spatial frequency'); ylabel('number of images')
xlim([0 4]);
subplot(1,2,2);plot(peaks, 'o-'); ylabel('category index'); ylabel('max spatial frequency');
xlim([0 25]);
% Compute luminance histograms
figure ('Name', 'NEW STIM LUM');hold on
for ii = 1:length(stimulus.im_cell)
im = stimulus.im_cell{ii}(:,:,1);
% Plot histogram per category
subplot(2,6,ii);
histogram(im(im~=mode(im(:)))); title('(mode excluded from hist)');
xlabel('Pixel values')
xlim([0 255])
title(stimulus.categories{ii});
end
%% DO THE SAME FOR THE ORIGINAL KAY STIMULI
% Pattern stimuli from Kay et al 2013
load('/Volumes/server/Projects/BAIR/Stimuli/Kay2013_stimuli/stimuli.mat');
% From http://kendrickkay.net/socmodel/index.html#contentsofstimuli
% Contents of 'stimuli.mat':
%
% 'images' contains the raw stimulus frames for stimulus sets 1, 2, and 3
% (concatenated). The 'images' variable is a cell vector of dimensions 1 x
% 260 (since 69+156+35=260). Each entry corresponds to one stimulus, and
% each stimulus consists of one or more frames. For stimulus set 1 (1
% through 69), all entries consist of 30 distinct frames. For stimulus set
% 2 (70 through 225), all entries consist of 9 distinct frames except for
% entry #174 which consists of 7 distinct frames. For stimulus set 3 (226
% through 260), all entries consist of a single frame. The resolution of
% the images in stimulus set 1 is 600 pixels x 600 pixels; the resolution
% of the images in stimulus sets 2?3 is 800 pixels x 800 pixels. For all
% images, the format is uint8; the range of values is [0,254]; and the
% background has a value of 127.
%
% 'conimages' contains the spatial masks (contrast images) used in the
% generation of some of the stimuli. There is a direct correspondence
% between 'conimages' and 'images'. The 'conimages' variable is a cell
% vector of dimensions 1 x 260. Each entry gives the mask that was used to
% generate the corresponding stimulus in 'images'. The indices of the
% stimuli that have associated masks are 1:69, 70:138, and 185:208. For the
% other indices, the entry in 'conimages' is simply the empty matrix. The
% resolution of the contrast images in stimulus set 1 is 600 pixels x 600
% pixels; the resolution of the contrast images in stimulus sets 2?3 is 256
% pixels x 256 pixels. For all contrast images, the format is double; and
% the range of values is [0,1] where a value of X indicates that at that
% pixel, the underlying stimulus, weighted by X, was blended with the gray
% background, weighted by 1?X.
%
% 'bpfilter' contains the band-pass filter used to generate some of the
% stimuli in stimulus sets 2?3. The filter is a matrix of dimensions 21 x
% 21 and was used in stimulus construction, at which point the image
% resolution was 256 pixels x 256 pixels.
knk_idx = [...
162 ... CRF-1
164 ... CRF-2
166 ... CRF-3
167 ... CRF-4
116 ... CRF-5
150 ... GRATING
154 ... PLAID
158 ... CIRCULAR
184 ... SPARSITY-1
183 ... SPARSITY-2
182 ... SPARSITY-3
181 ... SPARSITY-4
171 ... FACES-1
171 ... FACES-2
171 ... FACES-3
171 ... FACES-4
173 ... LETTERS-1
173 ... LETTERS-2
173 ... LETTERS-3
173 ... LETTERS-4
172 ... SCENES-1 (175??)
172 ... SCENES-2 (175??)
172 ... SCENES-3 (175??)
172 ... SCENES-4 (175??)
116 ... ONEPULSE-1
116 ... ONEPULSE-2
116 ... ONEPULSE-3
116 ... ONEPULSE-4
116 ... ONEPULSE-5
116 ... ONEPULSE-6
116 ... TWOPULSE-1
116 ... TWOPULSE-2
116 ... TWOPULSE-3
116 ... TWOPULSE-4
116 ... TWOPULSE-5
116 ... TWOPULSE-6
];
whichIm = {...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:2 ...
3:4 ...
5:6 ...
7:8 ...
1:2 ...
3:4 ...
5:6 ...
7:8 ...
1:2 ...
3:4 ...
5:6 ...
7:8 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
1:6 ...
};
knk_im_cell = [];
for ii = 1:24%length(knk_idx)
knk_im_cell{ii} = images{knk_idx(ii)}(:,:,whichIm{ii}(1));
end
figure('Name', 'OLD STIM');hold on
for ii = 1:24%length(knk_im_cell)
subplot(4,6,ii);
imshow(knk_im_cell{ii}(:,:,1));
end
% D = loadDisplayParams('cni_lcd');
D = loadDisplayParams('cni_lcd_mock');
figure('Name', 'OLD STIM SF');hold on
peaks = [];
for ii = 1:24%length(knk_im_cell)
im = knk_im_cell{ii}(:,:,1);
[frequencies, amplitudes, binnedFrequencies, binnedAmplitudes] = ...
compute2DamplitudeSpectrum(im, D);
[y,x] = max(binnedAmplitudes);
peaks(ii) = binnedFrequencies(x);
% Plot spectrum per category
subplot(4,6,ii);
plot(binnedFrequencies, binnedAmplitudes/max(binnedAmplitudes), 'LineWidth', 2);
xlabel('Cycles per degree')
xlim([0 7.5])
set(gca, 'XGrid', 'on', 'XTick', 0:1.5:7.5)
end
% Plot distribution of peaks
figure('Name', 'OLD STIM SF PEAKS');
subplot(1,2,1);histogram(peaks); xlabel('max spatial frequency'); ylabel('number of images')
xlim([0 4]);
subplot(1,2,2);plot(peaks, 'o-'); ylabel('category index'); ylabel('max spatial frequency');
xlim([0 25]);
% Compute luminance histograms
figure('Name', 'OLD STIM LUM');hold on
for ii = 1:24%length(knk_im_cell)
im = knk_im_cell{ii};
% Plot histogram per category
subplot(4,6,ii);
histogram(im(im~=mode(im(:)))); title('(mode excluded from hist)');
xlabel('Pixel values')
xlim([0 255])
end
%% make stimulus movie
% movie ----
% movieName = sprintf('~/Desktop/spatiotemporal%02d.avi', runnum);
% nFramePerSec = 60;
%
% v = VideoWriter(movieName);
% v.FrameRate = nFramePerSec;
% v.Quality = 100;
% open(v)
% c = 1;
% %fH = figure(); set(fH, 'Visible', 'off')
%
% cmap = gray(256);
%
% fprintf('Making scan number %d\n', runnum);
% for ii = 1 : length(stimulus.seq)
%
%
% im = uint8(stimulus.images(:,:,stimulus.seq(ii)));
% frame = im2frame(im, cmap);
%
% writeVideo(v, frame);
%
% if mod(ii,100) == 0, fprintf('.'); drawnow(); end
%
% end
% close(v)