-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaTMS_reprogramtask.m
2314 lines (1886 loc) · 82.8 KB
/
paTMS_reprogramtask.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
function paTMS_reprogramtask
%--------------- -----------------------------------------------------------
% paTMS_reprogamtask: the main function running the "paired-associative TMS
% action reprogramming task" using Matlab and PsychoToolbox
% This file is part of the paTMS experiment
% Copyright (C) 2016-2017
% Alberto Lazari [email protected]
% Olof van der Werf [email protected]
% Lennart Verhagen [email protected]
% version 2017-09-11
%--------------------------------------------------------------------------
%====================
%% INITIALIZE
%====================
% definitions and settings (boolean flags)
cfg = [];
cfg.flg.debug = 0; % run in debug mode (1) or not (0)
cfg.flg.tms = 1; % deliver tms pulses (1) or not (0)
cfg.flg.testcond = 0; % test the condition randomization (1) or not (0)
if ~cfg.flg.debug && ~cfg.flg.tms, warning('Are you sure you don''t want TMS pulses? You are not in debug-mode...'); end
if ~cfg.flg.debug && cfg.flg.testcond, error('The condition randomization can only be tested in debug mode...'); end
cfg.flg.suppresschecks = 2; % supress all PsychToolbox quality checks (2), just the sync testing (1), or none (0)
cfg.flg.dontclear = 1; % keep stimuli in bugger after `flip` until instructed otherwise
cfg.flg.setpath = 1; % (re)set the matlab path for PsychToolbox: don't reset (0), reset Psychtoolbox path only when found (1), reset whole matlab path (2)
cfg.flg.primaryscreen = 0; % use the primary screen to present the stimuli (1) or not (0)
% initialize settings, input/output, display, conditions, logfile
[cfg, pref, log] = Initialize(cfg);
% return quickly if only the condition randomization is tested
if cfg.flg.testcond, return; end
% always perform CleanUp function, even after an error
obj_cleanup = onCleanup(@() CleanUp(cfg.h,pref));
% give instructions, wait for start of session
[tim, log] = StartExp(cfg, log);
%====================
%% MAIN TRIAL LOOP
%====================
% loop over trials
t = 1;
while t <= cfg.n.trial + cfg.n.instr.trial
% give a rest before a new block
if LogGet(log, t, 'break')
% present practice instructions
if strcmpi(cfg.sessionName,'baseline') && t <= (cfg.n.instr.trial + 1)
[cfg, log] = PresentPractice(t, cfg, log);
% write last trial to logfile and start new instruction stage
if cfg.instr.restart
LogWrite(log, t);
t = 1;
continue;
end
end
% present a break
if t > cfg.n.instr.trial
cfg = PresentBreak(cfg);
end
end
% inter-trial interval
[tim, log] = PresentInterval(t, cfg, tim, log);
% present flankers and cue
[tim, log] = PresentStimuli(t, cfg, tim, log);
% monitor response and give TMS pulse(s)
[tim, log] = ResponseAndPulse(t, cfg, tim, log);
% update trial counter
t = t + 1;
% abort if the ESCAPE key is pressed after cue
if LogGet(log, t-1, 'respSide') == -1
break
end
end
%====================
%% WRAP UP
%====================
% write last trial to the logfile on the hard-disk
LogWrite(log, t-1);
% TODO: this will crash if you stop before the first trial...
% wait for some extra time
% log the end
% blank the screen?
% end of experiment screen. We clear the screen once they have made their response
DrawFormattedText(cfg.h.window, 'Thank you!\nThe task is finished.\n\nPress Esc Key To Exit.', 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbQueueWait;
% please note CleanUp is run automatically at the end, executing `sca`
%====================
%% END OF THE EXPERIMENT
%====================
%====================
%% TRIAL FUNCTIONS
%====================
function Instruction(cfg)
%% Instruction
%--------------------
% welcome to the task
messageStr = ' During the experiment, we are asking you to do a task. \n\n\n Press any key to see what the task will look like... ';
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% explaining the white cue and coloured flankers
Screen('FillRect', cfg.h.window, cfg.colour.white, cfg.rect.cue);
Screen('FillRect', cfg.h.window, cfg.colour.red, cfg.rect.flankerLeft);
Screen('FillRect', cfg.h.window, cfg.colour.green, cfg.rect.flankerRight);
messageStr = ' There will be a white square in the middle, \n\n and two "flankers" on the sides. \n\n\n\n\n\n\n\n\n\n\n\n\n Press any key to continue... ';
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% explain the that the cue will be coloured after a short delay
Screen('FillRect', cfg.h.window, cfg.colour.green, cfg.rect.cue);
Screen('FillRect', cfg.h.window, cfg.colour.red, cfg.rect.flankerLeft);
Screen('FillRect', cfg.h.window, cfg.colour.green, cfg.rect.flankerRight);
messageStr = ' After a short delay, \n\n the cue will become either red or green. \n\n\n\n\n\n\n\n\n\n\n\n\n Press any key to continue... ';
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% instruct which button should be pressed
Screen('FillRect', cfg.h.window, cfg.colour.green, cfg.rect.cue);
Screen('FillRect', cfg.h.window, cfg.colour.red, cfg.rect.flankerLeft);
Screen('FillRect', cfg.h.window, cfg.colour.green, cfg.rect.flankerRight);
messageStr = ' Then, press the key that corresponds with the side of the flanker, \n\n using your index fingers: \n\n left flanker: left key (left index finger) \n\n right flanker: right key (right index finger) \n\n\n\n\n\n\n\n\n\n\n\n\n\n Press any key to continue... \n\n\n\n\n';
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% TODO: give user a chance to abort the test by pressing the ESCAPE key
function TestPulses(cfg)
%% TestPulses
%--------------------
tim = [];
% welcome to the task
messageStr = ' Before we start, we will first deliver three pulses. \n\n\n Press any key to continue... ';
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% prepare black screen for baseline
Screen('FillRect', cfg.h.window, cfg.colour.black);
% add white (fixation) cue
Screen('FillRect', cfg.h.window, cfg.colour.white, cfg.rect.cue);
% present fixation cue on display as soon as possible
Screen('Flip', cfg.h.window);
% give three paired-pulses to help burn in the io64 mex file. This helps
% with the precision of the TMS pulse timing
for c = 1:3
% wait until the TMS stimulators are charged
if c == 1
WaitSecs(1);
else
WaitSecs(4);
end
% conditioning pulse
io64(cfg.h.port, cfg.port.address, cfg.port.condPulse);
tim.tmsCond = GetSecs;
WaitSecs('UntilTime',tim.tmsCond + cfg.dur.pulseWidth);
io64(cfg.h.port, cfg.port.address, cfg.port.zeroLines);
WaitSecs('UntilTime',tim.tmsCond + cfg.dur.IPI);
% test pulse
io64(cfg.h.port, cfg.port.address, cfg.port.testPulse);
tim.tmsPulse = GetSecs;
WaitSecs('UntilTime',tim.tmsPulse + cfg.dur.pulseWidth);
io64(cfg.h.port, cfg.port.address, cfg.port.zeroLines);
end
% TODO: give user a chance to abort the test by pressing the ESCAPE key
function [cfg, log] = PresentPractice(t, cfg, log)
%% PresentPractice
%--------------------
% some messages are instructions, others feedback
messageStr = '';
cfg.instr.restart = false;
switch t
% instructions for the start of the practice block
case 1
% instructions depend on the practice stage
switch cfg.instr.stage
case 1
% do not give TMS pulses
cfg.instr.tmsOrig = cfg.flg.tms;
cfg.flg.tms = 0;
% prepare for practise trials
messageStr = ' Now, there will be a few introductory trials for you to practice. \n\n\n Press any key to start... ';
case 2
% the very first practice block failed, re-doing
case 3
% the very first practice block were a success, doing one more time
messageStr = ' Please try to respond as fast as you can. \n\n Fixate on the middle cue \n\n and use the colour of the cue to speed up your response. \n\n\n\n Press any key to start... ';
case 4
% do not give TMS pulses
cfg.flg.tms = cfg.instr.tmsOrig;
% ready for the longer practice block
messageStr = ' Now, there are some more trials with pulses. \n\n\n\n Press any key to start... ';
end
case cfg.n.instr.trialdummy + 1
% give feedback at the end of the practice block
if cfg.instr.stage < 4
if cfg.instr.stage < 3
% feedback stage
if all(LogGet(log,1:5,'respCorrect')==1)
messageStr = ' Well done! This is the end of the trial session. \n\n Press any key to continue... ';
cfg.instr.stage = 3;
else
messageStr = ' Unfortunately, not all trials were correct. \n\n Please try again. \n\n Press any key to start... ';
cfg.instr.stage = 2;
end
else
% automatically move to the next (last) stage
cfg.instr.stage = 4;
end
% repeat or move to a new stage, restart the trial counter
cfg.instr.restart = true;
% with the inverted cue colour and instructed side
cueColour = 3 - LogGet(log,1:cfg.n.instr.trial,'cueColour');
log = LogSet(log,1:cfg.n.instr.trial,'cueColour',cueColour);
cueSide = 3 - LogGet(log,1:cfg.n.instr.trial,'cueSide');
log = LogSet(log,1:cfg.n.instr.trial,'cueSide',cueSide);
end
case cfg.n.instr.trial + 1
% present a white cue for a little bit
Screen('FillRect', cfg.h.window, cfg.colour.white, cfg.rect.cue);
Screen('Flip', cfg.h.window);
WaitSecs(1);
% prepare a message for the end of the practice block
messageStr = ' During the experiment, we ask you to \n\n keep your hands as relaxed as possible \n\n as well as keeping your head on the chinrest. \n\n Please only move your index fingers when the cue appears. \n\n Press any key to continue to the real experiment... ';
end
% present on the screen and wait for key stroke
if ~isempty(messageStr)
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
end
function [cfg] = PresentBreak(cfg)
%% PresentBreak
%--------------------
% TODO: give feedback about reaction time?
% give a break
if cfg.n.blockCurr > 0
% present a white cue for a little bit
Screen('FillRect', cfg.h.window, cfg.colour.white, cfg.rect.cue);
Screen('Flip', cfg.h.window);
WaitSecs(1);
% End of the current block
messageStr = sprintf('End of block %d out of %d. \n\n Please take a rest. \n\n Press any key to continue...', cfg.n.blockCurr, cfg.n.block);
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
end
% Ready for the new block
cfg.n.blockCurr = cfg.n.blockCurr + 1;
messageStr = sprintf('Starting block %d out of %d. \n\n Press any key to start...', cfg.n.blockCurr, cfg.n.block);
DrawFormattedText(cfg.h.window, messageStr, 'center', 'center', cfg.colour.white);
Screen('Flip', cfg.h.window);
KbStrokeWait;
% TODO: give user a chance to abort the test by pressing the ESCAPE key
function [tim, log] = PresentInterval(t, cfg, tim, log)
%% PresentInterval
%--------------------
% prepare black screen for baseline
Screen('FillRect', cfg.h.window, cfg.colour.black);
% add white (fixation) cue
Screen('FillRect', cfg.h.window, cfg.colour.white, cfg.rect.cue);
% present interval cue on display as soon as possible
tim.flip = Screen('Flip', cfg.h.window, 0, 1);
tim.interval = tim.flip;
% store the time of the interval in the log
log = LogSet(log, t, 'timeInterval', tim.interval);
% write previous trial to the logfile on the hard-disk
if t > 1
LogWrite(log, t-1);
end
% TODO: give user a chance to abort the test by pressing the ESCAPE key
function [tim, log] = PresentStimuli(t, cfg, tim, log)
%% PresentStimuli
%--------------------
% retrieve the cue colours
if LogGet(log, t, 'cueColour') == 1
cueColour = cfg.colour.red;
else
cueColour = cfg.colour.green;
end
% retrieve the flanker colours
if LogGet(log, t, 'flankerLeft') == 1
flankerLeftColour = cfg.colour.red;
flankerRightColour = cfg.colour.green;
else
flankerLeftColour = cfg.colour.green;
flankerRightColour = cfg.colour.red;
end
% add flankers (white cue is still present from the interval)
Screen('FillRect', cfg.h.window, flankerLeftColour, cfg.rect.flankerLeft);
Screen('FillRect', cfg.h.window, flankerRightColour, cfg.rect.flankerRight);
% calculate intended time of the next flip (after interval minus a buffer)
tim.flanker = tim.flip + cfg.dur.interval - cfg.dur.buffer;
% present flankers on display
tim.flip = Screen('Flip', cfg.h.window, tim.flanker, 1);
tim.flanker = tim.flip;
% calculate intended time of the next flip (450-600 ms after flankers minus a buffer)
tim.cue = tim.flip + cfg.dur.flanker(t) - cfg.dur.buffer;
% add the coloured cue
Screen('FillRect', cfg.h.window, cueColour, cfg.rect.cue);
% present coloured cue on display
tim.flip = Screen('Flip', cfg.h.window, tim.cue, 0);
tim.cue = tim.flip;
% store the time of the flankers and cue in the log
log = LogSet(log, t, 'timeFlanker', tim.flanker);
log = LogSet(log, t, 'timeCue', tim.cue);
function [tim, log] = ResponseAndPulse(t, cfg, tim, log)
%% GivePulse
%--------------------
% TODO: check if button was prematurely pressed
% initialize TMS pulse with zeros
tim.tmsCond = 0;
tim.tmsPulse = 0;
% give a pulse on this trial or not?
if LogGet(log, t, 'tmsPulse') == 0 || ~cfg.flg.tms
% just wait for the response, no TMS pulse
[tim.response, key] = WaitResponse(cfg.h.keyboard, [cfg.key.left cfg.key.right], 1, tim.flip+cfg.dur.maxRT, cfg.key.escape, 1);
else
% calculated intended time of the TMS pulse (single or paired pulse)
if LogGet(log, t, 'tmsPulse') == 2
% paired pulse
tim.tmsPulse = tim.flip + cfg.dur.tmsPulse - cfg.dur.IPI;
else
% single pulse
tim.tmsPulse = tim.flip + cfg.dur.tmsPulse;
end
% buffer = 0.001; % a minimal buffer to account for computing delays
buffer = 0; % WaitResponse is fast, no need for a buffer
% wait for response
[tim.response, key] = WaitResponse(cfg.h.keyboard, [cfg.key.left cfg.key.right], 1, tim.tmsPulse-buffer, cfg.key.escape, 1);
% paired pulse or not?
if LogGet(log, t, 'tmsPulse') == 2
% conditioning pulse
io64(cfg.h.port, cfg.port.address, cfg.port.condPulse);
tim.tmsCond = GetSecs;
WaitSecs('UntilTime',tim.tmsCond + cfg.dur.pulseWidth);
io64(cfg.h.port, cfg.port.address, cfg.port.zeroLines);
WaitSecs('UntilTime',tim.tmsCond + cfg.dur.IPI);
end
% test pulse
io64(cfg.h.port, cfg.port.address, cfg.port.testPulse);
tim.tmsPulse = GetSecs;
WaitSecs('UntilTime',tim.tmsPulse + cfg.dur.pulseWidth);
io64(cfg.h.port, cfg.port.address, cfg.port.zeroLines);
if key == 0
% continue to wait for response
[tim.response, key] = WaitResponse(cfg.h.keyboard, [cfg.key.left cfg.key.right], 1, tim.flip+cfg.dur.maxRT, cfg.key.escape, 0);
else
% response key is already pressed, skip TMS pulse but log with negative value
%tim.tmsPulse = 0;
log = LogSet(log, t, 'tmsPulse', -LogGet(log, t, 'tmsPulse'));
end
end
% TODO: wakey wakey if dur.maxRT?
%if key == 0
% wakey wakey
%end
% process the response
switch key
case 0
respSide = 0;
respCorrect = 0;
respRT = -1;
case {cfg.key.left, cfg.key.right}
if key == cfg.key.left
respSide = 1;
elseif key == cfg.key.right
respSide = 2;
end
if respSide == LogGet(log, t, 'cueSide')
respCorrect = 1;
else
respCorrect = -1;
end
respRT = tim.response - tim.cue;
otherwise
respSide = -abs(key);
respCorrect = 0;
respRT = -1;
end
% compare response to previous trial
respStaySwitch = 0;
if respSide > 0 && ~LogGet(log, t, 'break')
respStaySwitch = 1 + (respSide ~= LogGet(log, t-1, 'respSide'));
end
% store the response in the log
log = LogSet(log, t, 'respSide', respSide);
log = LogSet(log, t, 'respStaySwitch', respStaySwitch);
log = LogSet(log, t, 'respCorrect', respCorrect);
log = LogSet(log, t, 'respRT', respRT);
% store the TMS pulse and response times in the log
log = LogSet(log, t, 'timeTmsCond', tim.tmsCond);
log = LogSet(log, t, 'timeTmsPulse', tim.tmsPulse);
log = LogSet(log, t, 'timeResponse', tim.response);
%====================
%% OVERHEAD FUNCTIONS
%====================
function [cfg, pref, log] = Initialize(cfg)
%% Initialize
%--------------------
cfg.h = [];
% query for parameters and names
sessionList = {'baseline','expression','post'};
if cfg.flg.debug
% hard code the subject and session name
cfg.subjectName = 'debug';
sessionIdx = 1; % don't pick the 'baseline' session, it has instructions
else
cfg.subjectName = strjoin(inputdlg('Subject ID'));
sessionIdx = listdlg(...
'PromptString','What session?',...
'ListSize',[160 120],...
'SelectionMode','single',...
'ListString',sessionList);
end
cfg.sessionName = sessionList{sessionIdx};
% set the random number generator
if cfg.flg.debug
rng('default'); % use a reproducable order when in debug mode
else
rng('shuffle');
end
% do not start initialize the experiment if only a test of the condition
% randomization is requested
if cfg.flg.testcond
% initialize conditions
pref = [];
[cfg, log] = InitLog(cfg);
[cfg, log] = InitCond(cfg, log);
return
end
% (re)set Psychtoolbox path
SetPathPsychToolbox(cfg);
% set up PsychToolbox
PsychDefaultSetup(2); % should be at least 1 to ensure that keynaming is similar across all operating systems
% initialize the input and output devices
cfg = InitInputOutput(cfg);
% initialize the display
[cfg, pref] = InitDisplay(cfg);
%% initialize stimuli, conditions, durations, and logfile
%------------------------
% initialize stimuli
cfg = InitStim(cfg);
% initialize the logfile
[cfg, log] = InitLog(cfg);
% initialize conditions
[cfg, log] = InitCond(cfg, log);
% prepare instruction trials
[cfg, log] = PrepareInstruction(cfg, log);
% initialize durations
cfg = InitDur(cfg);
function SetPathPsychToolbox(cfg)
%% SetPathPsychToolbox
%--------------------
% test whether PsychToolbox is on the path
if ~isempty(regexpi(path,'psychtoolbox','once'))
% PsychToolbox is found on the path
% switch depending on flag
if cfg.flg.setpath == 1
% remove the PsychToolbox folders from the path
fprintf('\nRemoving existing PsychToolbox folders from path.\n');
pathSplit = regexp(path,pathsep,'split');
idx = ~cellfun(@isempty,regexpi(pathSplit,'psychtoolbox','once'));
pathRemove = strcat(pathSplit(idx),pathsep);
pathRemove = strcat(pathRemove{:});
rmpath(pathRemove);
elseif cfg.flg.setpath == 2
% reset the whole matlab path before continuing
restoredefaultpath;
else % cfg.flg.setpath == 0
% Nothing has to be done, return to caller
return
end % cfg.flg.setpath
end
% add Psychtoolbox to the path
disp('Setting up path for PsychToolbox.');
% define location of PsychToolbox (usually in the matlabroot/toolbox)
if ispc, userName=getenv('USERNAME'); else, userName=getenv('USER'); end
switch lower(userName)
case 'lab' % in the lab
dirPT = fullfile('C:','Program Files','Psychtoolbox');
case 'lennart' % on my laptop
dirPT = fullfile(userpath,'toolbox','PsychToolbox');
otherwise
error('User not recognized: location of Psychtoolbox not known');
end
% check if multiple PsychToolbox versions are found
versionListPT = dir([dirPT '*']);
if isempty(versionListPT)
error('No PsychToolbox found in specified location: %s',dirPT);
elseif length(versionListPT) == 1
versionPT = versionListPT(1).name;
% fprintf('\nOne PsychToolbox version found: %s\n',versionPT);
else
str = sprintf('\nPsychToolbox versions found:\n');
kk = 1:length(versionListPT);
for k = kk
str = sprintf('%s\t[%d]\t%s\n',str,k,versionListPT(k).name);
end
str = sprintf('%sPlease select a version: ',str);
sel = str2num(input(str,'s'));
while ~ismember(sel,kk)
str = sprintf('Please select one of the following numbers [%s]: ',num2str(kk));
sel = str2num(input(str,'s'));
end
versionPT = versionListPT(sel).name;
fprintf('Selected version: %s\n',versionPT);
end
% update PsychToolbox location to chosen version
dirPT = fileparts(dirPT);
dirPT = fullfile(dirPT,versionPT);
% generate path to be included
pathPT = genpath(dirPT);
% do not inlcude the svn folder
pathPTRemove = genpath(fullfile(dirPT,'.svn'));
pathPT = strrep(pathPT,pathPTRemove,'');
% for Windows: place the operating system specific basics folder above the general basics
if ispc
pathPTBasic1 = genpath(fullfile(dirPT,'PsychBasic'));
pathPTBasic2 = [fullfile(dirPT,'PsychBasic','MatlabWindowsFilesR2007a') ';'];
pathPTBasic2 = [pathPTBasic2 strrep(pathPTBasic1,pathPTBasic2,'')];
pathPT = strrep(pathPT,pathPTBasic1,pathPTBasic2);
else
%error('linux and OSX not supported yet');
end
% add psychtoolbox to path
addpath(pathPT)
% run startup from PsychToolbox
if (exist('PsychStartup','file') == 2)
PsychStartup;
elseif (exist('SetupPsychtoolbox','file') == 2)
SetupPsychtoolbox;
else
%warning('SetupTest:SetPath:Psychtoolbox','PsychToolbox startup script could not be located.');
disp('An older version of PsychToolbox is selected. The PsychStartup script cannot be run.');
end
function cfg = InitInputOutput(cfg)
%% InitInputOutput
%------------------------
%% set up keyboard and mouse
%--------------------
% start a keyboard queue to record the key presses and releases
cfg.h = StartKeyBoardQueue(cfg.h);
% set target keys
cfg.key.escape = KbName('ESCAPE'); % 41 on macOS
if ispc
cfg.key.left = KbName('LeftControl');
%cfg.key.right = KbName('RightControl');
%cfg.key.right = KbName('RightArrow');
cfg.key.right = KbName('Return');
else
cfg.key.left = KbName('LeftGUI'); % 227 on macOS
cfg.key.right = KbName('RightGUI'); % 231 on macOS
end
% move the cursor to the centre of the screen
%SetMouse(cfg.pos.xCentre, cfg.pos.yCentre);
if cfg.flg.debug
% show cursor as an arrow
ShowCursor('Arrow');
else
% hide the mouse cursor
HideCursor;
end
%% set up parallel port interface
%--------------------
if cfg.flg.tms
try
% initialize an input/output port
cfg.h.port = io64;
% query the status
cfg.port.status = io64(cfg.h.port);
if cfg.port.status ~= 0
error('input/output port setup failed');
end
% hardware address of the parallel port
cfg.port.address = hex2dec('D020');
catch ME
if cfg.flg.debug && ~ispc
warning('input/output port only supported on Windows, simply skipping now');
else
rethrow(ME);
end
end
% parallel port code values for TTL pulses (and zero on all lines)
cfg.port.testPulse = 32;
cfg.port.condPulse = 64;
cfg.port.zeroLines = 0;
else
% no port initialized
cfg.port = [];
end
function h = StartKeyBoardQueue(h)
%% StartKeyBoardQueue
%------------------------
if nargin < 1, h = []; end
% only listen to the FORP device
% cfg.h.keyboard = -1;
%
% % List of vendor IDs for valid FORP devices:
% vendorIDs = [1240 6171];
%
% Devices = PsychHID('Devices');
% % Loop through all KEYBOARD devices with the vendorID of FORP's vendor:
% for i = 1:size(Devices,2)
% if (strcmp(Devices(i).usageName,'Keyboard') || strcmp(Devices(i).usageName,'Keypad')) && ismember(Devices(i).vendorID, vendorIDs)
% cfg.h.keyboard = i;
% break;
% end
% end
%
% if cfg.h.keyboard == -1;
% error('No FORP-Device detected on your system');
% end
h.keyboard = [];
% disable keyboard for Matlab
%ListenChar(2);
% initialize cue
KbQueueCreate(h.keyboard);
% start recording
KbQueueStart(h.keyboard);
function [cfg, pref] = InitDisplay(cfg)
%% InitDisplay
%------------------------
%% setup performance checks and clean-up
%------------------------
% Screen is able to do a lot of configuration and performance checks on
% open, and will print out a fair amount of detailed information when
% it does. This checking behavior can be suppressed if you would like so.
pref = [];
if cfg.flg.suppresschecks > 0
% change the testing parameters
%default: Screen('Preference','SyncTestSettings' [, maxStddev=0.001 secs][, minSamples=50][, maxDeviation=0.1][, maxDuration=5 secs]);
[p1, p2, p3, p4] = Screen('Preference','SyncTestSettings',0.001,50,0.1,5);
pref.old.SyncTestSettings = num2cell([p1 p2 p3 p4]);
if cfg.flg.suppresschecks > 1
% and suppress them completely
pref.old.SkipSyncTests = Screen('Preference','SkipSyncTests',1);
pref.old.VisualDebugLevel = Screen('Preference','VisualDebugLevel',3);
pref.old.SupressAllWarnings = Screen('Preference','SuppressAllWarnings',1);
end
end
% TODO: on macOS it seems there are still warnings displayed. Why?!?
%Screen('Preference', 'VisualDebuglevel', 3)
%% setup display
%------------------------
% get screen handles
cfg.h.allscreens = Screen('Screens');
% use primary or secondary screen to present stimuli
if cfg.flg.primaryscreen
% use primary display
if ispc
cfg.h.screen = min(max(cfg.h.allscreens),1);
else
cfg.h.screen = min(cfg.h.allscreens);
end
else
% use secondary display
cfg.h.screen = max(cfg.h.allscreens);
end
% define colors
cfg.colour.black = BlackIndex(cfg.h.screen);
cfg.colour.white = WhiteIndex(cfg.h.screen);
cfg.colour.gray = (cfg.colour.black+cfg.colour.white)/2;
cfg.colour.red = [1 0 0]';
cfg.colour.green = [0 1 0]';
cfg.colour.blue = [0 0 1]';
% initialize the size of the display window
if cfg.flg.debug
cfg.pos.win = [0 0 640 480];
else
cfg.pos.win = [];
end
% open a display window, get the window handle and size
[cfg.h.window, cfg.pos.win] = PsychImaging('OpenWindow', cfg.h.screen, cfg.colour.black, cfg.pos.win, 32, 2);
% retrieve the size of the display window
[cfg.pos.width, cfg.pos.height] = Screen('WindowSize', cfg.h.window);
[cfg.pos.xCentre, cfg.pos.yCentre] = RectCenter(cfg.pos.win);
% switch to realtime-priority to reduce timing jitter and interruptions
% caused by other applications and the operating system itself:
if ispc
Priority(0);
%Priority(1); % This is not real-time priority to give the screen-capture program a chance to run smoothly
else
Priority(MaxPriority(cfg.h.window));
end
% get the flip interval (time between frame refresh)
cfg.dur = [];
cfg.dur.frame = Screen('GetFlipInterval',cfg.h.window);
% calculate a buffer of half a frame rate
cfg.dur.buffer = cfg.dur.frame/2;
function cfg = InitStim(cfg)
%% InitStim
%------------------------
% set cue and flanker dimensions
if cfg.flg.debug
cfg.rect.cueBase = [0 0 cfg.pos.width/32 cfg.pos.width/32];
cfg.rect.flankerBase = [0 0 cfg.pos.width/8 cfg.pos.width/8];
else
cfg.rect.cueBase = [0 0 50 50];
cfg.rect.flankerBase = [0 0 200 200];
end
% set flanker coordinates
xShiftFlanker = cfg.pos.width/4;
xPosFlankerLeft = cfg.pos.xCentre - xShiftFlanker;
xPosFlankerRight = cfg.pos.xCentre + xShiftFlanker;
% define flanker rectangles
cfg.rect.flankerLeft = CenterRectOnPointd(cfg.rect.flankerBase, xPosFlankerLeft, cfg.pos.yCentre);
cfg.rect.flankerRight = CenterRectOnPointd(cfg.rect.flankerBase, xPosFlankerRight, cfg.pos.yCentre);
% define cue rectangle
cfg.rect.cue = CenterRectOnPointd(cfg.rect.cueBase, cfg.pos.xCentre, cfg.pos.yCentre) ;
function [cfg, log] = InitLog(cfg)
%% InitLog
%----------
% initialize
log = [];
% set a log directory
log.subjectName = cfg.subjectName;
log.sessionName = cfg.sessionName;
log.dir = fullfile(fileparts(mfilename('fullpath')),'log');
if ~exist(log.dir,'dir'), mkdir(log.dir); end
% filename for the header
log.fileName.header = sprintf('logfile_header_%s_%s.txt',log.subjectName,log.sessionName);
log.fileName.header = fullfile(log.dir,log.fileName.header);
% filename for the logfile trial data
log.fileName.data = sprintf('logfile_data_%s_%s.txt',log.subjectName,log.sessionName);
log.fileName.data = fullfile(log.dir,log.fileName.data);
% variables in the logfile
% general
% 1. trialNumber number of the trial in the session (1:cfg.n.trial)
% 2. sequenceNumber number of the sequence in the session (1:cfg.n.sequence)
% 3. sequenceTrial number of the trial within a sequence (1:[4 7])
% 4. break the trial/sequence is preceded by a break (1) or not (0)
% flanker
% 5. flankerLeft the colour of the left flanker, red (1) or green (2)
% 6. flankerRight the colour of the right flanker, red (1) or green (2)
% cue
% 7. cueColour the colour of the cue, red (1) or green (2)
% 8. cueSide the side (hand) cued to respond with, left (1) or right (2)
% 9. cueStaySwitch whether the cue colour stays the same as the previous trial (1) or switches (2)
% 10. sideStaySwitch whether the cued side/hand stays the same as the previous trial (1) or switches (2)
% TMS pulse
% 11. tmsPulse the type of TMS pulse on the trial, none (0), single (1), or paired (2)
% response
% 12. respSide the given response, left (1) or right (2), or absent (0)
% 13. respStaySwitch whether the given response stayed the same as the previous side (1) or switches (2)
% 14. respCorrect whether the given response was correct (1), incorrect (-1), or absent (0)
% 15. respRT the reaction time in ms
% event timing
% 16. timeInterval
% 17. timeFlanker
% 18. timeCue
% 19. timeTmsCond
% 20. timeTmsPulse
% 21. timeResponse
% set the logfile variables
log.varName = {...
'trialNumber', 'sequenceNumber', 'sequenceTrial', 'break',...
'flankerLeft', 'flankerRight',...
'cueColour', 'cueSide', 'cueStaySwitch', 'sideStaySwitch',...
'tmsPulse',...
'respSide', 'respStaySwitch', 'respCorrect', 'respRT',...
'timeInterval', 'timeFlanker', 'timeCue', 'timeTmsCond', 'timeTmsPulse', 'timeResponse'};
% how to identify timing variables in the logfile
log.tim.varIdentifier = '^time';
function [cfg, log] = InitCond(cfg, log)
%% InitCond
%------------------------
% a few settings on how to bias the assignment of pulses to trials
flgBiasSwitchToDesign = true;
flgBiasStayToSeqMiddle = true;
flgBiasStayToNotAssigned = true;
flgBiasStayToNotAssignedMethod = 'absolute';
% do not allow more than 1000 iterations of a nested while loop before breaking
maxWhileLoopIter = 10^3;
%% experimental factorial design
%----------------------------------------
% specify the number of task conditions and pulses
cfg.n.pulseType = 2; % single and paired pulses
cfg.n.cueStaySwitch = 2; % cue colour stay and switch
cfg.n.side = 2; % response side/hand left and right
cfg.n.sideStaySwitch = 2; % response side/hand stay and switch
cfg.n.condCell = cfg.n.cueStaySwitch * cfg.n.side * cfg.n.sideStaySwitch * cfg.n.pulseType;
cfg.n.pulseCondCell = 7; % 7 pulses for each cell combination
cfg.n.pulse = cfg.n.condCell * cfg.n.pulseCondCell; % total number of pulses
% do not deliver a TMS pulse on the three trials after a break/start
cfg.n.afterBreak = 3;
% do not deliver a TMS pulse on the two trials after a switch trial
cfg.n.afterSwitch = 2;
% do not deliver a TMS pulse three trials before or after another TMS pulse
cfg.n.aroundPulse = 3;
% define the task conditions, create a repeatable condition matrix
condTile = 1 + cellfun(@str2double, num2cell(dec2bin(0:(cfg.n.condCell-1))));
% prepare the pseudo-randomisation for
% cueStaySwitch * side * sideStaySwitch * pulseType
cfg.n.cond = size(condTile,2);
% do not allow more than 3 sequences in a row to repeat the same condition
maxCondRepetition = 3;
% do not allow more than 4 repetitions of responding with the same hand
maxSideRepetition = 4;
%% sequence and block settings
%----------------------------------------
% the set of sequence lengths
sequenceVal = [4 5 6 7 8]; % original
%sequenceVal = [5 6 7 8]; % suggestion
% set number of blocks (separated by breaks) and block counter
cfg.n.block = 4;