forked from sleepdiary/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.js
1494 lines (1372 loc) · 60.1 KB
/
engine.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
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
/*
* Copyright 2020-2022 Sleepdiary Developers <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
"use strict";
/**
* Valid record statuses
* @enum {string}
*/
const DiaryStandardRecordStatus = {
/** user is currently awake */
awake : "awake" ,
/** user is in bed but not asleep */
in_bed: "in bed",
/** user is asleep */
asleep: "asleep",
/** user is currently turning off the lights in preparation to go to bed */
"lights off": "lights off",
/** user is currently turning on the lights after getting out of bed */
"lights on": "lights on",
/** user is eating some food, but not a full meal */
snack: "snack",
/** user is eating a full meal */
meal: "meal",
/** user is consuming alcohol */
alcohol: "alcohol",
/** user is consuming chocolate */
chocolate: "chocolate",
/** user is consuming caffeine */
caffeine: "caffeine",
/** user is consuming a drink that doesn't fit into any other category */
drink: "drink",
/** user is taking a sleeping pill, tranqulisier, or other medication to aid sleep */
"sleep aid": "sleep aid",
/** user is exercising */
exercise: "exercise",
/** user is using the toilet */
toilet: "toilet",
/** user is experiencing noise that disturbs their sleep */
noise: "noise",
/** user's wake-up alarm is trying to wake them up */
alarm: "alarm",
/** user is currently getting into bed */
"in bed": "in bed",
/** user is currently getting out of bed */
"out of bed": "out of bed",
};
/**
* @typedef {{
* start : number,
* end : number,
* status : DiaryStandardRecordStatus,
* start_timezone : (undefined|string),
* end_timezone : (undefined|string),
* duration : (undefined|number),
* tags : (undefined|Array<string>),
* comments : (undefined|Array<string|{time:number,text:string}>),
* day_number : number,
* start_of_new_day : boolean,
* is_primary_sleep : boolean,
* missing_record_after: boolean
* }} DiaryStandardRecord
*
* A single record in a diary (e.g. one sleep) - see README.md for details
*
*/
let DiaryStandardRecord;
/**
* @typedef {{
* average : number,
* mean : number,
* interquartile_mean : number,
* standard_deviation: number,
* interquartile_standard_deviation: number,
* median : number,
* interquartile_range : number,
* durations : Array<number|undefined>,
* interquartile_durations : Array<number|undefined>,
* rolling_average : Array<number|undefined>,
* timestamps : Array<number|undefined>
* }} DiaryStandardStatistics
*
* Information about records from a diary
*/
let DiaryStandardStatistics;
/**
* @typedef {null|DiaryStandardStatistics} MaybeDiaryStandardStatistics
*/
let MaybeDiaryStandardStatistics;
/**
* @public
* @unrestricted
* @augments DiaryBase
*
* @example
* let diary = new_sleep_diary(contents_of_my_file));
*
* // print the minimum expected day duration in milliseconds:
* console.log(diary.settings.minimum_day_duration);
* -> 12345
*
* // print the maximum expected day duration in milliseconds:
* console.log(diary.settings.maximum_day_duration);
* -> 23456
*
* // Print the complete list of records
* console.log(diary.records);
* -> [
* {
* // DiaryStandardRecordStatus value, usually "awake" or "asleep"
* status: "awake",
*
* // start and end time (in milliseconds past the Unix epoch), estimated if the user forgot to log some data:
* start: 12345678,
* end: 23456789,
* start_timezone: "Etc/GMT-1",
* end_timezone: "Europe/Paris",
*
* duration: 11111111, // or missing if duration is unknown
*
* // tags associated with this period:
* tags: [
* "tag 1",
* "tag 2",
* ...
* ],
*
* // comments recorded during this period:
* comments: [
* "comment with no associated timestamp",
* { time: 23456543, text: "timestamped comment" },
* ...
* ],
*
* // (estimated) day this record is assigned to:
* day_number: 1,
*
* // true if the current day number is greater than the previous record's day number:
* start_of_new_day: true,
*
* // whether this value is the primary sleep for the current day number:
* is_primary_sleep: false,
*
* // this is set if it looks like the user forgot to log some data:
* missing_record_after: true
*
* },
*
* ...
*
* ]
*
* // Print the user's current sleep/wake status:
* console.log(diary.latest_sleep_status());
* -> "awake"
*
* // Print the user's sleep statistics:
* console.log( diary.summarise_records( record => record.status == "asleep" ) );
* -> {
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* }
*
* // Print the user's day length statistics for the past 14 days:
* let cutoff = new Date().getTime() - 1000*60*60*24*14;
* console.log( diary.summarise_days( record => record.start > cutoff ) );
* -> {
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* }
*
* // Print the user's daily schedule on a 24-hour clock:
* console.log( diary.summarise_schedule();
* -> {
* sleep: { // time (GMT) when the user falls asleep:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* wake: { // time (GMT) when the user wakes up:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* }
*
* // Print the user's daily schedule on a 24-hour clock for the past 14 days:
* let cutoff = new Date().getTime() - 1000*60*60*24*14;
* console.log( diary.summarise_schedule( record => record.start > cutoff ) );
* -> {
* sleep: { // time (GMT) when the user falls asleep:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* wake: { // time (GMT) when the user wakes up:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* }
* // Print the user's daily schedule on a 25-hour clock, defaulting to Cairo's timezone:
* console.log( diary.summarise_schedule( null, 25*60*60*1000, "Africa/Cairo" ) );
* -> {
* sleep: { // time (Cairo) when the user falls asleep:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* wake: { // time (Cairo) when the user wakes up:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* }
*/
class DiaryStandard extends DiaryBase {
/**
* @param {Object} file - file contents, or object containing records
* @param {Array=} file.records - individual records from the sleep diary
* @param {number=} file.minimum_day_duration - minimum expected day duration in milliseconds
* @param {number=} file.maximum_day_duration - maximum expected day duration in milliseconds
* @param {Function=} serialiser - function to serialise output
*/
constructor(file,serialiser) {
super(file,serialiser);
if ( file["records"] && !file["file_format"] ) {
file = {
"file_format": () => "Standard",
"contents" : file,
};
}
/**
* Spreadsheet manager
* @protected
* @type {Spreadsheet}
*/
this["spreadsheet"] = new Spreadsheet(this,[
{
"sheet" : "Records",
"member" : "records",
"cells": [
{
"member": "status",
"regexp": new RegExp('^(' + Object.values(DiaryStandardRecordStatus).join('|') + ')$'),
"type" : "string",
},
{
"member" : "start",
"type" : "time",
"optional": true,
},
{
"member" : "end",
"type" : "time",
"optional": true,
},
{
"member": "start_timezone",
"type" : "string",
"optional": true,
},
{
"member": "end_timezone",
"type" : "string",
"optional": true,
},
{
"member" : "duration",
"type" : "duration",
"optional": true,
},
{
"members": ["tags"],
"export": (array_element,row,offset) => row[offset] = Spreadsheet.create_cell( (array_element["tags"]||[]).join("; ") ),
"import": (array_element,row,offset) => {
if ( row[offset]["value"] ) {
const tags = row[offset]["value"].split(/ *; */);
array_element["tags"] = tags;
}
return true;
}
},
{
"members": ["comments"],
"export": (array_element,row,offset) => row[offset] = Spreadsheet.create_cell(
(array_element["comments"]||[])
.map( c => c["time"] ? `TIME=${c["time"]} ${c["text"]}` : c )
.join("; ")
),
"import": (array_element,row,offset) => {
if ( row[offset]["value"] ) {
const comments =
row[offset]["value"]
.split(/ *; */)
.map( c => {
var time;
c = c.replace( /^TIME=([0-9]*) */, (_,t) => { time = parseInt(t,10); return '' });
return time ? { "time": time, "text": c } : c;
});
array_element["comments"] = comments;
}
return true;
},
},
{
"member": "day_number",
"type": "number",
"optional": true,
},
{
"member": "start_of_new_day",
"type": "boolean",
"optional": true,
},
{
"member": "is_primary_sleep",
"type": "boolean",
"optional": true,
},
{
"member": "missing_record_after",
"type": "boolean",
"optional": true,
},
]
},
{
"sheet" : "Settings",
"member" : "settings",
"type" : "dictionary",
"cells": [
{
"member": "minimum_day_duration",
"type" : "duration",
},
{
"member": "maximum_day_duration",
"type" : "duration",
},
],
},
]);
switch ( file["file_format"]() ) {
case "string":
try {
file = {
"file_format": () => "Standard",
"contents": /** @type (Object|null) */ (JSON.parse(file["contents"])),
}
} catch (e) {
return this.invalid(file);
}
if ( file["contents"]["file_format"] != "Standard" ) {
return this.invalid(file);
}
// FALL THROUGH
default:
if ( this.initialise_from_common_formats(file) ) return;
let contents = file["contents"];
if (
file["file_format"]() != "Standard" ||
contents === null ||
typeof(contents) != "object" ||
!Array.isArray(contents["records"])
) {
return this.invalid(file);
}
/**
* Individual records from the sleep diary
*
* @type Array<DiaryStandardRecord>
*/
this["records"] = contents["records"]
.map( r => Object.assign({},r) )
.sort( (a,b) => ( a["start"] - b["start"] ) || ( a["end"] - b["end"] ) )
;
const settings = contents["settings"]||contents,
minimum_day_duration = settings["minimum_day_duration"] || 16*60*60*1000,
maximum_day_duration = settings["maximum_day_duration"] || minimum_day_duration*2
;
this["settings"] = {
/**
* Minimum expected length for a day
*
* <p>We calculate day numbers by looking for "asleep"
* records at least this far apart.</p>
*
* @type number
*/
"minimum_day_duration": minimum_day_duration,
/**
* Maximum expected length for a day
*
* <p>We calculate skipped days by looking for "asleep"
* records at this far apart</p>
*
* @type number
*/
"maximum_day_duration": maximum_day_duration,
};
/*
* Calculate extra information
*/
let day_start = 0,
day_number = 0,
prev = {
"status": "",
"day_number": -1
},
day_sleeps = [],
sleep_wake_record = prev
;
this["records"]
.forEach( r => {
["start","end"].forEach( key => {
if ( r[key] == undefined ) delete r[key];
});
["tags","comments"].forEach( key => {
if ( !(r[key]||[]).length ) delete r[key];
});
if ( !r.hasOwnProperty("duration") ) {
r["duration"] = r["end"] - r["start"];
if ( isNaN(r["duration"]) ) delete r["duration"];
}
if ( r.hasOwnProperty("start_of_new_day") ) {
if ( r["start_of_new_day"] ) {
day_start = r["start"];
}
} else {
r["start_of_new_day"] =
r["status"] == "asleep" &&
r["start"] > day_start + minimum_day_duration
;
}
if ( r.hasOwnProperty("day_number") ) {
day_number = r["day_number"];
} else {
if ( r["start_of_new_day"] ) {
if ( r["start"] > day_start + maximum_day_duration ) {
// assume we skipped a day
day_number += 2;
} else {
day_number += 1;
}
day_start = r["start"];
}
r["day_number"] = day_number;
}
if ( r["status"] == "awake" || r["status"] == "asleep" ) {
if ( !sleep_wake_record.hasOwnProperty("missing_record_after") ) {
sleep_wake_record["missing_record_after"] = (
r["status"] == sleep_wake_record["status"]
);
}
sleep_wake_record = r;
}
if ( r["status"] == "asleep" ) {
if ( (day_sleeps[r["day_number"]]||{"duration":-Infinity})["duration"] < r["duration"] ) {
day_sleeps[r["day_number"]] = r;
}
}
if ( r.hasOwnProperty("comments") ) {
const comments = r["comments"];
if ( comments === undefined ) {
delete r["comments"];
} else if ( !Array.isArray(comments) ) {
r["comments"] = [ comments ];
}
}
prev = r;
})
;
day_sleeps.forEach( r => {
if ( r && !r.hasOwnProperty("is_primary_sleep") ) r["is_primary_sleep"] = true;
});
}
}
["to"](to_format) {
switch ( to_format ) {
case "output":
let contents = Object.assign({"file_format":this["file_format"]()},this);
delete contents["spreadsheet"];
return this.serialise({
"file_format": () => "string",
"contents": JSON.stringify(contents),
});
default:
return super["to"](to_format);
}
}
["merge"](other) {
let records = {};
[ this, other["to"](this["file_format"]()) ].forEach(
f => f["records"].forEach(
r => records[[ r["start"], r["end"], r["status"] ].join()] = r
)
);
this["records"] = Object.values(records).sort( (a,b) => ( a["start"] - b["start"] ) || ( a["end"] - b["end"] ) );
return this;
}
["file_format"]() { return "Standard"; }
["format_info"]() {
return {
"name": "Standard",
"title": "Standardised diary format",
"url": "/src/Standard",
"extension": ".json",
}
}
/**
* Internal function used by summarise_*
* @param {Array<Array<number>>} durations_and_timestamps - event durations and associated timestamps
* @param {number=} rolling_average_max - maximum allowed value for the rolling average (e.g. 24 hours)
* @private
*/
static summarise(durations_and_timestamps,rolling_average_max) {
let defined_durations = durations_and_timestamps
.map( r => r[0] )
.filter( r => r !== undefined ),
total_durations = defined_durations.length
;
if ( !total_durations ) return null;
let a_plus_b = (a,b) => a+b,
a_minus_b = (a,b) => a-b,
sum_of_squares = (a,r) => a + Math.pow(r - mean, 2) ,
rolling_window = [],
sorted_durations = defined_durations.sort(a_minus_b),
interquartile_durations = sorted_durations.slice(
Math.round( sorted_durations.length*0.25 ),
Math.round( sorted_durations.length*0.75 ),
),
mean,
untrimmed_mean = defined_durations.reduce(a_plus_b) / (total_durations||1),
interquartile_mean = interquartile_durations.reduce(a_plus_b) / (interquartile_durations.length||1),
ret = {
"average": untrimmed_mean,
"mean": untrimmed_mean,
"interquartile_mean": interquartile_mean,
"median": sorted_durations[Math.floor(sorted_durations.length/2)],
"interquartile_range": (
interquartile_durations[interquartile_durations.length-1] -
interquartile_durations[0]
),
"durations": durations_and_timestamps.map( r => r ? r[0] : undefined ),
"timestamps": durations_and_timestamps.map( r => r ? r[1] : undefined ),
"interquartile_durations": interquartile_durations,
"rolling_average": durations_and_timestamps.map(
rolling_average_max
? (_,n) => {
/*
* work around a similar issue to that described in summarise_schedule(),
* but using a different approach.
*
* Unlike summarise_schedule(), we want to switch between earlier and later
* values for every calculation, and can assume the rolling average
* has values in a relatively small range.
*/
if ( n < 14 ) return undefined;
const rolling_window = durations_and_timestamps
.slice(Math.max(0,n-13),n+1)
.map( r => r[0] )
.filter( r => r !== undefined ),
extremes = [ 0, 0 ]
;
rolling_window.forEach( duration => {
if ( duration<rolling_average_max*1/4 ) {
++extremes[0]
} else if ( duration>rolling_average_max*3/4 ) {
++extremes[1];
}
});
return (
rolling_window.length
? (
rolling_window.reduce( (a,b) => a + b )
+ ( extremes[0] < extremes[1]
? extremes[0]* rolling_average_max
: extremes[1]*-rolling_average_max
)
) / rolling_window.length
: undefined
);
}
: (_,n) => {
const rolling_window = durations_and_timestamps
.slice(Math.max(0,n-13),n+1)
.map( r => r[0] )
.filter( r => r !== undefined )
;
return (
( n >= 14 && rolling_window.length )
? rolling_window.reduce( (a,b) => a+b ) / rolling_window.length
: undefined
);
}
),
};
// calculate standard deviations:
mean = untrimmed_mean;
ret["standard_deviation"] = Math.sqrt( defined_durations.reduce(sum_of_squares,0) / total_durations );
mean = interquartile_mean;
ret["interquartile_standard_deviation"] = Math.sqrt( interquartile_durations.reduce(sum_of_squares,0) / interquartile_durations.length );
return ret;
}
/**
* Summary statistics (based on individual records)
*
* <p>Because real-world data tends to be quite messy, and because
* different users have different requirements, we provide several
* summaries for the data:</p>
*
* <ul>
* <li><tt>average</tt> is the best guess at what the
* user would intuitively consider the average duration of a
* record. The exact calculation is chosen from the list
* below, and may change in future. It is currently the
* <tt>trimmed_mean</tt>. If you don't have any specific
* requirements, you should use this and ignore the
* others.</li>
* <li><tt>mean</tt> and <tt>standard_deviation</tt> are
* traditional summary statistics for the duration, but are
* not recommended because real-world data tends to skew
* these values higher than one would expect.</li>
* <li><tt>interquartile_mean</tt> and <tt>interquartile_standard_deviation</tt>
* produce more robust values in cases like ours, because they
* ignore the highest and lowest few records.
* <li><tt>median</tt> and <tt>interquartile_range</tt> produce
* more robust results, but tend to be less representative when
* there are only a few outliers in the data.
* <li><tt>durations</tt> and <tt>interquartile_durations</tt>
* are the raw values the other statistics were created from.
* </ul>
*
* @public
*
* @param {function(*)=} filter - only examine records that match this filter
*
* @return MaybeDiaryStandardStatistics
*
* @example
* console.log( diary.summarise_records( record => record.status == "asleep" ) );
* -> {
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* }
*
*/
["summarise_records"](filter) {
return DiaryStandard.summarise(
( filter ? this["records"].filter(filter) : this["records"] )
.map( r => [ r["duration"], r["start"]||r["end"] ] )
);
}
/**
* Summary statistics (based on records grouped by day_number)
*
* <p>Similar to {@link DiaryStandard#summarise_records}, but
* groups records by day_number.</p>
*
* @public
*
* @see [summarise_records]{@link DiaryStandard#summarise_records}
* @tutorial Graph your day lengths
*
* @param {function(*)=} filter - only examine records that match this filter
*
* @return MaybeDiaryStandardStatistics
*
* @example
* console.log( diary.summarise_days( record => record.start > cutoff ) );
* -> {
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* }
*/
["summarise_days"](filter) {
let starts = [];
// get the earliest start time for each day:
( filter ? this["records"].filter(filter) : this["records"] )
.forEach( r => {
const day_number = r["day_number"];
if (
r["start_of_new_day"]
// "start" of new day is unreliable for the first day:
&& day_number
) {
starts[day_number] = r["start"];
}
});
// remove leading undefined start times:
while ( starts.length && !starts[0] ) {
starts.shift();
}
// calculate day duration relative to previous day:
let durations = [];
for ( let n=1; n<starts.length; ++n ) {
if ( starts[n] && starts[n-1] ) {
durations[n-1] = [ starts[n] - starts[n-1], starts[n-1] ];
}
}
return DiaryStandard.summarise(durations);
}
/**
* Summary statistics about the number of times an event occurs per day
*
* <p>Similar to {@link DiaryStandard#summarise_days}, but
* looks at totals instead of sums.</p>
*
* <p>The <tt>summarise_*</tt> functions examine sums, so missing
* values are treated as <tt>undefined</tt>. This function
* examines totals, so missing values are treated as <tt>0</tt>.
* The <tt>record_filter</tt> and <tt>day_filter</tt> parameters
* allow you to exclude days and records separately.</p>
*
* @public
*
* @see [summarise_records]{@link DiaryStandard#summarise_records}
*
* @param {function(*)=} record_filter - only examine records that match this filter
* @param {function(*)=} day_filter - only examine days that match this filter
*
* @return MaybeDiaryStandardStatistics
*
* @example
* console.log( diary.total_per_day(
* record => record.status == "asleep", // only count sleep records
* record => record.start > cutoff // ignore old records
* ) );
* -> {
* average : 1.234,
* mean : 1.345,
* interquartile_mean : 1.234,
* standard_deviation: 0.123,
* interquartile_standard_deviation: 0.012,
* median : 1,
* interquartile_range : 1,
* counts : [ undefined, 1, undefined, ... ],
* interquartile_counts : [ 1, 1, 2, 1, 1, 0, ... ],
* // included for compatibility with summarise_* functions:
* durations : [ undefined, 1, undefined, ... ],
* interquartile_durations : [ 1, 1, 2, 1, 1, 0, ... ],
* }
*/
["total_per_day"](record_filter,day_filter) {
let counts = [],
cutoff = (
// duration cannot be calculated for an incomplete day:
this["records"].length
? this["records"][this["records"].length-1]["day_number"]
: 0
);
( day_filter ? this["records"].filter(day_filter) : this["records"] )
.forEach( r =>
(
counts[r["day_number"]] = counts[r["day_number"]] || [ 0, r["start"] ]
)[0] += ( record_filter && !record_filter(r) ? 0 : 1 )
);
counts = counts.slice( 1, cutoff );
// remove leading undefined start times:
while ( counts.length && counts[0] === undefined ) {
counts.shift();
}
return DiaryStandard.summarise(counts);
}
/**
* Summary statistics about daily events
*
* <p>Somewhat similar to {@link DiaryStandard#summarise_records}.</p>
*
* <p>Calculates the time of day when the user is likey to wake up
* or go to sleep.</p>
*
* <p>Sleep/wake times are currently calculated based on the
* beginning/end time for each day's primary sleep, although this
* may change in future.</p>
*
* <p>Times are calculated according to the associated timezone.
* For example, say you woke up in New York at 8am, flew to Los
* Angeles, went to bed and woke up again at 8am local time. You
* would be counted as waking up at 8am both days, even though 27
* hours had passed between wake events.</p>
*
* <p>Records without a timezone are treated as if they had the
* environment's default timezone</p>
*
* @public
*
* @see [summarise_records]{@link DiaryStandard#summarise_records}
*
* @param {function(*)=} [filter=null] - only examine records that match this filter
* @param {number=} [day_length=86400000] - times of day are calculated relative to this amount of time
* @param {string=} [timezone=system_timezone] - default timezone for records
*
* @return {{
* sleep : MaybeDiaryStandardStatistics,
* wake : MaybeDiaryStandardStatistics
* }}
*
* @example
* console.log( diary.summarise_schedule() );
* -> {
* sleep: { // time when the user falls asleep:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* wake: { // time when the user wakes up:
* average : 12345.678,
* mean : 12356.789,
* interquartile_mean : 12345.678,
* standard_deviation: 12.56,
* interquartile_standard_deviation: 12.45,
* median : 12345,
* interquartile_range : 12,
* durations : [ undefined, 12345, undefined, ... ],
* interquartile_durations : [ 10000, 10001 ... 19998, 19999 ],
* },
* }
*/
["summarise_schedule"](filter,day_length,timezone) {
/*
* Note: this function needs to work around a weird issue.
*
* If a user went to sleep at 00:10am then at 11:50pm, a naive
* algorithm might calculate the user's mean sleep time to be
* midday instead of midnight. To avoid this problem, we
* calculate values twice - once normally and once with all
* numbers rotated by half the day length. Then we use
* whichever one has the lowest standard deviation.
*/