-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstat.js
More file actions
1137 lines (985 loc) · 35.4 KB
/
stat.js
File metadata and controls
1137 lines (985 loc) · 35.4 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 _ from 'lodash';
import React from 'react';
import i18next from 'i18next';
import {
generateBgRangeLabels,
classifyBgValue,
classifyCvValue,
reshapeBgClassesToBgBounds,
} from './bloodglucose';
import {
AUTOMATED_DELIVERY,
BG_COLORS,
BG_DISPLAY_MINIMUM_INCREMENTS,
DEFAULT_BG_BOUNDS,
LBS_PER_KG,
MGDL_UNITS,
MS_IN_DAY,
SCHEDULED_DELIVERY,
SETTINGS_OVERRIDE,
} from './constants';
import { getPumpVocabulary, getSettingsOverrides } from './device';
import { bankersRound, formatDecimalNumber, formatBgValue, formatStatsPercentage } from './format';
import { formatDuration } from './datetime';
const t = i18next.t.bind(i18next);
if (_.get(i18next, 'options.returnEmptyString') === undefined) {
// Return key if no translation is present
i18next.init({ returnEmptyString: false, nsSeparator: '|' });
}
export const dailyDoseUnitOptions = [
{
label: 'kg',
value: 'kg',
},
{
label: 'lb',
value: 'lb',
},
];
export const statTypes = {
barHorizontal: 'barHorizontal',
barBg: 'barBg',
input: 'input',
simple: 'simple',
};
export const statBgSourceLabels = {
cbg: t('CGM'),
smbg: t('BGM'),
};
export const statFormats = {
bgCount: 'bgCount',
bgRange: 'bgRange',
bgValue: 'bgValue',
cv: 'cv',
carbs: 'carbs',
duration: 'duration',
gmi: 'gmi',
percentage: 'percentage',
standardDevRange: 'standardDevRange',
standardDevValue: 'standardDevValue',
units: 'units',
unitsPerKg: 'unitsPerKg',
};
export const commonStats = {
averageGlucose: 'averageGlucose',
averageDailyDose: 'averageDailyDose',
bgExtents: 'bgExtents',
carbs: 'carbs',
coefficientOfVariation: 'coefficientOfVariation',
glucoseManagementIndicator: 'glucoseManagementIndicator',
readingsInRange: 'readingsInRange',
sensorUsage: 'sensorUsage',
standardDev: 'standardDev',
timeInAuto: 'timeInAuto',
timeInOverride: 'timeInOverride',
timeInRange: 'timeInRange',
totalInsulin: 'totalInsulin',
};
export const statFetchMethods = {
[commonStats.averageGlucose]: 'getAverageGlucoseData',
[commonStats.averageDailyDose]: 'getTotalInsulinData',
[commonStats.bgExtents]: 'getBgExtentsData',
[commonStats.carbs]: 'getCarbsData',
[commonStats.coefficientOfVariation]: 'getCoefficientOfVariationData',
[commonStats.glucoseManagementIndicator]: 'getGlucoseManagementIndicatorData',
[commonStats.readingsInRange]: 'getReadingsInRangeData',
[commonStats.sensorUsage]: 'getSensorUsage',
[commonStats.standardDev]: 'getStandardDevData',
[commonStats.timeInAuto]: 'getTimeInAutoData',
[commonStats.timeInOverride]: 'getTimeInOverrideData',
[commonStats.timeInRange]: 'getTimeInRangeData',
[commonStats.totalInsulin]: 'getInsulinData',
};
export const getSum = data => _.sum(_.map(data, d => _.max([d.value, 0])));
export const ensureNumeric = value => (_.isNil(value) || _.isNaN(value) ? -1 : parseFloat(value));
export const isRangeDefined = value => ensureNumeric(value) > -1;
export const formatDatum = (datum = {}, format, opts = {}) => {
let id = datum.id;
let value = _.isFinite(datum) ? datum : datum.value;
let suffix = datum.suffix || '';
let deviation;
let lowerValue;
let lowerColorId;
let upperValue;
let upperColorId;
const {
bgPrefs,
data,
useAGPFormat,
emptyDataPlaceholder = '--',
forcePlainTextValues = false,
} = opts;
const total = _.get(data, 'total.value');
const disableStat = () => {
id = 'statDisabled';
value = emptyDataPlaceholder;
};
switch (format) {
case statFormats.bgCount:
if (value >= 0) {
const precision = value < 0.05 ? 2 : 1;
// Note: the + converts the rounded, fixed string back to a number
// This allows 2.67777777 to render as 2.7 and 3.0000001 to render as 3 (not 3.0)
value = +value.toFixed(precision);
} else {
disableStat();
}
break;
case statFormats.bgRange:
value = generateBgRangeLabels(bgPrefs, { condensed: true })[id];
break;
case statFormats.bgValue:
if (value >= 0) {
id = classifyBgValue(_.get(bgPrefs, 'bgBounds'), bgPrefs?.bgUnits, value, 'threeWay');
value = formatBgValue(value, bgPrefs);
} else {
disableStat();
}
break;
case statFormats.carbs:
if (_.isPlainObject(value) && (value.grams > 0 || value.exchanges > 0)) {
const { grams, exchanges } = value;
value = [];
suffix = [];
if (grams > 0) {
value.push(formatDecimalNumber(grams));
suffix.push('g');
}
if (exchanges > 0) {
// Note: the + converts the rounded, fixed string back to a number
// This allows 2.67777777 to render as 2.7 and 3.0000001 to render as 3 (not 3.0)
value.push(+formatDecimalNumber(exchanges, 1));
suffix.push('exch');
}
} else {
disableStat();
}
break;
case statFormats.cv:
if (value >= 0) {
id = classifyCvValue(value);
value = useAGPFormat
? bankersRound(value, 1).toString()
: formatDecimalNumber(value);
suffix = '%';
} else {
disableStat();
}
break;
case statFormats.duration:
if (value >= 0) {
value = formatDuration(value, { condensed: true });
} else {
disableStat();
}
break;
case statFormats.gmi:
if (value >= 0) {
value = useAGPFormat
? bankersRound(value, 1).toString()
: formatDecimalNumber(value, 1);
suffix = '%';
} else {
disableStat();
}
break;
case statFormats.percentage:
if (total && total >= 0) {
value = _.max([value, 0]);
value = formatStatsPercentage(value / total);
suffix = '%';
} else {
disableStat();
}
break;
case statFormats.standardDevRange:
deviation = _.get(datum, 'deviation.value', -1);
if (value >= 0 && deviation >= 0) {
lowerValue = value - deviation;
lowerColorId = lowerValue >= 0
? classifyBgValue(_.get(bgPrefs, 'bgBounds'), bgPrefs?.bgUnits, lowerValue, 'threeWay')
: 'low';
upperValue = value + deviation;
upperColorId = classifyBgValue(_.get(bgPrefs, 'bgBounds'), bgPrefs?.bgUnits, upperValue, 'threeWay');
lowerValue = formatBgValue(lowerValue, bgPrefs);
upperValue = formatBgValue(upperValue, bgPrefs);
value = !forcePlainTextValues ? (
<span>
<span style={{
color: BG_COLORS[lowerColorId],
}}>
{lowerValue}
</span>
-
<span style={{
color: BG_COLORS[upperColorId],
}}>
{upperValue}
</span>
</span>
) : `${lowerValue}-${upperValue}`;
} else {
disableStat();
}
break;
case statFormats.standardDevValue:
if (value >= 0) {
value = formatBgValue(value, bgPrefs);
} else {
disableStat();
}
break;
case statFormats.units:
if (value >= 0) {
value = formatDecimalNumber(value, 1);
suffix = 'U';
} else {
disableStat();
}
break;
case statFormats.unitsPerKg:
if (suffix === 'lb') {
value = value * LBS_PER_KG;
}
suffix = 'U/kg';
if (value > 0 && _.isFinite(value)) {
value = formatDecimalNumber(value, 2);
} else {
disableStat();
}
break;
default:
break;
}
return {
id,
value,
suffix,
};
};
/**
* reconcileTIRPercentages
* @param {Object} timeInRanges - the percent TIR values for each range in decimal form
* - e.g. { veryLow: 0.012, low: 0.056, target: 0.612, high: 0.294, veryHigh: 0.021 }
*
* @returns {Object} an object with values corrected to sum up to 100%
* - if the values do not sum up to 100%, the 'high' range is adjusted to compensate
* - in specific edge cases, the values may still sum up to 101%
*/
export const reconcileTIRPercentages = (timeInRanges) => {
const DECIMAL_PRECISION = 2;
// Round each TIR value to whole integers for percentages (e.g. 0.21428 -> 0.21)
const modifiedTimeInRanges = _.cloneDeep(timeInRanges);
const rangeKeys = _.keys(modifiedTimeInRanges);
_.forEach(rangeKeys, key => {
modifiedTimeInRanges[key] = bankersRound(modifiedTimeInRanges[key], DECIMAL_PRECISION);
});
// Calculate the sum of all TIR values. It should be close to 1 (or 100%)
const rangeValues = _.values(modifiedTimeInRanges);
const sum = _.reduce(rangeValues, (acc, cur) => acc + cur, 0);
// Error Case: If the discrepancy from 100% is >2%, there is something wrong with
// the incoming data. Performing additional calculations on TIR would compound the
// error. Instead, we'll return the data in its original state.
if (sum < 0.98 || sum > 1.02) return timeInRanges;
// Calculate the difference from 100% and dump the discrepancy into the 'high' range.
// e.g. if sum === 0.99 and high === 0.21, we increase high to 0.22 so that all TIR
// values add up to 1 (or 100%).
const diff = 1 - sum;
let newHigh = (modifiedTimeInRanges.high || 0) + diff;
if (newHigh < 0) newHigh = 0;
if (newHigh > 1) newHigh = 1;
modifiedTimeInRanges.high = bankersRound(newHigh, DECIMAL_PRECISION);
return modifiedTimeInRanges;
};
/**
* reconcileTIRDatumValues
* @param {Object} statTIRDatum - the stat TIR datum
* - Should contain the following subfields:
* - data.data - an array of TIR datums for all of the ranges
* - data.total.value - a number representing the total time duration
*
* @returns {Object} a modified stat TIR datum so the percentages add to 100%
*/
export const reconcileTIRDatumValues = (statTIRDatum) => {
// For each of the individual range datums, calculate its percentage of the total
const ranges = {};
const total = statTIRDatum.data?.total?.value;
_.forEach(statTIRDatum.data.data, datum => {
ranges[datum.id] = datum.value / total;
});
// Reconcile the values to ensure the values sum up to 1 (or 100%)
const reconciledTimeInRanges = reconcileTIRPercentages(ranges);
// Multiply the reconciled percentages with the total to get the reconciled datum
// values. We return a modified stat TIR datum with these reconciled values.
const modifiedStatTIRDatum = _.cloneDeep(statTIRDatum);
const rangeKeys = _.keys(reconciledTimeInRanges);
_.forEach(rangeKeys, key => {
const datum = _.find(modifiedStatTIRDatum.data.data, d => d.id === key);
datum.value = reconciledTimeInRanges[key] * total;
});
// Add an indicator that these values are synthetic
modifiedStatTIRDatum.hasSyntheticReadings = true;
return modifiedStatTIRDatum;
};
export const getStatAnnotations = (data, type, opts = {}) => {
const { bgSource, days, manufacturer, bgPrefs } = opts;
const bgUnits = bgPrefs?.bgUnits || MGDL_UNITS;
const minimumIncrement = BG_DISPLAY_MINIMUM_INCREMENTS[bgUnits];
const {
targetUpperBound = DEFAULT_BG_BOUNDS[bgUnits].targetUpperBound,
veryHighThreshold = DEFAULT_BG_BOUNDS[bgUnits].veryHighThreshold,
} = bgPrefs?.bgBounds || {};
const highLowerBound = targetUpperBound + minimumIncrement;
const vocabulary = getPumpVocabulary(manufacturer);
const labels = { overrideLabel: vocabulary[SETTINGS_OVERRIDE], overrideLabelLowerCase: _.lowerCase(vocabulary[SETTINGS_OVERRIDE]) };
const annotations = [];
const bgStats = [
commonStats.averageGlucose,
commonStats.coefficientOfVariation,
commonStats.glucoseManagementIndicator,
commonStats.readingsInRange,
commonStats.timeInRange,
commonStats.standardDev,
];
switch (type) {
case commonStats.averageGlucose:
annotations.push(t('**Avg. Glucose ({{bgSourceLabel}}):** All {{bgSourceLabel}} glucose values added together, divided by the number of readings.', { bgSourceLabel: statBgSourceLabels[bgSource] }));
break;
case commonStats.averageDailyDose:
if (days > 1) {
annotations.push(t('**Avg. Daily Insulin:** All basal and bolus insulin delivery (in Units) added together, divided by the number of days in this view for which we have insulin data.'));
} else {
annotations.push(t('**Daily Insulin:** All basal and bolus insulin delivery (in Units) added together.'));
}
break;
case commonStats.carbs:
if (days > 1) {
annotations.push(t('**Avg. Daily Carbs**: All carb entries added together, then divided by the number of days in this view for which we have carb data. Note, these entries come from either bolus wizard events, or Apple Health records.'));
} else {
annotations.push(t('**Total Carbs**: All carb entries from bolus wizard events or Apple Health records added together.'));
}
annotations.push(t('Derived from _**{{total}}**_ carb entries.', { total: data.total }));
break;
case commonStats.coefficientOfVariation:
annotations.push(t('**CV (Coefficient of Variation):** How far apart (wide) glucose values are; research suggests a target of 36% or lower.'));
break;
case commonStats.glucoseManagementIndicator:
annotations.push(t('**GMI (Glucose Management Indicator):** Tells you what your approximate A1C level is likely to be, based on the average glucose level from your CGM readings.'));
break;
case commonStats.readingsInRange:
annotations.push(t('**Readings In Range:** Daily average of the number of {{smbgLabel}} readings.', { smbgLabel: statBgSourceLabels.smbg }));
break;
case commonStats.sensorUsage:
annotations.push(t('**Sensor Usage:** Time the {{cbgLabel}} collected data, divided by the total time represented in this view.', { cbgLabel: statBgSourceLabels.cbg }));
break;
case commonStats.standardDev:
annotations.push(t('**SD (Standard Deviation):** How far values are from the average.'));
break;
case commonStats.timeInAuto:
if (days > 1) {
annotations.push(t('**Time In {{automatedLabel}}:** Daily average of the time spent in automated basal delivery.', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] }));
annotations.push(t('**How we calculate this:**\n\n**(%)** is the duration in {{automatedLabel}} divided by the total duration of basals for this time period.\n\n**(time)** is 24 hours multiplied by % in {{automatedLabel}}.', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] }));
} else {
annotations.push(t('**Time In {{automatedLabel}}:** Time spent in automated basal delivery.', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] }));
annotations.push(t('**How we calculate this:**\n\n**(%)** is the duration in {{automatedLabel}} divided by the total duration of basals for this time period.\n\n**(time)** is total duration of time in {{automatedLabel}}.', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] }));
}
break;
case commonStats.timeInOverride:
if (days > 1) {
annotations.push(t('**Time In {{overrideLabel}}:** Daily average of the time spent in {{overrideLabelLowerCase}}.', labels));
annotations.push(t('**How we calculate this:**\n\n**(%)** is the duration in {{overrideLabelLowerCase}} divided by the total duration for this time period.\n\n**(time)** is 24 hours multiplied by % in {{overrideLabelLowerCase}}.', labels));
} else {
annotations.push(t('**Time In {{overrideLabel}}:** Time spent in {{overrideLabelLowerCase}}.', labels));
annotations.push(t('**How we calculate this:**\n\n**(%)** is the duration in {{overrideLabelLowerCase}} divided by the total duration for this time period.\n\n**(time)** is total duration of time in {{overrideLabelLowerCase}}.', labels));
}
break;
case commonStats.timeInRange:
if (!!veryHighThreshold) {
annotations.push(t('**Time in Range (TIR):** Percentage of time readings falling within the target range over the selected period.'));
annotations.push(t('**How we calculate this:**\n\n Percentages are calculated using deduplicated data, rounded to the nearest whole percent. In rare cases where rounding causes totals to exceed or fall short of 100%, we add or subtract 1% from the High ({{ highLowerBound }}-{{ veryHighThreshold }} {{ bgUnits }}) category per AGP guidance to maintain consistency.', { veryHighThreshold, highLowerBound, bgUnits }));
} else {
annotations.push(t('**Time in Range (TIR):** Percentage of time readings falling within the target range over the selected period.'));
annotations.push(t('**How we calculate this:**\n\n Percentages are calculated using deduplicated data, rounded to the nearest whole percent. In rare cases where rounding causes totals to exceed or fall short of 100%, we add or subtract 1% from the High (>{{ targetUpperBound }} {{ bgUnits }}) category per AGP guidance to maintain consistency.', { targetUpperBound, bgUnits }));
}
break;
case commonStats.totalInsulin:
if (days > 1) {
annotations.push(t('**Total Insulin:** All basal and bolus insulin delivery (in Units) added together, divided by the number of days in this view for which we have insulin data'));
} else {
annotations.push(t('**Total Insulin:** All basal and bolus insulin delivery (in Units) added together'));
}
annotations.push(t('**How we calculate this:**\n\n**(%)** is the respective total of basal or bolus delivery divided by total insulin delivered for the time period for which we have insulin data.'));
break;
default:
break;
}
if (data.insufficientData) {
annotations.push(t('**Why is this stat empty?**\n\nThere is not enough data present in this view to calculate it.'));
} else if (_.includes(bgStats, type)) {
if (bgSource === 'smbg') {
annotations.push(t('Derived from _**{{total}}**_ {{smbgLabel}} readings.', { total: _.get(data, 'counts.total', data.total), smbgLabel: statBgSourceLabels.smbg }));
}
}
return annotations;
};
export const getStatData = (data, type, opts = {}) => {
const vocabulary = getPumpVocabulary(opts.manufacturer);
const settingsOverrides = getSettingsOverrides(opts.manufacturer);
const bgRanges = generateBgRangeLabels(opts.bgPrefs, { condensed: true });
let statData = {
raw: {
days: opts.days,
...data,
},
};
const readingsInRangeDataPath = opts.days > 1 ? 'dailyAverages' : 'counts';
switch (type) {
case commonStats.averageGlucose:
statData.data = [
{
value: ensureNumeric(data.averageGlucose),
},
];
statData.dataPaths = {
summary: 'data.0',
};
break;
case commonStats.averageDailyDose:
statData.data = [
{
id: 'insulin',
input: {
id: 'weight',
label: 'Weight',
suffix: {
id: 'units',
options: dailyDoseUnitOptions,
value: opts.suffixValue || dailyDoseUnitOptions[0],
},
type: 'number',
value: opts.inputValue ? ensureNumeric(opts.inputValue) : undefined,
},
output: {
label: 'Daily Dose ÷ Weight',
type: 'divisor',
dataPaths: {
dividend: 'data.0',
},
},
value: ensureNumeric(data.totalInsulin),
},
];
statData.dataPaths = {
input: 'data.0.input',
output: 'data.0.output',
summary: 'data.0',
};
break;
case commonStats.bgExtents:
statData.data = [
{
id: 'bgMax',
value: ensureNumeric(data.bgMax),
title: t('Max BG'),
},
{
id: 'bgMin',
value: ensureNumeric(data.bgMin),
title: t('Min BG'),
},
];
break;
case commonStats.carbs:
statData.data = [
{
value: {
grams: ensureNumeric(_.get(data, 'carbs.grams')),
exchanges: ensureNumeric(_.get(data, 'carbs.exchanges')),
},
},
];
statData.dataPaths = {
summary: 'data.0',
};
break;
case commonStats.coefficientOfVariation:
statData.data = [
{
id: 'cv',
value: ensureNumeric(data.coefficientOfVariation),
},
];
statData.dataPaths = {
summary: 'data.0',
};
break;
case commonStats.glucoseManagementIndicator:
statData.data = [
{
id: 'gmi',
value: ensureNumeric(data.glucoseManagementIndicator),
},
{
id: 'gmiAGP',
value: ensureNumeric(data.glucoseManagementIndicatorAGP),
},
];
statData.dataPaths = {
summary: 'data.0',
summaryAGP: 'data.1',
};
break;
case commonStats.readingsInRange:
statData.data = _.filter([
(isRangeDefined(data[readingsInRangeDataPath]?.veryLow) && ({
id: 'veryLow',
value: ensureNumeric(data[readingsInRangeDataPath].veryLow),
title: t('Readings Below Range'),
legendTitle: bgRanges.veryLow,
})),
{
id: 'low',
value: ensureNumeric(data[readingsInRangeDataPath].low),
title: t('Readings Below Range'),
legendTitle: bgRanges.low,
},
{
id: 'target',
value: ensureNumeric(data[readingsInRangeDataPath].target),
title: t('Readings In Range'),
legendTitle: bgRanges.target,
},
{
id: 'high',
value: ensureNumeric(data[readingsInRangeDataPath].high),
title: t('Readings Above Range'),
legendTitle: bgRanges.high,
},
(isRangeDefined(data[readingsInRangeDataPath]?.veryHigh) && ({
id: 'veryHigh',
value: ensureNumeric(data[readingsInRangeDataPath].veryHigh),
title: t('Readings Above Range'),
legendTitle: bgRanges.veryHigh,
})),
], Boolean);
statData.total = { value: getSum(statData.data) };
statData.dataPaths = {
summary: [
'data',
_.findIndex(statData.data, { id: 'target' }),
],
totalReadings: 'raw.counts.total',
averageDailyReadings: 'total',
};
break;
case commonStats.sensorUsage:
statData.data = [
{
value: ensureNumeric(data.sensorUsage),
},
{
value: ensureNumeric(data.sensorUsageAGP),
},
];
statData.total = { value: ensureNumeric(data.total) };
statData.dataPaths = {
summary: 'data.0',
summaryAGP: 'data.1',
};
break;
case commonStats.standardDev:
statData.data = [
{
value: ensureNumeric(data.averageGlucose),
deviation: {
value: ensureNumeric(data.standardDeviation),
},
},
];
statData.dataPaths = {
summary: 'data.0.deviation',
title: 'data.0',
};
break;
case commonStats.timeInAuto:
statData.data = [
{
id: 'basalAutomated',
value: ensureNumeric(data.automated),
title: t('Time In {{automatedLabel}}', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] }),
legendTitle: vocabulary[AUTOMATED_DELIVERY],
},
{
id: 'basal',
value: ensureNumeric(data.manual),
title: t('Time In {{scheduledLabel}}', { scheduledLabel: vocabulary[SCHEDULED_DELIVERY] }),
legendTitle: vocabulary[SCHEDULED_DELIVERY],
},
];
statData.total = { value: getSum(statData.data) };
statData.dataPaths = {
summary: [
'data',
_.findIndex(statData.data, { id: 'basalAutomated' }),
],
};
break;
case commonStats.timeInOverride:
statData.data = _.map(settingsOverrides, override => ({
id: override,
value: ensureNumeric(_.get(data, override, 0)),
title: t('Time In {{overrideLabel}}', { overrideLabel: _.get(vocabulary, [override, 'label']) }),
legendTitle: _.get(vocabulary, [override, 'label']),
}));
statData.sum = { value: getSum(statData.data) };
statData.total = { value: MS_IN_DAY };
statData.dataPaths = {
summary: 'sum',
};
break;
case commonStats.timeInRange:
statData.data = _.filter([
(isRangeDefined(data.durations.veryLow) && ({
id: 'veryLow',
value: ensureNumeric(data.durations.veryLow),
title: t('Time Below Range'),
legendTitle: bgRanges.veryLow,
})),
{
id: 'low',
value: ensureNumeric(data.durations.low),
title: t('Time Below Range'),
legendTitle: bgRanges.low,
},
{
id: 'target',
value: ensureNumeric(data.durations.target),
title: t('Time In Range'),
legendTitle: bgRanges.target,
},
{
id: 'high',
value: ensureNumeric(data.durations.high),
title: t('Time Above Range'),
legendTitle: bgRanges.high,
},
(isRangeDefined(data.durations.veryHigh) && ({
id: 'veryHigh',
value: ensureNumeric(data.durations.veryHigh),
title: t('Time Above Range'),
legendTitle: bgRanges.veryHigh,
})),
], Boolean);
statData.total = { value: getSum(statData.data) };
statData.dataPaths = {
summary: [
'data',
_.findIndex(statData.data, { id: 'target' }),
],
};
break;
case commonStats.totalInsulin:
statData.data = [
{
id: 'insulin',
pattern: {
id: 'diagonalStripes',
color: 'rgba(0,0,0,0.15)',
},
value: ensureNumeric(data.insulin),
title: t('Other Insulin'),
legendTitle: t('Other'),
annotations: [t('**Other:** Insulin logged from a source outside of a connected pump - for example, a manual injection or inhaled dose.')],
hideEmpty: true,
},
{
id: 'bolus',
value: ensureNumeric(data.bolus),
title: t('Bolus Insulin'),
legendTitle: t('Bolus'),
},
{
id: 'basal',
value: ensureNumeric(data.basal),
title: t('Basal Insulin'),
legendTitle: t('Basal'),
},
];
statData.total = { id: 'insulin', value: getSum(statData.data) };
statData.dataPaths = {
summary: 'total',
title: 'total',
};
break;
default:
statData = undefined;
break;
}
return statData;
};
export const getStatTitle = (type, opts = {}) => {
const { bgSource, days } = opts;
const vocabulary = getPumpVocabulary(opts.manufacturer);
const bgTypeLabel = bgSource === 'cbg' ? t('Glucose') : t('BG');
let title;
switch (type) {
case commonStats.averageGlucose:
title = t('Avg. Glucose ({{bgSourceLabel}})', { bgSourceLabel: statBgSourceLabels[bgSource] });
break;
case commonStats.averageDailyDose:
title = (days > 1) ? t('Avg. Daily Insulin') : t('Total Insulin');
break;
case commonStats.bgExtents:
title = t('{{bgTypeLabel}} Extents ({{bgSourceLabel}})', { bgSourceLabel: statBgSourceLabels[bgSource], bgTypeLabel });
break;
case commonStats.carbs:
title = (days > 1) ? t('Avg. Daily Carbs') : t('Total Carbs');
break;
case commonStats.coefficientOfVariation:
title = t('CV ({{bgSourceLabel}})', { bgSourceLabel: statBgSourceLabels[bgSource] });
break;
case commonStats.glucoseManagementIndicator:
title = t('GMI ({{bgSourceLabel}})', { bgSourceLabel: statBgSourceLabels[bgSource] });
break;
case commonStats.readingsInRange:
title = (days > 1) ? t('Avg. Daily Readings In Range') : t('Readings In Range');
break;
case commonStats.sensorUsage:
title = t('Sensor Usage');
break;
case commonStats.standardDev:
title = t('Std. Deviation ({{bgSourceLabel}})', { bgSourceLabel: statBgSourceLabels[bgSource] });
break;
case commonStats.timeInAuto:
title = (days > 1)
? t('Avg. Daily Time In {{automatedLabel}}', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] })
: t('Time In {{automatedLabel}}', { automatedLabel: vocabulary[AUTOMATED_DELIVERY] });
break;
case commonStats.timeInOverride:
title = (days > 1)
? t('Avg. Daily Time In {{overrideLabel}}', { overrideLabel: vocabulary[SETTINGS_OVERRIDE] })
: t('Time In {{overrideLabel}}', { overrideLabel: vocabulary[SETTINGS_OVERRIDE] });
break;
case commonStats.timeInRange:
title = (days > 1) ? t('Avg. Daily Time In Range') : t('Time In Range');
break;
case commonStats.totalInsulin:
title = (days > 1) ? t('Avg. Daily Total Insulin') : t('Total Insulin');
break;
default:
title = '';
break;
}
return title;
};
export const getStatDefinition = (data = {}, type, opts = {}) => {
let stat = {
annotations: getStatAnnotations(data, type, opts),
collapsible: _.get(opts, 'collapsible', false),
data: getStatData(data, type, opts),
id: type,
title: getStatTitle(type, opts),
type: statTypes.barHorizontal,
};
switch (type) {
case commonStats.averageGlucose:
stat.dataFormat = {
label: statFormats.bgValue,
summary: statFormats.bgValue,
};
stat.type = statTypes.barBg;
stat.units = _.get(opts, 'bgPrefs.bgUnits');
break;
case commonStats.averageDailyDose:
stat.alwaysShowSummary = true;
stat.dataFormat = {
output: statFormats.unitsPerKg,
summary: statFormats.units,
};
stat.type = statTypes.input;
break;
case commonStats.bgExtents:
stat.dataFormat = {
label: statFormats.bgValue,
summary: statFormats.bgValue,
};
stat.type = statTypes.simple;
stat.units = _.get(opts, 'bgPrefs.bgUnits');
break;
case commonStats.carbs:
stat.dataFormat = {
summary: statFormats.carbs,
};
stat.type = statTypes.simple;
break;
case commonStats.coefficientOfVariation:
stat.dataFormat = {
summary: statFormats.cv,
};
stat.type = statTypes.simple;
break;
case commonStats.glucoseManagementIndicator:
stat.dataFormat = {
summary: statFormats.gmi,
};
stat.type = statTypes.simple;
break;
case commonStats.readingsInRange:
stat.alwaysShowTooltips = true;
stat.dataFormat = {
label: statFormats.percentage,
summary: statFormats.percentage,
tooltip: statFormats.bgCount,
tooltipTitle: statFormats.bgRange,
count: statFormats.bgCount,
};
stat.legend = true;
stat.hideSummaryUnits = true;
stat.reverseLegendOrder = true;
stat.units = _.get(opts, 'bgPrefs.bgUnits');
break;
case commonStats.sensorUsage:
stat.dataFormat = {
summary: statFormats.percentage,
};
stat.type = statTypes.simple;
break;
case commonStats.standardDev:
stat.dataFormat = {
label: statFormats.standardDevValue,
summary: statFormats.standardDevValue,
title: statFormats.standardDevRange,
};
stat.type = statTypes.barBg;
stat.units = _.get(opts, 'bgPrefs.bgUnits');
break;
case commonStats.timeInAuto:
stat.alwaysShowTooltips = true;
stat.dataFormat = {
label: statFormats.percentage,
summary: statFormats.percentage,
tooltip: statFormats.duration,
};
stat.legend = true;
break;
case commonStats.timeInOverride:
stat.alwaysShowTooltips = true;
stat.dataFormat = {
label: statFormats.percentage,