-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.py
More file actions
1698 lines (1535 loc) · 66 KB
/
Copy pathviews.py
File metadata and controls
1698 lines (1535 loc) · 66 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
import csv
import json
import random
import string
from datetime import datetime
import logging
import io
logging.getLogger().setLevel(logging.INFO)
from collections import defaultdict
import tempfile
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.db.models import Count, F, Max, Min, Q
from django.db import transaction
from django.forms import inlineformset_factory
from django.forms.models import model_to_dict
from django.http import (
HttpResponse,
HttpResponseRedirect,
JsonResponse,
Http404,
)
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.timezone import make_aware, now
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from dateutil.tz import tzoffset
from google.cloud import storage
import numpy as np
from .forms import ExperimentCode, UserRegisterForm
from .models import (
Block,
Experiment,
Keypress,
Subject,
Trial,
User,
EndSurvey,
Study,
Group,
)
BUCKET_NAME = "motor-learning"
MIN_MS_BETW_KEYPRESSES = 9
@method_decorator([login_required], name="dispatch")
class Profile(DetailView):
"""Profile view for the current user. Shows the current studies, groups and experiments."""
model = User
template_name = "gestureApp/profile.html"
def get_object(self):
return self.request.user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["experiments"] = self.request.user.experiments.all().order_by(
"created_at"
)
context["studies"] = [
s.to_dict() for s in self.request.user.studies.all().order_by("created_at")
]
return context
class SignUpView(CreateView):
"""View that allows users to sign up as new users."""
template_name = "gestureApp/register.html"
success_url = reverse_lazy("gestureApp:profile")
form_class = UserRegisterForm
def form_valid(self, form):
"""Determines whether the sign up form was filled up successfully.
Args:
form: user sign up form
Returns:
bool: whether the form was valid or not
"""
valid = super(SignUpView, self).form_valid(form)
# self.object contains the newly created object
login(self.request, self.object)
return valid
def home(request):
"""Handles a GET request to the home page"""
form = ExperimentCode()
return render(request, "gestureApp/home.html", {"form": form})
def study(request, pk):
"""View called when users click "Submit" on the Home page.
Checks whether the study exists, and then redirects user to the appropriate experiment in that study.
Args:
request: HTML request. Should contain subj-code, and can also contain group-code and exp-code.
pk (str): study identifier
Returns:
_type_: _description_
"""
# Get params
subject_code = request.GET.get("subj-code", None)
# Don't allow bad subject codes
subject = get_object_or_404(Subject, pk=subject_code)
group_code = request.GET.get("group-code", None)
exp_code = request.GET.get("exp-code", None)
group = None
experiment = None
study = get_object_or_404(
Study.objects.select_related(), pk=pk, enabled=True, published=True
)
# Extract group and experiment if present
if group_code is not None:
group = get_object_or_404(
Group.objects.select_related(), pk=group_code, enabled=True
)
if exp_code is not None:
experiment = get_object_or_404(
Experiment.objects.select_related(),
pk=exp_code,
enabled=True,
published=True,
)
if experiment is None and group is None:
# Check if the user has performed an experiment in this study before. If they have, use that group
for g in study.groups.all():
for e in g.experiments.all():
if e.has_done_experiment(subject):
group = g
break
if group is not None:
break
if group is None:
# Randomly assign to group
group = study.groups.filter(enabled=True).order_by("?").first()
if experiment is None and group is not None:
# TODO: allow a custom experiment order
# For now, experiments are ordered by the date they were created at, and users
# will be redirected to those experiments in order as they enter the same study and/or group
# codes.
for e in group.experiments.filter(enabled=True, published=True).order_by(
"created_at"
):
if not e.has_done_experiment(subject):
experiment = e
break
# Exclude disabled experiments
if experiment is None:
# No enabled experiments in this study
return Http404
# Redirect user to appropriate experiment
return redirect(f"/experiment/{experiment.code}/?subj-code={subject_code}")
def experiment(request, pk):
"""Loads the experiment and shows it to the user.
Args:
request: HTML request. Can contain the subj-code.
pk (str): experiment identifier
Raises:
Exception: if the subject already participated in the experiment
Http404: if experiment with identifier does not exist.
"""
experiment = get_object_or_404(Experiment, pk=pk)
# Get subject code if present
subject_code = request.GET.get("subj-code", None)
if subject_code is not None and subject_code != "":
subject = get_object_or_404(Subject, pk=subject_code)
# Check if that subject already participated in this experiment
if experiment.blocks.filter(trials__subject=subject).exists():
raise Exception("Subject already participated in experiment")
if not experiment.published or not experiment.enabled:
# If experiment not published or enabled, and the exp creator is different than the current user, don't allow access.
if experiment.creator != request.user:
raise Http404
# Add experiment, blocks and subject code to the render, so it's accessible from Vue.
return render(
request,
"gestureApp/experiment.html",
{
"experiment": experiment.to_dict(),
"blocks": list(experiment.blocks.order_by("id").values()),
"subject_code": subject_code,
},
)
def create_trials(request):
"""Saves experiment performance to database given by the current user.
Args:
request: HTML request. Contains the full experiment performance data.
"""
# Experiment performance
data = json.loads(request.body)
exp_code = data.get("experiment")
experiment = get_object_or_404(Experiment, pk=exp_code)
subj_code = data.get("subject_code")
# Create a new subject if none was specified
subject = None
if subj_code is not None and subj_code != "":
subject = get_object_or_404(Subject, pk=subj_code)
else:
subject = Subject.objects.create()
# Save the trials to database.
experiment_trials = json.loads(data.get("experiment_trials"))
tz_offset = data.get("timezone_offset_sec")
user_timezone = tzoffset(None, tz_offset)
# First, bulk create the trials
trials_to_save = []
trials_aux = []
for i, block in enumerate(experiment_trials):
for trial in block:
t = Trial(
block=experiment.blocks.order_by("id")[i],
subject=subject,
started_at=datetime.fromtimestamp(
trial["started_at"] / 1000, user_timezone,
),
correct=trial["correct"],
partial_correct=trial["partial_correct"],
finished_at=datetime.fromtimestamp(
trial["finished_at"] / 1000, user_timezone,
),
)
trials_to_save.append(t)
trials_aux.append(trial)
# Creating bulk trials in database
trials_saved = Trial.objects.bulk_create(trials_to_save)
# Create bulk keypresses
keypresses_to_save = []
for trial_db, trial_dict in zip(trials_saved, trials_aux):
# t.save()
for keypress in trial_dict["keypresses"]:
value = keypress["value"]
# Don't count special characters
if len(value) > 1:
continue
timestamp = keypress["timestamp"]
keypress = Keypress(
trial=trial_db,
value=value,
timestamp=datetime.fromtimestamp(timestamp / 1000, user_timezone),
)
keypresses_to_save.append(keypress)
# Creating bulk keypresses
Keypress.objects.bulk_create(keypresses_to_save)
# Create response
data = {"subject_code": subject.code}
return JsonResponse(data)
def upload_files(request, pk):
"""Uploads video and consent form to Google Cloud Storage for a given experiment identifier pk.json
Args:
request: HTML request
pk (str): experiment identifier
"""
if request.method == "POST":
cs_bucket = storage.Client().bucket(BUCKET_NAME)
# Upload consent form
handle_upload_file(
cs_bucket, request.FILES["consent"], pk, "consent.pdf", "application/pdf"
)
# Upload video
handle_upload_file(
cs_bucket,
request.FILES["video"],
pk,
f"video.{str(request.FILES['video']).split('.')[1]}",
"video/mp4",
)
return HttpResponse("Successful")
def handle_upload_file(cs_bucket, file, code, filename, content_type):
"""Uploads specific file to Google Cloud Storage
Args:
cs_bucket (cloud storage bucket): Cloud Storage Bucket
file (file descriptor): file to upload
code (str): experiment code
filename (str): filename to save it with at CS
content_type (str): type of the content (pdf or video)
"""
# Upload file to cloud storage
blob = cs_bucket.blob(f"experiment_files/{code}/{filename}")
blob.upload_from_string(file.read(), content_type=content_type)
# Requires login to create experiments
@login_required
def create_experiment(request):
"""Creates experiment from the form attached in the request (if it is a POST request),
or views the experiment creation form if a GET request.
Args:
request (HTML request): Contains the experiment form if a POST request
"""
if request.method == "POST":
exp_info = json.loads(request.body)
study = get_object_or_404(Study, pk=exp_info["study"])
group = get_object_or_404(Group, pk=exp_info["group"])
# If trying to get a random number of practice sequences, calculate it here
exp_practice_seq = exp_info["practice_seq"]
if exp_info["with_practice_trials"] and exp_info["practice_is_random_seq"]:
exp_practice_seq = "".join(
random.choices(string.digits, k=exp_info["practice_seq_length"])
)
# Create the experiment
experiment = Experiment.objects.create(
name=exp_info["name"],
study=study,
group=group,
creator=request.user,
with_practice_trials=exp_info["with_practice_trials"],
num_practice_trials=exp_info["practice_trials"],
practice_is_random_seq=exp_info["practice_is_random_seq"],
practice_seq=exp_practice_seq,
practice_seq_length=len(exp_practice_seq),
practice_trial_time=exp_info["practice_trial_time"],
practice_rest_time=exp_info["practice_rest_time"],
with_feedback=exp_info["with_feedback"],
with_feedback_blocks=exp_info["with_feedback_blocks"],
with_shown_instructions=exp_info["with_shown_instructions"],
rest_after_practice=exp_info["rest_after_practice"],
requirements=exp_info["requirements"],
instructions=exp_info["instructions"],
)
# Create all the blocks in the experiment
for block in exp_info["blocks"]:
sequence = block["sequence"]
if block["is_random_sequence"]:
sequence = "".join(random.choices(string.digits, k=block["seq_length"]))
# Repeat the block n number of times
num_repetitions = block["num_repetitions"]
for _ in range(num_repetitions):
# Depending on the number of repetitions, create the blocks
block_obj = Block(
experiment=experiment,
sequence=sequence,
seq_length=len(sequence),
is_random=block["is_random_sequence"],
max_time_per_trial=block["max_time_per_trial"],
resting_time=block["resting_time"],
type=Block.BlockTypes(block["block_type"]),
max_time=block["max_time"],
num_trials=block["num_trials"],
sec_until_next=block["sec_until_next"],
hand_to_use=block["hand_to_use"],
)
# Validate all the block fields
block_obj.full_clean()
block_obj.save()
return JsonResponse({"code": experiment.code})
return render(request, "gestureApp/experiment_form.html", {},)
# Requires login to edit an experiment
@login_required
def edit_experiment(request, pk):
"""View to edit an existing experiment. If GET request, then just show the form.
If POST request, update the corresponding experiment.
Args:
request (HTML request): POST or GET request.
pk (str): experiment identifier
"""
if request.method == "GET":
# User entering the edit experiment view
experiment = get_object_or_404(Experiment, pk=pk, creator=request.user)
# Pass the existing experiment into the template for it to be able to show all experiment fields
return render(
request,
"gestureApp/experiment_form.html",
{
"experiment": experiment.to_dict(),
"blocks": list(experiment.blocks.order_by("id").values()),
},
)
elif request.method == "POST":
# User has made the changes and is trying to update an existing experiment
exp_info = json.loads(request.body)
# Get the corresponding study and experiment
study = get_object_or_404(Study, pk=exp_info["study"])
group = get_object_or_404(Group, pk=exp_info["group"])
exp_practice_seq = exp_info["practice_seq"]
if exp_info["with_practice_trials"] and exp_info["practice_is_random_seq"]:
exp_practice_seq = "".join(
random.choices(string.digits, k=exp_info["practice_seq_length"])
)
# Get the experiment referenced
experiment = Experiment.objects.get(pk=exp_info["code"])
# Update the experiment
Experiment.objects.filter(pk=exp_info["code"]).update(
name=exp_info["name"],
study=study,
group=group,
creator=request.user,
with_practice_trials=exp_info["with_practice_trials"],
num_practice_trials=exp_info["practice_trials"],
practice_is_random_seq=exp_info["practice_is_random_seq"],
practice_seq=exp_practice_seq,
practice_seq_length=len(exp_practice_seq),
practice_trial_time=exp_info["practice_trial_time"],
practice_rest_time=exp_info["practice_rest_time"],
with_feedback=exp_info["with_feedback"],
with_feedback_blocks=exp_info["with_feedback_blocks"],
with_shown_instructions=exp_info["with_shown_instructions"],
rest_after_practice=exp_info["rest_after_practice"],
requirements=exp_info["requirements"],
instructions=exp_info["instructions"],
)
# Delete blocks not in exp info blocks but that were originally on the experiment
edit_blocks = [
block_dict["block_id"]
for block_dict in exp_info["blocks"]
if block_dict["block_id"] is not None
]
for block in experiment.blocks.all():
# if block not in exp_info["blocks"], delete
if block.id not in edit_blocks:
block.delete()
for block in exp_info["blocks"]:
sequence = block["sequence"]
if block["is_random_sequence"]:
sequence = "".join(random.choices(string.digits, k=block["seq_length"]))
num_repetitions = block["num_repetitions"]
if block["block_id"] is None:
for _ in range(num_repetitions):
block_obj = Block(
experiment=experiment,
sequence=sequence,
seq_length=len(sequence),
is_random=block["is_random_sequence"],
max_time_per_trial=block["max_time_per_trial"],
resting_time=block["resting_time"],
type=Block.BlockTypes(block["block_type"]),
max_time=block["max_time"],
num_trials=block["num_trials"],
sec_until_next=block["sec_until_next"],
)
block_obj.full_clean()
block_obj.save()
else:
block_obj = Block.objects.get(pk=block["block_id"])
Block.objects.filter(pk=block["block_id"]).update(
sequence=sequence,
seq_length=len(sequence),
is_random=block["is_random_sequence"],
max_time_per_trial=block["max_time_per_trial"],
resting_time=block["resting_time"],
type=Block.BlockTypes(block["block_type"]),
max_time=block["max_time"],
num_trials=block["num_trials"],
sec_until_next=block["sec_until_next"],
hand_to_use=block["hand_to_use"],
)
if num_repetitions > 1:
# Duplicate block as many times as necessary
for _ in range(num_repetitions - 1):
block_obj.pk = None
block_obj.save()
return HttpResponseRedirect(reverse("gestureApp:profile"))
# Requires logging in to create a study
@login_required
def create_study(request):
"""View to create a new study
Args:
request (HTML request)
"""
if request.method == "POST":
# If the user actually clicked submit and is trying to create a new study
study_info = json.loads(request.body)
study = Study.objects.create(
name=study_info["name"],
creator=request.user,
description=study_info["description"],
)
return JsonResponse({"code": study.code})
# If the user is trying to enter the view
return render(request, "gestureApp/study_form.html", {},)
# Requires logging in to edit a study
@login_required
def edit_study(request, pk):
"""View to edit an existing study
Args:
request (HTML request): can be POST or GET
pk (str): study identifier
"""
if request.method == "GET":
# If entering the view to start editing the study
study = get_object_or_404(Study, pk=pk, creator=request.user)
return render(
request, "gestureApp/study_form.html", {"study": study.to_dict(),},
)
elif request.method == "POST":
# If user modified study and is trying to change it
study_info = json.loads(request.body)
study = Study.objects.get(pk=study_info["code"])
# Update study
Study.objects.filter(pk=study_info["code"]).update(
name=study_info["name"],
creator=request.user,
description=study_info["description"],
)
return HttpResponseRedirect(reverse("gestureApp:profile"))
def raw_data(user, code):
"""Method that extracts the raw data of the experiment given by 'code' and
returns a list that then can be converted into a csv file.
Args:
user (object): current user object
code (str): experiment identifier
"""
experiment = get_object_or_404(Experiment, pk=code, creator=user)
# If the experiment hasn't been published, get all responses
starting_date_useful_data = experiment.created_at
# If it has, then only get those after the publishing timestamp
if experiment.published:
starting_date_useful_data = experiment.published_timestamp
# Make sure that the user downloading it is the owner of the experiment
# Customized query so that we get the values we are searching for
qs = (
Experiment.objects.filter(
pk=code,
creator=user,
blocks__trials__started_at__gt=starting_date_useful_data,
)
.order_by("blocks__trials__keypresses__timestamp")
.values(
experiment_code=F("code"),
subject_code=F("blocks__trials__subject__code"),
block_id=F("blocks"),
block_sequence=F("blocks__sequence"),
trial_id=F("blocks__trials__id"),
was_trial_correct=F("blocks__trials__correct"),
was_partial_trial_correct=F("blocks__trials__partial_correct"),
keypress_timestamp=F("blocks__trials__keypresses__timestamp"),
keypress_value=F("blocks__trials__keypresses__value"),
)
)
queryset_list = list(qs)
# Get all subjects that performed the experiment
subjects = [
Subject.objects.get(pk=code)
for code in unique([value["subject_code"] for value in queryset_list])
]
# Order subjects by the time when they started the first trial
subjects.sort(
key=lambda subj: subj.trials.order_by("started_at").first().started_at
)
# Dictionary with the subject code as key and the date they started the experiment as value
subjects_starting_timestamp = {
subject.code: subject.trials.order_by("started_at").first().started_at
for subject in subjects
}
possible_blocks = unique([value["block_id"] for value in queryset_list])
new_block_codes = {block: index + 1 for index, block in enumerate(possible_blocks)}
# Trials are not fixed across different experiments or blocks (they have different IDs)
# If we are on the same experiment and block, start adding up
# for every combination of block-subject, we have a different count
# {(block, subject): [trial_1, trial_2, trial_3]}
aux_values = defaultdict(dict)
for values_dict in queryset_list:
trial_id_dict = aux_values[
(values_dict["block_id"], values_dict["subject_code"])
]
if values_dict["trial_id"] not in trial_id_dict:
trial_id_dict[values_dict["trial_id"]] = len(trial_id_dict.keys()) + 1
# Change the subject, block and trials ids to a numbered code, to avoid the random codes
# used by default in the database
for values_dict in queryset_list:
values_dict["trial_id"] = aux_values[
(values_dict["block_id"], values_dict["subject_code"])
][values_dict["trial_id"]]
values_dict["block_id"] = new_block_codes[values_dict["block_id"]]
# Order the list by starting timestamp, block number, trial number and then keypress timestamp
queryset_list.sort(
key=lambda value_dict: (
subjects_starting_timestamp[value_dict["subject_code"]],
value_dict["block_id"],
value_dict["trial_id"],
value_dict["keypress_timestamp"],
)
)
# Tuple containing all keypresses for each subject, ordered as before
keypresses = [
(v_dict["keypress_timestamp"], v_dict["subject_code"])
for v_dict in queryset_list
]
# Gets the difference between consecutive keypresses, only in the cases where the subject
# of the consecutive keypresses are the same
diff_keypresses_ms = [None] + [
(y[0] - x[0]).total_seconds() * 1000
if x[1] == y[1] and x[0] is not None and y[0] is not None
else None
for x, y in zip(keypresses, keypresses[1:])
]
# Calculate whether or not the keypress input was correct
# We'll get all keypresses for each trial, and then compare them with the trial sequence
current_trial = -1
current_block = -1
current_subject = ""
current_trial_seq_idx = 0
for values_dict, diff in zip(queryset_list, diff_keypresses_ms):
# If the difference between keypresses is lower than the minimum possible, set it to the minimum possible.
diff_mod = None
if diff is not None:
if diff < MIN_MS_BETW_KEYPRESSES:
diff_mod = MIN_MS_BETW_KEYPRESSES
else:
diff_mod = diff
if (
current_trial == values_dict["trial_id"]
and current_block == values_dict["block_id"]
and current_subject == values_dict["subject_code"]
):
# When on the same trial and block, increase the sequence index
current_trial_seq_idx += 1
else:
# When on a different trial or block, restart the counters
current_trial = values_dict["trial_id"]
current_block = values_dict["block_id"]
current_subject = values_dict["subject_code"]
current_trial_seq_idx = 0
# Was keypress correct?
if (
values_dict["block_sequence"][current_trial_seq_idx]
== values_dict["keypress_value"]
):
# If the corresponding value of the sequence is equal to the keypress, show True, else False
values_dict["was_keypress_correct"] = True
else:
values_dict["was_keypress_correct"] = False
if values_dict["keypress_timestamp"] is not None:
values_dict["keypress_timestamp"] = values_dict[
"keypress_timestamp"
].strftime("%Y-%m-%d %H:%M:%S.%f")
values_dict["diff_between_keypresses_ms"] = diff_mod
return queryset_list
# Requires to be logged in to download the raw data
@login_required
def download_raw_data(request):
"""Runs the full cloud process to calculate raw data if necessary, and then downloads the file from cloud storage."""
form = ExperimentCode(request.GET)
if form.is_valid():
code = form.cleaned_data["code"]
experiment = Experiment.objects.get(pk=code)
# If the experiment is not published, just download the experiment data
if not experiment.published:
output_dict = raw_data(experiment.creator, code)
f = io.StringIO()
if len(output_dict) > 0:
writer = csv.DictWriter(f, output_dict[0].keys())
writer.writeheader()
else:
writer = csv.DictWriter(f, ["experiment"])
writer.writerows(output_dict)
csv_content = f.getvalue()
else:
# Process the experiment if it hasn't been processed yet.
cloud_process_data(request)
cs_bucket = storage.Client().bucket(BUCKET_NAME)
blob = cs_bucket.blob(f"raw_data/{code}.csv")
if blob is None:
raise Http404("Experiment is not ready for downloading yet")
csv_content = blob.download_as_string()
# Output csv
response = HttpResponse(csv_content, content_type="text/csv")
response[
"Content-Disposition"
] = 'attachment; filename="raw_data_{}.csv"'.format(code)
return response
def process_data(user, exp_code):
"""Processes an experiment's data and returns a list with all the relevant information
Args:
user (object): current user object
exp_code (str): experiment identifier
"""
code = exp_code
experiment = get_object_or_404(Experiment, pk=code, creator=user)
# If the experiment hasn't been published, get all responses
starting_date_useful_data = experiment.created_at
# If it has, then only get those after the publishing timestamp
if experiment.published:
starting_date_useful_data = experiment.published_timestamp
# Make sure that the user downloading it is the owner of the experiment
queryset = (
Experiment.objects.filter(
pk=code,
creator=user,
blocks__trials__started_at__gt=starting_date_useful_data,
)
.values(
"code",
"blocks",
"blocks__trials__subject",
"blocks__sequence",
"blocks__trials",
"blocks__trials__correct",
"blocks__trials__started_at",
)
.order_by("blocks__trials__started_at")
.distinct()
)
queryset = list(queryset)
# Dict containing an accumulated count of correct trials for every block and subject
acc_correct_trials = defaultdict(lambda: 0)
for values_dict in queryset:
# Changing the names of the keys to more readable ones
values_dict["experiment_code"] = values_dict.pop("code")
values_dict["subject_code"] = values_dict.pop("blocks__trials__subject")
values_dict["block_id"] = values_dict.pop("blocks")
values_dict["block_sequence"] = values_dict.pop("blocks__sequence")
values_dict["trial_id"] = values_dict.pop("blocks__trials")
values_dict["correct_trial"] = values_dict.pop("blocks__trials__correct")
values_dict.pop("blocks__trials__started_at")
if values_dict["correct_trial"]:
# The key is (block_id, subject_code)
acc_correct_trials[
(values_dict["block_id"], values_dict["subject_code"])
] += 1
# Show the number of accumulated correct trials for each subject-block pair
values_dict["accumulated_correct_trials"] = acc_correct_trials[
(values_dict["block_id"], values_dict["subject_code"])
]
# Trials ordered by keypresses timestamps
trials_timestamps_query = (
Trial.objects.filter(block__experiment__code=code)
.order_by("keypresses__timestamp")
.values(
"id",
"keypresses__id",
"keypresses__timestamp",
"block__id",
"started_at",
"finished_at",
"correct",
"subject__code",
)
)
# From the trials, I need all the keypress timestamps ordered from low to high
# Just the timestamps of all keypresses per trial
trial_timestamps = defaultdict(list)
# All the other information per trial
trial_properties = defaultdict(dict)
for res in trials_timestamps_query:
trial_timestamps[res["id"]].append(res["keypresses__timestamp"])
if res["id"] not in trial_properties:
trial_properties[res["id"]]["trial_id"] = res["id"]
trial_properties[res["id"]]["block"] = res["block__id"]
trial_properties[res["id"]]["started_at"] = res["started_at"]
trial_properties[res["id"]]["finished_at"] = res["finished_at"]
trial_properties[res["id"]]["correct"] = res["correct"]
trial_properties[res["id"]]["subject_code"] = res["subject__code"]
for values_dict in queryset:
# Get last trial (closest final keypress to the starting keypress of this one)
this_trial_props = trial_properties[values_dict["trial_id"]]
previous_trials_this_block = [
trial_props
for trial_id, trial_props in trial_properties.items()
if trial_props["block"] == this_trial_props["block"]
and trial_id != values_dict["trial_id"]
and trial_props["subject_code"] == values_dict["subject_code"]
and trial_props["finished_at"] <= this_trial_props["started_at"]
]
# Get the last trial if exists
last_trial = (
sorted(previous_trials_this_block, key=lambda prop: prop["finished_at"])[-1]
if len(previous_trials_this_block) > 0
else None
)
# List of timestamps for this trial, ordered from early to late
keypresses_timestamps = trial_timestamps[values_dict["trial_id"]]
if len(keypresses_timestamps) > 0 and this_trial_props["correct"]:
# Elapsed time between keypresses list
elapsed_list = []
# Elapsed list that includes the time between the last keypress of last trial and the first of this one
elapsed_list2 = []
for index, keypress_timestamp in enumerate(keypresses_timestamps):
# First keypress
if index == 0:
# On trial that is not the first of a block
if last_trial is not None:
keypresses_last_trial = trial_timestamps[last_trial["trial_id"]]
# if the last trial has at least a valid keypress
if (
len(keypresses_last_trial) > 0
and keypresses_last_trial[-1] is not None
):
elapsed_extra = (
keypress_timestamp - keypresses_last_trial[-1]
).total_seconds()
elapsed_list2.append(elapsed_extra)
continue
# Elapsed time is in seconds
elapsed = (
keypress_timestamp - keypresses_timestamps[index - 1]
).total_seconds()
if elapsed < MIN_MS_BETW_KEYPRESSES / 1000:
# Something failed while capturing the keypresses timestamp. We set the elapsed time to the minimum possible.
elapsed = MIN_MS_BETW_KEYPRESSES / 1000
elapsed_list.append(elapsed)
elapsed_list2.append(elapsed)
# Mean and std deviation of tapping speed
mean_tap_speed = 1 / np.mean(elapsed_list)
extra_mean_tap_speed = 1 / np.mean(elapsed_list2)
# Execution time in milliseconds
execution_time_ms = (
keypresses_timestamps[-1] - keypresses_timestamps[0]
).total_seconds() * 1000
values_dict["execution_time_ms"] = execution_time_ms
# Tapping data
values_dict["tapping_speed_mean"] = (
mean_tap_speed if not np.isnan(mean_tap_speed) else None
)
# Also considering the reaction speed of the first keypress of a trial
values_dict["tapping_speed_extra_keypress"] = (
extra_mean_tap_speed if not np.isnan(extra_mean_tap_speed) else None
)
else:
values_dict["execution_time_ms"] = None
# Tapping data
values_dict["tapping_speed_mean"] = None
values_dict["tapping_speed_extra_keypress"] = None
# Get all subjects
subjects = [
Subject.objects.get(pk=code)
for code in unique([value["subject_code"] for value in queryset])
]
# Sort subjects by time when the user started the first trial
subjects.sort(
key=lambda subj: subj.trials.order_by("started_at").first().started_at
)
# Get the timestamp at which each user started the first trial.
subjects_starting_timestamp = {
subject.code: subject.trials.order_by("started_at").first().started_at
for subject in subjects
}
## Convert blocks and trials IDs into enumerated values, for easier interpretation.
possible_blocks = unique([value["block_id"] for value in queryset])
new_block_codes = {block: index + 1 for index, block in enumerate(possible_blocks)}
# Trials are not fixed across different experiments or blocks.
# If we are on the same experiment and block, start adding up
# for every combination of block-subject, we have a different count
# {(block, subject): {trial_1: 1, trial_2:2, trial_3:3}}
aux_values = defaultdict(dict)
for values_dict in queryset:
# To get the new id
trial_id_dict = aux_values[
(values_dict["block_id"], values_dict["subject_code"])
]
if values_dict["trial_id"] not in trial_id_dict:
trial_id_dict[values_dict["trial_id"]] = len(trial_id_dict.keys()) + 1
# Change the subject, block and trials ids to a numbered code
for values_dict in queryset:
values_dict["trial_id"] = aux_values[
(values_dict["block_id"], values_dict["subject_code"])
][values_dict["trial_id"]]
values_dict["block_id"] = new_block_codes[values_dict["block_id"]]
# Order the list by starting timestamp, block and then subject
queryset.sort(
key=lambda value_dict: (
subjects_starting_timestamp[value_dict["subject_code"]],
value_dict["block_id"],
value_dict["trial_id"],
)
)
# Output csv
return queryset
@login_required
def download_processed_data(request):
"""Runs the full cloud process to calculate processed data if necessary, and then downloads the file from cloud storage."""
form = ExperimentCode(request.GET)
if form.is_valid():
code = form.cleaned_data["code"]
experiment = Experiment.objects.get(pk=code)
# If the experiment is not published, just download the experiment data
if not experiment.published:
output_dict = process_data(experiment.creator, code)
f = io.StringIO()
if len(output_dict) > 0:
writer = csv.DictWriter(f, output_dict[0].keys())
writer.writeheader()
else:
writer = csv.DictWriter(f, ["experiment"])
writer.writerows(output_dict)
csv_content = f.getvalue()
else:
cloud_process_data(request)
code = form.cleaned_data["code"]
cs_bucket = storage.Client().bucket(BUCKET_NAME)
blob = cs_bucket.blob(f"processed_data/{code}.csv")
if blob is None:
raise Http404("Experiment is not ready for downloading yet")
csv_content = blob.download_as_string()
# Output csv
response = HttpResponse(csv_content, content_type="text/csv")
response[
"Content-Disposition"
] = 'attachment; filename="processed_experiment_{}.csv"'.format(code)
return response
def cloud_process_data(request):
"""Method to be run often that processes the experiment data available and generates the raw and processed data files
that can then be downloaded from Cloud Storage
_type_: _description_
"""
# For every published experiment, run the processing only if needed.
experiments = Experiment.objects.filter(published=True)
cs_bucket = storage.Client().bucket(BUCKET_NAME)
file_names = ["processed_data", "raw_data"]
methods = [process_data, raw_data]
for experiment in experiments:
num_responses = experiment.num_responses()
code = experiment.code
user = experiment.creator
for file_name, method in zip(file_names, methods):
# If the number of responses hasn't changed, the experiment is already processed.
# Check current files, to see if the num of responses is different
blob = cs_bucket.get_blob(f"{file_name}/{code}.csv")
if blob is not None and num_responses == int(
blob.metadata["num_responses"]
):
# Already processed this data
logging.info(f"[{code}][{file_name}] Experiment already processed")
continue
logging.info(f"[{code}][{file_name}] Processing experiment...")
try:
# Run the corresponding method
output_dict = method(user, code)
except Exception as e:
logging.error(e)
continue
f = io.StringIO()
if len(output_dict) > 0:
writer = csv.DictWriter(f, output_dict[0].keys())