-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequential_task_functions_binary_one_face.js
317 lines (275 loc) · 12.1 KB
/
sequential_task_functions_binary_one_face.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
/**
Functions in Sequential Task
**/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function getRandomElement (list){
return list[Math.floor(Math.random()*list.length)];
}
function loadFacePool(start,end) { //the start and ending index of the images
var pool = [];
for(i = start; i < (end+1); i++){
pool.push( 'img/A' + i + '.jpg'); pool.push( 'img/B' + i + '.jpg');
pool.push( 'img/C' + i + '.jpg'); pool.push( 'img/D' + i + '.jpg');
pool.push( 'img/E' + i + '.jpg'); pool.push( 'img/F' + i + '.jpg');
pool.push( 'img/G' + i + '.jpg'); pool.push( 'img/H' + i + '.jpg');
}
return pool;
}
function createSlideList(start,end){
var list = [];
for (i = start; i < (end+1); i++){
list.push( 'img/ins/sequential_task/Slide ' + i + '.png');}
return list;
}
function getNextSlide () { //use to shift instruction slides
var currentSlide = slideList.shift();
return currentSlide
}
function loadStimulus(end) { //the start and ending index of the images
var list = [];
for(i = 1; i < (end+1); i++){
list.push( 'stimulus/' + i + '.jpg');}
return list;
}
function getStim (){
Face.stim = Face.stims.shift();
return Face.stim; //get last stim of the stim list
}
function check_consent (){
if ($('#consent_checkbox').is(':checked')) {
return true;
}else {
alert("If you wish to participate, you must check the box next to the statement 'I agree to participate in this study.'");
return false;}
}
function checkID (){
var lasttrialdata = jsPsych.data.getLastTrialData().select('responses').values[0];
var textInput = JSON.parse(lasttrialdata).Q0;
var patt = new RegExp("^[a-zA-Z_0-9]{1,}$"); //the first and last character (this doesn't allow punctuations)
if (!patt.test(textInput)){ //test if first/last character in response exist
alert("Please, enter your participant id");
return true; }
else{ return false;}
}
function checkAnswer (){
var inputText = jsPsych.data.getLastTrialData().select('responses').values[0];
var text = JSON.parse(inputText).Q0;
var patt = new RegExp("[A-Za-z0-9 _.,!'/$]"); // this allows punctuations
if (!patt.test(inputText )){ //test if first/last character in response exist
alert("Please describe the image just showed in a few words (this will be uses for validation purposes)");
return true; }
else{ return false;}
}
function checkPhone (){
var choice = jsPsych.data.getLastTrialData().select('button_pressed').values[0];
if(choice == 0){
alert('As mentioned in the study description, this study can only be done a computer and would not work on a smartphone. Your experiment will be terminated and the window will be closed.');
window.close();
return true;
} else { return false;}
}
function getWord (){ //get a word for attention check from the word list
Face.word = Face.wordList.shift();
return Face.word;
}
function binaryFaces(){ //Select face for memory task
var current_face_identity = Face.personX;
var current_face_valence = Face.emotionX;
var low_face = ('img/' + current_face_identity + (current_face_valence + 1) +'.jpg');
var high_face = ('img/' + current_face_identity + (current_face_valence + 50) +'.jpg');
var stimulus_iamages = "<div id='myDiv' style='height: 200px; width: 560px'>" + "<div style='float: left;'><img src=" + "'" + low_face + "'" + "></img>" + "</div>" + "<div style='float: right;'><img src=" + "'" + high_face + "'" + "></img>" + "</div>";
return stimulus_iamages;
}
function checkTyping(){ //test if type correctly
var inputText = jsPsych.data.getLastTrialData().select('responses').values[0];
var text = JSON.parse(inputText).Q0;
if (Face.word !== text){
falseAnswer += 1;
alert("Attention! Please type the word correctly. If the alert shows up for 4 times, the experiment will be automatically terminated.");
Face.wordList.unshift(Face.word);
if (falseAnswer == falseAllowance){ //if participant gets alert this number of times
alert("Hi! You've made too much errors in typing the word suggesting that you are not paying attention to the task. The task will be Terminated");
window.close();
}else{return true;} }
else {falseAnswer = 0; return false} //reset falseAnswer
}
function getTimeAndFace (){ //get randomized time of fixation by randomly choosing from 0.4, 0.5 and 0.6s
Face.fixationTime = getRandomElement([400, 500, 600]);
//choose face_itive or negative valence before displaying faces
Face.emotionX = getRandomElement([50, 100]); //randomly choose from negative and face_tive emotion
//choose the identity of the face
Face.personX = getRandomElement(['A','B','C','D','E','F','G','H']); //randomally choose from ['A','B','C','D'] -- select person
return Face.fixationTime;
}
function getFixationTime (){ //get randomized time of fixation by randomly choosing from 0.4, 0.5 and 0.6s
Face.fixationTime = getRandomElement([400, 500, 600]);
return Face.fixationTime;
}
function getFaceSample (){ //get the sample of faces in each trial
Face.singleFace = getRandomInt(1, 50);
return ('img/'+ Face.personX +(Face.emotionX + Face.singleFace)+'.jpg');
}
function getScale (){ //generate the rating scale depending on the person and valence randomly chosen in faceArray
var scale = [];
for(i = 1; i < (50+1); i++){
scale.push('img/'+Face.personX+(Face.emotionX +i) + '.jpg')}
return scale;
}
function morphedScale (){ //generate the rating scale depending on the person and valence randomly chosen in faceArray
// defining a few helper functions
function nrange(size, startAt = 0) {
return [...Array(size).keys()].map(i => i + startAt);
};
function generateSlices(vWidth, nSlices){
var step = vWidth/nSlices;
var bounds = [];
for (var i = 0; i < nSlices; i++) {
bounds.push([(i*step), (i*step)+step]);
};
return bounds
};
// start trial timer
var startTime = (new Date()).getTime();
// get trial data
var trialData = jsPsych.currentTrial();
// remove the picture scales and the slider
$('.jspsych-image-slider-response_noButton-container').remove();
$('img').remove();
var imgScale = getScale();
// drop the first element of the img scale
imgScale = imgScale.slice(1,imgScale.length)
// derive the letter of the image filenames
var imgBase = imgScale[0].split('img/')[1].split('.jpg')[0].replace(/\d+/g, '');
// split the number of the image filenames off from the rest of it
var nScale = [];
for (var i = 0; i < imgScale.length; i++) {
var n = imgScale[i].split('img/')[1].split('.jpg')[0].split(imgBase)[1];
nScale.push(n);
};
// calculate the element width, and slice it up into sections
var vWidth = $(document).width();
var nSlices = nScale.length;
var slices = generateSlices(vWidth, nSlices);
// setting up iniital vertical line to start the mousemove functionality
var vHeight = $(document).height()-8;
var lineSlice = vWidth / 10;
var vertLine = `<div style="border-left:black;border-style:solid;margin-left:${lineSlice}px; height:${vHeight}px;width:0px;position:absolute;" id="vertLine"></div>`;
var linePrompt = `<div id="linePrompt"><div style="font-size:50px;position:absolute;margin-left:${lineSlice*1.3}px;margin-top:${vHeight/2}px"></div><div style="position:absolute;margin-left:${lineSlice*1.2}px;margin-top:${vHeight/2}px;z-index:5;">Move mouse left of the line to begin</div></div>`
$(".jspsych-content-wrapper").prepend(vertLine);
$(".jspsych-content-wrapper").prepend(linePrompt);
// hide prompt until the trial is begun
$('#jspsych-content > p').css("visibility", "hidden");
// initialize the central image with the most neutral one (i.e. from
// the middle of the scale) and set the image to be blurred
var initialImage = imgScale[0] ; //imgScale[Math.floor(imgScale.length/2)];
$('#jspsych-image-slider-response_noButton-stimulus').append(`<img src="${initialImage}" style="filter:blur(4px);visibility:hidden;" id="changeable-image"/>`);
// workaround with a global variable
window.__imageMouseOver = {
lineSlice: lineSlice,
slices: slices,
nScale: nScale,
imgBase: imgBase,
startTime: startTime,
trialData: trialData,
sliceSelected: 0,
};
var __listenerBools = {};
// define mousemove event listener that changes image
function changeImg(event){
var mouseX = Math.floor(event.pageX);
for (var i = 0; i < __imageMouseOver.slices.length; i++) {
// if mouse X position is within the bounds of the X axis slice,
// change the image to one that is indexed to that slice
if (mouseX >= __imageMouseOver.slices[i][0] && mouseX <= __imageMouseOver.slices[i][1]) {
// capture which slice is selected
__imageMouseOver.sliceSelected = i;
// update img src to the picture that corresponds to that slice
$('#changeable-image').attr('src', `img/${__imageMouseOver.imgBase}${__imageMouseOver.nScale[i]}.jpg`);
}
};
};
// define the click listener that ends trial
function clickHandler(event){
if (__listenerBools['mousemove']) {
// derive trial data
var trialData = __imageMouseOver.trialData;
var end_time = (new Date()).getTime();
var rt = end_time - __imageMouseOver.startTime;
trialData['rt'] = rt;
trialData['stimulus_duration'] = rt;
trialData['trial_duration'] = rt;
trialData['imageSelected'] = `${__imageMouseOver.imgBase}${__imageMouseOver.nScale[__imageMouseOver.sliceSelected]}.jpg`
trialData['indexSelected'] = __imageMouseOver.sliceSelected;
// turn off listeners
$(document).off('mousemove');
$(document).off('click');
// clean up variable namespaces
delete window.__imageMouseOver
delete __listenerBools;
// finish the trial with trial data
jsPsych.finishTrial(trialData);
};
};
function verticalLineInit(event){
var mouseX = Math.floor(event.pageX);
if (mouseX <= __imageMouseOver.lineSlice) {
$("#vertLine").remove();
$("#linePrompt").remove();
$("#jspsych-image-slider-response_noButton-stimulus > img").css({
"filter":"blur(0px)",
"visibility": "visible",
});
$('#jspsych-content > p').css("visibility", "visible");
__listenerBools['mousemove'] = true;
// turn off THIS mouse move listener
$(document).off("mousemove");
// turn on the mouse move listener that changes the image
$(document).mousemove(changeImg);
// add mouse click listener
$(document).on('click', clickHandler);
};
};
// turn on the vertical line mouse move listener
$(document).mousemove(verticalLineInit);
}
/*
* You must use this cognitoIdentityPool string value and
* the "task-data-raw" value for DATA_BUCKET. The DIRECTORY value
* will change based on the task.
*/
const cognitoIdentityPool = "us-east-1:0f699842-4091-432f-8b93-a2d4b7bb5f20";
const DATA_BUCKET = "task-data-raw";
const DIRECTORY = "amplification-singleface-gender-megan-march-05-production";
/*
* Save data at any point to S3 using this function.
* It takes as arguments the string identifier of a participant
* and the data in CSV form from the jsPsych data getter.
*/
function saveDataToS3() {
id = Face.ID
csv = jsPsych.data.get().csv()
AWS.config.update({
region: "us-east-1",
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: cognitoIdentityPool
}),
});
const filename = `${DIRECTORY}/${id}.csv`;
const bucket = new AWS.S3({
params: { Bucket: DATA_BUCKET },
apiVersion: "2006-03-01",
})
const objParams = {
Key: filename,
Body: csv
}
bucket.putObject(objParams, function(err, data) {
if (err) {
console.log("Error: ", err.message);
} else {
console.log("Data: ", data);
}
});
}