generated from cogtoolslab/project_template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
setup.js
539 lines (500 loc) · 18.2 KB
/
setup.js
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
var DEBUG_MODE = true; //print debug and piloting information to the console
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var prolificID = urlParams.get("PROLIFIC_PID"); // ID unique to the participant
var studyID = urlParams.get("STUDY_ID"); // ID unique to the study
var sessionID = urlParams.get("SESSION_ID"); // ID unique to the particular submission
var projName = urlParams.get("projName");
var expName = urlParams.get("expName");
var iterName = urlParams.get("iterName");
var inputID = null; // ID unique to the session served
/****************************************************
If you have any other URL Parameters that you need
for your experiment, read them in them here.
ie;
var dominoNumbers = urlParams.get("num_dominos")
*****************************************************/
function logTrialtoDB(data) {
data.dbname = projName;
data.colname = expName;
data.iterationName = iterName;
data.inputid = inputID;
data.projName = projName;
data.expName = expName;
data.sessionID = sessionID;
data.studyID = studyID;
if (DEBUG_MODE) {
console.log(
"Logging data to db: " +
projName +
"\tcol: " +
expName +
"\titeration: " +
iterName
);
console.log("Data: " + data);
}
socket.emit("currentData", data);
}
function launchExperiment() {
var stimInfo = {
proj_name: projName,
exp_name: expName,
iter_name: iterName,
};
if (DEBUG_MODE) {
console.log(
"Project Name: ",
projName,
"Experiment Name: ",
expName,
"iteration Name: ",
iterName,
"stimInfo",
stimInfo
);
}
socket.emit("getStims", stimInfo);
socket.on("stims", (experimentConfig) => {
if (DEBUG_MODE) {
console.log("Received from database:",experimentConfig);
}
buildAndRunExperiment(experimentConfig);
});
}
function buildAndRunExperiment(experimentConfig) {
/*
This function should be modified to fit your specific experiment needs.
The code you see here is an example for one kind of experiment.
The function receives stimuli / experiment configs from your database,
and should build the appropriate jsPsych timeline. For each trial, make
sure to specify an onFinish function that saves the trial response.
--> see `stim_on_finish` function for an example.
*/
if (DEBUG_MODE) {
console.log("building experiment with config: ", experimentConfig);
}
var gameid = experimentConfig.gameid;
inputID = experimentConfig.inputid;
//randomize button order on a subject basis
var get_random_choices = () => {
if (Math.random() > 0.5) {
return ["NO", "YES"];
} else {
return ["YES", "NO"];
}
};
var choices = get_random_choices(); //randomize button order
// Define trial object with boilerplate
function Experiment() {
(this.type = "video-overlay-button-response"), (this.dbname = projName);
this.colname = expName;
this.iterationName = iterName;
this.inputid = inputID;
this.response_allowed_while_playing = false;
// this.phase = 'experiment';
this.condition = "prediction";
this.prompt = "Is the red object going to hit the yellow area?";
this.choices = choices;
}
function FamiliarizationExperiment() {
// extends Experiment to provide basis for familizarization trials
Experiment.call(this);
this.condition = "familiarization_prediction";
}
var last_correct = undefined; //was the last trial correct? Needed for feedback in familiarization
var correct = 0;
var total = 0;
var last_yes = undefined;
// These are flags to control which trial types are included in the experiment
const includeIntro = true;
const includeSurvey = true;
const includeMentalRotation = false;
const includeGoodbye = true;
const includeFamiliarizationTrials = true;
var gameid = experimentConfig.gameid;
var stims = experimentConfig.stims;
var familiarization_stims = experimentConfig.familiarization_stims;
if (DEBUG_MODE) {
console.log("gameid", gameid);
console.log("stims", stims);
console.log("familiarization_stims", familiarization_stims);
}
// at end of each trial save data locally and send data to server
var main_on_finish = function (data) {
// let's add gameID and relevant database fields
data.gameID = gameid;
data.inputID = inputID;
logTrialtoDB(data);
};
// at end of each trial save data locally and send data to server
var stim_on_finish = function (data) {
/* You need to add these database fields to correctly log trials */
data.gameID = gameid;
data.stims_not_preloaded = /^((?!chrome|android).)*safari/i.test(
navigator.userAgent
); //HACK turned off preloading stimuli for Safari in jspsych-video-button-response.js
jsPsych.data.addProperties(jsPsych.currentTrial()); //let's make sure to send ALL the data //TODO: maybe selectively send data to db
// lets also add correctness info to data
data.correct = data.target_hit_zone_label == (data.response == "YES");
if (data.correct) {
correct += 1;
}
total += 1;
if (DEBUG_MODE) {
if (data.correct) {
console.log(
"Correct, got ",
_.round((correct / total) * 100, 2),
"% correct"
);
} else {
console.log(
"Wrong, got ",
_.round((correct / total) * 100, 2),
"% correct"
);
}
}
last_correct = data.correct; //store the last correct for familiarization trials
last_yes = data.response == "YES"; //store if the last reponse is yes
logTrialtoDB(data);
};
var stim_log = function (data) {
if (DEBUG_MODE) {
console.log(
"This is " + data.stim_ID + " with label " + data.target_hit_zone_label
);
}
};
// Now construct trials list
var experimentInstance = new Experiment();
var familiarizationExperimentInstance = new FamiliarizationExperiment();
var fixation = {
// per https://stackoverflow.com/questions/35826810/fixation-cross-in-jspsych
type: "html-keyboard-response",
stimulus: '<div style="font-size:60px">+</div>',
choices: jsPsych.NO_KEYS,
// trial_duration: 1000, // in ms
on_start: (trial) => {
trial.trial_duration = Math.random() * 1000 + 500; //random duration in milliseconds
},
post_trial_gap: 0,
on_finish: () => {}, // do nothing on trial end
};
// set up familiarization trials
var familiarization_trials_pre = _.map(
familiarization_stims,
function (n, i) {
return _.extend({}, familiarizationExperimentInstance, n, {
trialNum: i,
stimulus: [n.mp4s_url],
overlay: [n.maps_url],
overlay_time: 2,
blink_time: 500,
stop: 1.5, //STIM DURATION stop the video after X seconds
width: 500,
height: 500,
post_trial_gap: 0,
on_start: stim_log,
on_finish: stim_on_finish,
prolificID: prolificID,
studyID: studyID,
sessionID: sessionID,
gameID: gameid,
target_hit_zone_label: n.does_target_contact_zone,
stim_ID: n.stimulus_name,
// save_trial_parameters: {} //selectively save parameters
});
}
);
var familiarization_trials_post = _.map(
familiarization_stims,
function (n, i) {
return _.extend({}, familiarizationExperimentInstance, n, {
trialNum: i,
stimulus: [n.mp4s_url], //rename stim_url for the video plugin
// stop: 1.5, //STIM DURATION stop the video after X seconds
response_allowed_while_playing: false,
width: 500,
height: 500,
post_trial_gap: 0,
on_finish: () => {}, //do nothing after trial shown
prolificID: prolificID,
studyID: studyID,
sessionID: sessionID,
gameID: gameid,
target_hit_zone_label: n.does_target_contact_zone,
stim_ID: n.stimulus_name,
choices: ["Next"],
prompt: () => {
if (last_correct & last_yes) {
return "✅ Nice, you got that right. The red object did indeed hit the yellow area. Above, you see the full video.";
} else if (last_correct & !last_yes) {
return "✅ Nice, you got that right. The red object indeed did not hit the yellow area. Above, you see the full video.";
} else if (!last_correct & last_yes) {
return "❌ Sorry, you got that one wrong. The red object did not hit the yellow area. Above, you see the full video.";
} else {
return "❌ Sorry, you got that one wrong. The red object did hit the yellow area. Above, you see the full video.";
}
},
// save_trial_parameters: {} //selectively save parameters
});
}
);
var end_familiarization = {
type: "instructions",
pages: ["You're now ready to start the full experiment."],
show_clickable_nav: true,
allow_backward: false,
delay: false,
on_finish: () => {
correct = 0;
total = 0; //reset the counters for the console feedback
},
};
var familiarization_trials = _.flatten(
_.zip(familiarization_trials_pre, familiarization_trials_post)
);
familiarization_trials.push(end_familiarization);
// Variables shared for all trials. Set up the important stuff here.
var trials = _.map(stims, function (n, i) {
return _.extend({}, experimentInstance, n, {
trialNum: i,
stimulus: [n.mp4s_url],
overlay: [n.maps_url],
overlay_time: 2,
blink_time: 500,
stimulus_metadata: n, //to dump all the metadata back to mongodb
stop: 1.5, //STIM DURATION stop the video after X seconds
width: 500,
height: 500,
post_trial_gap: 0,
on_start: stim_log,
on_finish: stim_on_finish,
prolificID: prolificID,
studyID: studyID,
sessionID: sessionID,
gameID: gameid,
target_hit_zone_label: n.does_target_contact_zone,
stim_ID: n.stimulus_name,
// save_trial_parameters: {} //selectively save parameters
});
});
//add fixation crosses
trials = _.flatten(_.zip(_.fill(Array(trials.length), fixation), trials));
if (DEBUG_MODE) {
console.log("experiment trials", trials);
console.log("familiarization trials", familiarization_trials);
}
var instructionsHTML = {
str1: [
"<p> On each trial, you will see a brief video of a few objects interacting.</p><p>Your task will be to predict whether \
a certain event will happen after the video ends.</p><p>Before the video starts, you'll see one object flash in red and an area in yellow. Remember these objects! You'll be asked if the object marked in red will touch the area marked in yellow.\
</p><div><img src=\"img/blinkingdemo.gif\"></div><p>You will do a few “warmup” trials first, followed by 150 real trials. For the warmup trials, you will find out whether your response was correct or not, but you won't on the real trials.",
],
};
// add consent pages
consentHTML = {
str2: [
"<u><p id='legal'>Consent to Participate</p></u>",
"<p id='legal'>By completing this study, you are participating in a \
study being performed by cognitive scientists in the UC San Diego \
Department of Psychology. The purpose of this research is to find out\
how people understand visual information. \
You must be at least 18 years old to participate. There are neither\
specific benefits nor anticipated risks associated with participation\
in this study. Your participation in this study is completely voluntary\
and you can withdraw at any time by simply exiting the study. You may \
decline to answer any or all of the following questions. Choosing not \
to participate or withdrawing will result in no penalty. Your anonymity \
is assured; the researchers who have requested your participation will \
not receive any personal information about you, and any information you \
provide will not be shared in association with any personally identifying \
information.</p>",
].join(" "),
str3: [
"<u><p id='legal'>Consent to Participate</p></u>",
"<p> If you have questions about this research, please contact the \
researchers by sending an email to \
<b><a href='mailto://[email protected]'>[email protected]</a></b>. \
These researchers will do their best to communicate with you in a timely, \
professional, and courteous manner. If you have questions regarding your \
rights as a research subject, or if problems arise which you do not feel \
you can discuss with the researchers, please contact the UC San Diego \
Institutional Review Board.</p><p>Click 'Next' to continue \
participating in this study.</p>",
].join(" "),
str4: "<p> We expect this study to take approximately 10 to 15 minutes to complete, \
including the time it takes to read these instructions.</p>",
str5: "<p>If you encounter a problem or error, send us an email \
([email protected]) and we will make sure you're compensated \
for your time! Please pay attention and do your best! Thank you!</p><p> Note: \
We recommend using Firefox or Chrome. We have not tested this study in other browsers.</p>",
};
//combine instructions and consent
var introMsg = {
type: "instructions",
pages: [
// consentHTML.str1,
consentHTML.str2,
consentHTML.str3,
instructionsHTML.str1,
// instructionsHTML.str2,
// instructionsHTML.str3,
consentHTML.str4,
consentHTML.str5,
// instructionsHTML.str5,
],
show_clickable_nav: true,
allow_backward: true,
delay: false,
delayTime: 2000,
};
// exit survey trials
var exitSurveyAge = {
type: "survey-text",
on_finish: main_on_finish,
questions: [
{
prompt: "How old are you?",
rows: 1,
columns: 3,
name: "participantAge",
placeholder: "Age",
},
],
};
var exitSurveyChoice = {
type: "survey-multi-choice",
on_finish: main_on_finish,
preamble: "<strong><u>Survey</u></strong>",
questions: [
{
prompt: "What is your sex?",
name: "participantSex",
horizontal: true,
options: ["Male", "Female", "Neither/Other/Do Not Wish To Say"],
required: true,
},
// {
// prompt: "How old are you?",
// name: "participantAge",
// horizontal: false,
// options: [
// "Under 12 years old",
// "12-17 years old",
// "18-24 years old",
// "25-34 years old",
// "35-44 years old",
// "45-54 years old",
// "55-64 years old",
// "65-74 years old",
// "75 years or older",
// ],
// required: true
// },
{
prompt: "What is the highest level of education you have completed?",
name: "participantEducation",
horizontal: false,
options: [
"High school",
"Some high school",
"Bachelor’s degree",
"Master’s degree",
"Ph.D. or higher",
"Associates degree",
"Trade school",
"Prefer not to say",
"Other",
],
required: true,
},
{
prompt:
"Did you encounter any technical difficulties while completing this study? \
This could include: images were glitchy (e.g., did not load), ability to click \
was glitchy, or sections of the study did \
not load properly.",
name: "technicalDifficultiesBinary",
horizontal: true,
options: ["Yes", "No"],
required: true,
},
],
};
var surveyTextInfo = _.omit(_.extend({}, new Experiment()), [
"type",
"dev_mode",
]);
var exitSurveyText = _.extend({}, surveyTextInfo, {
type: "survey-text",
questions: [
{
prompt: "What strategies did you use to predict what will happen?",
rows: 5,
columns: 40,
},
// { prompt: "What criteria mattered most when evaluating " + experimentInstance.condition + "?", rows: 5, columns: 40 },
// { prompt: "What criteria did not matter when evaluating " + experimentInstance.condition + "?", rows: 5, columns: 40 },
// { prompt: "Any final thoughts?", rows: 5, columns: 40 }
],
on_finish: main_on_finish,
});
// add goodbye page
var goodbye = {
type: "instructions",
pages: [
"Congrats! You are all done. Thanks for participating in our game. Click 'Next' to submit this study.",
],
on_start: (trial) => {
//write the score to HTML
trial.pages = [
"Congrats! You are all done. Thanks for participating in our game. You've gotten " +
_.round((correct / total) * 100, 0) +
"% correct🎉! Click 'Next' to submit this study.",
];
},
show_clickable_nav: true,
allow_backward: false,
delay: false,
on_finish: function () {
// $(".confetti").remove();
document.body.innerHTML =
"<p> Please wait. You will be redirected back to Prolific in a few moments.</p>";
setTimeout(function () {
location.href =
"https://app.prolific.co/submissions/complete?cc=50AEDCF9";
}, 500);
// sendData();
},
//change the link below to your prolific-provided URL
// window.open("https://app.prolific.co/submissions/complete?cc=7A827F20","_self");
};
// mental rotation task
var mentalRotationChoice = {
type: "image-button-response",
image_url: "img/shepard_metzler_rotation_task_1.png", //taken from http://dx.doi.org/10.1109/CTS.2009.5067476
choices: ["A", "B", "C"],
upper_bound: "",
lower_bound: "",
prompt:
"Which of the three objects on the right is a rotated version of the object on the left?",
on_finish: main_on_finish,
};
// add all experiment elements to trials array
if (includeFamiliarizationTrials)
trials = _.concat(familiarization_trials, trials);
if (includeIntro) trials.unshift(introMsg);
if (includeSurvey) trials.push(exitSurveyText);
if (includeSurvey) trials.push(exitSurveyChoice);
if (includeSurvey) trials.push(exitSurveyAge);
if (includeMentalRotation) trials.push(mentalRotationChoice);
if (includeGoodbye) trials.push(goodbye);
jsPsych.init({
timeline: trials,
default_iti: 1000,
show_progress_bar: true,
});
}