-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstimMakeHRFExperiment.m
258 lines (199 loc) · 10.7 KB
/
stimMakeHRFExperiment.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
function stimMakeHRFExperiment(stimParams, runNum, stimDurationSeconds, onsetTimeMultiple, stimulusType, TR)
%stimMakeHRFExperiment(stimParams, runNum, stimDurationSeconds, onsetTimeMultiple, stimulusType)
%
% Stimuli are presented for stimDurationSeconds, with an exponentially
% distributed interstimulus interval (mean ~9s, range 3-24s).
%
% stimulusType = ...
% {'hrfPattern' 'hrfPatternInverted' 'hrfChecker' 'hrfCheckerInverted'};
% See s_Make_BAIR_Visual_Experiments for context
%% Make the images
% Determine if we're creating the master or loading resizing for a specific display
site = stimParams.experimentSpecs.Row{1};
frameRate = stimParams.display.frameRate;
switch site
case 'master'
% Experiment specs
if strcmpi(stimulusType, 'HRFPATTERNBREATHINGCHALLENGE')
numberOfEventsPerRun = 71;
else
numberOfEventsPerRun = 32;
end
preScanPeriod = round(30/TR)*TR;
postScanPeriod = preScanPeriod;
minimumISIinSeconds = 3;
maximumISIinSeconds = 24;
% Specify the pattern density in some arbitrary unit: a value of 20
% gives a moderately dense pattern: See Kay et al, 2013 PLOS CB, figure 5B
stripesPerImage = 20;
imageSizeInPixels = size(stimParams.stimulus.images);
% The number of images is 2 x the number of stimuli + 1. We multiply by 2
% because the stimuli may be shown as paired images (a pattern and its
% contrast reversal). We add 1 to define the blank stimulus.
numImages = numberOfEventsPerRun*2+1;
blankImageIndex = numImages;
backgroundIntensity = 128;
images = zeros([imageSizeInPixels numImages], 'uint8')+backgroundIntensity;
% Loop to make the images
for ii = 1:numberOfEventsPerRun
disp(['Creating stimulus number: ' num2str(ii)]);
if contains(stimulusType, 'checker','IgnoreCase',true)
imageForThisTrial = createCheckerboard(stimParams, round(stripesPerImage/3));
elseif contains(stimulusType, 'pattern','IgnoreCase',true)
imageForThisTrial = createPatternStimulus(stimParams, stripesPerImage);
else
error('Unknown stimulus type %s', stimulusType);
end
% Double to unsigned 8 bit integer, needed for vistadisp
image8Bit = uint8((imageForThisTrial+.5)*255);
% The contrast reversed images will be used for only those experiments
% where the pulse has a contrast reversal, otherwise ignored
imageContrastReversed = uint8((-imageForThisTrial+.5)*255);
images(:,:,ii) = image8Bit;
images(:,:,ii+numberOfEventsPerRun) = imageContrastReversed;
end
% Store the images in 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;
stimulus.categories = {upper(stimulusType)};
stimulus.images = images;
% Add a category label to be able to combine stimuli across runs
stimulus.cat = ones(1,numberOfEventsPerRun);
stimulus.duration = ones(1,numberOfEventsPerRun)*stimDurationSeconds;
% Specify event timing, with an exponential distribution of ISIs
[onsets, onsetIndices] = getExponentialOnsets(numberOfEventsPerRun, preScanPeriod, ...
minimumISIinSeconds, maximumISIinSeconds, onsetTimeMultiple, frameRate);
stimulus.onsets = onsets;
% Define total length of stimulation sequence at frame rate resolution
stimulus.seqtiming = 0:1/frameRate:onsets(numberOfEventsPerRun)+stimDurationSeconds+postScanPeriod;
stimulus.seq = zeros(size(stimulus.seqtiming))+blankImageIndex;
% Add fixation sequence
minDurationInSeconds = 1;
maxDurationInSeconds = 5;
fixSeq = createFixationSequence(stimulus, 1/frameRate, minDurationInSeconds, maxDurationInSeconds);
stimulus.fixSeq = fixSeq;
% Randomize the assignment of image to trial
trialIndex = randperm(numberOfEventsPerRun);
stimulus.trialindex = trialIndex;
stimulus.seq(onsetIndices) = trialIndex;
% Specify the image sequence within each stimulus, which depends on the
% stimulus duration and the dwell time per image, as well as whether or not
% we include a contrast reversal
imagesPerTrial = round(stimDurationSeconds*frameRate);
sequencePerTrial = zeros(1,imagesPerTrial);
switch lower(stimulusType)
case {'hrfpatterninverted' 'hrfcheckerinverted'}
% paired images per trial, ie an image and its contrast reversal
contrastReversal = true;
otherwise
% single image pre trial
contrastReversal = false;
end
% Add the contrast reversed stimuli to the sequence
if contrastReversal
sequencePerTrial(imagesPerTrial/2+1:imagesPerTrial) = numberOfEventsPerRun;
end
% Add the stimulus sequence index
for ii = 1:numberOfEventsPerRun
indices = onsetIndices(ii) + (0:imagesPerTrial-1);
stimulus.seq(indices) = sequencePerTrial + trialIndex(ii);
end
% Generate a save name
fname = sprintf('%s_%s_%d.mat', site, lower(stimulusType), runNum);
otherwise
% Resize the master stimuli to the required stimulus size for this
% modality and display
fprintf('[%s]: Loading master stimuli for: %s\n', mfilename, site);
% Load the master stimuli
stimulus = loadBAIRStimulus(lower(stimulusType), 'master', runNum);
% The desired new ImageSize
imageSizeInPixels = size(stimParams.stimulus.images);
% Resize
fprintf('[%s]: Resizing master stimuli for: %s\n', mfilename, site);
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);
stimulus.images = uint8((imagesMasked+.5)*255);
% Overwrite master stimulus with settings for this modality
% and display
stimulus.cmap = stimParams.stimulus.cmap;
stimulus.srcRect = stimParams.stimulus.srcRect;
stimulus.dstRect = stimParams.stimulus.destRect;
stimulus.display = stimParams.display;
% Add triggers for non-fMRI modalities
switch lower(stimParams.modality)
case 'fmri'
% no trigger sequence needed
otherwise
% Create an empty trigger sequence
trigSeq = zeros(size(stimulus.seq));
blankImageIndex = mode(stimulus.seq);
% Write image identity into trigger sequence:
stimulus.trigSeq = stimulus.seq;
stimulus.trigSeq(stimulus.seq == blankImageIndex) = 0;
% 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
maxUpdateInterval = 0.25;
stimulus = sparsifyStimulusStruct(stimulus, maxUpdateInterval);
% Generate a save name
fname = sprintf('%s_%s_%d.mat', site, lower(stimulusType), runNum);
% Add table with elements to write to tsv file for BIDS
onset = reshape(round(stimulus.onsets,3), [length(stimulus.onsets) 1]);
duration = ones(length(stimulus.onsets),1) * stimDurationSeconds;
trial_type = ones(length(stimulus.onsets),1);
trial_name = repmat(upper(stimulusType), length(stimulus.onsets),1);
stim_file = repmat(fname, length(stimulus.onsets),1);
stim_file_index = reshape(stimulus.trialindex, [length(stimulus.onsets) 1]);
stimulus.tsv = table(onset, duration, trial_type, trial_name, stim_file, stim_file_index);
% add modality
stimulus.modality = stimParams.modality;
end
% Save
stimulus.site = site;
fprintf('[%s]: Saving stimuli in: %s\n', mfilename, fullfile(vistadispRootPath, 'StimFiles', fname));
save(fullfile(vistadispRootPath, 'StimFiles', fname), 'stimulus')
end
function [onsets, indices] = getExponentialOnsets(numStimuli, preScanPeriod, minISI, maxISI, onsetTimeMultiple, frameRate)
% Draw numStimuli ISIs from an exponential distribution from [minISI maxISI]
x = linspace(0,1,numStimuli-1) * (1-exp(-minISI)) + exp(-minISI);
ISIs = -log(x)/minISI;
ISIs = ISIs*(maxISI-minISI)+minISI;
% % DEBUG
% disp(mean(ISIs))
%
% figure(1),clf, set(gcf, 'Color', 'w')
% set(gca, 'FontSize', 24); hold on
% plot(ISIs, 'o-', 'LineWidth', 4, 'MarkerSize', 12); axis tight
% ylabel('ITI (s)'); xlabel('Trial')
% Round off the ISIs to multiples of temporalResolution
ISIs = round(ISIs/onsetTimeMultiple)*onsetTimeMultiple;
% Compute the cumulative sum of ISIs to get the onset times
prescan = round(preScanPeriod/onsetTimeMultiple)*onsetTimeMultiple;
onsets = cumsum([prescan ISIs(randperm(numStimuli-1))]);
% Match the stimulus presentation to the frame rate
onsets = round(onsets*frameRate)/frameRate;
% Derive indices into the stimulus sequence (defined at temporalResolution)
indices = round(onsets*frameRate)+1;
% % Debug
% figure(2), clf; set(gcf, 'Color', 'w')
% set(gca, 'FontSize', 24, 'XTick', 0:60:300, 'YTick', []); hold on
% stem(onsets, ones(1,numStimuli+1), 'LineWidth', 2)
% xlabel('Time (s)')
% hgexport(gcf, fullfile(BAIRRootPath, 'figures', 'HRF_onsets.eps'))
end