-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopsTreeNodeTaskSingleCPDotsReversal.m
1434 lines (1248 loc) · 63.2 KB
/
topsTreeNodeTaskSingleCPDotsReversal.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 topsTreeNodeTaskSingleCPDotsReversal < topsTreeNodeTask
% @class topsTreeNodeTaskRTDots
%
% recall the sequence of blocks
% Tut1 Tutorial 1
% Quest Block 1 (Quest)
% Tut2 Tutorial 2
% Block2 Block 2 (standard dots task)
% Tut3 Tutorial 3
% Block3 Blocks 3+ (dual-report task)
%
% 11/28/18 created by aer / reviewed by jig
%
properties % (SetObservable) % uncomment if adding listeners
% Trial properties.
%
% Set useQuest to a handle to a topsTreeNodeTaskSingleCPDotsReversal to use it
% to get coherences
% Possible values of dotsDuration:
% [] (default) ... RT task
% [val] ... use given fixed value
% [min mean max] ... specify as pick from exponential distribution
% 'indep' ... specified in self.independentVariables
settings = struct( ...
'useQuest', [], ...
'coherencesFromQuest', [], ...
'possibleDirections', [0 180], ...
'directionPriors', [], ... % change For asymmetric priors
'referenceRT', [], ...
'fixationRTDim', 0.4, ...
'targetDistance', 10, ... % meaning 10 degs to the left and right of fp, as in Palmer/Huk/Shadlen/2005
'textStrings', '', ...
'correctImageIndex', 1, ...
'errorImageIndex', 3, ...
'correctPlayableIndex', 1, ...
'errorPlayableIndex', 2, ...
'deactivateConsoleStatus', true, ...
'recordDotsPositions', false, ...
'subjectCode', ''); % flag controlling whether to store dots positions or not
% Timing properties
timing = struct( ...
'showInstructions', 0, ...
'waitAfterInstructions', 0.5, ...
'fixationTimeout', 5.0, ...
'holdFixation', 0.2, ...
'showSmileyFace', 0.5, ...
'showFeedback', 1.0, ...
'interTrialInterval', 1.0, ... % as in Palmer/Huk/Shadlen 2005
'preDots', [0.2 0.7 4.8],... % truncated exponential time between fixation and dots onset as in Palmer/Huk/Shadlen 2005. Actual code is this one: https://github.com/TheGoldLab/Lab-Matlab-Control/blob/c4bebf2fc40111ca4c58f801bc6f9210d2a824e6/tower-of-psych/foundation/runnable/topsStateMachine.m#L534
'dotsDuration1', [], ...
'dotsDuration2', [], ...
'dotsTimeout', 5.0, ...
'dirChoiceTimeout', 3.0, ...
'cpChoiceTimeout', 8.0);
% settings about the trial sequence to use
trialSettings = struct( ...
'numTrials', 204, ... % theoretical number of valid trials per block
'loadFromFile', false, ... % load trial sequence from files?
'csvFile', '', ... % file of the form filename.csv
'jsonFile', ''); ... % file of the form filename_metadata.json
% Quest properties
questSettings = struct( ...
'stimRange', 0:100, ... % coherence levels
'thresholdRange', 0.5:.5:100, ... % cannot start at 0 with Weibull
'slopeRange', 2, ... % we don't estimate the slope
'guessRate', 0.5, ... % because it is a 2AFC task
'lapseRange', 0.001, ... % this lapse will affect percent correct at threshold, so we estimate it
'recentGuess', [], ...
'viewingDuration', .4); % stimulus duration for Quest (sec)
% Array of structures of independent variables, used by makeTrials
% NOTE: DO NOT CHANGE THE ORDERING OF THE ENTRIES BELOW!
% 1. initDirection
% 2. coherence
% 3. viewingDuration
% 4. condProbCP
% 5. timeCP
independentVariables = struct( ...
'name', {...
'initDirection', ...
'coherence', ...
'viewingDuration', ...
'condProbCP', ...
'timeCP'}, ...
'values', {...
[0 180], ... % allowed initial directions
[10 30 70], ... % coherence values, if not a Quest
.1:.1:.4, ... % viewingDuration (sec)
.5, ... % probability of CP, given that the trial is longer than timeCP
.2}, ... % time of CP
'priors', {[], [], [], [], []});
% dataFieldNames are used to set up the trialData structure
trialDataFields = {...
'dirRT', ...
'dirChoice', ...
'dirCorrect', ...
'cpRT', ...
'cpChoice', ...
'cpCorrect', ...
'initDirection', ...
'endDirection', ...
'presenceCP', ...
'coherence', ...
'viewingDuration', ...
'condProbCP', ...
'timeCP', ...
'randSeedBase', ...
'fixationOn', ...
'fixationStart', ...
'targetOn', ...
'dotsOn', ...
'dotsOff', ...
'dirChoiceTime', ...
'dirReleaseChoiceTime', ...
'cpChoiceTime', ...
'targetOff', ...
'fixationOff', ...
'feedbackOn', ...
'CPresponseSide', ...
'startResponseTwo'};
% empty struct that will later be filled, only if
% self.settings.recordDotsPositions is true.
%%%%%%%%%%%%%%%%%%%%%%%%
% Description of fields:
% dotsPositions is a 1-by-JJ cell, where JJ is the number of
% trials run in the experiment. Each entry of the
% cell will contain matrix equal to
% dotsDrawableDotKinetogram.dotsPositions
% dumpTime is a cell array of times, each computed as
% feval(self.clockFunction).
% The times are computed by the dumpDots() method,
% once at the end of every trial. They should be
% compared to the 'trialStart' time stamp in order
% to assign a sequence of dots frames to a
% particular trial.
dotsInfo = struct('dotsPositions', [], 'dumpTime', []);
% Drawables settings
drawable = struct( ...
...
... % Stimulus ensemble and settings
'stimulusEnsemble', struct( ...
...
... % Fixation drawable settings
'fixation', struct( ...
'fevalable', @dotsDrawableTargets, ...
'settings', struct( ...
'xCenter', 0, ...
'yCenter', 0, ...
'nSides', 100, ...
'width', .4, ...% 0.4 deg vis. angle as in Palmer/Huk/Shadlen 2005
'height', .4, ...
'colors', [1 0 0])), ...% red as in Palmer/Huk/Shadlen 2005, and blue at dotsOn
...
... % Targets drawable settings
'targets', struct( ...
'fevalable', @dotsDrawableTargets, ...
'settings', struct( ...
'nSides', 100, ...
'width', .8*ones(1,2), ... % 0.8 deg vis. angle as in Palmer/Huk/Shadlen 2005
'height', .8*ones(1,2), ...
'colors', [1 0 0])), ...% red as in Palmer/Huk/Shadlen 2005) ...
...
... % Smiley face for feedback
'smiley', struct( ...
'fevalable', @dotsDrawableImages, ...
'settings', struct( ...
'fileNames', {{'smiley.jpg'}}, ...
'height', 2)), ...
...
... % Dots drawable settings
'dots', struct( ...
'fevalable', @dotsDrawableDotKinetogram, ...
'settings', struct( ...
'xCenter', 0, ...
'yCenter', 0, ...
'coherenceSTD', 10, ...
'stencilNumber', 1, ...
'pixelSize', 6, ... % Palmer/Huk/Shadlen 2005 use 3, but they have 25.5 px per degree!
'diameter', 5, ... % as in Palmer/Huk/Shadlen 2005
'density', 90, ... % 16.7 in Palmer/Huk/Shadlen 2005
'speed', 5, ... % as in Palmer/Huk/Shadlen 2005 (and 3 interleaved frames)
'recordDotsPositions', false)), ...
... % CP Targets drawable settings
'cpLeftTarget', struct( ...
'fevalable', @dotsDrawableText, ...
'settings', struct( ...
'x', -12, ...
'y', 0)), ...
...
'cpRightTarget', struct( ...
'fevalable', @dotsDrawableText, ...
'settings', struct( ...
'x', 12, ...
'y', 0))));
% Readable settings
readable = struct( ...
...
... % The readable object
'reader', struct( ...
...
'copySpecs', struct( ...
...
... % The gaze windows
'dotsReadableEye', struct( ...
'bindingNames', 'stimulusEnsemble', ...
'prepare', {{@updateGazeWindows}}, ...
'start', {{@defineEventsFromStruct, struct( ...
'name', {'holdFixation', 'breakFixation', 'choseLeft', 'choseRight'}, ...
'ensemble', {'stimulusEnsemble', 'stimulusEnsemble', 'stimulusEnsemble', 'stimulusEnsemble'}, ... % ensemble object to bind to
'ensembleIndices', {[1 1], [1 1], [2 1], [2 2]})}}), ...
...
... % The keyboard events .. 'uiType' is used to conditinally use these depending on the theObject type
'dotsReadableHIDKeyboard', struct( ...
'start', {{@defineEventsFromStruct, struct( ...
'name', {'holdFixation', 'choseLeft', 'choseRight', 'choseCP', 'choseNOCP'}, ...
'component', {'KeyboardSpacebar', 'KeyboardLeftArrow', 'KeyboardRightArrow', 'KeyboardC', 'KeyboardN'}, ...
'isRelease', {true, false, false, false, false})}}), ...
...
... % Gamepad
'dotsReadableHIDGamepad', struct( ...
'start', {{@defineEventsFromStruct, struct( ...
'name', {'holdFixation', ... % A button
'choseLeft', ... % left trigger
'choseRight', ... % right trigger
'startTask', ... % B button
'choseCP', ... % X button
'choseNOCP'}, ... % Y button
'component', {'Button1', ... % button ID 3
'Trigger1', ...% button ID 7
'Trigger2', ...% button ID 8
'Button2', ... % button ID 4
'Button3', ... % button ID 5
'Button4'}, ...% button ID 6
'isRelease', {true, ...
false, ...
false, ...
false, ...
false, ...
false})}}), ...
...
... % Ashwin's magic buttons
'dotsReadableHIDButtons', struct( ...
'start', {{@defineEventsFromStruct, struct( ...
'name', {'holdFixation', 'choseLeft', 'choseRight'}, ...
'component', {'KeyboardSpacebar', 'KeyboardLeftShift', 'KeyboardRightShift'}, ...
'isRelease', {true, false, false})}}), ...
...
... % Dummy to run in demo mode
'dotsReadableDummy', struct( ...
'start', {{@defineEventsFromStruct, struct( ...
'name', {'holdFixation'}, ...
'component', {'auto_1'})}}))));
% requests for 2 responses if true; for decide on direction, then
% decide on presence/absence of change point
isDualReport = false;
getMoney = false;
metadatafile = 'subj_metadata.json';
end
properties (SetAccess = protected)
% The quest object
quest;
% Boolean flag, whether the specific trial has a change point or not
isCP;
% Check for changes in properties that require drawables to be
% recomputed
targetDistance;
end
methods
%% Constructor
% Use topsTreeNodeTask method, which can parse the argument list
% that can set properties (even those nested in structs)
function self = topsTreeNodeTaskSingleCPDotsReversal(varargin)
% ---- Make it from the superclass
%
self = self@topsTreeNodeTask(varargin{:});
end
%% Make trials (overloaded)
% this method exists in the super class, but for now, I reimplement
% it as I find it to be buggy in the superclass.
%
% Utility to make trialData array using array of structs (independentVariables),
% which must be a property of the given task with fields:
%
% 1. name: string name
% 2. values: vector of unique values
% 3. priors: vector of priors (or empty for equal priors)
%
% trialIterations is number of repeats of each combination of
% independent variables
%
function makeTrials(self, independentVariables, trialIterations)
%
if self.trialSettings.loadFromFile
trialsTable = ...
readtable(self.trialSettings.csvFile);
metaData = ...
loadjson(self.trialSettings.jsonFile);
% set values that are common to all trials
self.trialSettings.numTrials = self.trialIterations;
ntr = self.trialSettings.numTrials;
% produce copies of trialData struct to render it ntr x 1
self.trialData = repmat(self.trialData(1), ntr, 1);
% taskID
[self.trialData.taskID] = deal(self.taskID);
% condProbCP
[self.trialData.condProbCP] = ...
deal(metaData.cond_prob_cp);
% timeCP
[self.trialData.timeCP] = ...
deal(self.independentVariables(5).values(1));
trlist = num2cell(1:ntr);
% trialIndex
[self.trialData.trialIndex] = deal(trlist{:});
% set values that are specific to each trial
for tr = 1:ntr
% initDirection
if strcmp(trialsTable.dir(tr), 'left')
self.trialData(tr).initDirection = 180;
else
self.trialData(tr).initDirection = 0;
end
% endDirection and presenceCP
if strcmp(trialsTable.cp(tr), 'True')
self.trialData(tr).endDirection = ...
self.flipDirection( ...
self.trialData(tr).initDirection);
self.trialData(tr).presenceCP = 1.0; % numeric for FIRA
else
self.trialData(tr).endDirection = ...
self.trialData(tr).initDirection;
self.trialData(tr).presenceCP = 0;
end
% coherence (3 possible values)
cohMetaData = trialsTable.coh(tr);
if isnumeric(cohMetaData)
cohMetaData = num2str(cohMetaData);
end
if strcmp(cohMetaData, '0')
self.trialData(tr).coherence = ...
self.independentVariables(2).values(1);
elseif strcmp(cohMetaData, 'th')
self.trialData(tr).coherence = ...
self.independentVariables(2).values(2);
elseif strcmp(cohMetaData, '100')
self.trialData(tr).coherence = ...
self.independentVariables(2).values(3);
end
% viewingDuration
self.trialData(tr).viewingDuration = ...
trialsTable.vd(tr) / 1000;
end
% we only use the old makeTrials() for the Quest node
elseif strcmp(self.name, 'Quest') || strcmp(self.name, 'Tut1')
% if trialIterations arg is not provided or is empty, set it to
% 1
if nargin < 3 || isempty(trialIterations)
trialIterations = 1;
end
% Loop through to set full set of values for each variable
for ii = 1:length(independentVariables)
% now do something only if priors field is nonempty
%
% update values based on priors, if they are given in the
% format: [proportion_value_1 proportion_value_2 ... etc]
%
% check that priors vector has same length as values
% vector, and that the sum of the entries in priors is
% positive
if length(independentVariables(ii).priors) == ...
length(independentVariables(ii).values) && ...
sum(independentVariables(ii).priors) > 0
% TOTEST
% rescale priors by greatest common divisor
priors = independentVariables(ii).priors;
priors = priors./gcd(sym(priors));
% TOTEST -- what does this currently do?
% now re-make values array based on priors
values = [];
for jj = 1:length(priors)
values = cat(1, values, repmat( ...
independentVariables(ii).values(jj), priors(jj), 1));
end
% re-save the values
independentVariables(ii).values = values;
end
end
% get values as cell array and make ndgrid
values = {independentVariables.values};
grids = cell(size(values));
[grids{:}] = ndgrid(values{:});
% update trialData struct array with "trialIterations" copies of
% each trial, defined by unique combinations of the independent
% variables
ntr = numel(grids{1}) * trialIterations;
self.trialData = repmat(self.trialData(1), ntr, 1);
[self.trialData.taskID] = deal(self.taskID);
trlist = num2cell(1:ntr);
[self.trialData.trialIndex] = deal(trlist{:});
[self.trialData.presenceCP] = deal(0);
% loop through the independent variables and set in each trialData
% struct. Make sure to repeat each set trialIterations times.
for ii = 1:length(independentVariables)
values = num2cell(repmat(grids{ii}(:), trialIterations, 1));
[self.trialData.(independentVariables(ii).name)] = deal(values{:});
end
end
end
% %% debug cross
% function debug_cross(self)
%
% % ---- Activate event and check for it
% %
% self.helpers.reader.theObject.setEventsActiveFlag({'x','y'})
% xeventName = self.helpers.reader.readEvent({'x'});
% yeventName = self.helpers.reader.readEvent({'y'});
%
%
%
% % Nothing... keep checking
% while isempty(xeventName) && isempty(yeventName)
% self.helpers.feedback.show('text', ...
% {'waiting for cross press'}, ...
% 'showDuration', 0.1, ...
% 'blank', false);
%
% xeventName = self.helpers.reader.readEvent({'x'});
% yeventName = self.helpers.reader.readEvent({'y'});
% end
%
% if ~isempty(xeventName)
% ev='x';
% elseif ~isempty(yeventName)
% ev='y';
% end
%
% self.helpers.feedback.show('text', ...
% ['event ',ev,' detected!'], ...
% 'showDuration', 3.5, ...
% 'blank', true);
% end
%% Self paced break screen
function self_paced_break(self)
% ---- Activate event and check for it
%
self.helpers.reader.theObject.setEventsActiveFlag('startTask')
eventName = self.helpers.reader.readEvent({'startTask'});
% Nothing... keep checking
while isempty(eventName)
if ismember(self.name,{'Tut1', 'Tut2', 'Tut3', 'Quest', 'Block2', 'Block3'})
self.helpers.feedback.show('text', ...
{['You may start the next block by pressing', ...
' the B button.']}, ...
'showDuration', 0.1, ...
'blank', false);
else
breakstr = 'Take a break if you wish.';
self.helpers.feedback.show('text', ...
{breakstr, ...
['You may start the next block by pressing', ...
' the B button.']}, ...
'showDuration', 0.1, ...
'blank', false);
end
eventName = self.helpers.reader.readEvent({'startTask'});
end
if ~isempty(self.trialSettings.jsonFile) && ~ismember(self.name, {'Tut1', 'Tut2', 'Tut3', 'Block2'})
metaData = ...
loadjson(self.trialSettings.jsonFile);
if metaData.prob_cp < 0.5
cpfreq = 'a LOW';
elseif metaData.prob_cp == 0.5
cpfreq = 'a MEDIUM';
elseif metaData.prob_cp == .8
cpfreq = 'a HIGH';
end
self.helpers.feedback.show('text', ...
['This block has ',cpfreq,' number of switch trials'], ...
'showDuration', 6.5, ...
'blank', true);
end
end
%% Start task (overloaded)
%
% Put stuff here that you want to do before each time you run this
% task
function startTask(self)
% manually add dummy events related to x and y directions of
% directional cross on gamepad
readableObj = self.helpers.reader.theObject;
if isa(readableObj,'dotsReadableHIDGamepad')
readableObj.defineEvent('x', 'component', 9);
readableObj.defineEvent('y', 'component', 10);
end
self.trialIterationMethod = 'sequential'; % enforce sequential
self.randomizeWhenRepeating = false;
% ---- Set up independent variables if Quest task
%
if strcmp(self.name, 'Quest') || strcmp(self.name, 'Tut1') % when we are running the task as Quest node
% Initialize and save Quest object
self.quest = qpInitialize(qpParams( ...
'stimParamsDomainList', { ...
self.questSettings.stimRange}, ...
'psiParamsDomainList', { ...
self.questSettings.thresholdRange, ...
self.questSettings.slopeRange, ...
self.questSettings.guessRate, ...
self.questSettings.lapseRange}, ...
'qpOutcomeF',@(x) qpSimulatedObserver(x,@qpPFStandardWeibull,simulatedPsiParams), ...
'qpPF', @qpPFStandardWeibull));
% Update independent variable struct using initial value
self.setIndependentVariableByName('coherence', 'values', ...
self.getQuestGuess());
self.setIndependentVariableByName('condProbCP', 'values', 0);
self.setIndependentVariableByName('viewingDuration', ...
'values', self.questSettings.viewingDuration);
elseif ~isempty(self.settings.useQuest) % when we are running the task AFTER a Quest node
% get Quest threshold
questThreshold = self.settings.useQuest.getQuestThreshold( ...
self.settings.coherencesFromQuest);
% get coherence value corresponding to 98 pCorrect
% questHighCoh = self.settings.useQuest.getQuestCoh(.98);
% if questHighCoh > 100
% questHighCoh = 100;
% end
questHighCoh = 100;
% Update independent variable struct using Quest's fit
self.setIndependentVariableByName('coherence', 'values', ...
[0, questThreshold, questHighCoh]);
self.setIndependentVariableByName('coherence', 'priors', ...
[30 40 30]);
end
% % debug
% self.debug_cross()
%
% ---- Self-paced break screen
% we offer the subject the possibility to take a break
% the subject triggers the start of the task with a key press
self.self_paced_break()
% ---- Initialize the state machine
%
self.initializeStateMachine();
% ---- Show task-specific instructions
%
self.helpers.feedback.show('text', self.settings.textStrings, ...
'showDuration', self.timing.showInstructions);
pause(self.timing.waitAfterInstructions);
% pre-allocate cell size to record dots positions and states
if self.settings.recordDotsPositions
self.dotsInfo.dotsPositions = cell(1,length(self.trialIndices));
self.dotsInfo.dumpTime = self.dotsInfo.dotsPositions;
end
end
%% Finish task (overloaded)
%
% Put stuff here that you want to do after each time you run this
% task
function finishTask(self)
% fetch current total accrued reward for this session
curr_tot_reward = ...
self.caller.nodeData.getItemFromGroupWithMnemonic('Settings', 'accruedReward');
pause(0.1)
early_abort = false;
tot_trials = numel(self.trialData);
valid_trials = 0;
for t = 1:tot_trials
trial = self.trialData(t);
if isnan(trial.dirCorrect)
early_abort = true;
block_reward = 0;
break
elseif isnan(trial.cpCorrect) && self.isDualReport
early_abort = true;
block_reward = 0;
break
end
valid_trials = valid_trials + 1;
end
% compute money reward
if length(self.name) > 4 % it is either a BlockX or Quest
if strcmp(self.name(1:5), 'Block')
full_correct_counter = 0;
trial_counter = 0;
if ~early_abort
for t = 1:tot_trials
trial = self.trialData(t);
if trial.coherence == 100
trial_counter = trial_counter + 1;
if trial.dirCorrect && trial.cpCorrect
full_correct_counter = full_correct_counter + 1;
end
end
end
self.getMoney = (full_correct_counter / trial_counter) > 0.75;
if self.getMoney
if strcmp(self.name, 'Block2')
block_reward = 2;
else
block_reward = 4;
end
self.helpers.feedback.show('text', ...
{['Well done! You earned $', ...
num2str(block_reward)], ...
['Total = $', num2str(curr_tot_reward + block_reward)]}, ...
'showDuration', 4.5, ...
'blank', false);
else
self.helpers.feedback.show('text', ...
{'You did not earn additional money on this block.', ...
'Let us know if something is wrong.'}, ...
'showDuration', 4.5, ...
'blank', false);
block_reward = 0;
end
else
self.getMoney = false;
end
elseif strcmp(self.name(1:5), 'Quest')
if ~early_abort
block_reward = 2;
self.helpers.feedback.show('text', ...
['You earned your first $', ...
num2str(block_reward),' with this block!'], ...
'showDuration', 4.5, ...
'blank', false);
end
end
else % it was a tutorial block
block_reward = 0;
end
curr_tot_reward = curr_tot_reward + block_reward;
% store reward entries in topsGroupedList from parent topNode
self.caller.nodeData.addItemToGroupWithMnemonic(curr_tot_reward, 'Settings', 'accruedReward');
self.caller.nodeData.addItemToGroupWithMnemonic(block_reward, 'Settings', [self.name,'_reward']);
fprintf('=============================================================')
fprintf(char(10))
fprintf(' End of %s, block reward %d, total reward %d, aborted block=%d', ...
self.name, block_reward, curr_tot_reward, early_abort)
fprintf(char(10))
fprintf('=============================================================')
fprintf(char(10))
% store metadata
% first get the session struct
fullMetaData = loadjson(self.metadatafile);
tmpStruct=fullMetaData.(self.settings.subjectCode);
if isempty(tmpStruct)
lastSessionName = 'session0';
else
allSessions = fieldnames(tmpStruct);
lastSessionName = allSessions{end};
end
if self.taskID == 1
% for first block in session, create struct
currSessionName = [lastSessionName(1:end-1),...
num2str(str2double(lastSessionName(end))+1)];
fullMetaData.(self.settings.subjectCode).(currSessionName) = struct();
fullMetaData.(self.settings.subjectCode).(currSessionName).trialFolder = 'Blocks003';
stg = self.caller.filename(end-31:end-16);
fullMetaData.(self.settings.subjectCode).(currSessionName).sessionTag = stg;
else
currSessionName = lastSessionName;
end
subjStruct = fullMetaData.(self.settings.subjectCode);
% initialize block struct
subjStruct.(currSessionName).(self.name) = struct();
subjBlockStruct = subjStruct.(currSessionName).(self.name);
if strcmp(self.name(1:3), 'Tut')
iscomplete = valid_trials > 0;
else
iscomplete = block_reward > 0;
end
% then fill out the struct with task data
subjBlockStruct.completed = iscomplete;
subjBlockStruct.aborted = early_abort;
subjBlockStruct.reward = block_reward;
subjBlockStruct.numTrials = valid_trials;
% write Quest parameters if completed:
if strcmp(self.name, 'Quest') && iscomplete
psiParamsIndex = qpListMaxArg(self.quest.posterior);
subjBlockStruct.QuestFit = self.quest.psiParamsDomain(psiParamsIndex,:);
end
% then save back struct to metadata file
fullMetaData.(self.settings.subjectCode).(currSessionName).(self.name) = ...
subjBlockStruct;
savejson('', fullMetaData, self.metadatafile);
end
%% Start trial
%
% Put stuff here that you want to do before each time you run a trial
function startTrial(self)
% ---- check whether a CP will occur in this trial or not
%
% Get current task/trial
trial = self.getTrial();
%ensemble = self.helpers.stimulusEnsemble.theObject;
%initialDirection = ensemble.getObjectProperty('direction',4);
% if CP time is longer than viewing duration, no CP
if trial.presenceCP
self.isCP = true;
self.timing.dotsDuration1 = trial.timeCP;
self.timing.dotsDuration2 = trial.viewingDuration - trial.timeCP;
else
self.isCP = false;
self.timing.dotsDuration1 = trial.viewingDuration;
self.timing.dotsDuration2 = 0;
if isnan(trial.endDirection)
trial.endDirection = trial.initDirection;
end
end
self.setTrial(trial);
% ---- Prepare components
%
self.prepareDrawables();
self.prepareReadables();
self.prepareStateMachine();
% jig sets the timing in the statelist
self.stateMachine.editStateByName('showDotsEpoch1', 'timeout', self.timing.dotsDuration1);
self.stateMachine.editStateByName('switchDots', 'timeout', self.timing.dotsDuration2);
% ---- Inactivate all of the readable events
%
self.helpers.reader.theObject.deactivateEvents();
% ---- Show information about the task/trial
%
% Task information
% string of the form
% <block name> (block X/Y): <num dir correct> dirCorrect, <>
taskString = sprintf('%s (block %d/%d): %d dirCorrect, %d dirError, mean dirRT=%.2f, %d cpCorrect, %d cpError, mean dirRT=%.2f, epoch1=%.2f, epoch2=%.2f dualReport=%d', ...
self.name, ...
self.taskID, ...
length(self.caller.children), ...
sum([self.trialData.dirCorrect]==1), ...
sum([self.trialData.dirCorrect]==0), ...
nanmean([self.trialData.dirRT]), ...
sum([self.trialData.cpCorrect]==1), ...
sum([self.trialData.cpCorrect]==0), ...
nanmean([self.trialData.cpRT]), ...
self.timing.dotsDuration1, ...
self.timing.dotsDuration2, ...
self.isDualReport);
% Trial information
trial = self.getTrial();
trialString = sprintf('Trial %d/%d, init dir=%d, coh=%.0f', ...
self.trialCount, ...
numel(self.trialData), ...
trial.initDirection, ...
trial.coherence);
% Show the information
self.statusStrings = {taskString, trialString};
if self.settings.deactivateConsoleStatus
% Possibly update the gui using the new task
self.caller.updateGUI('_updateTaskStatus', self, 1:length(self.statusStrings));
else
self.updateStatus(); % just update the second one
end
end
%% Flip direction of dots
%
% very simple function that
function direction2 = flipDirection(self, direction1)
pd = self.settings.possibleDirections;
direction2 = pd(~(pd == direction1));
end
%% Finish Trial
%
% Could add stuff here
function finishTrial(self)
% add numFrames field to trial struct
trial = self.getTrial();
self.setTrial(trial);
% Conditionally update Quest
if strcmp(self.name, 'Quest') || strcmp(self.name, 'Tut1')
% ---- Check for bad trial
%
trial = self.getTrial();
if isempty(trial) || ~(trial.dirCorrect >= 0)
return
end
% ---- Update Quest
%
% (expects 1=error, 2=correct)
self.quest = qpUpdate(self.quest, self.questSettings.recentGuess, ...
trial.dirCorrect+1);
% Update next guess, if there is a next trial
if self.trialCount < length(self.trialIndices)
self.trialData(self.trialIndices(self.trialCount+1)).coherence = ...
self.getQuestGuess();
end
% ---- Set reference coherence to current threshold
% and set reference RT
%
self.settings.coherences = self.getQuestThreshold( ...
self.settings.coherencesFromQuest);
self.settings.referenceRT = nanmedian([self.trialData.dirRT]);
end
end
%% Check for direction choice
%
% Save choice/RT information and set up feedback for the dots task
function nextState = checkForDirChoice(self, events, eventTag)
% ---- Check for event
%
% self.helpers.reader.theObject.flushData()
% self.helpers.reader.theObject.setEventsActiveFlag(events)
eventName = self.helpers.reader.readEvent(events, self, eventTag);
% Nothing... keep checking
if isempty(eventName)
nextState = [];
return
end
% Get current task/trial
trial = self.getTrial();
trial.dirChoice = double(strcmp(eventName, 'choseRight'));
% Compute RT wrt dotsOff
trial.dirRT = trial.dirChoiceTime - trial.dotsOff;
if trial.dirRT < 0 || isnan(trial.dirRT)
nextState = 'blank';
pause(0.1)
self.helpers.feedback.show('text', ...
{'You answered too soon.', ...
'Please wait until the dots disappear.'}, ...
'showDuration', 4, ...
'blank', true);
else
% Jump to next state when done
if self.isDualReport
nextState = 'waitForReleasFX';
else
% Override completedTrial flag
self.completedTrial = true;
nextState = 'blank';
end
% Mark as correct/error
trial.dirCorrect = double( ...
(trial.dirChoice==0 && trial.endDirection==180) || ...
(trial.dirChoice==1 && trial.endDirection==0));
% ---- Possibly show smiley face
if trial.dirCorrect == 1 && self.timing.showSmileyFace > 0 && ~self.isDualReport
self.helpers.stimulusEnsemble.draw({3, [1 2 4]});
pause(self.timing.showSmileyFace);
end
end
% ---- Re-save the trial
%
self.setTrial(trial);
end
%% Check for direction choice trigger Release
%
% Save choice/RT information and set up feedback for the dots task
function nextState = checkForReleaseDirChoice(self, events, eventTag)
% ---- Check for event
%
% self.helpers.reader.theObject.flushData()
% self.helpers.reader.theObject.setEventsActiveFlag(events)
eventName = self.helpers.reader.readEvent(events, self, eventTag);
% Nothing... keep checking
if isempty(eventName)
nextState = [];
return
end
% Jump to next state when done
nextState = 'blank1';
end
%% Check for CP choice
%
% Save choice/RT information and set up feedback for the dots task
function nextState = checkForCPChoice(self, events, eventTag)
% ---- Check for event
%
% self.helpers.reader.theObject.flushData()
% self.helpers.reader.theObject.setEventsActiveFlag(events)
eventName = self.helpers.reader.readEvent(events, self, eventTag);
% Nothing... keep checking
if isempty(eventName)
nextState = [];
return
end
% ---- Good choice!
%
nextState='blank';
% Override completedTrial flag
self.completedTrial = true;