-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathrunExperiment.m
3199 lines (2905 loc) · 112 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 < optickaCore
%> @class runExperiment
%> @brief The main experiment manager.
%>
%> RUNEXPERIMENT accepts a variable sequence « taskSequence », stimulus set «
%> 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 a DAQ systems using digital I/O
%> and communication over a TCP/UDP client⇄server socket (via «dataConnection»).
%> It also interfaces with hardware like eyetrackers
%>
%> 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 optickatest.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
sessionData struct =struct('subjectName','Simulcra',...
'researcherName','Jane Doe', ...
'labName','lab','labLocation','',...
'sessionPrefix','session','alyxIP','');
%> a metaStimulus class instance holding our stimulus objects
stimuli metaStimulus
%> a taskSequence class instance determining our stimulus variables
task taskSequence
%> a screenManager class instance managing the PTB Screen
screen screenManager
%> filename for a stateMachine state info file
stateInfoFile char = ''
%> user functions file that can be passed to the state machine
userFunctionsFile char = ''
%> what strobe device to use
%> device = '' | display++ | datapixx | labjackt | labjack | nirsmart
%> optional port = not needed for most of the interfaces
%> optional config = plain | plexon style strobe
%> default stim OFF strobe value
strobe struct = struct('device','','port','',...
'mode','plain','stimOFFValue',255)
%> what reward device to use
reward struct = struct('device','','port','',...
'board','');
%> which eyetracker to use
eyetracker struct = struct('device','','dummy',true,...
'esettings',[],'tsettings',[],...
'isettings',[],'psettings',[])
touch struct = struct('device','','dummy',true)
%> use control commands to start / stop recording
%> device = intan | plexon | none
%> port = tcp port
control struct = struct('device','','port','127.0.0.1:5000')
%> Keyboard device, use -1 for all keyboards (slower) or [] for
%> default
keyboardDevice = [];
%> log all frame times?
logFrames logical = true
%> enable debugging? (poorer temporal fidelity)
debug logical = false
%> verbose logging to command window?
verbose = false
end
properties (Transient = true)
%> structure for screenManager on initialisation and info from opticka
screenSettings struct = struct()
%> this lets the opticka UI leave commands to runExperiment
uiCommand char = ''
%> return if runExperiment is running (true) or not (false)
isRunning logical = false
end
properties (Hidden = true)
%> flip as fast as possible?
benchmark logical = false
%> draw simple fixation cross during trial for MOC tasks?
drawFixation logical = false
%> shows the info text and position grid during stimulus presentation
visualDebug logical = false
%> 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 struct
%> ask for comments?
askForComments = false
%> show a white square in the top-right corner to trigger a photodiode
%> attached to screen for MOC task. For stateMachine tasks you need
%> to pass in the drawing command for this to take effect.
photoDiode logical = false
%> turn diary on for runTask, saved to the same folder as the data
diaryMode logical = false
%> opticka version, passed on first use by opticka
optickaVersion char
%> do we record times for every function run by state machine?
logStateTimers logical = false
%> do we ask for comments for runMOC
comments logical = true
%> our old stimulus structure used to be a simple cell, now we use metaStimulus
stimulus
%> audio device
audioDevice = []
%> DEPRECATED
subjectName char = ''
%> DEPRECATED
researcherName char = ''
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)
%> log of timings for MOC tasks
runLog
%> log of timings for state machine tasks
taskLog
%> behavioural responses log
behaviouralRecord
%> stateMachine object
stateMachine
%> eyetracker manager object
eyeTracker
%> strobe / trigger manager
strobeDevice
%> user functions object
userFunctions
%> data connection
dC
%> state machine control cell array
stateInfo cell = {}
%> general computer info retrieved using PTB Screen('computer')
computer
%> PTB version information: Screen('version')
ptb
%> copy of screen settings from screenManager
screenVals struct
%> previous info populated during load of a saved object
previousInfo struct = struct()
end
properties (SetAccess = private, GetAccess = private)
pauseToggle = 0
%> general info on current run
currentInfo
%> variable info on the current run
variableInfo
%> send a strobe on next flip?
sendStrobe logical = false
%> need an eyetracker sample on next flip?
needSample logical = false
%> send an eyetracker SYNCTIME on next flip?
sendSyncTime logical = false
%> do we flip the screen or not?
doFlip logical = true
%> do we flip the eyetracker window? 0=no 1=yes 2=yes+clear
doTrackerFlip double = 0;
%> is it MOC run (false) or stateMachine runTask (true)?
isRunTask logical = true
%> are we using taskSequeence or not?
isTask logical = true
%> should we stop the task?
stopTask logical = false
%> prestimuli
stimShown = false
%> properties allowed to be modified during construction
allowedProperties = {'reward','strobe','eyetracker','control',...
'logFrames','logStateTimers','sessionData',...
'stateInfoFile','userFunctionFile','dummyMode','stimuli','task',...
'screen','visualDebug','debug','verbose','screenSettings','benchmark',...
'comments','arduinoPort','photoDiode'}
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 = optickaCore.addDefaults(varargin,struct('name','Run Experiment'));
me=me@optickaCore(args); %superclass constructor
me.parseArgs(args,me.allowedProperties);
end
% ===================================================================
function runMOC(me, tS)
%> @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
%> @param tS structure with some options to pass
% ===================================================================
%------initialise the rewardManager global object
[rM] = initialiseGlobals(me);
if rM.isOpen
try rM.close; rM.reset; end
end
try
if isfield(me.reward,'port') && ~isempty(me.reward.port); rM.port = me.reward.port; end
if isfield(me.reward,'board') && ~isempty(me.reward.board); rM.board = me.reward.board; end
end
refreshScreen(me);
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
%===============================initialise runLog for this run
me.previousInfo.runLog = [];
me.runLog = [];
me.taskLog = []; clear timeLogger;
me.runLog = timeLogger();
tL = me.runLog;
tL.name = me.name;
if me.logFrames
tL.preAllocate(me.screenVals.fps*60*15);
end
%===============================make a short handle to the screenManager and metaStimulus objects
me.stimuli.screen = me.screen;
s = me.screen;
stims = me.stimuli;
if ~exist('tS','var') || isempty(tS)
tS.controlPlexon = false;
tS.askForComments = true;
end
if ~isfield(tS,'controlPlexon'); tS.controlPlexon = false; end
if ~isfield(me,'askForComments'); tS.askForComments = false; end
%===============================initialise task
task = me.task;
initialise(task, true);
%-----------------------------------------------------------
try%======This is our main TRY CATCH experiment display loop
%-----------------------------------------------------------
me.lastIndex = 0;
me.isRunning = true;
me.isRunTask = false;
%================================INIT SAVE
% subject, sessionPrefix, lab, create
[me.paths.alfPath, sessionID, dateID] = me.getALF(me.sessionData.subjectName,...
me.sessionData.sessionPrefix,me.sessionData.labName, true);
me.name = [me.sessionData.subjectName '-' sessionID '-' dateID]; %give us a run name
%================================get pre-run comments for this data collection
prompt = '\bfCHECK Recording system! \itInitial Comment for this MOC Run?';
updateComments(me,prompt);
s.comment = me.comment; io.comment = me.comment; tL.comment = me.comment; tS.comment = me.comment;
%=============================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');
%================================open the PTB screen and setup stimuli
me.screenVals = s.open(me.debug,tL);
stims.verbose = me.verbose;
task.fps = me.screenVals.fps;
setup(stims, s); %run setup() for each stimulus
if s.movieSettings.record; prepareMovie(s); end
%================================initialise and set up I/O
io = configureIO(me); %#ok<*PROPLC>
dC = dataConnection('protocol','tcp');
%========================================Start amplifier
%
if strcmp(me.control.device,'intan')
addr = strsplit(me.control.port,':');
dC.rAddress = addr{1};
dC.rPort = addr{2};
try
open(dC);
write(dC,uint8(['set Filename.BaseFilename ' me.name]));
write(dC,uint8(['set Filename.Path ' 'C:/OptickaFiles']));
write(dC,uint8('set runmode run'));
catch
warning('runTask cannot contact intan!!!')
me.control.device = '';
end
elseif strcmp(me.control.device,'plexon')
if strcmp(me.strobe.device,'datapixx') || strcmp(me.strobe.device,'display++')
startRecording(io);
WaitSecs(0.5);
resumeRecording(io);
elseif strcmp(me.strobe.device,'labjack')
% Trigger the omniplex (TTL on FIO1) into paused mode
io.setDIO([2,0,0]);WaitSecs(0.001);io.setDIO([0,0,0]);
WaitSecs(0.5);
io.setDIO([3,0,0],[3,0,0])%(Set HIGH FIO0->Pin 24), unpausing the omniplex
end
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(stims);
for i = 1:s.screenVals.fps*2
draw(stims);
drawBackground(s);
drawText(s,'Warming up the GPU, Eyetracker and I/O systems...');
s.drawPhotoDiodeSquare([0 0 0 1]);
finishDrawing(s);
animate(stims);
if ~mod(i,10); io.sendStrobe(me.strobe.stimOFFValue); end
flip(s);
optickaCore.getKeys();
end
update(stims); %make sure stimuli are set back to their start state
if ismethod(me,'resetLog'); resetLog(me); end
io.resetStrobe;flip(s);flip(s);
tL.screenLog.beforeDisplay = GetSecs();
%===========================double check the labJackT handle is still valid
if isa(io,'labJackT') && io.isOpen && ~io.isHandleValid
io.close;
io.open;
disp('We had to reopen the labJackT to ensure a stable connection...')
end
%=============================profiling starts here if uncommented
%profile clear; profile on;
%===========================take over the keyboard + max priority
KbReleaseWait; %make sure keyboard keys are all released
if me.debug == false
%warning('off'); %#ok<*WNOFF>
ListenChar(-1); %2=capture all keystrokes
end
if ~isdeployed
try commandwindow; end
end
Priority(MaxPriority(s.win)); %bump our priority to maximum allowed
%================================Set state for first trial
me.updateMOCVars(1,1); %------set the variables for the very first run
task.isBlank = true;
task.tick = 1;
task.switched = 1;
task.totalRuns = 1;
tL.t.miss(1) = 0;
tL.t.stimTime(1) = 0;
tL.t.vbl(1) = Screen('Flip', s.win);
tL.lastvbl = tL.vbl(1);
tL.startTime = tL.lastvbl;
tL.screenLog.beforeDisplay = tL.lastvbl;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DISPLAY LOOP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while ~task.taskFinished
if task.isBlank
if me.photoDiode;s.drawPhotoDiodeSquare([0 0 0 1]); end
else
draw(stims);
if me.photoDiode;s.drawPhotoDiodeSquare([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 task.isBlank
if strcmpi(me.uiCommand,'stop');break; end
[~,name,~] = optickaCore.getKeys(me.keyboardDevice);
if strcmpi(name,'q'); break; end
end
%================= UPDATE TASK ===================%
updateMOCTask(me,tL.lastvbl); %update our task structure
%=======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 && matches(me.strobe.device,'display++')
sendStrobe(io); me.sendStrobe = false;
elseif me.sendStrobe && matches(me.strobe.device,'datapixx')
triggerStrobe(io); me.sendStrobe = false;
end
%======= FLIP: Show it at correct retrace: ========%
nextvbl = tL.lastvbl + me.screenVals.halfisi;
if me.logFrames == true
[tL.t.vbl(task.tick),tL.t.show(task.tick), ...
tL.t.flip(task.tick),tL.t.miss(task.tick)] ...
= Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.t.vbl(task.tick);
elseif ~me.benchmark
[tL.t.vbl, tL.t.show, tL.t.flip, tL.t.miss] ...
= Screen('Flip', s.win, nextvbl);
tL.lastvbl = tL.t.vbl;
else
tL.t.vbl = Screen('Flip', s.win, 0, 2, 2);
tL.lastvbl = tL.t.vbl;
end
%======LabJack: I/O needs to send strobe immediately after screen flip -----%
if me.sendStrobe && matches(me.strobe.device,{'labjackt','nirsmart'})
sendStrobe(io); me.sendStrobe = false;
end
%===================Logging=======================%
if task.tick == 1 && ~me.benchmark
tL.startTime = tL.t.vbl(1); %respecify this with actual stimulus vbl
task.startTime = tL.startTime; %respecify this with actual stimulus vbl
end
if me.logFrames
if ~task.isBlank
tL.t.stimTime(task.tick)=1+task.switched;
else
tL.t.stimTime(task.tick)=0-task.switched;
end
end
if s.movieSettings.record ...
&& ~task.isBlank ...
&& (s.movieSettings.loop <= s.movieSettings.nFrames)
s.addMovieFrame();
end
%===================Tick tock!=======================%
task.tick=task.tick+1; tL.tick = task.tick;
end
%==================================================================%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Finished display loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%==================================================================%
ListenChar(0);
drawBackground(s);
vbl=Screen('Flip', s.win);
tL.screenLog.afterDisplay=vbl;
%================================Amplifier control
if strcmp(me.control.device,'intan')
write(dC,uint8('set runmode stop'));
elseif strcmp(me.control.device,'plexon')
if strcmp(me.strobe.device,'datapixx') || strcmp(me.strobe.device,'display++')
pauseRecording(io);
WaitSecs(0.25)
stopRecording(io);
elseif strcmp(me.strobe.device,'labjack')
io.setDIO([0,0,0],[1,0,0]); %this is RSTOP, pausing the omniplex
io.setDIO([2,0,0]);WaitSecs(0.05);io.setDIO([0,0,0]); %we stop recording mode completely
end
end
%-----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 = task.tick / (tL.screenLog.afterDisplay - tL.startTime);
fprintf('\n---> BENCHMARK FPS = %g\n', tL.screenLog.benchmark);
end
s.screenVals.info = Screen('GetWindowInfo', s.win);
try resetScreenGamma(s); end
if matches(me.eyetracker.device,'eyelink')
try close(me.eyeTracker); end
me.eyeTracker = [];
end
try finaliseMovie(s,false); end
try reset(stims); end
try close(s); end
try close(io); end
removeEmptyValues(tL);
me.tS = tS; %store our tS structure for backup
prompt = '\bfFinal Comment for this MOC Run?';
updateComments(me,prompt);
s.comment = me.comment; io.comment = me.comment; tL.comment = me.comment; tS.comment = me.comment;
%================================SAVE the DATA
sname = [me.paths.alfPath filesep 'opticka.raw.' me.name '.mat'];
rE = me;
save(sname,'rE','tS');
fprintf('\n\n#####################\n===>>> <strong>SAVED DATA to: %s</strong>\n#####################\n\n',sname)
assignin('base', 'tS', tS); % assign tS in base for manual checking
%================================SAVE the DATA
tL.calculateMisses;
if tL.nMissed > 0
fprintf('\n!!!>>> >>> >>> There were %i MISSED FRAMES <<< <<< <<<!!!\n',tL.nMissed);
end
if s.movieSettings.record; playMovie(s); end
me.isRunning = false;
me.visualDebug = false;
catch ERR
me.isRunning = false;
fprintf('\n\n---!!! ERROR in runExperiment.runMOC()\n');
if strcmp(me.control.device,'plexon')
pauseRecording(io); %pause plexon
WaitSecs(0.25)
stopRecording(io);
close(io);
end
%profile off; profile clear
warning('on');
Priority(0);
ListenChar(0);
ShowCursor;
resetScreenGamma(s);
try close(s); end
try close(me.eyeTracker); end
me.eyeTracker = [];
me.behaviouralRecord = [];
try close(rM); end
clear tL s tS bR rM eT io sM
rethrow(ERR);
end
end %==============END runMOC
% ===================================================================
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.
%>
% ===================================================================
if exist(me.stateInfoFile,'file') && contains(me.stateInfoFile, 'DefaultStateInfo') && me.stimuli.n == 0
warning('You are trying to start a Default behavioural task without stimuli!');
return
end
if isempty(me.screen) || isempty(me.task)
me.initialise; %we set up screenManager and taskSequence objects
end
refreshScreen(me);
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([alfPath filesep 'log.text.' 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.userFunctions = [];
me.stateInfo = {};
if isa(me.stateMachine,'stateMachine'); me.stateMachine.reset; me.stateMachine = []; end
%------initialise the rewardManager global object
[rM, aM] = initialiseGlobals(me);
if rM.isOpen
try rM.close; rM.reset; end
end
try
if isfield(me.reward,'port') && ~isempty(me.reward.port); rM.port = me.reward.port; end
if isfield(me.reward,'board') && ~isempty(me.reward.board); rM.board = me.reward.board; end
end
%------initialise an audioManager for beeps,playing sounds etc.
aM.device = me.audioDevice;
if isempty(me.audioDevice) || me.audioDevice >= 0
aM.silentMode = false;
reset(aM);
if ~aM.isSetup; try setup(aM); end; end
aM.beep(2000,0.1,0.1);
else
reset(aM);
aM.silentMode = true;
end
if ischar(me.comment);me.comment = string(me.comment);end
%--------------------------------------------------------------
% 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.runName = me.name; %==name of this run
tS.name = 'generic';%==name of this protocol
tS.useTask = false; %==use taskSequence (randomised variable task object)
tS.includeErrors = false; %==do error trials count to move taskSequence forward
tS.keyExclusionPattern = ["fixate","stimulus"]; %==which states skip keyboard check
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.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.correctSound = [2000, 0.1, 0.1]; %==freq,length,volume
tS.errorSound = [300, 1, 1]; %==freq,length,volume
tS.fixX = 0;
tS.fixY = 0;
%------initialise time logs for this run
me.taskLog = []; clear timeLogger;
me.taskLog = timeLogger();
tL = me.taskLog; %short handle to log
tL.name = me.name;
if me.logFrames
tL.preAllocate(me.screenVals.fps*60*15);
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 PTB screen and setup stimuli
me.screenVals = s.open(me.debug, tL);
stims.verbose = me.verbose;
task.fps = s.screenVals.fps;
setup(stims, s);
%================================initialise and set up I/O
io = configureIO(me);
dC = me.dC;
%================================set up the eyetracker interface
configureEyetracker(me, s);
eT = me.eyeTracker;
%================================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(p,me.paths.root); p = me.paths.protocols; end
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; uF.verbose = me.verbose;
%================================initialise the state machine
me.stateMachine = [];
clear stateMachine; % this seems to improve performance with logging!!!
me.stateMachine = stateMachine('verbose', me.verbose,...
'realTime', task.realTime, 'name', me.name);
sM = me.stateMachine;
if task.realTime; sM.timeDelta = 0; else; sM.timeDelta=s.screenVals.ifi; end
sM.fnTimers = me.logStateTimers; %record fn evaluations?
if isempty(me.stateInfoFile) || ~exist(me.stateInfoFile,'file') || contains(me.stateInfoFile, ['opticka' filesep '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
stateInfoTmp = [];
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
if isempty(stateInfoTmp)
errordlg('runExperiment.runTask(): State File loading failed!!!');
end
me.stateInfo = stateInfoTmp;
didFind=false;
for jj = 1:length(stateInfoTmp(:))
stemp = stateInfoTmp{jj};
if ~iscell(stemp); continue; end
for kk = 1:length(stemp)
if contains(char(stemp{kk}),regexpPattern('\(eT\s*?,')) && eT.isOff
warning('The State Machine contains eyeTracker functions BUT you have the eyetracker turned OFF!')
didFind=true;break
end
end
if didFind; break; end
end
addStates(sM, me.stateInfo);
me.paths.stateInfoFile = me.stateInfoFile;
clear stateInfoTmp
end
uF.sM = sM;
me.lastXPosition = tS.fixX;
me.lastYPosition = tS.fixY;
me.lastXExclusion = [];
me.lastYExclusion = [];
if ~eT.isOff
me.eyetracker.name = tS.name;
if me.eyetracker.dummy; eT.isDummy = true; end %===use dummy or real eyetracker?
if tS.saveData; eT.recordData = true; end %===save Eyetracker data?
end
if isfield(tS,'rewardTime'); bR.rewardTime = tS.rewardTime; end
%================================initialise save file
% subject, sessionPrefix, lab, create
if tS.saveData
[me.paths.alfPath, sessionID, dateID] = me.getALF(me.sessionData.subjectName,...
me.sessionData.sessionPrefix, [], true);
me.name = [me.sessionData.subjectName '-' sessionID '-' dateID]; %give us a run name
else
[me.paths.alfPath, ~, dateID] = me.getALF(me.sessionData.subjectName,...
me.sessionData.sessionPrefix, [], false);
me.name = [me.sessionData.subjectName '-' dateID]; %give us a run name
end
eT.paths.alfPath = me.paths.alfPath;
if matches(lower(me.eyetracker.device),'eyelink')
eT.saveFile = [eT.paths.alfPath 'eyelink.raw.' me.name '.edf'];
else
eT.saveFile = [eT.paths.alfPath 'tobii.raw.' me.name '.mat'];
end
fprintf('\n\n\n===>>>>>> START BEHAVIOURAL TASK: %s <<<<<<===',me.name);
fprintf('\tInitial Path: %s\n',me.paths.alfPath);
fprintf('\tInitial Comments: %s\n\n\n',me.comment);
%================================get pre-run comments for this data collection
prompt = '\bf CHECK Recording system! \it Initial Comment for this Task Run?';
updateComments(me,prompt);
bR.comment = me.comment; eT.comment = me.comment; sM.comment = me.comment; io.comment = me.comment; tL.comment = me.comment; tS.comment = me.comment;
%===========================set up our behavioural plot
if tS.showBehaviourPlot
fprintf('===>>> Creating Behavioural Record Plot Window...\n');
createPlot(bR, eT);
WaitSecs(0.01); drawnow; WaitSecs(0.01); drawnow;
end
%================================raise priority
fprintf('===>>> Increasing Priority...\n');
op = Screen('Preference', 'Verbosity',4);
Priority(MaxPriority(s.win)); %bump our priority to maximum allowed
Screen('Preference', 'Verbosity',op);
%============================================================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')
t = GetSecs();
WaitSecs('UntilTime',t+0.01);
tSM = stateMachine();
tSM.warmUp(); clear tSM;
show(stims); % allows all child stimuli to be drawn
getStimulusPositions(stims);
if ~isempty(me.eyetracker.device); resetAll(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 GPU, Eyetracker and I/O systems...');
finishDrawing(s);
animate(stims); % run our stimulus animation routines to the next frame
if ~mod(i,10); sendStrobe(io, 255); end % send a strobed word
if ~eT.isOff
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
trackerDrawEyePosition(eT);
end
[~, ~, ~] = optickaCore.getKeys(me.keyboardDevice);
flip(s);
if ~eT.isOff && eT.secondScreen; trackerFlip(eT, 1, false); end
end
resetLog(stims);
if ~eT.isOff
resetAll(eT);
trackerClearScreen(eT);
if eT.secondScreen; trackerFlip(eT, 0, true); end
end
resetStrobe(io); flip(s); flip(s); % reset the strobe system
%=============================Preemptive save in case of crash or error: SAVES IN /TMP
rE = me;
tS.tmpFile = [tempdir filesep 'TEMP' me.name '.mat'];
fprintf('\n===>>> Save initial state in case of crash: %s ...\n',tS.tmpFile);
save(tS.tmpFile,'rE','tS');
fprintf('\t ... Saved!\n');
%=============================Ensure we open the reward manager
if matches(me.reward.device,'arduino') && isa(rM,'arduinoManager') && ~rM.isOpen
fprintf('===>>> Opening Arduino for sending reward TTLs\n');
open(rM);
elseif matches(me.reward.device,'labjack') && isa(rM,'labJack')
fprintf('===>>> Opening LabJack for sending reward TTLs\n');
open(rM);
end
%===========================Start amplifier
if strcmp(me.control.device,'intan')
try
if ~dC.isOpen; open(dC); end
write(dC,uint8(['set Filename.BaseFilename ' me.name]));
write(dC,uint8(['set Filename.Path ' me.paths.savedData]));
write(dC,uint8(['set Note1 ' me.name]));
write(dC,uint8(['set Note2 ' me.comment(1,:)]));
write(dC,uint8('set runmode record'));
WaitSecs(0.5);
catch
warning('runTask cannot contact intan!!!')
me.control.device = '';
end
elseif strcmp(me.control.device,'plexon')
if strcmp(me.strobe.device,'datapixx') || strcmp(me.strobe.device,'display++')
startRecording(io);
WaitSecs(0.5);
resumeRecording(io);
elseif strcmp(me.strobe.device,'labjack')
% Trigger the omniplex (TTL on FIO1) into paused mode
io.setDIO([2,0,0]);WaitSecs(0.001);io.setDIO([0,0,0]);
WaitSecs(0.5);
io.setDIO([3,0,0],[3,0,0])%(Set HIGH FIO0->Pin 24), unpausing the omniplex
end
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.totalTicks = 1; % a tick counter
me.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;
%===========================double check the labJackT handle is still valid
if isa(io,'labJackT')
if ~io.isHandleValid
io.close;
io.open;
disp('===>>> We reopened the labJackT to ensure a stable connection...');
end
assert(io.isServerRunning, true, '===>>> LabJack T Server Not Running!!!');
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
%=============================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.t.vbl(1) = Screen('Flip', s.win);
tL.lastvbl = tL.t.vbl(1);
tL.t.miss(1) = 0;
tL.t.stimTime(1) = 0;
tL.startTime = tL.lastvbl;
tL.screenLog.beforeDisplay = tL.lastvbl;
tL.screenLog.trackerStartTime = getTrackerTime(eT);
tL.screenLog.trackerStartOffset = getTimeOffset(eT);
%==============================IGNITE the stateMachine!
fprintf('\n\n===>>> Igniting the State Machine... <<<===\n');
start(sM);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Display + task loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while me.stopTask == false
%------ Check eye position manually. -----%
if me.needSample && ~eT.isOff; getSample(eT); end
%------ Run stateMachine one step forward -----%
update(sM);
%------ Extra bits if we will flip -----%
if me.doFlip
if s.visualDebug; drawGrid(s); infoTextScreen(me); end
finishDrawing(s);
end
%------ Check keyboard for commands (remember we can turn
% this off using either tS.keyExclusionPattern
% [per-state toggle] or tS.checkKeysDuringStimulus).
if isempty(tS.keyExclusionPattern) || ~matches(sM.currentName,tS.keyExclusionPattern)
checkKeys(me);
end
%----- FLIP: Show it at correct retrace: -----%
if me.doFlip
%------ Display++ or DataPixx: I/O send strobe