/
runExperiment.m
2594 lines (2401 loc) · 90.5 KB
/
runExperiment.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
% ========================================================================
classdef runExperiment < octickaCore
%> @class runExperiment
%> @brief The main experiment manager.
%>
%> RUNEXPERIMENT accepts a task « taskSequence », stimuli « metaStimulus » and
%> for behavioural tasks a « stateMachine » state machine file, and runs the
%> stimuli based on the task objects passed. This class uses the fundamental
%> configuration of the screen (calibration, size etc. via « screenManager »),
%> and manages communication to the DAQ systems using digital I/O and
%> communication over a UDP client⇄server socket (via « dataConnection »).
%>
%> There are 2 main experiment types:
%> 1) MOC (method of constants) tasks -- uses stimuli and task objects
%> directly to run standard randomised variable tasks. See octickatest.m
%> for an example. Does not use the «stateMachine».
%> 2) Behavioural tasks that use state machines for control logic. These
%> tasks still use stimuli and task objects to provide stimuli and
%> variable lists, but use a state machine to control the task
%> structure.
%>
%> Stimuli should be « metaStimulus » class, so for example:
%>
%> ```
%> myStim = metaStimulus;
%> myStim{1} = gratingStimulus('mask',true,'sf',1);
%> task = taskSequence; % this creates randomised variable lists
%> task.nVar = struct('name','angle','stimulus',1,'values',[-90 0 90]);
%> myExp = runExperiment('stimuli', myStim,'task', task);
%> runMOC(myExp); % run method of constants type experiment
%> ```
%>
%> will run a minimal experiment showing a 1c/d circularly masked grating.
%>
%> @todo refactor checkKey(): can we use a config for keyboard commands?
%>
%> Copyright ©2014-2022 Ian Max Andolina — released: LGPL3, see LICENCE.md
% ========================================================================
properties
%> a metaStimulus class instance holding our stimulus objects
stimuli
%> a taskSequence class instance determining our stimulus variables
task
%> a screenManager class instance managing the PTB Screen
screen
%> filename for a stateMachine state info file
stateInfoFile = ''
%> user functions file that can be passed to the state machine
userFunctionsFile = ''
%> use a Display++ for strobed digital I/O?
useDisplayPP = false
%> use a dataPixx for strobed digital I/O?
useDataPixx = false
%> use a LabJack T4/T7 for strobed digital I/O?
useLabJackTStrobe = false
%> use LabJack U3/U6 for strobed digital I/O?
useLabJackStrobe = false
%> use LabJack for reward TTL?
useLabJackReward = false
%> use Arduino for reward TTL?
useArduino = false
%> use Eyelink eyetracker?
useEyeLink = false
%> use Tobii eyetracker?
useTobii = false
%> use eye occluder (custom arduino device) for monocular stimulation?
useEyeOccluder = false
%> use a dummy mode for the eyetrackers?
dummyMode = false
%> log all frame times?
logFrames = true
%> enable debugging? (poorer temporal fidelity)
debug = false
%> shows the info text and position grid during stimulus presentation
visualDebug = false
%> draw simple fixation cross during trial for MOC tasks?
drawFixation = false
%> flip as fast as possible?
benchmark = false
%> verbose logging to command window?
verbose = false
%> what value to send on stimulus OFF
stimOFFValue = 255
%> subject name
subjectName = 'Simulcra'
%> researcher name
researcherName = 'Jane Doe'
end
properties (Transient = true)
%> structure for screenManager on initialisation and info from octicka
screenSettings = struct()
%> this lets the octicka UI leave commands to runExperiment
uiCommand = ''
end
properties (Hidden = true)
%> used to select single stimulus in training mode
stimList = []
%> which stimulus is selected?
thisStim = []
%> tS is the runtime settings structure, saved here as a backup
tS
%> what mode to run the Display++ digital I/O in? Plexon requires
%> the use of a strobe trigger line, whereas most other equipment
%> just uses simple threshold reading
dPPMode = 'plain'
%> which port is the arduino on?
arduinoPort = ''
%> initial eyelink settings
elsettings = []
%> initial tobii settings
tobiisettings = []
%> turn diary on for runTask, saved to the same folder as the data
diaryMode = false
%> octicka version, passed on first use by octicka
octickaVersion
logStateTimers = false
%> our old stimulus structure used to be a simple cell, now we use metaStimulus
stimulus
end
properties (Transient = true, Hidden = true)
%> keep track of several task values during runTask()
lastXPosition = 0
lastYPosition = 0
lastXExclusion = []
lastYExclusion = []
lastSize = 1
lastIndex = 0
end
properties (SetAccess = private, GetAccess = public)
%> send a strobe on next flip?
sendStrobe = false
%> need an eyetracker sample on next flip?
needSample = false
%> send an eyetracker SYNCTIME on next flip?
sendSyncTime = false
%> do we flip the screen or not?
doFlip = true
%> do we flip the eyetracker window? 0=no 1=yes 2=yes+clear
doTrackerFlip = 0;
%> stateMachine
stateMachine
%> eyetracker manager object
eyeTracker
%> generic IO manager
io
%> DataPixx control object
dPixx
%> Display++ control object
dPP
%> LabJack control object
lJack
%> Arduino control object
arduino
%> magstim manager
mS
%> user functions object
userFunctions
%> state machine control cell array
stateInfo = {}
%> general computer info retrieved using PTB Screen('computer')
computer
%> PTB version information: Screen('version')
ptb
%> copy of screen settings from screenManager
screenVals
%> log of timings for MOC tasks
runLog
%> log of timings for state machine tasks
taskLog
%> behavioural responses log
behaviouralRecord
%> general info on current run
currentInfo
%> variable info on the current run
variableInfo
%> previous info populated during load of a saved object
previousInfo = struct()
%> return if runExperiment is running (true) or not (false)
isRunning = false
end
properties (SetAccess = private, GetAccess = private)
%> fInc for managing keyboard sensitivity
fInc = 6
%> is it MOC run (false) or stateMachine runTask (true)?
isRunTask = true
%> are we using taskSequeence or not?
isTask = true
%> should we stop the task?
stopTask = false
%> properties allowed to be modified during construction
allowedProperties = {'useDisplayPP','useDataPixx','useEyeLink',...
'useArduino','dummyMode','logFrames','subjectName','researcherName',...
'useTobii','stateInfoFile','userFunctionFile','dummyMode','stimuli','task',...
'screen','visualDebug','useLabJack','useLabJackTStrobe','useLabJackStrobe','debug',...
'useEyeOccluder','verbose','screenSettings','benchmark'}
end
events %causing a major MATLAB 2019a crash when loading .mat files that contain events, removed for the moment
%runInfo
%calls when we quit
%abortRun
%calls after all runs finish
%endAllRuns
end
%=======================================================================
methods %------------------PUBLIC METHODS
%=======================================================================
% ===================================================================
function me = runExperiment(varargin)
%> @fn runExperiment
%>
%> runExperiment CONSTRUCTOR
%>
%> @param varargin can be passed as a structure or name,arg pairs
%> @return instance of the class.
% ===================================================================
args = octickaCore.addDefaults(varargin,struct('name','Run Experiment'));
me=me@octickaCore(args); %superclass constructor
me.parseArgs(args,me.allowedProperties);
end
% ===================================================================
function runMOC(me)
%> @fn runMOC
%>
%> runMOC uses built-in loop for experiment control and runs a
%> methods-of-constants (MOC) experiment with the settings passed to
%> it (stimuli,task and screen). This is different to the runTask
%> method as it doesn't use a stateMachine for experimental logic,
%> just a minimal deterministic trial+block loop.
%>
%> @todo currently we can only record eye positions with the
%> eyelink, add other tracker support
%>
%> @param me required class object
% ===================================================================
% we try not to use global variables, however the external eyetracker
% API does not easily allow us to pass objects and so we use global
% variables in this specific case...
global rM %eyetracker calibration needs access to reward manager
if isempty(me.screen) || isempty(me.task)
me.initialise;
end
if isempty(me.stimuli) || me.stimuli.n < 1
error('No stimuli present!!!');
end
if me.screen.isPTB == false
errordlg('There is no working PTB available!');
error('There is no working PTB available!');
end
initialiseSaveFile(me); %generate a savePrefix for this run
me.name = [me.subjectName '-' me.savePrefix]; %give us a run name
%------initialise runLog for this run
me.previousInfo.runLog = me.runLog;
me.taskLog = timeLogger();
me.runLog = timeLogger();
tL = me.runLog;
s = me.screen;
t = me.task;
%-----------------------------------------------------------
try%======This is our main TRY CATCH experiment display loop
%-----------------------------------------------------------
me.lastIndex = 0;
me.isRunning = true;
me.isRunTask = false;
%------open the PTB screen
me.screenVals = s.open(me.debug,tL);
me.stimuli.screen = s; %make sure our stimuli use the same screen
me.stimuli.verbose = me.verbose;
t.fps = me.screenVals.fps;
setup(me.stimuli); %run setup() for each stimulus
if s.movieSettings.record; prepareMovie(s); end
%------configure IO
io = configureIO(me);
if me.useDataPixx || me.useDisplayPP
startRecording(io);
WaitSecs(0.5);
elseif me.useLabJackStrobe
% Trigger the omniplex (TTL on FIO1) into paused mode
io.setDIO([2,0,0]);WaitSecs(0.001);io.setDIO([0,0,0]);
end
%------set up the eyelink interface
if me.useEyeLink || me.useTobii
if me.useTobii
warning('Tobii not valid for a MOC task, switching to eyelink dummy mode');
me.useTobii = false; me.useEyeLink = true; me.dummyMode = true;
end
me.eyeTracker = eyelinkManager();
eT = me.eyeTracker;
eT.isDummy = me.dummyMode;
eT.saveFile = [me.paths.savedData pathsep me.savePrefix 'RUN.edf'];
initialise(eT, s);
trackerSetup(eT);
end
initialise(t); %------initialise the task for this run
me.updateMOCVars(1,1); %------set the variables for the very first run;
KbReleaseWait; %------make sure keyboard keys are all released
%------bump our priority to maximum allowed
Priority(MaxPriority(s.win));
%--------------unpause Plexon-------------------------
if me.useDataPixx || me.useDisplayPP
resumeRecording(io);
elseif me.useLabJackStrobe
io.setDIO([3,0,0],[3,0,0])%(Set HIGH FIO0->Pin 24), unpausing the omniplex
end
if me.useEyeLink; startRecording(eT); end
%------------------------------------------------------------
% lets draw 2 seconds worth of the stimuli we will be using
% covered by a blank. Primes the GPU and other components with the sorts
% of stimuli/tasks used and this does appear to minimise
% some of the frames lost on first presentation for very complex
% stimuli using 32bit computation buffers...
fprintf('\n===>>> Warming up the GPU and I/O systems... <<<===\n');
show(me.stimuli);
if me.useEyeLink; trackerClearScreen(eT); end
for i = 1:s.screenVals.fps*2
draw(me.stimuli);
drawBackground(s);
s.drawPhotoDiodeSquare([0 0 0 1]);
finishDrawing(s);
animate(me.stimuli);
if ~mod(i,10); io.sendStrobe(255); end
if me.useEyeLink
getSample(eT);
trackerDrawText(eT,'Warming Up System');
trackerMessage(eT,'Warmup test');
end
flip(s);
end
update(me.stimuli); %make sure stimuli are set back to their start state
io.resetStrobe;flip(s);flip(s);
tL.screenLog.beforeDisplay = GetSecs();
%-----profiling starts here
%profile clear; profile on;
%-----final setup
ListenChar(-1);
me.task.tick = 1;
me.task.switched = 0;
me.task.isBlank = true; %lets start in a blank
if me.logFrames == true
tL.screenLog.stimTime(1) = 1;
end
tL.vbl(1) = GetSecs();
tL.startTime = tL.vbl(1);
%==================================================================%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Our display loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%==================================================================%
while ~me.task.taskFinished
if me.task.isBlank
if s.photoDiode;s.drawPhotoDiodeSquare([0 0 0 1]);end
if me.drawFixation;s.drawCross(0.4,[0.3 0.3 0.3 1]);end
else
if ~isempty(s.backgroundColour);s.drawBackground;end
draw(me.stimuli);
if s.photoDiode;s.drawPhotoDiodeSquare([1 1 1 1]);end
if me.drawFixation;s.drawCross(0.4,[1 1 1 1]);end
end
if s.visualDebug;s.drawGrid;me.infoTextScreen;end
Screen('DrawingFinished', s.win); % Tell PTB that no further drawing commands will follow before Screen('Flip')
%========= check for keyboard if in blank ========%
if me.task.isBlank
if strcmpi(me.uiCommand,'stop');break;end
[~,~,kc] = KbCheck(-1);
if strcmpi(KbName(kc),'q')
%notify(me,'abortRun');
break; %break the while loop
end
end
%============== Get eye position==================%
if me.useEyeLink; getSample(me.eyeTracker); end
%================= UPDATE TASK ===================%
updateMOCTask(me); %update our task structure
%============== Send Strobe =======================%
if (me.useDisplayPP || me.useDataPixx) && me.sendStrobe
triggerStrobe(io);
me.sendStrobe = false;
end
%======= FLIP: Show it at correct retrace: ========%
nextvbl = tL.lastvbl + me.screenVals.halfisi;
if me.logFrames == true
[tL.vbl(me.task.tick),tL.show(me.task.tick),tL.flip(me.task.tick),tL.miss(me.task.tick)] = Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.vbl(me.task.tick);
elseif me.benchmark == true
tL.vbl = Screen('Flip', s.win, 0, 2, 2);
tL.lastvbl = tL.vbl;
else
tL.vbl = Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.vbl;
end
%===================Logging=======================%
if me.task.tick == 1
if me.benchmark == false
tL.startTime=tL.vbl(1); %respecify this with actual stimulus vbl
end
end
if me.logFrames == true
if me.task.isBlank == false
tL.stimTime(me.task.tick)=1+me.task.switched;
else
tL.stimTime(me.task.tick)=0-me.task.switched;
end
end
if s.movieSettings.record ...
&& ~me.task.isBlank ...
&& (s.movieSettings.loop <= s.movieSettings.nFrames)
s.addMovieFrame();
end
%===================Tick tock!=======================%
me.task.tick=me.task.tick+1; tL.tick = me.task.tick;
end
%==================================================================%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Finished display loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%==================================================================%
ListenChar(0);
s.drawBackground;
vbl=Screen('Flip', s.win);
tL.screenLog.afterDisplay=vbl;
if me.useDataPixx || me.useDisplayPP
pauseRecording(io);
elseif me.useLabJackStrobe
io.setDIO([0,0,0],[1,0,0]); %this is RSTOP, pausing the omniplex
end
%notify(me,'endAllRuns');
%-----get our profiling report for our task loop
%profile off; profile report; profile clear
tL.screenLog.deltaDispay=tL.screenLog.afterDisplay - tL.screenLog.beforeDisplay;
tL.screenLog.deltaUntilDisplay=tL.startTime - tL.screenLog.beforeDisplay;
tL.screenLog.deltaToFirstVBL=tL.vbl(1) - tL.screenLog.beforeDisplay;
if me.benchmark == true
tL.screenLog.benchmark = me.task.tick / (tL.screenLog.afterDisplay - tL.startTime);
fprintf('\n---> BENCHMARK FPS = %g\n', tL.screenLog.benchmark);
end
s.screenVals.info = Screen('GetWindowInfo', s.win);
s.resetScreenGamma();
if me.useEyeLink
close(me.eyeTracker);
me.eyeTracker = [];
end
s.finaliseMovie(false);
me.stimuli.reset();
s.close();
if me.useDataPixx || me.useDisplayPP
stopRecording(io);
close(io);
elseif me.useLabJackStrobe
me.lJack.setDIO([2,0,0]);WaitSecs(0.05);me.lJack.setDIO([0,0,0]); %we stop recording mode completely
me.lJack.close;
me.lJack=[];
end
tL.calculateMisses;
if tL.nMissed > 0
fprintf('\n!!!>>> >>> >>> There were %i MISSED FRAMES <<< <<< <<<!!!\n',tL.nMissed);
end
s.playMovie();
me.isRunning = false;
catch ME
me.isRunning = false;
fprintf('\n\n---!!! ERROR in runExperiment.runMOC()\n');
getReport(ME)
if me.useDataPixx || me.useDisplayPP
pauseRecording(io); %pause plexon
WaitSecs(0.25)
stopRecording(io);
close(io);
end
%profile off; profile clear
Priority(0);
ListenChar(0);
ShowCursor;
resetScreenGamma(s);
close(s);
close(me.eyeTracker);
me.eyeTracker = [];
me.behaviouralRecord = [];
close(rM);
me.lJack=[];
me.io = [];
clear tL s tS bR rM eT io sM
rethrow(ME)
end
end
% ===================================================================
function runTask(me)
%> @fn runTask
%>
%> runTask runs a state machine (behaviourally) driven task.
%>
%> Uses a StateInfo.m file to control the behavioural paradigm. The
%> state machine controls the logic of the experiment, and this
%> method manages the display loop.
%>
% ===================================================================
% we try not to use global variables, however the external
% eyetracker API does not easily allow us to pass objects and so
% we use global variables in this specific case...
global rM %#ok<*GVMIS> %global reward manager we can share with eyetracker
global aM %global audio manager we can share with eyetracker
refreshScreen(me);
initialiseSaveFile(me); %generate a savePrefix for this run
me.name = [me.subjectName '-' me.savePrefix]; %give us a run name
if isempty(me.screen) || isempty(me.task)
me.initialise; %we set up screenManager and taskSequence objects
end
if me.screen.isPTB == false %NEED PTB!
errordlg('There is no working PTB available!');
error('There is no working PTB available!');
end
%------enable diary logging if requested
if me.diaryMode
diary off
diary([me.paths.savedData filesep me.name '.log']);
end
%------make sure we reset any state machine functions to not cause
% problems when they are reassigned below. For example, io interfaces
% can be reset unless we clear this before we open the io.
me.stateInfo = {};
if isa(me.stateMachine,'stateMachine'); me.stateMachine.reset; me.stateMachine = []; end
%------initialise the rewardManager global object
if ~isa(rM,'arduinoManager')
rM=arduinoManager();
end
if rM.isOpen
rM.close; rM.reset;
end
%------initialise an audioManager for beeps,playing sounds etc.
if ~exist('aM','var') || isempty(aM) || ~isa(aM,'audioManager')
aM=audioManager;
end
aM.silentMode = false;
if ~aM.isSetup; aM.setup; end
aM.beep(1000,0.1,0.1);
if isempty(regexpi(me.comment, '^Protocol','once'))
me.comment = '';
end
fprintf('\n\n\n===>>>>>> Start task: %s <<<<<<===\n\n\n',me.name);
%--------------------------------------------------------------
% tS is a general structure to hold various parameters will be saved
% after the run; prefer structure over class to keep it light. These
% defaults can be overwritten by the StateFile.m
tS = struct();
tS.name = 'generic';%==name of this protocol
tS.useTask = false; %==use taskSequence (randomised variable task object)
tS.keyExclusionPattern = ["fixate","stimulus"]; %==which states skip keyboard check
tS.checkKeysDuringStimulus = false; %==allow keyboard control? Slight drop in performance
tS.enableTrainingKeys = false; %==enable keys useful during task training, but not for data recording
tS.recordEyePosition = false; %==record eye position within PTB, **in addition** to the eyetracker?
tS.askForComments = false; %==little UI requestor asks for comments before/after run
tS.saveData = false; %==save behavioural and eye movement data?
tS.controlPlexon = false; %==send start/stop commands to a plexon?
tS.showBehaviourPlot = true; %==open the behaviourPlot figure? Can cause more memory use
tS.rewardTime = 250; %==TTL time in milliseconds
tS.rewardPin = 2; %==Output pin, 2 by default with Arduino.
tS.tOut = 5; %==if wrong response, how long to time out before next trial
tS.useMagStim = false; %==set up magstim [deprecated]?
tS.tobiiFlipRate = 8; %==how many flip frames constitute 1 tobii flip?
%------initialise time logs for this run
me.previousInfo.taskLog = me.taskLog;
me.runLog = [];
me.taskLog = timeLogger();
tL = me.taskLog; %short handle to log
tL.name = me.name;
if me.logFrames;tL.preAllocate(me.screenVals.fps*60*60);end
%-----behavioural record
me.behaviouralRecord = behaviouralRecord('name',me.name); %#ok<*CPROP>
bR = me.behaviouralRecord; %short handle
%------make a short handle to the screenManager and metaStimulus objects
me.stimuli.screen = me.screen;
s = me.screen;
stims = me.stimuli;
%------initialise task
task = me.task;
initialise(task, true);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try %================This is our main TASK setup=====================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
me.lastIndex = 0;
me.isRunning = true;
me.isRunTask = true;
%================================open the eyetracker interface
if me.useTobii
me.eyeTracker = tobiiManager();
if ~isempty(me.tobiisettings); me.eyeTracker.addArgs(me.tobiisettings); end
else
me.eyeTracker = eyelinkManager();
if ~isempty(me.elsettings); me.eyeTracker.addArgs(me.elsettings); end
end
eT = me.eyeTracker;
eT.verbose = me.verbose;
eT.saveFile = [me.paths.savedData filesep me.subjectName '-' me.savePrefix '.edf'];
if ~me.useEyeLink && ~me.useTobii
eT.isDummy = true;
else
eT.isDummy = me.dummyMode;
end
if isfield(tS,'rewardTime')
bR.rewardTime = tS.rewardTime;
end
%================================open the PTB screen and setup stimuli
me.screenVals = s.open(me.debug,tL);
if me.screenVals.fps < 90
me.fInc = 6;
else
me.fInc = 8;
end
stims.verbose = me.verbose;
setup(stims); %run setup() for each stimulus
task.fps = s.screenVals.fps;
%================================initialise and set up I/O
io = configureIO(me);
%================================initialise the user functions object
if ~exist(me.userFunctionsFile,'file')
me.userFunctionsFile = [me.paths.root filesep 'userFunctions.m'];
end
[p,f] = fileparts(me.userFunctionsFile);
if ~matches(f,"userFunctions")
copyfile(me.userFunctionsFile,[p filesep 'userFunctions.m']);
run([p filesep 'userFunctions.m']);
else
run(me.userFunctionsFile)
end
me.userFunctions = ans; %#ok<NOANS>
uF = me.userFunctions;
uF.rE = me; uF.s = s; uF.task = task; uF.eT = eT;
uF.stims = stims; uF.io = io; uF.rM = rM;
%================================initialise the state machine
sM = stateMachine('verbose',me.verbose,'realTime',task.realTime,'timeDelta',1e-4,'name',me.name);
me.stateMachine = sM;
sM.fnTimers = me.logStateTimers; %record fn evaluations?
if isempty(me.stateInfoFile) || ~exist(me.stateInfoFile,'file') || strcmp(me.stateInfoFile, 'DefaultStateInfo.m')
me.stateInfoFile = [me.paths.root filesep 'DefaultStateInfo.m'];
me.paths.stateInfoFile = me.stateInfoFile;
end
if ~exist(me.stateInfoFile,'file')
errordlg('runExperiment.runTask(): Please specify a valid State Machine file!!!');
else
me.stateInfoFile = regexprep(me.stateInfoFile,'\s+','\\ ');
disp(['======>>> Loading State File: ' me.stateInfoFile]);
clear(me.stateInfoFile);
if ~isdeployed
run(me.stateInfoFile);
else
runDeployed(me.stateInfoFile);
end
me.stateInfo = stateInfoTmp;
addStates(sM, me.stateInfo);
me.paths.stateInfoFile = me.stateInfoFile;
end
uF.sM = sM;
%================================set up the eyetracker interface
configureEyetracker(me, eT, s);
%================================get pre-run comments for this data collection
if tS.askForComments
comment = inputdlg({'CHECK Recording system!!! Initial Comment for this Run?'},['Run Comment for ' me.name]);
if ~isempty(comment)
comment = comment{1};
me.comment = [me.name ':' comment];
bR.comment = me.comment; eT.comment = me.comment; sM.comment = me.comment; io.comment = me.comment; tL.comment = me.comment; tS.comment = me.comment;
end
end
%============================================================WARMUP
% lets draw ~1 seconds worth of the stimuli we will be using
% covered by a blank. This primes the GPU, eyetracker, IO
% and other components with the same stimuli/task code used later...
fprintf('\n===>>> Warming up the GPU, Eyetracker and I/O systems... <<<===\n');
tSM = stateMachine();
tSM.warmUp(); clear tSM;
show(stims); % allows all child stimuli to be drawn
getStimulusPositions(stims);
if me.useEyeLink || me.useTobii; resetAll(eT);trackerClearScreen(eT); end % blank eyelink screen
for i = 1:s.screenVals.fps*1
draw(stims); % draw all child stimuli
drawBackground(s); % draw our blank background
drawPhotoDiodeSquare(s, [mod(i,2) mod(i,2) mod(i,2) 1]); % set our photodiode square white
drawText(s,'Warming up the GPU, Eyetracker and I/O systems...');
finishDrawing(s);
animate(stims); % run our stimulus animation routines to the next frame
if ~mod(i,10); io.sendStrobe(255); end % send a strobed word
if me.useEyeLink || me.useTobii
getSample(eT); % get an eyetracker sample
if i == 1
trackerMessage(eT,sprintf('WARMUP_TEST %i',getTaskIndex(me)));
trackerDrawStatus(eT,'Warming Up System',stims.stimulusPositions);
end
end
flip(s);
if me.useTobii && eT.secondScreen; trackerFlip(eT,1); end
end
update(stims); %make sure all stimuli are set back to their start state
if me.useEyeLink || me.useTobii
resetAll(eT);
if eT.secondScreen; trackerClearScreen(eT);trackerFlip(eT,0); end
end
io.resetStrobe;flip(s);flip(s); % reset the strobe system
%=============================Premptive save in case of crash or error: SAVES IN /TMP
rE = me;
tS.tmpFile = [tempdir filesep me.name '.mat'];
fprintf('===>>> Save initial state: %s\n',tS.tmpFile);
save(tS.tmpFile,'rE','tS');
%=============================Ensure we open the reward manager
if me.useArduino && isa(rM,'arduinoManager') && ~rM.isOpen
fprintf('======>>> Opening Arduino for sending reward TTLs\n');
open(rM);
elseif me.useLabJackReward && isa(rM,'labJack')
fprintf('======>>> Opening LabJack for sending reward TTLs\n');
open(rM);
end
%===========================Start Plexon in paused mode (the plexon can be
% controlled using specific trigger values, see the omniplex
% settings for details).
if tS.controlPlexon && (me.useDisplayPP || me.useDataPixx)
fprintf('===>>> Triggering I/O systems... <<<===\n');
pauseRecording(io); %make sure this is set low first
startRecording(io);
WaitSecs(1);
end
%===========================Initialise our various counters
task.tick = 1;
task.switched = 1;
task.totalRuns = 1;
me.isTask = tS.useTask;
if me.isTask
updateVariables(me, task.totalRuns, true, false); % set to first variable
update(stims); %update our stimuli ready for display
else
updateVariables(me, 1, false, false); % set to first variable
update(stims); %update our stimuli ready for display
end
tS.keyTicks = 0; %tick counter for reducing sensitivity of keyboard
tS.keyHold = 1; %a small loop to stop overeager key presses
tS.totalTicks = 1; % a tick counter
tS.pauseToggle = 1; %toggle pause/unpause
tS.eyePos = []; %locally record eye position
tS.initialTaskIdx.comment = 'This is the task index before the task starts, it may be modified by resetRun() during task...';
tS.initialTaskIdx.index = task.outIndex;
tS.initialTaskIdx.vars = task.outValues;
thisTobiiFlip = inf;
%===========================double check the labJackT handle is still valid
if isa(io,'labJackT') && ~io.isHandleValid
io.close;
io.open;
warning('We had to reopen the labJackT to ensure a stable connection...');
end
%===========================set up our behavioural plot
if tS.showBehaviourPlot; createPlot(bR, eT); drawnow; end
%===========================take over the keyboard + max priority
KbReleaseWait; %make sure keyboard keys are all released
if me.debug == false
ListenChar(-1); %2=capture all keystrokes
end
if ~isdeployed
try commandwindow; end
end
Priority(MaxPriority(s.win)); %bump our priority to maximum allowed
%=============================profiling starts here if uncommented
%profile clear; profile on;
%=============================initialise our log times and vbl's
me.needSample = false;
me.stopTask = false;
me.doFlip = false;
me.doTrackerFlip = false;
me.sendStrobe = false;
tL.vbl(1) = Screen('Flip', s.win);
tL.lastvbl = tL.vbl(1);
tL.miss(1) = 0;
tL.stimTime(1) = 0;
tL.startTime = tL.lastvbl;
tL.screenLog.beforeDisplay = tL.lastvbl;
tL.screenLog.trackerStartTime = getTrackerTime(eT);
tL.screenLog.trackerStartOffset = getTimeOffset(eT);
useParallel = true;
%==============================IGNITE the stateMachine!
fprintf('\n===>>> Igniting the State Machine... <<<===\n');
start(sM);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Display + task loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while me.stopTask == false
%------run the stateMachine one step forward
update(sM);
if me.doFlip && s.visualDebug; s.drawGrid; me.infoTextScreen; end
if me.doFlip; s.finishDrawing(); end % potential optimisation, but note stateMachine may run non-drawing tasks in update()
%------check eye position manually. Also potentially log
% this retrieved value, but REMEMBER eyetracker will save
% the properly sampled eye data in the EDF; this is
% just a backup sampled at the GPU FPS wrapped in the
% PTB loop.
if me.needSample; getSample(eT); end
if tS.recordEyePosition && me.useEyeLink
saveEyeInfo(me, sM, eT, tS);
end
%------Check keyboard for commands (remember we can turn
% this off using either tS.keyExclusionPattern
% [per-state toggle] or tS.checkKeysDuringStimulus).
if ~matches(sM.currentName,tS.keyExclusionPattern)
tS = checkKeys(me,tS);
end
%-----FLIP: Show it at correct retrace: -----%
if me.doFlip
%------Display++ or DataPixx: I/O send strobe
% command for this screen flip needs to be sent
% PRIOR to the flip! Also remember DPP will be
% delayed by one flip
if me.sendStrobe && me.useDisplayPP
sendStrobe(io); me.sendStrobe = false;
elseif me.sendStrobe && me.useDataPixx
triggerStrobe(io); me.sendStrobe = false;
end
%------Do the actual Screen flip, save times if
% enabled.
nextvbl = tL.lastvbl + me.screenVals.halfisi;
if me.logFrames == true
[tL.vbl(tS.totalTicks),tL.show(tS.totalTicks),...
tL.flip(tS.totalTicks),tL.miss(tS.totalTicks)] ...
= Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.vbl(tS.totalTicks);
thisN = tS.totalTicks;
elseif ~me.benchmark
[tL.vbl, tL.show, tL.flip, tL.miss] = Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.vbl;
thisN = 1;
else
tL.vbl = Screen('Flip', s.win, 0, 2, 2);
tL.lastvbl = tL.vbl;
thisN = 0;
end
%----- LabJack: I/O needs to send strobe immediately after screen flip -----%
if me.sendStrobe && me.useLabJackTStrobe
sendStrobe(io); me.sendStrobe = false;
%Eyelink('Message', sprintf('MSG:SYNCSTROBE value:%i @ vbl:%20.40g / totalTicks: %i', io.sendValue, tL.lastvbl, tS.totalTicks));
end
%----- Send Eyetracker messages -----%
if me.sendSyncTime % sends SYNCTIME message to eyetracker
syncTime(eT);
me.sendSyncTime = false;
end
%------Log stim / no stim + missed frame -----%
if thisN > 0
logStim(tL,sM.currentName,thisN);
end
%-------If we missed a frame record it somewhere -----%
if thisN > 0 && tL.miss(thisN) > 0 && tL.stimTime(thisN) > 0
addMessage(tL,[],[],'We missed a frame during stimulus');
end
%----- increment our global tick counter -----%
tS.totalTicks = tS.totalTicks + 1; tL.tick = tS.totalTicks;
else % me.doFlip == FALSE
% still wait for IFI time
WaitSecs(s.screenVals.ifi);
end % END me.doFlip
%----- For second display, do we flip? -----%
if me.useTobii && me.doTrackerFlip > -1
if thisTobiiFlip >= tS.tobiiFlipRate
trackerFlip(eT, me.doTrackerFlip)
thisTobiiFlip = 1;
else
thisTobiiFlip = thisTobiiFlip + 1;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end %======================END OF TASK LOOP=========================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tL.screenLog.afterDisplay = tL.lastvbl;
tL.screenLog.trackerEndTime = getTrackerTime(eT);
tL.screenLog.trackerEndOffset = getTimeOffset(eT);
try %#ok<*TRYNC>
drawBackground(s);
trackerClearScreen(eT);
trackerDrawStatus(eT,['FINISHED TASK:' me.name]);
trackerFlip(eT,0);
Screen('Flip', s.win);
Priority(0);
ListenChar(0);
RestrictKeysForKbCheck([]);
ShowCursor;
end
try updatePlot(bR, me); end %update our behavioural plot for final state
try show(stims); end %make all stimuli visible again, useful for editing
try reset(stims); end %reset stims back to initial state
me.isRunning = false;
%-----get our profiling report for our task loop
%profile off; profile viewer;
if me.useDisplayPP || me.useDataPixx
pauseRecording(io); %pause plexon
WaitSecs(0.5);
stopRecording(io);
WaitSecs(0.5);
close(io);
end
try close(s); end %screen
try close(io); end % I/O system
try close(eT); end % eyetracker, should save the data for us we've already given it our name and folder
try close(aM); end % audio manager
try close(rM); end % reward manager
WaitSecs(0.25);
fprintf('\n\n======>>> Total ticks: %g | stateMachine ticks: %g\n', tS.totalTicks, sM.totalTicks);
fprintf('======>>> Tracker Time: %g | PTB time: %g | Drift Offset: %g\n', ...