-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocessPhotodiodeStrobe.m
386 lines (373 loc) · 17 KB
/
preprocessPhotodiodeStrobe.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
function [ photodiodeFrameTimes ] = preprocessPhotodiodeStrobe( photodiodeFilename, params )
%preprocessPhotodiodeStrobe extracts frame times from a photodiode signal
% Inputs:
% - analogInData: data array returned by preprocessAnalogIn (channels x samples)
% - params: struct with the fields
% - needPhotodiode: return immediately if 0 (type: logical)
% - analogInChannelInd: this is the index of the photodiode channel in the list of analog in
% channels specified in the paramFile (type: int)
% - centerCornerOffset: this is the offset, in ms, of the photodiode
% trigger from the screen-center frame time
% (type: float)
% - levelCalibType: (type: string) options are:
% - hardcode
% -
% -
%
%
% - numLevels: (type: int)
% - hardcodeFromFile: (type: logical)
% - saveCalibFile: (type: logical)
% - inputCalibrationFile (required only if hardcodeFromFile): (type: string)
% - outputCalibrationFile (required only if saveCalibFile): (type:string)
if ~params.needPhotodiode
photodiodeFrameTimes = [];
return
end
% todo: fix this to use photodiodeFilename
diodeTrace = analogInData(params.analogInChannelInd,:);
diodeTrace = -1*(diodeTrace - mean(diodeTrace)); %this makes frames peaks
centerCornerOffset = params.centerCornerOffset;
frameNumCeiling = ceil(length(diodeTrace)*params.framerate/params.sampleRate);
% Preprocessing logic:
% 1) Find peaks in the inverted diode trace. A peak occurs when the cathode ray passes the diode,
% even on black pixels. However, additional small-prominence peaks occur due to noise
% 2) Sort peaks by their height: since both the the signal and its
% second derivative are high at true peaks, they should be the largest
rawPeaks = findpeaks(diodeTrace);
rawPeaksSorted = sort(diodeTrace(rawPeaks.loc),'descend');
rawPeaksSorted = rawPeaksSorted(1:frameNumCeiling);
% additional todo: add frame count and alternation checks for manual levels
if strcmp(params.levelCalibType,'hardcode')
if params.hardcodeFromFile
switch params.numLevels
case 1
load(params.inputCalibrationFile,'highThreshold');
case 2
load(params.inputCalibrationFile,'highThreshold','lowThreshold');
case 3
load(params.inputCalibrationFile,'highThreshold','midThreshold','lowThreshold');
end
else
switch params.numLevels
case 1
highThreshold = params.levelHigh;
case 2
highThreshold = params.levelHigh;
lowThreshold = params.levelLow;
case 3
highThreshold = params.levelHigh;
midThreshold = params.levelMid;
lowThreshold = params.levelLow;
end
end
end
if any(strcmp(params.levelCalibType, {'auto','autoAndPlot','autoAndCheck'}))
% Auto-calibration logic:
% The largest jumps in the plot of sorted peak heights should occur between true peak types,
% or between the smallest peak type and the largest noise peak. So find and sort those jumps,
% then place level cut-offs at the mid-point of the largest ones.
peakDiffs = diff(rawPeaksSorted);
[peakDiffsSorted,peakDiffsSortInds] = sort(peakDiffs);
if ~(strcmp(params.levelCalibType,'hardcodeAndPlot') || strcmp(params.levelCalibType,'hardcodeAndCheck'))
switch params.numLevels
case 1
highThresholdDiffInd = peakDifSortInds(1);
highThreshold = (rawPeaksSorted(highThresholdDiffInd + 1) - rawPeaksSorted(highThresholdDiffInd))/2;
case 2
highThresholdDiffInd = min(peakDiffSortInds(1:2)); %note: these end up on the high side of the threshold,i.e. the low index side
lowThresholdDiffInd = max(peakDiffSortInds(1:2));
highThreshold = (rawPeaksSorted(highThresholdDiffInd + 1) - rawPeaksSorted(highThresholdDiffInd))/2;
lowThreshold = (rawPeaksSorted(lowThresholdDiffInd + 1) - rawPeaksSorted(lowThresholdDiffInd))/2;
case 3
highThresholdDiffInd = min(peakDiffSortInds(1:3)); %note: these end up on the high side of the threshold,i.e. the low index side
lowThresholdDiffInd = max(peakDiffSortInds(1:3));
midThresholdDiffInd = setdiff(peakDiffSortInds(1:3),[highThresholdDiffInd, lowThresholdDiffInd]);
highThreshold = (rawPeaksSorted(highThresholdDiffInd + 1) - rawPeaksSorted(highThresholdDiffInd))/2;
midThreshold = (rawPeaksSorted(midThresholdDiffInd + 1) - rawPeaksSorted(midThresholdDiffInd))/2;
lowThreshold = (rawPeaksSorted(lowThresholdDiffInd + 1) - rawPeaksSorted(lowThresholdDiffInd))/2;
end
end
end
% if two levels, check that frames alternate appropriately
if params.numLevels == 2
frameSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold);
highPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > highThreshold);
lowPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold && diodeTrace(rawPeaks.loc) < highThreshold);
frameCountDiff = length(highPeakSampleInds) - length(lowPeakSampleInds);
% with correct alternation, smallest interval between subsequent high peaks must tbe greater than longest frame; same for low peaks
frameAlternationError = (min(min(diff(highPeakSampleInds)),min(diff(lowPeakSampleInds))) > max(diff(frameSampleInds)));
end
%make plots, if requested, or if auto calib failed
if any(strcmp(params.levelCalibType,{'autoAndPlot','autoAndCheck','hardcodeAndPlot','hardcodeAndCheck'})) || (params.numLevels == 2 && (abs(frameCountDiff) > 1 || frameAlternationError))
if params.numLevels == 2 && abs(frameCountDiff) > 1
fprintf('Frame count mismatch: Found %d bright-square frames and %d dark-square frames. Starting manual check.\n',...
length(highPeakSampleInds),length(lowPeakSampleInds));
end
if params.numLevels == 2 && frameAlternationError
fprintf('Found light-dark frame alternation error. Starting manual check.\n');
end
if any(strcmp(params.levelCalibType, {'hardcodeAndPlot','hardcodeAndCheck','hardcode'}))
calibSuffix = 'hard code';
else
calibSuffix = 'auto';
end
figure();
subplot(1,2,1);
framesToPlot = 10; %magic number; should move to top
sampleRange = ceil(frameSampleInds(1) - 5*params.sampleRate/params.framerate):ceil(frameSampleInds(1) + framesToPlot*params.sampleRate/params.framerate)
plot(sampleRange,diodeTrace(sampleRange));
hold on
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend121 = {'raw trace',sprintf('high threshold %s',calibSuffix)}; %note: 121 refers to the subplot
if params.numLevels == 3
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend121 = horzcat(forLegend121, {sprintf('mid threshold %s',calibSuffix)});
end
if params.numLevels > 1
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend121 = horzcat(forLegend121, {sprintf('low threshold %s',calibSuffix)});
end
plot(frameSampleInds(1:framesToPlot), diodeTrace(frameSampleInds(1:framesToPlot)));
forLegend121 = horzcat(forLegend121, {'frameTimes'});
legend(forLegend121);
subplot(1,2,2);
plot(rawPeaksSorted);
hold on
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend122 = {'peak levels',sprintf('high threshold %s',calibSuffix)}; %note: 122 refers to the subplot
if params.numLevels == 3
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend122 = horzcat(forLegend122, {sprintf('mid threshold %s',calibSuffix)});
end
if params.numLevels > 1
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend122 = horzcat(forLegend122, {sprintf('low threshold %s',calibSuffix)});
end
legend(forLegend122);
drawnow();
if any(strcmp(params.levelCalibType,{'autoAndCheck','hardcodeAndCheck'})) || params.numLevels == 2
tmp = input('Accept high threshold? Enter y or n: ','s');
if strcmp(tmp,'n')
tmp = input('Enter new high threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter new high threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
highThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend121 = horzcat(forLegend121,{'high threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend122 = horzcat(forLegend121,{'high threshold manual'});
legend(forLegend122);
end
end
if params.numLevels == 3
tmp = input('Accept mid threshold? Enter y or n: ','s');
if strcmp(tmp,'n')
tmp = input('Enter new mid threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter new mid threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
midThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend121 = horzcat(forLegend121,{'mid threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend122 = horzcat(forLegend121,{'mid threshold manual'});
legend(forLegend122);
end
end
end
if params.numLevels > 1
tmp = input('Accept low threshold? Enter y or n: ','s');
if strcmp(tmp,'n')
tmp = input('Enter new low threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter new low threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
lowThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend121 = horzcat(forLegend121,{'low threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend122 = horzcat(forLegend121,{'low threshold manual'});
legend(forLegend122);
end
end
end
end
end
% if two levels, check that frames alternate appropriately
if params.numLevels == 2
frameSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold);
highPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > highThreshold);
lowPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold && diodeTrace(rawPeaks.loc) < highThreshold);
frameCountDiff = length(highPeakSampleInds) - length(lowPeakSampleInds);
% with correct alternation, smallest interval between subsequent high peaks must tbe greater than longest frame; same for low peaks
frameAlternationError = (min(min(diff(highPeakSampleInds)),min(diff(lowPeakSampleInds))) > max(diff(frameSampleInds)));
notValid = (abs(frameCountDiff) > 1 || frameAlternationError);
if notValid
if abs(frameCountDiff) > 1
tmp = input(sprintf('Frame count mismatch: Found %d bright-square frames and %d dark-square frames. Press ENTER to start manual check, or q to quit.',...
length(highPeakSampleInds),length(lowPeakSampleInds)));
end
if frameAlternationError
tmp = input(sprintf('Found light-dark frame alternation error. Press ENTER to start manual check, or q to quit.'));
end
while ~strcmp('tmp',{'','q'})
tmp = imput('Invalid input. Press ENTER to re-start manual check, or q to quit.');
end
if isempty(tmp)
notValid = 1;
else
notValid = 0;
end
end
else
notValid = 0;
end
if strcmp(params.levelCalibType,'manual') || notValid
notValid = 1;
while notValid
figure();
subplot(1,2,1);
framesToPlot = 10; %magic number; should move to top
sampleRange = ceil(length(diodeTrace)/2 - (framesToPlot/2)*params.sampleRate/params.framerate):ceil(length(diodeTrace)/2 - (framesToPlot/2)*params.sampleRate/params.framerate)
plot(sampleRange,diodeTrace(sampleRange));
forLegend121 = {'raw trace'};
legend(forLegend121);
subplot(1,2,2);
plot(rawPeaksSorted);
forLegend122 = {'peak levels'};
legend(forLegend122);
drawnow();
tmp = input('Enter the high threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter the high threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
highThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend121 = horzcat(forLegend121,{'high threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [highThreshold highThreshold]);
forLegend122 = horzcat(forLegend121,{'high threshold manual'});
legend(forLegend122);
end
if params.numLevels == 3
tmp = input('Enter the mid threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter the mid threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
midThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend121 = horzcat(forLegend121,{'mid threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [midThreshold midThreshold]);
forLegend122 = horzcat(forLegend121,{'mid threshold manual'});
legend(forLegend122);
end
end
if params.numLevels > 1
tmp = input('Enter the low threshold, or ''quit'' to continue without photodiode sync:','s');
while isempty(str2num(tmp)) && ~strcmp(tmp,'quit')
tmp = input('Invalid input: enter the low threshold, or ''quit'' to continue without photodiode sync:','s');
end
if strcmp(tmp,'quit')
return %todo: need to handle this better
else
lowThreshold = str2num(tmp);
subplot(1,2,1);
h = get(gca,'xlim');
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend121 = horzcat(forLegend121,{'low threshold manual'});
legend(forLegend121);
subplot(1,2,2);
h = get(gca,'xlim');
plot([h(1) h(2)], [lowThreshold lowThreshold]);
forLegend122 = horzcat(forLegend121,{'low threshold manual'});
legend(forLegend122);
end
end
% if two levels, check that frames alternate appropriately
if params.numLevels == 2
frameSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold);
highPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > highThreshold);
lowPeakSampleInds = rawPeaks.loc(diodeTrace(rawPeaks.loc) > lowThreshold && diodeTrace(rawPeaks.loc) < highThreshold);
frameCountDiff = length(highPeakSampleInds) - length(lowPeakSampleInds);
% with correct alternation, smallest interval between subsequent high peaks must tbe greater than longest frame; same for low peaks
frameAlternationError = (min(min(diff(highPeakSampleInds)),min(diff(lowPeakSampleInds))) > max(diff(frameSampleInds)));
notValid = (abs(frameCountDiff) > 1 || frameAlternationError);
if notValid
if abs(frameCountDiff) > 1
tmp = input(sprintf('Frame count mismatch: Found %d bright-square frames and %d dark-square frames. Press ENTER to re-start manual check, or q to quit.',...
length(highPeakSampleInds),length(lowPeakSampleInds)));
end
if frameAlternationError
tmp = input(sprintf('Found light-dark frame alternation error. Press ENTER to re-start manual check, or q to quit.'));
end
while ~strcmp('tmp',{'','q'})
tmp = imput('Invalid input. Press ENTER to re-start manual check, or q to quit.');
end
if isempty(tmp)
continue
else
break
end
end
else
notValid = 0;
end
end
end
if params.saveCalibFig
%saveFigure(outDir,sprintf(,runNum), figData, saveFig, exportFig, saveFigData, sprintf('%s, Run %s',dateSubject,runNum));
end
if params.saveCalibFile
switch params.numLevels
case 1
save(params.outputCalibrationFilename, 'highThreshold');
case 2
save(params.outputCalibrationFilename, 'highThreshold', 'lowThreshold');
case 3
save(params.outputCalibrationFilename, 'highThreshold', 'midThreshold', 'lowThreshold');
end
end
end