-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpTrialLoop.js
More file actions
1770 lines (1438 loc) · 63.8 KB
/
expTrialLoop.js
File metadata and controls
1770 lines (1438 loc) · 63.8 KB
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
// � by Caspar Goeke and Holger Finger
/**
* This class stores all informations of a task. Most importantly, it has one or more sequences of frames and pages.
* It stores the factorGroups and per factorGroup one subSequence.
*
* @param {ExpData} expData - The global ExpData, where all instances can be retrieved by id.
* @constructor
*/
var ExpTrialLoop = function (expData) {
this.expData = expData;
this.parent = null;
// serialized:
this.editorX = ko.observable(0);
this.editorY = ko.observable(0);
this.editorWidth = ko.observable(120);
this.editorHeight = ko.observable(60);
this.id = ko.observable(guid());
this.displayInitialCountdown = ko.observable(true);
this.syncTaskStart = ko.observable(true);
this.useEyetrackingV2 = ko.observable(false);
this.useDriftCorrection = ko.observable(true);
this.eyetrackingV2numRecalibPoints = ko.observable(3).extend({ numeric: 0 });
this.eyetrackingV2numDriftPoints = ko.observable(6).extend({ numeric: 0 });
this.zoomMode = ko.observable('fullscreen'); // fullscreen or visualDegree or pixel or millimeter
this.visualDegreeToUnit = ko.observable(25);
//properties
this.name = ko.observable("New Task");
this.type = "ExpTrialLoop";
this.subSequence = ko.observable(null);
this.subSequencePerFactorGroup = ko.observableArray([]);
this.factorGroups = ko.observableArray([]);
this.eventVariables = ko.observableArray([]); // still needed?
//properties
this.repsPerTrialType = ko.observable(1).extend({ numeric: 0 });
this.isActive = ko.observable(false);
// randomization settings
this.randomizationOverview = ko.observable("standard");
this.blockFixedFactorConditions = ko.observable(false);
this.orderOfConditions = ko.observable("fixed");
this.trialRandomization = ko.observable("permute");
this.fixedTrialOrder = ko.observable('');
this.uploadedTrialOrder = ko.observableArray([]);
this.subjectCounterType = ko.observable("global"); // global or group
this.randomizationConstraint = ko.observable("none");
this.minIntervalBetweenRep = ko.observable(0).extend({ numeric: 0 });
this.maxIntervalSameCondition = ko.observable(3).extend({ numeric: 3 });
this.randomTrialSelection = ko.observable("untilMinimum");
this.determineNrTrials = ko.observable("minimumWithoutZero");
this.trialSelectionBalance = ko.observable("balancedPerCondGroup");
this.fixedNumTrialsPerCondGroup = ko.observable(1);
this.allTrialsToAllSubjects = ko.observable(true);
this.numberTrialsToShow = ko.observable(null);
this.balanceAmountOfConditions = ko.observable(true);
this.trialLoopActivated = ko.observable(true);
this.customStartTrial = ko.observable(1);
// external devices
this.webcamEnabled = ko.observable(false);
this.isSeparator = ko.observable(false);
// not serialized
this.isInitialized = ko.observable(false);
this.shape = "square";
this.label = "Experiment";
this.portTypes = ["executeIn", "executeOut"];
this.selectionSpec = ko.observable(null);
var self = this;
this.totalNrTrials = ko.computed(function () {
var l = 0;
for (var i = 0; i < self.factorGroups().length; i++) {
var facGroup = self.factorGroups()[i];
for (var k = 0; k < facGroup.conditionsLinear().length; k++) {
l = l + facGroup.conditionsLinear()[k].trials().length;
}
}
return l
}, this);
this.trialsDefinedForNSubjects = ko.computed(function () {
var n = self.uploadedTrialOrder().length;
var out = [];
for (var i = 1; i <= n; i++) {
out.push(i);
}
return out;
}, this);
this.vars = ko.computed(function () {
var array = [];
var eventList = this.eventVariables();
for (var i = 0; i < eventList.length; i++) {
array.push(eventList[i]);
}
return array;
}, this);
this.shortName = ko.computed(function () {
if (self.name()) {
return (self.name().length > 40 ? self.name().substring(0, 39) + '...' : self.name());
}
else return '';
});
this.zoomMode.subscribe(function (newVal) {
if (newVal == "visualDegree") {
if (self.expData.varPixelDensityPerMM()) {
self.expData.varPixelDensityPerMM().includeInGlobalVarList(true);
self.expData.varPixelDensityPerMM().isRecorded(true);
self.expData.notifyChanged();
}
}
if (newVal != "fullscreen") {
if (self.expData.varDisplayWidthX()) {
self.expData.varDisplayWidthX().includeInGlobalVarList(true);
self.expData.varDisplayWidthX().isRecorded(true);
self.expData.varDisplayWidthY().includeInGlobalVarList(true);
self.expData.varDisplayWidthY().isRecorded(true);
self.expData.notifyChanged();
}
if (self.expData.varScreenTotalWidthX()) {
self.expData.varScreenTotalWidthX().includeInGlobalVarList(true);
self.expData.varScreenTotalWidthX().isRecorded(true);
self.expData.varScreenTotalWidthY().includeInGlobalVarList(true);
self.expData.varScreenTotalWidthY().isRecorded(true);
self.expData.notifyChanged();
}
}
});
this.useEyetrackingV2.subscribe(function (newVal) {
if (newVal) {
self.expData.studySettings.isWebcamEnabled(true);
self.expData.studySettings.minRes(true);
self.expData.studySettings.minWidth(600);
self.expData.studySettings.minWidth(600);
}
});
};
/**
* Is called to initialize a newly created exp trial loop (instead of initialization via loadJS)
*/
ExpTrialLoop.prototype.initNewInstance = function (pageOrFrame, withFactor) {
this.addFactorGroup(pageOrFrame, withFactor);
};
ExpTrialLoop.prototype.addNewFrame = function () {
var frame = new FrameData(this.expData);
this.subSequence().addNewSubElement(frame);
frame.parent = this.subSequence();
};
ExpTrialLoop.prototype.getTextRefs = function (textArrOuter, label) {
jQuery.each(this.subSequence().elements(), function (index, elem) {
elem.getTextRefs(textArrOuter, label + '.frame' + (index + 1));
});
return textArrOuter;
};
ExpTrialLoop.prototype.addFactorGroup = function (pageOrFrame, withFactor) {
var factorGroup = new FactorGroup(this.expData, this);
var nr_in_task = this.factorGroups().length + 1;
var nr_in_exp = this.expData.availableTasks().indexOf(this);
if (nr_in_exp <= 0) {
nr_in_exp = this.expData.availableTasks().length + 1;
}
factorGroup.name("trial_group_" + nr_in_task);
// add a new subSequence for the new group (if there are not already enough subSequences):
var subsequence = new Sequence(this.expData);
subsequence.parent = this;
subsequence.setFactorGroup(factorGroup);
// add new frame or page
if (pageOrFrame == 'frame') {
var elem = new FrameData(this.expData);
elem.name('frame_1');
// add instructions content to first frame:
if (uc.userdata.accountSettingsData.initTasksWithDemo()) {
var newDemoElem = new DisplayTextElement(this.expData);
var newDemoWrap = new FrameElement(this.expData);
newDemoWrap.name("Instructions");
newDemoWrap.addContent(newDemoElem);
newDemoWrap.parent = elem;
newDemoWrap.editorX(10);
newDemoWrap.editorY(10);
newDemoWrap.editorWidth(780);
newDemoWrap.editorHeight(430);
elem.addNewSubElement(newDemoWrap);
newDemoElem.init();
newDemoElem.text().rawText("<p><span style=\"font-size:24px;\"><span style=\"font-family:latobold;\">Explanation of the Trial-System</span></span><br>If this task contains several trials, please use the trial system located in the left panel of the editor:<br><br><span style=\"font-size:16px;\"><span style=\"font-family:latobold;\">← Factor Tree (center of the left panel):</span></span><br><span style=\"font-size:12px;\">Here you can specify the variation types for different trials in this task. Different <span style=\"font-family:latobold;\">Trial-Groups</span> allow you to edit different frame sequences that are completely independent from each other. But keep in mind, that different Trial-Groups have the drawback that later modifications cannot be made simultanously to trials that are in different Trial-Groups. Within a Trial-Group you can specify multiple <span style=\"font-family:latobold;\">Factors</span> each with different <span style=\"font-family:latobold;\">Levels</span> that allow you define specific small variations between trials. If your task contains many trials with small variations between them, it is advisable to use combinations of Factors and Levels to define these small variations. If you select a Trial-Group, all modifications in the editor will effect the <span style=\"font-family:latobold;\">Default-Trial</span> of this Trial-Group, meaning that all changes will be made to all trial variations within this Trial-Group and previously made variations will be overwritten. If you select a Level, all modifications in the editor will effect only all trials with this Level.</span><br><br><span style=\"font-family:latobold;\"><span style=\"font-size:16px;\">← Trials & Conditions (bottom of the left panel):</span></span><br><span style=\"font-size:12px;\"><span style=\"font-family:lato;\">Here you can see all defined Trials and Conditions based on the Factors and Levels that were specified in the \"Factor Tree\". Per Trial-Group you can see all </span><span style=\"font-family:latobold;\">Conditions</span><span style=\"font-family:lato;\">, which are generated by all combinations of Factors and Levels in that Trial-Group. You can select specific Conditions here to modify small variations from the Default-Trial for this Condition. Furthermore, you can specify the number of trials (</span><span style=\"font-family:latobold;\"># Trials</span></span><span style=\"font-family:lato;\"><span style=\"font-size:12px;\">) that should be defined per Condition.</span><br><br>A more detailed explanation of the Trial-System can be found in the documentation under Trial-System.</span><br></p>");
}
}
else if (pageOrFrame == 'page') {
var elem = new PageData(this.expData);
elem.name('page_1');
}
subsequence.addNewSubElement(elem);
subsequence.currSelectedElement(elem);
// new factor
if (withFactor) {
var newFactor = new Factor(this.expData, factorGroup);
newFactor.init("factor1_tg" + nr_in_task + "_task" + nr_in_exp);
newFactor.updateLevels();
factorGroup.addFactor(newFactor);
subsequence.addVariableToWorkspace(newFactor.globalVar());
}
this.factorGroups.push(factorGroup);
this.subSequencePerFactorGroup.push(subsequence);
this.subSequence(subsequence);
this.reAddEntities(this.expData.entities);
this.expData.notifyChanged();
};
ExpTrialLoop.prototype.addSequenceToDataModel = function (subsequence) {
this.factorGroups.push(subsequence.factorGroup);
this.subSequencePerFactorGroup.push(subsequence);
this.subSequence(subsequence);
this.reAddEntities(this.expData.entities);
this.expData.notifyChanged();
window.location.reload(true)
};
ExpTrialLoop.prototype.removeFactorGroup = function (facGroupIdx) {
this.factorGroups.splice(facGroupIdx, 1);
this.subSequencePerFactorGroup.splice(facGroupIdx, 1);
this.subSequence(this.subSequencePerFactorGroup()[0]);
this.expData.notifyChanged();
};
ExpTrialLoop.prototype.renameGroup = function (facGroupIdx, flag) {
if (flag == "true") {
this.factorGroups()[facGroupIdx].editName(true);
}
else if (flag == "false") {
this.factorGroups()[facGroupIdx].editName(false);
}
};
ExpTrialLoop.prototype.getCondGroups = function () {
var factorGroups = this.factorGroups();
var fixedFactorConds = [];
var totalNrTrialsMin = 0;
var totalNrTrialsMax = 0;
var totalNrTrialsMinWithoutZero = 0;
for (var i = 0; i < factorGroups.length; i++) {
var obj = this.getCondGroupsOneTrialGroup(factorGroups[i]);
for (var k = 0; k < obj.fixedFactorConds.length; k++) {
fixedFactorConds.push(obj.fixedFactorConds[k]);
}
totalNrTrialsMin += obj.totalNrTrialsMin;
totalNrTrialsMax += obj.totalNrTrialsMax;
totalNrTrialsMinWithoutZero += obj.totalNrTrialsMinWithoutZero;
}
var obj2 = {
fixedFactorConds: fixedFactorConds,
totalNrTrialsMax: totalNrTrialsMax,
totalNrTrialsMin: totalNrTrialsMin,
totalNrTrialsMinWithoutZero: totalNrTrialsMinWithoutZero
};
return obj2;
};
ExpTrialLoop.prototype.getCondGroupsOneTrialGroup = function (factorGroup) {
var conditions = factorGroup.conditionsLinear();
var arrOfOneFacGroup = factorGroup.getFixedFactorConditions();
var fixedFactorConds = [];
var count = 0;
var totalNrTrialsMin = 0;
var totalNrTrialsMax = 0;
var totalNrTrialsMinWithoutZero = 0;
for (var k = 0; k < arrOfOneFacGroup.length; k++) {
count++;
var condArray = arrOfOneFacGroup[k];
var totalVariations = 0;
var varArray = [];
for (var j = 0; j < condArray.length; j++) {
totalVariations += conditions[condArray[j]].trials().length;
varArray.push(conditions[condArray[j]].trials().length);
}
function withoutZero(value) {
return value > 0;
}
var arrWithoutZero = varArray.filter(withoutZero);
if (arrWithoutZero.length == 0) {
var minVarWithoutZero = 0;
}
else {
var minVarWithoutZero = Math.min.apply(null, arrWithoutZero);
}
var minVar = Math.min.apply(null, varArray);
var maxVar = Math.max.apply(null, varArray);
totalNrTrialsMin += minVar;
totalNrTrialsMax += maxVar;
totalNrTrialsMinWithoutZero += minVarWithoutZero;
var obj = {
nrOfCondition: count,
nameOfFactorGroup: factorGroup.name(),
nrOfVariations: totalVariations,
minNrOfTrials: minVar,
maxNrOfTrials: maxVar,
minNrOfTrialsWithoutZero: minVarWithoutZero,
nrOfSubConditions: condArray.length
};
fixedFactorConds.push(obj);
}
var obj2 = {
fixedFactorConds: fixedFactorConds,
totalNrTrialsMax: totalNrTrialsMax,
totalNrTrialsMin: totalNrTrialsMin,
totalNrTrialsMinWithoutZero: totalNrTrialsMinWithoutZero
};
return obj2;
};
ExpTrialLoop.prototype.getTrialRandomizationOneRun = function (subjCounterGlobal, subjCounterPerGroup) {
var allTrials = [];
for (var facGroupIdx = 0; facGroupIdx < this.factorGroups().length; facGroupIdx++) {
var factorGroup = this.factorGroups()[facGroupIdx];
var outArr = this.getFactorLevels(factorGroup);
var factorLevels = outArr[0];
var factorIndicies = outArr[1];
var conditions = this.getConditionFromFactorLevels(factorIndicies, factorLevels, facGroupIdx);
var trials = this.drawTrialsFromConditions(conditions, facGroupIdx);
allTrials.push(trials);
}
var trialsRandomized = this.getRandomizedTrials(allTrials, subjCounterGlobal, subjCounterPerGroup);
return trialsRandomized;
};
ExpTrialLoop.prototype.doTrialRandomization = function (subjCounterGlobal, subjCounterPerGroup) {
if (this.allTrialsToAllSubjects()) {
return this.getTrialRandomizationOneRun(subjCounterGlobal, subjCounterPerGroup);
}
else {
var condGroups = this.getCondGroups();
var numberTrialsToShow = this.numberTrialsToShow();
if (condGroups.totalNrTrialsMin < numberTrialsToShow && condGroups.totalNrTrialsMin > 0) {
var trialsRandomizedAll = [];
// do new random draws until we have the number trials requested:
while (trialsRandomizedAll.length < parseInt(numberTrialsToShow)) {
$.merge(trialsRandomizedAll, this.getTrialRandomizationOneRun(subjCounterGlobal, subjCounterPerGroup));
}
// reduce number to amount requested:
if (trialsRandomizedAll.length > numberTrialsToShow) {
trialsRandomizedAll = trialsRandomizedAll.slice(0, numberTrialsToShow);
}
return trialsRandomizedAll;
}
else {
var trialsRandomized = this.getTrialRandomizationOneRun(subjCounterGlobal, subjCounterPerGroup);
// TODO: filter trialsRandomized based on defined proportions between conditions
if (trialsRandomized.length > numberTrialsToShow) {
trialsRandomized = trialsRandomized.slice(0, numberTrialsToShow);
}
return trialsRandomized;
}
}
};
ExpTrialLoop.prototype.drawTrialsFromConditions = function (conditions, facGroupIdx) {
// sort condition according to amount of trials, so that condition with less trials are chosen first, which allows for balancing
var sortArr = [];
for (var condIdx = 0; condIdx < conditions.length; condIdx++) {
sortArr.push(conditions[condIdx].trials().length);
}
var indices = new Array(sortArr.length);
for (var i = 0; i < sortArr.length; ++i) {
indices[i] = i;
}
indices.sort(function (a, b) { return sortArr[a] < sortArr[b] ? -1 : sortArr[a] > sortArr[b] ? 1 : 0; });
var newCondArr = [];
for (var condIdx = 0; condIdx < sortArr.length; condIdx++) {
newCondArr.push(conditions[indices[condIdx]]);
}
//////////////////////////////////////////////////////////////
var ffConds = this.factorGroups()[facGroupIdx].getFixedFactorConditions();
var excludedTrialsPerCondGroup = [];
for (var condGroup = 0; condGroup < ffConds.length; condGroup++) {
excludedTrialsPerCondGroup.push([]);
}
var Trials = [];
for (var trialIndex = 0; trialIndex < newCondArr.length; trialIndex++) {
var condition = newCondArr[trialIndex];
var condGroup = this.getCondGroup(condition.conditionIdx() - 1, ffConds);
var obj = this.getCondGroupsOneTrialGroup(condition.factorGroup);
if (this.randomTrialSelection() == "allDefined") {
var nrExistingTrials = condition.trials().length;
}
else if (this.randomTrialSelection() == "untilMinimum") {
if (this.determineNrTrials() == "minimumWithZero") {
var nrExistingTrials = obj.fixedFactorConds[condGroup].minNrOfTrials;
}
else if (this.determineNrTrials() == "minimumWithoutZero") {
var nrExistingTrials = obj.fixedFactorConds[condGroup].minNrOfTrialsWithoutZero;
}
else if (this.determineNrTrials() == "setFixedNum") {
var nrExistingTrials = this.fixedNumTrialsPerCondGroup();
if (nrExistingTrials > obj.fixedFactorConds[condGroup].minNrOfTrials) {
nrExistingTrials = obj.fixedFactorConds[condGroup].minNrOfTrials;
}
}
}
var options = [];
for (var i = 0; i < nrExistingTrials; i++) {
if (this.trialSelectionBalance() == "balancedPerCondGroup") {
if (excludedTrialsPerCondGroup[condGroup].indexOf(i) < 0) {
options.push(i);
}
}
else if (this.trialSelectionBalance() == "unbalancedPerCondGroup") {
options.push(i);
}
}
if (options.length < 1) {
console.log("WARNING,uneven amount of trials within condition group is forcing to choose trials unbalanced...");
for (var i = 0; i < condition.trials().length; i++) {
options.push(i);
}
}
var randValue = Math.floor(Math.random() * options.length);
var trialRandIdx = options[randValue];
excludedTrialsPerCondGroup[condGroup].push(trialRandIdx);
var chosenTrial = condition.trials()[trialRandIdx];
Trials.push(chosenTrial);
}
// sanity check
var trialRepIdx = [];
for (var trialIndex = 0; trialIndex < Trials.length; trialIndex++) {
if (Trials[trialIndex]) {
trialRepIdx.push(Trials[trialIndex].uniqueId());
}
else {
throw "trial is defined"
}
}
var checkSortArray = trialRepIdx.slice().sort();
var results = [];
for (var i = 0; i < checkSortArray.length - 1; i++) {
if (checkSortArray[i + 1] == checkSortArray[i]) {
console.log("Warning, double trial entry");
}
}
return Trials
};
ExpTrialLoop.prototype.getCondGroup = function (conditionIdx, ffConds) {
var ffGroup = null;
for (var condGroup = 0; condGroup < ffConds.length; condGroup++) {
var group = ffConds[condGroup];
if (group.indexOf(conditionIdx) >= 0) {
ffGroup = condGroup;
break
}
}
return ffGroup
};
ExpTrialLoop.prototype.getFactorLevelArray = function (factorGroup) {
var factors = factorGroup.factors();
var levelArray = [];
var index = 0;
var indicies = [];
for (var facIdx = 0; facIdx < factors.length; facIdx++) {
var factor = factors[facIdx];
if (factor.factorType() == 'random' && factor.randomizationType() == 'balancedBetweenSubj') {
levelArray.push([]);
indicies.push(facIdx);
for (var lvlIdx = 0; lvlIdx < factor.globalVar().levels().length; lvlIdx++) {
levelArray[index].push(factor.globalVar().levels()[lvlIdx].name());
}
index++
}
}
return [levelArray, indicies];
};
ExpTrialLoop.prototype.getAllFactorCrossing = function (arr) {
if (arr.length == 0) {
return [];
}
else if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = this.getAllFactorCrossing(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + ',' + allCasesOfRest[i]);
}
}
return result;
}
};
ExpTrialLoop.prototype.getFactorLevels = function (factorGroup) {
var arr = factorGroup.getFixedFactorLevels();
var allConds = arr[0];
var factorNames = arr[1];
var ffConds = factorGroup.getFixedFactorConditions();
var factors = factorGroup.factors();
var factorLevels = [];
var obj = this.getCondGroupsOneTrialGroup(factorGroup);
var fixedFactorConds = obj.fixedFactorConds;
var globalVarNames = [];
for (var facIdx = 0; facIdx < factors.length; facIdx++) {
globalVarNames.push(factors[facIdx].globalVar().name());
}
for (var i = 0; i < ffConds.length; i++) {
if (this.determineNrTrials() == "minimumWithZero") {
var NrTrialCount = fixedFactorConds[i].minNrOfTrials;
}
else if (this.determineNrTrials() == "minimumWithoutZero") {
var NrTrialCount = fixedFactorConds[i].minNrOfTrialsWithoutZero;
}
else if (this.determineNrTrials() == "setFixedNum") {
var NrTrialCount = this.fixedNumTrialsPerCondGroup();
if (NrTrialCount > fixedFactorConds[i].minNrOfTrials) {
NrTrialCount = fixedFactorConds[i].minNrOfTrials;
}
}
for (var k = 0; k < NrTrialCount; k++) {
var temp = allConds[ffConds[i][0]].slice(0);
factorLevels.push(temp)
}
}
// randomization for between Subject balanced factors
var out = this.getFactorLevelArray(factorGroup);
var indicies = out[1];
if (indicies.length > 0) {
var table = this.getAllFactorCrossing(out[0]);
if (!(window.uc === undefined)) {
// editor
var subjCount = 0;
if (table.length > 0) {
var levels = table[subjCount].split(",");
}
else {
var levels = [];
}
}
else {
// player
var subjCount = (player.subjCounterPerGroup - 1) % table.length;
var levels = table[subjCount].split(",");
}
for (var i = 0; i < levels.length; i++) {
factorNames.push(indicies[i]);
var fixValue = levels[i];
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
factorLevels[trialIdx].push(fixValue);
}
}
}
// randomization for unbalanced and balanced within task
for (var facIdx = 0; facIdx < factors.length; facIdx++) {
factor = factors[facIdx];
if (factor.factorType() == 'random') {
var factor = factors[facIdx];
var facName = factor.globalVar().name();
var levels = factor.globalVar().levels();
var nrLevels = levels.length;
if (factor.randomizationType() == 'unbalanced') {
factorNames.push(facIdx);
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
var randValue = Math.floor(Math.random() * nrLevels);
factorLevels[trialIdx].push(levels[randValue].name());
}
}
else if (factor.randomizationType() == 'unbalancedBetweenSubj') {
factorNames.push(facIdx);
var randValue = Math.floor(Math.random() * factor.globalVar().levels().length);
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
factorLevels[trialIdx].push(levels[randValue].name());
}
}
else if (factor.randomizationType() == 'balancedTask') {
factorNames.push(facIdx);
var trialSplit = Math.floor(factorLevels.length / nrLevels);
var remainder = factorLevels.length % nrLevels;
var randIdx = [];
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
randIdx.push(trialIdx);
}
var randIndicies = this.reshuffle(randIdx);
var trialIdx = 0;
for (var lvlIndex = 0; lvlIndex < levels.length; lvlIndex++) {
for (var repIndex = 0; repIndex < trialSplit; repIndex++) {
factorLevels[randIndicies[trialIdx]].push(levels[lvlIndex].name());
trialIdx++;
}
}
for (var remain = 0; remain < remainder; remain++) {
factorLevels[randIndicies[trialIdx]].push(levels[remain].name());
trialIdx++;
}
}
}
}
var arr = this.getResolutionOrder(factors, factorNames);
var resolutionOrder = arr[0];
var factorDependencies = arr[1];
for (var facIndx = 0; facIndx < resolutionOrder.length; facIndx++) {
var factor = resolutionOrder[facIndx];
var dependencies = factorDependencies[facIndx];
if (factor.factorType() == 'random' && factor.randomizationType() == 'balancedInFactors') {
if (dependencies.length == 0) { //if their are no dependencies just balance this factor in the task
var facName = factor.globalVar().name();
var levels = factor.globalVar().levels();
var facIdx = factors.indexOf(factor);
var nrLevels = levels.length;
factorNames.push(facIdx);
var trialSplit = Math.floor(factorLevels.length / nrLevels);
var remainder = factorLevels.length % nrLevels;
var randIdx = [];
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
randIdx.push(trialIdx);
}
var randIndicies = this.reshuffle(randIdx);
var trialIdx = 0;
for (var lvlIndex = 0; lvlIndex < levels.length; lvlIndex++) {
for (var repIndex = 0; repIndex < trialSplit; repIndex++) {
factorLevels[randIndicies[trialIdx]].push(levels[lvlIndex].name());
trialIdx++;
}
}
for (var remain = 0; remain < remainder; remain++) {
factorLevels[randIndicies[trialIdx]].push(levels[remain].name());
trialIdx++;
}
}
else {
var levelLegthes = [];
var levelNames = [];
var facNames = [];
for (var depIdx = 0; depIdx < dependencies.length; depIdx++) {
levelLegthes.push(dependencies[depIdx].globalVar().levels().length);
facNames.push(dependencies[depIdx].globalVar().name());
levelNames.push([]);
for (var k = 0; k < dependencies[depIdx].globalVar().levels().length; k++) {
levelNames[depIdx].push(dependencies[depIdx].globalVar().levels()[k].name());
}
}
var count = 1;
var existingNames = [];
for (var i = 0; i < levelLegthes.length; i++) {
count *= levelLegthes[i];
var facName = facNames[i];
var newNames = levelNames[i];
var existingNamesCopy = existingNames.slice();
existingNames = [];
for (var k = 0; k < newNames.length; k++) {
var newName = '/' + facName + '_' + newNames[k] + '/';
if (i > 0) {
for (var j = 0; j < existingNamesCopy.length; j++) {
var newEntry = existingNamesCopy[j] + newName;
existingNames.push(newEntry);
}
}
else {
existingNames.push(newName);
}
}
}
var counterArr = new Array(count);
counterArr.fill(0);
var levels = factor.globalVar().levels();
for (var trial = 0; trial < factorLevels.length; trial++) {
var combinedVal = '';
for (var facneedIdx = 0; facneedIdx < facNames.length; facneedIdx++) {
var idx1 = globalVarNames.indexOf(facNames[facneedIdx]);
var idx2 = factorNames.indexOf(idx1);
var levelVal = factorLevels[trial][idx2];
combinedVal += '/' + facNames[facneedIdx] + '_' + levelVal + '/';
}
var conditionIndex = existingNames.indexOf(combinedVal);
if (conditionIndex >= 0) {
var currentLevelVal = counterArr[conditionIndex];
var value = levels[currentLevelVal].name();
factorLevels[trial].push(value);
counterArr[conditionIndex]++;
if (counterArr[conditionIndex] > levels.length - 1) {
counterArr[conditionIndex] = 0;
}
}
else {
console.log("error: the factor combination could not be found.")
}
}
var facIdx = factors.indexOf(factor);
factorNames.push(facIdx);
}
}
}
return [factorLevels, factorNames]
};
ExpTrialLoop.prototype.getResolutionOrder = function (factors, factorNames) {
// get nested dependencies
var resolvedFactors = [];
for (var facIdx = 0; facIdx < factorNames.length; facIdx++) {
resolvedFactors.push(factors[factorNames[facIdx]].globalVar().id());
}
var unresolvedFactors = [];
for (var facIdx = 0; facIdx < factors.length; facIdx++) {
if (factorNames.indexOf(facIdx) < 0) {
unresolvedFactors.push(factors[facIdx]);
}
}
var factorDependencies = [];
for (var facIdx = 0; facIdx < unresolvedFactors.length; facIdx++) {
factorDependencies.push([]);
var dependencies = unresolvedFactors[facIdx].balancedInFactors();
for (var k = 0; k < dependencies.length; k++) {
if (dependencies[k].hasDependency()) {
var factor = this.expData.entities.byId[dependencies[k].id];
factorDependencies[facIdx].push(factor);
}
}
}
var newFactorDependencies = [];
var resolutionOrder = [];
var outerIdx = 0;
var l = unresolvedFactors.length;
while (unresolvedFactors.length > 0 && outerIdx <= l) {
var found = false;
var idx = 0;
while (!found && idx <= factorDependencies.length) {
var depFactors = factorDependencies[idx];
var unresFactor = unresolvedFactors[idx];
var ok = true;
if (depFactors) {
for (var d = 0; d < depFactors.length; d++) {
var depFactor = depFactors[d];
if (resolvedFactors.indexOf(depFactor.globalVar().id()) == -1) {
ok = false;
}
}
if (ok == true) {
found = true;
resolutionOrder.push(unresFactor);
newFactorDependencies.push(depFactors);
resolvedFactors.push(unresFactor.globalVar().id());
unresolvedFactors.splice(idx, 1);
factorDependencies.splice(idx, 1);
}
else {
idx++;
}
}
else {
idx++;
}
}
outerIdx++;
}
return [resolutionOrder, newFactorDependencies];
};
ExpTrialLoop.prototype.resetFactorDependencies = function () {
for (var i = 0; i < this.factorGroups().length; i++) {
var facs = this.factorGroups()[i].factors();
for (var k = 0; k < facs.length; k++) {
facs[k].resetFactorDependencies();
}
}
}
ExpTrialLoop.prototype.getConditionFromFactorLevels = function (factorIndicies, factorLevels, factorGroup) {
var conditions = this.factorGroups()[factorGroup].conditionsLinear();
var allCondLevels = [];
for (var condIdx = 0; condIdx < conditions.length; condIdx++) {
var facLevels = conditions[condIdx].factorLevels();
var concatStr = '';
for (var facIndex = 0; facIndex < facLevels.length; facIndex++) {
if (facIndex < (facLevels.length - 1) && facLevels[facIndex]) {
concatStr += facLevels[facIndex].name() + ',';
}
else if (facLevels[facIndex]) {
concatStr += facLevels[facIndex].name();
}
}
allCondLevels.push(concatStr);
}
var reIndexed = [];
for (var i = 0; i < factorIndicies.length; i++) {
reIndexed.push(factorIndicies.indexOf(i))
}
var presentedConditions = [];
for (var trialIdx = 0; trialIdx < factorLevels.length; trialIdx++) {
var temp = factorLevels[trialIdx];
var temp2 = [];
for (var i = 0; i < temp.length; i++) {
temp2.push(temp[reIndexed[i]])
}
var searchStr = temp2.join();
var condIdx = allCondLevels.indexOf(searchStr);
if (condIdx >= 0 && condIdx <= conditions.length - 1) {
presentedConditions.push(conditions[allCondLevels.indexOf(searchStr)]);
}
else {
console.log("error condition not found in randomization procedure");
}
}
if (this.determineNrTrials() == "minimumWithoutZero") {
var self = this;
var replacedConditionsPerCondGroup = {};
var newConditions = presentedConditions.map(function (condition) {
if (condition.isDeactivated()) {
var condGroups = condition.factorGroup.getFixedFactorConditions();
var condGroup = condition.getCondGroup(condGroups);
if (!(replacedConditionsPerCondGroup.hasOwnProperty(condGroup))) {
replacedConditionsPerCondGroup[condGroup] = [];
}
var replacedCondition = self.getReplacementCondition(condition, replacedConditionsPerCondGroup[condGroup]);
return replacedCondition;
}
else {
return condition
}
});
return newConditions
}
else {
return presentedConditions
}
};
ExpTrialLoop.prototype.getReplacementCondition = function (condition, condArray) {
var condGroups = condition.factorGroup.getFixedFactorConditions();
var partnerConds = condition.getPartnerConditions(condGroups);
var currentL = condArray.length;