-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactigraphy_app.py
More file actions
1480 lines (1153 loc) · 52.2 KB
/
actigraphy_app.py
File metadata and controls
1480 lines (1153 loc) · 52.2 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
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
from dash import Dash, dcc, html, Input, Output, State, callback_context
import dash_daq as daq
import plotly.express as px
import pandas as pd
import rdata
import re
import numpy as np
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import dash_bootstrap_components as dbc
import time
import json
import csv
import os
import sys
import base64
import calendar
import math
from pathlib import Path
from os import listdir
from os.path import exists, isfile, join
from datetime import date, datetime, timedelta
from plotly.subplots import make_subplots
from pandas.tseries.offsets import *
import argparse
#print(daq.__version__)
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
#config = {
# "modeBarButtonsToAdd": [
# "drawrect",
# ]
#}
parser=argparse.ArgumentParser(
description='''Actigraphy APP to manually correct annotations for the sleep log diary. ''',
epilog="""APP developed by Child Mind Institute.""")
parser.add_argument('input_folder', help='GGIR output folder')
args=parser.parse_args()
#global input_datapath
'''
input_datapath = sys.argv[1]
files = [f for f in listdir(input_datapath+'/meta/ms4.out') if f.endswith(".RData")]
files = sorted(files)
'''
input_datapath = sys.argv[1]
files = [f for f in listdir(input_datapath) if f.startswith("output_")]
files = sorted(files)
if (exists(os.path.join(input_datapath+'/logs'))):
log_path = os.path.join(input_datapath+'/logs')
else:
os.mkdir(os.path.join(input_datapath+'/logs'))
log_path = os.path.join(input_datapath+'/logs')
#print(files)
def which(self):
try:
self = list(iter(self))
except TypeError as e:
raise Exception("""'which' method can only be applied to iterables.
{}""".format(str(e)))
indices = [i for i, x in enumerate(self) if bool(x) == True]
return(indices)
pd.Series.which = which
# Function to load the ms4.out file and get some useful variables
def load_ms4_file(filename):
filepath = os.path.abspath(os.path.join(input_datapath + '/output_' + filename + '/meta/ms4.out', filename + '.gt3x.RData'))
night_summary = rdata.parser.parse_file(filepath)
night_summary_converted = rdata.conversion.convert(night_summary)
nights = night_summary_converted.get("nightsummary").night
num_nights = np.size(nights)
sleeponset = night_summary_converted.get("nightsummary").sleeponset
sleepduration = night_summary_converted.get("nightsummary").SptDuration
n_summary_data = np.array([nights, sleeponset, sleepduration])
week_day = night_summary_converted.get("nightsummary").weekday
sleep_dates = night_summary_converted.get("nightsummary").get("calendar_date")
sleeponset_time_all = night_summary_converted.get("nightsummary").get("sleeponset")
wake_time_all = night_summary_converted.get("nightsummary").get("wakeup")
return num_nights, sleeponset, sleepduration, n_summary_data, week_day, sleep_dates, sleeponset_time_all, wake_time_all
# Function to load the metadata file and get some useful variables
def load_metadata(filename):
identifier = filename
filename = 'meta_' + filename
filepath = os.path.abspath(os.path.join(input_datapath + '/output_' + identifier + '/meta/basic', filename + '.gt3x.RData'))
basic = rdata.parser.parse_file(filepath)
basic_converted = rdata.conversion.convert(basic)
ACC = basic_converted.get("M").get("metashort").get("ENMO")*1000
nonwearscore = basic_converted.get("M").get("metalong").get("nonwearscore")
nw_time = basic_converted.get("M").get("metalong").get("timestamp")
anglez = basic_converted.get("M").get("metashort").get("anglez")
date_time = basic_converted.get("M").get("metashort").get("timestamp")
ws3_interm = basic_converted.get("M").get("windowsizes")
ws3 = ws3_interm[0]
ws2 = ws3_interm[1]
axis_range = int((2*(60/ws3)*60))
return ACC, nonwearscore, nw_time, anglez, date_time, ws3, ws2, axis_range
# Function to create the act graphs
def create_graphs(filename):
identifier = filename[7:]
# First, load files (ms4.out and metadata)
num_nights, sleeponset, sleepduration, n_summary_data, week_day, sleep_dates, sleeponset_time_all, wake_time_all = load_ms4_file(identifier)
ACC, nonwearscore, nw_time, anglez, date_time, ws3, ws2, axis_range = load_metadata(identifier)
#timestamp = load_csv_file(filename)
# Index 0=year; 1=month; 2=day; 3=hour; 4=min; 5=sec; 6=timezone
time_split = date_time.str.split(r"T|-|:", expand=True)
sec = time_split[5]
min_vec = time_split[4]
hour = time_split[3]
time_matrix = np.column_stack((sec, min_vec, hour))
time = sec + min_vec + hour
ddate = time_split[0] + "-" + time_split[1] + "-" + time_split[2]
nightsi = np.where(time == "000012")
nightsi = nightsi[0]
# Easy way to get all the dates and then plot the date correctly
ddate_new = ddate[nightsi+1]
ddate_new = pd.Index(ddate_new)
# Prepare nonwear information for plotting
nonwear = np.zeros((np.size(ACC)))
# take instances where nonwear was detected (on ws2 time vector) and map results onto a ws3 lenght vector for plotting purposes
if (np.sum(np.where(nonwearscore > 1))):
nonwear_elements = np.where(nonwearscore > 1)
nonwear_elements = nonwear_elements[0]
for j in range(1, np.size(nonwear_elements)):
# The next if deals with the cases in which the first point is a nowwear data
# When this happens, the data takes a minute to load on the APP
# TO-DO: find a better way to treat the nonwear cases in the first datapoint
if nonwear_elements[j-1] == 0:
nonwear_elements[j-1] = 1
match_loc = np.where(nw_time[nonwear_elements[j-1]] == date_time)
match_loc = match_loc[0]
nonwear[int(match_loc):int((int(match_loc)+(ws2/ws3)-1))] = 1
xaxislabels = ("noon", "2pm", "4pm", "6pm", "8pm", "10pm", "midnight", "2am", "4am", "6am", "8am", "10am", "noon")
wdaynames = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
npointsperday = int((60/ws3)*1440)
# Creating auxiliary vectors to store the data
vec_acc = np.zeros((len(nightsi)+1, npointsperday))
vec_ang = np.zeros((len(nightsi)+1, npointsperday))
vec_sleeponset = np.zeros(len(nightsi)+1)
vec_wake = np.zeros(len(nightsi)+1)
vec_sleep_hour = np.zeros(len(nightsi)+1)
vec_sleep_min = np.zeros(len(nightsi)+1)
vec_wake_hour = np.zeros(len(nightsi)+1)
vec_wake_min = np.zeros(len(nightsi)+1)
vec_nonwear = np.zeros((len(nightsi)+1, npointsperday))
if (len(nightsi) > 0):
nplots = np.size(nightsi)+1
x = range(1, npointsperday+1, 1)
daycount = 1
#for g in range(1,len(sleep_dates)+1):
for g in range(1, nplots+1):
print("Creating graph ", g)
skip = 0
check_date = 1
change_date = 0
if daycount == 1:
t0 = 1
t1 = nightsi[daycount-1]
non_wear = nonwear[range(t0, t1+1)]
if daycount > 1 and daycount < nplots:
t0 = nightsi[daycount-2]+1
t1 = nightsi[daycount-1]
non_wear = nonwear[range(t0, t1+1)]
if daycount == nplots:
t0 = nightsi[daycount-2]
t1 = np.size(date_time)
non_wear = nonwear[range(t0, t1)]
# Day with 25 hours, just pretend that 25th hour did not happen
if (((t1 - t0) + 1) / (60*60/ws3) == 25):
t1 = t1 - (60*60/ws3)
t1 = int(t1)
# Day with 23 hours, just extend timeline with 1 hour
if (((t1 - t0) + 1) / (60*60/ws3) == 23):
t1 = t1 + (60*60/ws3)
t1 = int(t1)
# Initialize daily "what we think you did" vectors
acc = abs(ACC[range(t0, t1+1)])
ang = anglez[range(t0, t1+1)]
non_wear = nonwear[range(t0, t1)]
extension = range(0, (npointsperday-(t1-t0))-1, 1)
extra_extension = range(0, 1)
# check to see if there are any sleep onset or wake annotations on this day
sleeponset_loc = 0
wake_loc = 0
sw_coefs = [12, 36]
# Index 0=day; 1=month; 2=year
sleep_dates_split = sleep_dates.str.split(r"/", expand=True)
# Double check because some dates are like 2019-02-25 and other dates are like 2019-2-25
# Or some dates are like 2019-02-01 and other dates are like 2019-02-1
for i in range(1, len(sleep_dates_split)+1):
if (len(sleep_dates_split[0][i]) == 1):
sleep_dates_split[0][i] = "0" + sleep_dates_split[0][i]
if (len(sleep_dates_split[1][i]) == 1):
sleep_dates_split[1][i] = "0" + sleep_dates_split[1][i]
new_sleep_date = sleep_dates_split[2] + "-" + sleep_dates_split[1] + "-" + sleep_dates_split[0]
# check for sleeponset & wake time that is logged on this day before midnight
curr_date = ddate[t0]
# check to see if it is the first day that has less than 24 and starts after midnight
if ((t1 - t0) < ((60*60*12)/ws3)): # if there is less than half a days worth of data
list_temp = list(curr_date)
temp = int(curr_date[8:]) - 1
if (len(str(temp)) == 1):
temp = "0" + str(temp)
else:
temp = str(temp)
list_temp[8:] = temp
curr_date = ''.join(list_temp)
new_sleep_date = pd.concat([pd.Series(curr_date), new_sleep_date])
if (daycount == 1):
# Updating the all days variable to include the day before (without act data) on the first position
ddate_new = pd.concat([pd.Series(curr_date), pd.Series(ddate_new)])
ddate_new = ddate_new.reset_index()
ddate_new = ddate_new[0]
change_date = 1
# Since the first day started before midnight:
#ddate_new = new_sleep_date
if (curr_date in str(new_sleep_date)):
check_date = 0
idx = list(new_sleep_date).index(curr_date)
if (check_date == False):
# Get sleeponset
sleeponset_time = sleeponset_time_all[idx+1]
if ((sleeponset_time >= sw_coefs[0]) & (sleeponset_time < sw_coefs[1])):
sleeponset_hour = int(sleeponset_time)
if (sleeponset_hour == 24):
sleeponset_hour = 0
if (sleeponset_hour > 24):
sleeponset_hour = sleeponset_hour - 24
sleeponset_min = (sleeponset_time - int(sleeponset_time)) * 60
if (int(sleeponset_min) == 60):
sleeponset_min = 0
sleeponset_locations = (((pd.to_numeric(hour[t0:t1])) == sleeponset_hour) & ((pd.to_numeric(min_vec[t0:t1])) == int(sleeponset_min))).which()
sleeponset_locations = list(pd.to_numeric(sleeponset_locations)+2)
# Need to change this line to work with boolean
#if(sleeponset_locations[0] == True):
if (len(sleeponset_locations) == 0):
sleeponset_loc = 0
else:
sleeponset_loc = sleeponset_locations[0]
# Get wakeup
wake_time = wake_time_all[idx+1]
if((wake_time >= sw_coefs[0]) & (wake_time < sw_coefs[1])):
wake_hour = int(wake_time)
if (wake_hour == 24):
wake_hour = 0
if (wake_hour > 24):
wake_hour = wake_hour - 24
wake_min = (wake_time - int(wake_time)) * 60
if (wake_min == 60):
wake_min = 0
wake_locations = (((pd.to_numeric(hour[t0:t1])) == wake_hour) & ((pd.to_numeric(min_vec[t0:t1])) == int(wake_min))).which()
wake_locations = list(pd.to_numeric(wake_locations)+2)
# Need to change this line to work with boolean
#if(wake_locations[0] == True):
if (len(wake_locations) == 0):
wake_loc = 0
else:
wake_loc = wake_locations[0]
vec_sleep_hour[g-1] = sleeponset_hour
vec_sleep_min[g-1] = sleeponset_min
vec_wake_hour[g-1] = wake_hour
vec_wake_min[g-1] = wake_min
# add extensions if <24hr of data
# hold adjustments amounts on first and last day plots
if ((((t1 - t0)+1) != npointsperday) & (t0 == 1)):
extension = [0]*((npointsperday-(t1-t0))-1)
acc = extension + list(acc)
ang = extension + list(ang)
non_wear = extension + list(non_wear)
t1 = len(acc)
if len(non_wear) < 17280:
non_wear = list(extra_extension) + list(non_wear)
if (len(acc) == (len(x)+1)):
extension = extension[1:(len(extension))]
acc = acc[1:(len(acc))]
ang = ang[1:(len(ang))]
non_wear = non_wear[1:(len(non_wear))]
extension_mat = np.zeros([len(extension), 6])
# adjust any sleeponset / wake annotations if they exist:
if (sleeponset_loc != 0):
sleeponset_loc = sleeponset_loc + len(extension)
if (wake_loc != 0):
wake_loc = wake_loc + len(extension)
elif (((t1-t0)+1) != npointsperday & (t1 == len(time))):
extension = [0]*((npointsperday-(t1-t0)))
acc = list(acc) + extension
ang = list(ang) + extension
non_wear = list(non_wear) + extension
if len(non_wear) < 17280:
non_wear = list(non_wear) + extension
if (len(acc) == (len(x)+1)):
extension = extension[1:(len(extension))]
acc = acc[1:(len(acc))]
ang = ang[1:(len(ang))]
non_wear = non_wear[1:(len(non_wear))] + list(extra_extension)
extension_mat = np.zeros([len(extension), 6])
#for i in range(len(acc)):
# if acc[int(i)] >= 900:
# acc[int(i)] = 900
# Comment the next line if the app will create two different graphs: one for the arm movement and one for the z-angle
acc = (np.array(acc)/14) - 210
# storing important variables in vectors to be accessed later
vec_acc[g-1] = acc
vec_ang[g-1] = ang
vec_sleeponset[g-1] = sleeponset_loc
vec_wake[g-1] = wake_loc
vec_nonwear[g-1] = non_wear
daycount = daycount + 1
#print(vec_wake)
vec_line = []
#vec_line = [0 for i in range((daycount-1)*2)]
# Setting nnights = 70 because GGIR version 2.0-0 need a value for the nnights variable.
vec_line = [0 for i in range((70)*2)]
#wake = [sleeplog_file[idx] for idx in range(len(sleeplog_file)) if idx%2==1]
#print(type(wake))
#sleep = [sleeplog_file[idx] for idx in range(len(sleeplog_file)) if idx%2!=1]
excl_night = [0 for i in range(daycount)]
nap_times = [0 for i in range(daycount)]
review_night = [0 for i in range(daycount)]
ddate_temp = ddate_new[0]
new_sleep_date_temp = new_sleep_date[1]
if ((ddate_new[0] != new_sleep_date[1]) and (change_date == 0) and (ddate_temp[8:] > new_sleep_date_temp[8:])):
ddate_new = pd.concat([pd.Series(new_sleep_date[1]), pd.Series(ddate_new)])
ddate_new = ddate_new.reset_index()
ddate_new = ddate_new[0]
if (len(new_sleep_date) != daycount-1):
new_sleep_date = pd.concat([new_sleep_date, pd.Series(curr_date)])
new_sleep_date = new_sleep_date.reset_index()
new_sleep_date = new_sleep_date[0]
return identifier, axis_range, daycount, week_day, new_sleep_date, vec_acc, vec_ang, vec_sleeponset, vec_wake, vec_sleep_hour, vec_sleep_min, vec_wake_hour, vec_wake_min, vec_line, npointsperday, excl_night, vec_nonwear, ddate_new, nap_times, date_time, review_night
# File example:
# ID onset_N1 wake_N1 onset_N2 wake_N2 onset_N3 wake_N3 ...
def create_GGIR_file(identifier, number_of_days, filename):
n_columns = number_of_days*2
headline = []
first_line = []
headline.append("ID")
for ii in range(1, number_of_days+1):
onset_name = 'onset_N' + str(ii)
wake_name = 'wakeup_N' + str(ii)
headline.append(onset_name)
headline.append(wake_name)
f = open(os.path.join(log_path,filename), 'w')
writer = csv.writer(f)
writer.writerow(headline)
f.close()
def save_GGIR_file(hour_vector, fig_variables, filename):
identifier = fig_variables[0]
daycount = fig_variables[2]
vec_line = hour_vector
#filename = 'sleep_log_' + identifier + '_' + datetime.now() + '.csv'
filename = 'sleeplog_' + identifier + '.csv'
data_line = []
data_line.append(identifier)
#print("vec_line: ", vec_line)
for ii in range(np.size(vec_line)):
if (vec_line[ii] != 0):
data_line.append(vec_line[ii])
else:
data_line.append("NA")
# data_line.append(sleep)
# data_line.append(wake)
if (exists(os.path.join(log_path,filename))):
os.remove(os.path.join(log_path,filename))
create_GGIR_file(identifier, 70, filename)
else:
create_GGIR_file(identifier, 70, filename)
f = open(os.path.join(log_path,filename), 'a')
writer = csv.writer(f)
writer.writerow(data_line)
f.close()
def save_log_file(name, identifier):
global filename
todays_date_time = datetime.now()
todays_date = todays_date_time.strftime("%Y-%m-%d")
todays_time = todays_date_time.strftime("%H:%M:%S")
#filename = 'sleep_log_' + identifier + '_' + str(todays_date) + '_' + str(todays_time) + '.csv'
filename = 'sleeplog_' + identifier + '.csv'
header = []
log_info = []
log_info.append(name)
log_info.append(identifier)
log_info.append(date.today())
#log_info.append(datetime.now())
log_info.append(filename)
if (exists(os.path.join(log_path, 'log_file.csv'))):
f = open(os.path.join(log_path, 'log_file.csv'), 'a')
writer = csv.writer(f)
writer.writerow(log_info)
f.close()
else:
f = open(os.path.join(log_path, 'log_file.csv'), 'w')
writer = csv.writer(f)
header.append("Username")
header.append("Participant")
header.append("Date")
header.append("Filename")
writer.writerow(header)
writer.writerow(log_info)
f.close()
return filename
def open_sleeplog_file(identifier):
filename = 'sleeplog_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
sleeplog_file = pd.read_csv(filename_path, index_col = 0)
sleeplog_file = sleeplog_file.iloc[0]
wake = [sleeplog_file[idx] for idx in range(len(sleeplog_file)) if idx%2==1]
#print(type(wake))
sleep = [sleeplog_file[idx] for idx in range(len(sleeplog_file)) if idx%2!=1]
'''
for i in range(0, len(sleep)):
if sleep[i] == '3:0:00':
sleep[i] = 10800
for j in range(0, len(wake)):
if wake[j] == '3:0:00':
wake[j] = 10800
'''
return sleep, wake
def save_sleeplog_file(identifier, day, sleep, wake):
filename = 'sleeplog_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
df = pd.read_csv(filename_path)
df.iloc[0,0] = identifier
sleep_time, wake_time = point2time(sleep, wake)
df.iloc[0,((day)*2)-1] = sleep_time
df.iloc[0,((day)*2)] = wake_time
df.to_csv(filename_path, index=False)
'''
def save_multiple_sleeplog(identifier, multiple_log):
todays_date_time = datetime.now()
#if (multiple_log == None or multiple_log == []):
# multiple_log = ''
filename = 'multiple_sleeplog_' + identifier + '.csv'
nap_times = 0
header = []
log_info = []
# Adjusting nap times variable to insert all days in the same column
for i in range(1, np.size(multiple_log)+1):
if multiple_log[i-1] == 1:
if nap_times == 0:
nap_times = i
else:
nap_times = str(nap_times) + ' ' + str(i)
# If file exists, remove older file, create a new one, and store the data
if (exists(os.path.join(log_path, filename))):
os.remove(os.path.join(log_path, filename))
f = open(os.path.join(log_path, filename), 'w')
writer = csv.writer(f)
header.append("ID")
header.append("Days with multiple sleep times")
log_info.append(identifier)
log_info.append(nap_times)
writer.writerow(header)
writer.writerow(log_info)
f.close()
# If file does not exists, create the file and append the information to the new file
else:
f = open(os.path.join(log_path, filename), 'w')
writer = csv.writer(f)
header.append("ID")
header.append("Days with multiple sleep times")
log_info.append(identifier)
log_info.append(nap_times)
writer.writerow(header)
writer.writerow(log_info)
f.close()
return filename
'''
def save_log_analysis_completed(identifier, completed):
todays_date_time = datetime.now()
filename = 'participants_with_completed_analysis.csv'
header = []
log_info = []
log_info.append(identifier)
log_info.append(completed)
log_info.append(todays_date_time)
# If file exists, append the new information on the existing file
if (exists(os.path.join(log_path, 'participants_with_completed_analysis.csv'))):
f = open(os.path.join(log_path, 'participants_with_completed_analysis.csv'), 'a')
writer = csv.writer(f)
writer.writerow(log_info)
f.close()
# If file does not exists, create the file and append the information to the new file
else:
f = open(os.path.join(log_path, 'participants_with_completed_analysis.csv'), 'w')
writer = csv.writer(f)
header.append("Participant")
header.append("Is the sleep log analysis completed?")
header.append("Last modified")
writer.writerow(header)
writer.writerow(log_info)
f.close()
# File format:
# ID, day_part5, relyonguider_part4, night_part4
def save_excluded_night(identifier, excl_night):
filename = 'data_cleaning_file_' + identifier + '.csv'
nights_excluded = 0
header = []
data_night = []
# Adjusting night variable to the format accepted by GGIR
for i in range(1, np.size(excl_night)+1):
if excl_night[i-1] == 1:
if nights_excluded == 0:
nights_excluded = i
else:
nights_excluded = str(nights_excluded) + ' ' + str(i)
# Saving the csv file
# If file exists, remove older file, create a new one, and store the data
if (exists(os.path.join(log_path, filename))):
#os.remove(os.path.join(log_path, filename))
f = open(os.path.join(log_path, filename), 'w')
writer = csv.writer(f)
header.append("ID")
header.append("day_part5")
header.append("relyonguider_part4")
header.append("night_part4")
data_night.append(identifier)
data_night.append("")
data_night.append("")
data_night.append(nights_excluded)
writer.writerow(header)
writer.writerow(data_night)
f.close()
# If file does not exists, create a new file, and store the data
else:
f = open(os.path.join(log_path, filename), 'w')
writer = csv.writer(f)
header.append("ID")
header.append("day_part5")
header.append("relyonguider_part4")
header.append("night_part4")
data_night.append(identifier)
data_night.append("")
data_night.append("")
data_night.append(nights_excluded)
writer.writerow(header)
writer.writerow(data_night)
f.close()
print("Excluded nights formated: ", nights_excluded)
def create_datacleaning(identifier):
daycount = fig_variables[2]
filename = 'missing_sleep_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
data = ['0' for ii in range(0, daycount-1)]
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(data)
f.close()
def save_datacleaning(identifier, datacleaning_log):
filename = 'missing_sleep_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
data = datacleaning_log
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(data)
f.close()
def open_datacleaning(identifier):
filename = 'missing_sleep_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
df = pd.read_csv(filename_path, header=None)
datacleaning = [df.iloc[0,idx] for idx in range(0,daycount-1)]
return datacleaning
def create_multiple_sleeplog(identifier):
daycount = fig_variables[2]
filename = 'multiple_sleeplog_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
data = ['0' for ii in range(0, daycount-1)]
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(data)
f.close()
def save_multiple_sleeplog(identifier, multiple_log):
filename = 'multiple_sleeplog_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
data = multiple_log
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(data)
f.close()
def open_multiple_sleeplog(identifier):
filename = 'multiple_sleeplog_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
df = pd.read_csv(filename_path, header=None)
multiple_sleep = [df.iloc[0,idx] for idx in range(0,daycount-1)]
return multiple_sleep
def create_review_night_file(identifier):
daycount = fig_variables[2]
filename = 'review_night_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
dataline = ['0' for ii in range(1, daycount)]
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(dataline)
f.close()
def save_review_night(identifier, review_night):
filename = 'review_night_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
data = review_night
f = open(filename_path, 'w')
writer = csv.writer(f)
writer.writerow(data)
f.close()
def open_review_night(identifier):
filename = 'review_night_' + identifier + '.csv'
filename_path = os.path.join(log_path, filename)
daycount = fig_variables[2]
df = pd.read_csv(filename_path, header=None)
vec_nights = [df.iloc[0,idx] for idx in range(0,daycount-1)]
return vec_nights
def store_sleep_diary(day, sleep, wake):
vec_line = fig_variables[13]
if (sleep == 0 and wake == 0):
vec_line[(day*2)-2] = 0
vec_line[day*2-1] = 0
else:
onset_point2time = point2time(sleep, wake)
vec_line[(day*2)-2] = onset_point2time[0]
vec_line[day*2-1] = onset_point2time[1]
return vec_line
def store_excluded_night(day):
excl_night = fig_variables[15]
excl_night[day-1] = 1
return excl_night
def point2time_timestamp(point):
axis_range = fig_variables[1]
npointsperday = fig_variables[14]
if point > 6*axis_range:
temp_point = ((point*24)/npointsperday)-12
else:
temp_point = (point*24)/npointsperday+12
temp_point_hour = int(temp_point)
temp_point_min = (temp_point - int(temp_point)) * 60
if (int(temp_point_min) == 60):
temp_point_min = 00
if int(temp_point_min) < 10:
temp_point_min = '0' + str(int(temp_point_min))
point_new = str(temp_point_hour) + ':' + temp_point_min
else:
point_new = str(temp_point_hour) + ':' + str(int(temp_point_min))
return point_new
def point2time(sleep, wake):
axis_range = fig_variables[1]
npointsperday = fig_variables[14]
all_dates = fig_variables[17]
#print(axis_range)
# Get sleeponset
if int(sleep) == 0:
sleep_point2time = '3:0:00'
else:
if sleep > 6*axis_range:
temp_sleep = ((sleep*24)/npointsperday)-12
else:
temp_sleep = (sleep*24)/npointsperday+12
temp_sleep_hour = int(temp_sleep)
temp_sleep_min = (temp_sleep - int(temp_sleep)) * 60
if (int(temp_sleep_min) == 60):
temp_sleep_min = 0
sleep_point2time = str(temp_sleep_hour) + ':' + str(int(temp_sleep_min)) + ':00'
# Get wakeup
if int(wake) == 0:
wake_point2time = '3:0:00'
else:
if wake > 6*axis_range:
temp_wake = ((wake*24)/npointsperday)-12
else:
temp_wake = (wake*24)/npointsperday+12
temp_wake_hour = int(temp_wake)
temp_wake_min = (temp_wake - int(temp_wake)) * 60
if (int(temp_wake_min) == 60):
temp_wake_min = 0
wake_point2time = str(temp_wake_hour) + ':' + str(int(temp_wake_min)) + ':00'
return sleep_point2time, wake_point2time
def time2point(sleep, wake, day):
axis_range = fig_variables[1]
npointsperday = fig_variables[14]
all_dates = fig_variables[17]
if sleep == 0:
sleep2return = 0
else:
sleep_split = sleep.split(":")
# Get sleep time and transform to timepoints
sleep_time_hour = int(sleep_split[0])
sleep_time_min = int(sleep_split[1])
# hour
if sleep_time_hour >= 0 and sleep_time_hour < 12:
sleep_time_hour = (((sleep_time_hour+12)*8640)/12)
else:
sleep_time_hour = ((sleep_time_hour-12)*8640)/12
# minute
if sleep_time_min == 0:
sleep_time_min = 0
else:
sleep_time_min = ((sleep_time_min*12))
sleep2return = sleep_time_hour + sleep_time_min
if wake == 0:
wake2return = 0
else:
wake_split = wake.split(":")
# Get wake time and transform to timepoints
wake_time_hour = int(wake_split[0])
wake_time_min = int(wake_split[1])
# hour
if wake_time_hour >= 0 and wake_time_hour < 24:
wake_time_hour = ((wake_time_hour+12)*17280)/24
else:
wake_time_hour = ((wake_time_hour-12)*17280)/24
# minute
if wake_time_min == 0:
wake_time_min = 0
else:
wake_time_min = ((wake_time_min*12))
wake2return = wake_time_hour + wake_time_min
return sleep2return, wake2return
def timestamp_to_decimaltime(time, is_sleep):
time_split = time.split(':')
time_decimal = ((int(time_split[0]) * 60) + int(time_split[1]))/60
if (is_sleep == 1):
if time_decimal > 12:
time_decimal = time_decimal - 24
return time_decimal
def decimaltime_to_timestamp(time):
time_int = int(time)
time_decimal = int((time*60) % 60)
time_string = str(time_int) + ':' + str(time_decimal)
return time_string
def calculate_sleep_duration(sleeponset, wakeup):
sleep_decimal = timestamp_to_decimaltime(sleeponset, 1)
wake_decimal = timestamp_to_decimaltime(wakeup, 0)
sleep_duration_decimal = wake_decimal - sleep_decimal
sleep_duration = decimaltime_to_timestamp(sleep_duration_decimal)
return sleep_duration
def hour_to_time_string(hour):
if hour % 24 == 0:
return 'noon'
if (hour + 12) % 24 == 0:
return 'midnight'
clock_hour = hour % 12
am_pm = 'am' if (hour // 12) % 2 == 1 else 'pm'
return f'{clock_hour}{am_pm}'
colors = {
'background': '#FFFFFF',
'text': '#111111',
'title_text': '#0060EE'
}
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.Img(src='/assets/CMI_Logo_title.png', style={'height':'60%', 'width':'60%'}),
html.Div([
dcc.ConfirmDialog(
id='insert-user',
message='Insert the evaluator\'s name before continue'
)
]),
html.Div([
dcc.Input(
id="input_name",
type="text",
placeholder="Insert evaluator's name",
disabled=False,
size="40"