-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
BgGraphBuilder.java
2373 lines (2072 loc) · 114 KB
/
BgGraphBuilder.java
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
package com.eveningoutpost.dexdrip.UtilityModels;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Toast;
import com.eveningoutpost.dexdrip.AddCalibration;
import com.eveningoutpost.dexdrip.GcmActivity;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.Models.APStatus;
import com.eveningoutpost.dexdrip.Models.BgReading;
import com.eveningoutpost.dexdrip.Models.BloodTest;
import com.eveningoutpost.dexdrip.Models.Calibration;
import com.eveningoutpost.dexdrip.Models.Forecast;
import com.eveningoutpost.dexdrip.Models.Forecast.PolyTrendLine;
import com.eveningoutpost.dexdrip.Models.Forecast.TrendLine;
import com.eveningoutpost.dexdrip.Models.HeartRate;
import com.eveningoutpost.dexdrip.Models.Iob;
import com.eveningoutpost.dexdrip.Models.JoH;
import com.eveningoutpost.dexdrip.Models.Libre2RawValue;
import com.eveningoutpost.dexdrip.Models.Prediction;
import com.eveningoutpost.dexdrip.Models.Profile;
import com.eveningoutpost.dexdrip.Models.StepCounter;
import com.eveningoutpost.dexdrip.Models.Treatments;
import com.eveningoutpost.dexdrip.Models.UserError;
import com.eveningoutpost.dexdrip.R;
import com.eveningoutpost.dexdrip.Services.ActivityRecognizedService;
import com.eveningoutpost.dexdrip.calibrations.CalibrationAbstract;
import com.eveningoutpost.dexdrip.calibrations.PluggableCalibration;
import com.eveningoutpost.dexdrip.insulin.opennov.Options;
import com.eveningoutpost.dexdrip.processing.SmootherFactory;
import com.eveningoutpost.dexdrip.store.FastStore;
import com.eveningoutpost.dexdrip.store.KeyStore;
import com.eveningoutpost.dexdrip.ui.classifier.NoteClassifier;
import com.eveningoutpost.dexdrip.ui.dialog.DoseAdjustDialog;
import com.eveningoutpost.dexdrip.ui.helpers.BitmapLoader;
import com.eveningoutpost.dexdrip.ui.helpers.ColorUtil;
import com.eveningoutpost.dexdrip.utils.DexCollectionType;
import com.eveningoutpost.dexdrip.utils.LibreTrendGraph;
import com.eveningoutpost.dexdrip.utils.math.RollingAverage;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.android.gms.location.DetectedActivity;
import com.rits.cloning.Cloner;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lecho.lib.hellocharts.formatter.LineChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.util.ChartUtils;
import lombok.Getter;
import lombok.val;
import static com.eveningoutpost.dexdrip.Models.JoH.tolerantParseDouble;
import static com.eveningoutpost.dexdrip.UtilityModels.ColorCache.X;
import static com.eveningoutpost.dexdrip.UtilityModels.ColorCache.getCol;
public class BgGraphBuilder {
public static final int FUZZER = (int) (30 * Constants.SECOND_IN_MS);
public final static long DEXCOM_PERIOD = 300_000; // 5 minutes
public final static double NOISE_TRIGGER = 10;
public final static double NOISE_TRIGGER_ULTRASENSITIVE = 1;
public final static double NOISE_TOO_HIGH_FOR_PREDICT = 60;
public final static double NOISE_HIGH = 200;
public final static double NOISE_FORGIVE = 100;
public static double low_occurs_at = -1;
public static double previous_low_occurs_at = -1;
private static double low_occurs_at_processed_till_timestamp = -1;
private static long noise_processed_till_timestamp = -1;
private final static String TAG = "jamorham graph";
//private final static int pluginColor = Color.parseColor("#AA00FFFF"); // temporary
private final static int pluginSize = 2;
final int pointSize;
final int axisTextSize;
final int previewAxisTextSize;
final int hoursPreviewStep;
//private final int numValues = (60 / 5) * 24;
public long end_time = (new Date().getTime() + (60000 * 10)) / FUZZER;
public long predictive_end_time;
public long start_time = end_time - ((60000 * 60 * 24)) / FUZZER;
private final static long timeshift = 500_000;
private static final int MAX_VALUES = 60 * 24;
// flag to indicate if readings data has been adjusted
private static boolean plugin_adjusted = false;
private boolean smoother_adjusted;
// used to prevent concurrency problems with calibration plugins
private static final ReentrantLock readings_lock = new ReentrantLock();
private final List<Treatments> treatments;
private final static boolean d = false; // debug flag, could be read from preferences
private Context context;
private SharedPreferences prefs;
public double highMark;
public double lowMark;
public double defaultMinY;
public double defaultMaxY;
public boolean doMgdl;
public static double capturePercentage = -1;
@Getter
private int predictivehours = 0;
private boolean prediction_enabled = false;
private boolean simulation_enabled = false;
private static double avg1value = 0;
private static double avg2value = 0;
private static int avg1counter = 0;
private static double avg1startfuzzed = 0;
private static int avg2counter = 0;
private final int loaded_numValues;
private final long loaded_start, loaded_end;
private final List<BgReading> bgReadings;
private List<Libre2RawValue> Libre2RawValues;
private final List<Calibration> calibrations;
private final List<BloodTest> bloodtests;
private final List<PointValue> inRangeValues = new ArrayList<>();
private final List<PointValue> backfillValues = new ArrayList<>();
private final List<PointValue> remoteValues = new ArrayList<>();
private final List<PointValue> highValues = new ArrayList<>();
private final List<PointValue> lowValues = new ArrayList<>();
private final List<PointValue> badValues = new ArrayList<>();
private final List<PointValue> pluginValues = new ArrayList<PointValue>();
private final List<PointValue> rawInterpretedValues = new ArrayList<PointValue>();
private final List<PointValue> filteredValues = new ArrayList<PointValue>();
private final List<PointValue> bloodTestValues = new ArrayList<PointValue>();
private final List<PointValue> calibrationValues = new ArrayList<PointValue>();
private final List<PointValue> treatmentValues = new ArrayList<PointValue>();
private final List<PointValue> smbValues = new ArrayList<>();
private final List<PointValue> iconValues = new ArrayList<>();
private final List<PointValue> iobValues = new ArrayList<PointValue>();
private final List<PointValue> cobValues = new ArrayList<PointValue>();
private final List<PointValue> predictedBgValues = new ArrayList<PointValue>();
private final List<PointValue> polyBgValues = new ArrayList<PointValue>();
private final List<PointValue> noisePolyBgValues = new ArrayList<PointValue>();
private final List<PointValue> activityValues = new ArrayList<PointValue>();
private final List<PointValue> annotationValues = new ArrayList<>();
private final Pattern posPattern = Pattern.compile(".*?pos:([0-9.]+).*");
private final boolean hidePriming = Options.hidePrimingDoses();
private static TrendLine noisePoly;
public static double last_noise = -99999;
public static double original_value = -99999;
public static double best_bg_estimate = -99999;
public static double last_bg_estimate = -99999;
private KeyStore keyStore = FastStore.getInstance();
private final boolean showSMB = Pref.getBoolean("show_smb_icons", true);
public BgGraphBuilder(Context context) {
this(context, new Date().getTime() + (60000 * 10));
}
public BgGraphBuilder(Context context, long end) {
this(context, end - (60000 * 60 * 24), end);
}
public BgGraphBuilder(Context context, long start, long end) {
this(context, start, end, MAX_VALUES, true);
}
public BgGraphBuilder(Context context, long start, long end, int numValues, boolean show_prediction) {
this(context, start, end, numValues, show_prediction, false);
}
public BgGraphBuilder(Context context, long start, long end, int numValues, boolean show_prediction, final boolean useArchive) {
// swap argument order if needed
if (start > end) {
long temp = end;
end = start;
start = temp;
if (d) Log.d(TAG, "Swapping timestamps");
}
if (d)
Log.d(TAG, "Called timestamps: " + JoH.dateTimeText(start) + " -> " + JoH.dateTimeText(end));
this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
prediction_enabled = show_prediction;
if (prediction_enabled)
simulation_enabled = prefs.getBoolean("simulations_enabled", true);
end_time = end / FUZZER;
start_time = start / FUZZER;
readings_lock.lock();
try {
// store the initialization values used for this instance
loaded_numValues = numValues;
loaded_start = start;
loaded_end = end;
bgReadings = BgReading.latestForGraph(numValues, start, end);
if (DexCollectionType.getDexCollectionType() == DexCollectionType.LibreReceiver)
Libre2RawValues = Libre2RawValue.latestForGraph(numValues, start, end);
plugin_adjusted = false;
smoother_adjusted = false;
} finally {
readings_lock.unlock();
}
if ((end - start) > 80000000) {
try {
capturePercentage = ((bgReadings.size() * 100) / ((end - start) / 300000));
//Log.d(TAG, "CPTIMEPERIOD: " + Long.toString(end - start) + " percentage: " + JoH.qs(capturePercentage));
} catch (Exception e) {
capturePercentage = -1; // invalid reading
}
}
bloodtests = BloodTest.latestForGraph(numValues, start, end);
// get extra calibrations so we can use them for historical readings
calibrations = Calibration.latestForGraph(numValues, start - (3 * Constants.DAY_IN_MS), end);
treatments = Treatments.latestForGraph(numValues, start, end + (120 * 60 * 1000));
this.context = context;
this.highMark = tolerantParseDouble(prefs.getString("highValue", "170"), 170);
this.lowMark = tolerantParseDouble(prefs.getString("lowValue", "70"), 70);
this.doMgdl = (prefs.getString("units", "mgdl").equals("mgdl"));
defaultMinY = unitized(40);
defaultMaxY = unitized(250);
pointSize = isXLargeTablet(context) ? 5 : 3;
axisTextSize = isXLargeTablet(context) ? 20 : Axis.DEFAULT_TEXT_SIZE_SP;
previewAxisTextSize = isXLargeTablet(context) ? 12 : 5;
hoursPreviewStep = isXLargeTablet(context) ? 2 : 1;
}
private double bgScale() {
if (doMgdl)
return Constants.MMOLL_TO_MGDL;
else
return 1;
}
static public boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
static public boolean isLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public static double mmolConvert(double mgdl) {
return mgdl * Constants.MGDL_TO_MMOLL;
}
public static String noiseString(double thisnoise) {
if (thisnoise > NOISE_HIGH) return "Extreme";
if (thisnoise > NOISE_TOO_HIGH_FOR_PREDICT) return "Very High";
if (thisnoise > NOISE_TRIGGER) return "High";
if (thisnoise > NOISE_TRIGGER_ULTRASENSITIVE && Pref.getBooleanDefaultFalse("engineering_mode") && Pref.getBooleanDefaultFalse("bg_compensate_noise_ultrasensitive"))
return "Some";
return "Low";
}
private void extend_line(List<PointValue> points, double x, float y) {
if (points.size() > 1) {
points.remove(1); // replace last
}
points.add(new HPointValue(x, y));
Log.d(TAG, "Extend line size: " + points.size());
}
private List<Line> predictiveLines() {
final List<Line> lines = new LinkedList<>();
final boolean g_prediction = Pref.getBooleanDefaultFalse("show_g_prediction");
final boolean medtrum = Pref.getBooleanDefaultFalse("show_medtrum_secondary");
if (medtrum || g_prediction) {
final List<Prediction> plist = Prediction.latestForGraph(4000, loaded_start, loaded_end);
if (plist.size() > 0) {
final List<PointValue> gpoints = new ArrayList<>(plist.size());
final float yscale = !doMgdl ? (float) Constants.MGDL_TO_MMOLL : 1f;
for (Prediction p : plist) {
switch (p.source) {
case "EGlucoseRx":
final PointValue point = new HPointValue(((double) (p.timestamp + (Constants.MINUTE_IN_MS * 10)) / FUZZER), (float) (p.glucose * yscale));
gpoints.add(point);
break;
case "Medtrum2nd":
final PointValue mpoint = new HPointValue(((double) p.timestamp / FUZZER), (float) (p.glucose * yscale));
gpoints.add(mpoint);
break;
}
}
if (gpoints.size() > 0) {
lines.add(new Line(gpoints)
.setHasLabels(false)
.setHasPoints(true)
.setHasLines(false)
.setPointRadius(1)
.setColor(ChartUtils.darkenColor(ChartUtils.darkenColor(getCol(X.color_predictive)))));
}
}
}
return lines;
}
private List<Line> basalLines() {
final List<Line> basalLines = new ArrayList<>();
if (prefs.getBoolean("show_basal_line", false)) {
final float yscale = doMgdl ? (float) Constants.MMOLL_TO_MGDL : 1f;
final List<APStatus> aplist = APStatus.latestForGraph(2000, loaded_start, loaded_end);
if (aplist.size() > 0) {
// divider line
final Line dividerLine = new Line();
dividerLine.setTag("tbr"); // not quite true
dividerLine.setHasPoints(false);
dividerLine.setHasLines(true);
dividerLine.setStrokeWidth(1);
dividerLine.setColor(getCol(X.color_basal_tbr));
dividerLine.setPathEffect(new DashPathEffect(new float[]{10.0f, 10.0f}, 0));
dividerLine.setReverseYAxis(true);
dividerLine.setHasPoints(false);
final float one_hundred_percent = (100 * yscale) / 100f;
final List<PointValue> divider_points = new ArrayList<>(2);
divider_points.add(new HPointValue(loaded_start / FUZZER, one_hundred_percent));
dividerLine.setPointRadius(0);
divider_points.add(new HPointValue(loaded_end / FUZZER, one_hundred_percent));
dividerLine.setValues(divider_points);
basalLines.add(dividerLine);
final List<PointValue> points = new ArrayList<>(aplist.size());
int last_percent = -1;
int count = aplist.size();
for (APStatus item : aplist) {
if (--count == 0 || (item.basal_percent != last_percent)) {
final float this_ypos = (Math.min(item.basal_percent, 500) * yscale) / 100f; // capped at 500%
points.add(new HPointValue((double) item.timestamp / FUZZER, this_ypos));
last_percent = item.basal_percent;
}
}
final Line line = new Line(points);
line.setFilled(true);
line.setFillFlipped(true);
line.setHasGradientToTransparent(true);
line.setHasPoints(false);
line.setStrokeWidth(1);
line.setHasLines(true);
line.setSquare(true);
line.setPointRadius(1);
line.setReverseYAxis(true);
line.setBackgroundUnclipped(true);
line.setGradientDivider(10f);
line.setColor(getCol(X.color_basal_tbr));
basalLines.add(line);
}
}
return basalLines;
}
// line illustrating result from step counter
private List<Line> stepsLines() {
final List<Line> stepsLines = new ArrayList<>();
if ((prefs.getBoolean("use_pebble_health", true)
&& prefs.getBoolean("show_pebble_movement_line", true))) {
final List<StepCounter> pmlist = StepCounter.deltaListFromMovementList(StepCounter.latestForGraph(2000, loaded_start, loaded_end));
PointValue last_point = null;
final boolean d = false;
if (d) Log.d(TAG, "Delta: pmlist size: " + pmlist.size());
final float yscale = doMgdl ? (float) Constants.MMOLL_TO_MGDL : 1f;
final float ypos = 6 * yscale; // TODO Configurable
//final long last_timestamp = pmlist.get(pmlist.size() - 1).timestamp;
final float MAX_SIZE = 50;
int flipper = 0;
int accumulator = 0;
for (StepCounter pm : pmlist) {
if (last_point == null) {
last_point = new HPointValue((double) pm.timestamp / FUZZER, ypos);
} else {
final PointValue this_point = new HPointValue((double) pm.timestamp / FUZZER, ypos);
final double time_delta = this_point.getX() - last_point.getX();
if (time_delta > 1) {
final List<PointValue> new_points = new ArrayList<>();
new_points.add(last_point);
new_points.add(this_point);
last_point = this_point; // update pointer
final Line this_line = new Line(new_points);
flipper ^= 1;
this_line.setColor((flipper == 0) ? getCol(X.color_step_counter1) : getCol(X.color_step_counter2));
float stroke_size = Math.min(MAX_SIZE, (float) Math.log1p(((double) (pm.metric + accumulator)) / time_delta) * 4);
if (d) Log.d(TAG, "Delta stroke: " + stroke_size);
this_line.setStrokeWidth((int) stroke_size);
if (d)
Log.d(TAG, "Delta-Line: " + JoH.dateTimeText(pm.timestamp) + " time delta: " + time_delta + " total: " + (pm.metric + accumulator) + " lsize: " + stroke_size + " / " + (int) stroke_size);
accumulator = 0;
if (this_line.getStrokeWidth() > 0) {
stepsLines.add(this_line);
this_line.setHasPoints(false);
this_line.setHasLines(true);
} else {
if (d) Log.d(TAG, "Delta skip: " + JoH.dateTimeText(pm.timestamp));
}
if (d)
Log.d(TAG, "Delta-List: " + JoH.dateTimeText(pm.timestamp) + " time delta: " + time_delta + " val: " + pm.metric);
} else {
accumulator += pm.metric;
if (d)
Log.d(TAG, "Delta: added: " + JoH.dateTimeText(pm.timestamp) + " metric: " + pm.metric + " to accumulator: " + accumulator);
}
}
}
if (d)
Log.d(TAG, "Delta returning stepsLines: " + stepsLines.size() + " final accumulator remaining: " + accumulator);
}
return stepsLines;
}
// line illustrating result from heartrate monitor
private List<Line> heartLines() {
final boolean d = false;
final List<Line> heartLines = new ArrayList<>();
if ((prefs.getBoolean("use_pebble_health", true)
&& prefs.getBoolean("show_pebble_movement_line", true))) {
final List<HeartRate> heartRates = HeartRate.latestForGraph(2000, loaded_start, loaded_end);
// final long condenseCutoffMs = Pref.getBooleanDefaultFalse("smooth_heartrate") ? (10 * Constants.MINUTE_IN_MS) : FUZZER;
final long condenseCutoffMs = Pref.getBooleanDefaultFalse("smooth_heartrate") ? (10 * Constants.MINUTE_IN_MS) : 1000 * 30 * 5;
final List<HeartRate> condensedHeartRateList = new ArrayList<>();
for (HeartRate thisHeartRateRecord : heartRates) {
final int condensedListSize = condensedHeartRateList.size();
if (condensedListSize > 0) {
final HeartRate tailOfList = condensedHeartRateList.get(condensedListSize - 1);
// if its close enough to merge then average with previous
if ((thisHeartRateRecord.timestamp - tailOfList.timestamp) < condenseCutoffMs) {
tailOfList.bpm = (tailOfList.bpm += thisHeartRateRecord.bpm) / 2;
} else {
// not close enough to merge
condensedHeartRateList.add(thisHeartRateRecord);
}
} else {
condensedHeartRateList.add(thisHeartRateRecord); // first record
}
}
if (d) Log.d(TAG, "heartrate before size: " + heartRates.size());
if (d) Log.d(TAG, "heartrate after c size: " + condensedHeartRateList.size());
//final float yscale = doMgdl ? (float) Constants.MMOLL_TO_MGDL : 1f;
final float yscale = doMgdl ? 10f : 1f;
float ypos; //
final List<PointValue> new_points = new ArrayList<>();
if (d) UserError.Log.d("HEARTRATE", "Size " + condensedHeartRateList.size());
for (HeartRate pm : condensedHeartRateList) {
if (d)
UserError.Log.d("HEARTRATE: ", JoH.dateTimeText(pm.timestamp) + " \tHR: " + pm.bpm);
ypos = (pm.bpm * yscale) / 10;
final PointValue this_point = new HPointValue((double) pm.timestamp / FUZZER, ypos);
new_points.add(this_point);
}
final Line macroHeartRateLine = new Line(new_points);
for (Line this_line : autoSplitLine(macroHeartRateLine, 30)) {
this_line.setColor(getCol(X.color_heart_rate1));
this_line.setStrokeWidth(6);
this_line.setHasPoints(false);
this_line.setHasLines(true);
this_line.setCubic(true);
heartLines.add(this_line);
}
}
return heartLines;
}
private List<Line> motionLine() {
final ArrayList<ActivityRecognizedService.motionData> motion_datas = ActivityRecognizedService.getForGraph((long) start_time * FUZZER, (long) end_time * FUZZER);
List<PointValue> linePoints = new ArrayList<>();
final float ypos = (float) highMark;
int last_type = -9999;
final ArrayList<Line> line_array = new ArrayList<>();
Log.d(TAG, "Motion datas size: " + motion_datas.size());
if (motion_datas.size() > 0) {
motion_datas.add(new ActivityRecognizedService.motionData((long) end_time * FUZZER, DetectedActivity.UNKNOWN)); // terminator
for (ActivityRecognizedService.motionData item : motion_datas) {
Log.d(TAG, "Motion detail: " + JoH.dateTimeText(item.timestamp) + " activity: " + item.activity);
if ((last_type != -9999) && (last_type != item.activity)) {
extend_line(linePoints, (double)item.timestamp / FUZZER, ypos);
Line new_line = new Line(linePoints);
new_line.setHasLines(true);
new_line.setPointRadius(0);
new_line.setStrokeWidth(1);
new_line.setAreaTransparency(40);
new_line.setHasPoints(false);
new_line.setFilled(true);
switch (last_type) {
case DetectedActivity.IN_VEHICLE:
new_line.setColor(Color.parseColor("#70445599"));
break;
case DetectedActivity.ON_FOOT:
new_line.setColor(Color.parseColor("#70995599"));
break;
}
line_array.add(new_line);
linePoints = new ArrayList<>();
}
//current
switch (item.activity) {
case DetectedActivity.ON_FOOT:
case DetectedActivity.IN_VEHICLE:
extend_line(linePoints, (double)(item.timestamp / FUZZER), ypos);
last_type = item.activity;
break;
default:
// do nothing?
break;
}
}
}
Log.d(TAG, "Motion array size: " + line_array.size());
return line_array;
}
public LineChartData lineData() {
// if (d) Log.d(TAG, "START lineData from: " + JoH.backTrace());
JoH.benchmark(null);
LineChartData lineData = new LineChartData(defaultLines(false));
JoH.benchmark("Default lines create - bggraph builder");
lineData.setAxisYLeft(yAxis());
lineData.setAxisXBottom(chartXAxis());
return lineData;
}
public LineChartData previewLineData(LineChartData hint) {
LineChartData previewLineData;
if (hint == null) {
previewLineData = new LineChartData(lineData());
} else {
JoH.benchmark(null);
Cloner cloner = new Cloner();
// cloner.setDumpClonedClasses(true);
cloner.dontClone(
lecho.lib.hellocharts.model.PointValue.class,
lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter.class,
lecho.lib.hellocharts.model.Axis.class,
android.graphics.DashPathEffect.class);
previewLineData = cloner.deepClone(hint);
JoH.benchmark("Clone preview data");
if (d) Log.d(TAG, "Cloned preview chart data");
}
previewLineData.setAxisYLeft(yAxis());
previewLineData.setAxisXBottom(previewXAxis());
// reduce complexity of preview chart by removing some lines
final List<Line> removeItems = new ArrayList<>();
int unlabledLinesSize = 1;
if (isXLargeTablet(context)) {
unlabledLinesSize = 2;
}
for (Line lline : previewLineData.getLines()) {
if (((lline.getPointRadius() == pluginSize) && (lline.getPointColor() == getCol(X.color_secondary_glucose_value)))
|| ((lline.getColor() == getCol(X.color_step_counter1) || (lline.getColor() == getCol(X.color_step_counter2) || (lline.getColor() == getCol(X.color_heart_rate1)))))) {
removeItems.add(lline); // remove plugin or step counter plot from preview graph
}
if ((lline.hasLabels() && (lline.getPointRadius() > 0))) {
lline.setPointRadius(3); // preserve size for treatments
lline.setPointColor(Color.parseColor("#FFFFFF"));
} else if (lline.getPointRadius() > 0) {
lline.setPointRadius(unlabledLinesSize);
}
lline.setHasLabels(false);
}
for (Line item : removeItems) {
previewLineData.getLines().remove(item);
}
for (Line item : previewLineData.getLines()) {
switch (item.getTag()) {
case "smb":
case "icon":
item.setBitmapScale(item.getBitmapScale() / 3);
break;
}
}
// needs more adjustments - foreach
return previewLineData;
}
public synchronized List<Line> defaultLines(boolean simple) {
List<Line> lines = new ArrayList<Line>();
try {
addBgReadingValues(simple);
if (!simple) {
// motion lines
if (Pref.getBoolean("motion_tracking_enabled", false) && Pref.getBoolean("plot_motion", false)) {
lines.addAll(motionLine());
}
lines.addAll(basalLines());
lines.addAll(heartLines());
lines.addAll(stepsLines());
lines.addAll(predictiveLines());
}
Line[] calib = calibrationValuesLine();
Line[] treatments = treatmentValuesLine();
for (Line subLine : autoSplitLine(treatments[2], 10)) {
lines.add(subLine); // iob line
}
predictive_end_time = simple ? end_time : ((end_time * FUZZER) + (60000 * 10) + (Constants.HOUR_IN_MS * predictivehours)) / FUZZER; // used first in ideal/highline
// predictive_end_time = (new Date().getTime() + (60000 * 10) + (1000 * 60 * 60 * predictivehours)) / FUZZER; // used first in ideal/highline
if (prefs.getBoolean("show_full_average_line", false)) {
if (avg2value > 0) lines.add(avg2Line());
}
if (prefs.getBoolean("show_recent_average_line", true)) {
if (avg1value > 0) lines.add(avg1Line());
}
if (prefs.getBoolean("show_target_line", false)) {
lines.add(idealLine());
}
lines.add(treatments[3]); // activity
lines.add(treatments[5]); // predictive
lines.add(treatments[6]); // cob
lines.add(treatments[7]); // poly predict
if (prefs.getBoolean("show_libre_trend_line", false)) {
if (DexCollectionType.hasLibre()) {
lines.add(libreTrendLine());
}
}
lines.add(minShowLine());
lines.add(maxShowLine());
lines.add(highLine());
lines.add(predictiveHighLine());
lines.add(lowLine());
lines.add(predictiveLowLine());
if (prefs.getBoolean("show_filtered_curve", true)) {
// use autosplit here too
final ArrayList<Line> filtered_lines = filteredLines();
for (Line thisline : filtered_lines) {
lines.add(thisline);
}
}
lines.add(rawInterpretedLine());
lines.add(remoteValuesLine()); // TODO conditional ?
lines.add(backFillValuesLine()); // TODO conditional ?
lines.add(badValuesLine());
lines.add(inRangeValuesLine());
lines.add(lowValuesLine());
lines.add(highValuesLine());
List<Line> extra_lines = extraLines();
for (Line eline : extra_lines) {
lines.add(eline);
}
// check show debug option here - drawn on top of others
lines.add(treatments[8]); // noise poly predict
if (showSMB) {
lines.addAll(smbLines());
}
lines.addAll(iconLines());
lines.add(calib[0]); // white circle of calib in background
lines.add(treatments[0]); // white circle of treatment in background
lines.add(calib[1]); // red dot of calib in foreground
lines.add(treatments[1]); // blue dot in centre // has annotation
lines.add(treatments[4]); // annotations
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Error in bgbuilder defaultlines: " + e.toString());
}
return lines;
}
public Line highValuesLine() {
Line highValuesLine = new Line(highValues);
//highValuesLine.setColor(ChartUtils.COLOR_ORANGE);
highValuesLine.setColor(getCol(X.color_high_values));
highValuesLine.setHasLines(false);
highValuesLine.setPointRadius(pointSize);
highValuesLine.setHasPoints(true);
return highValuesLine;
}
public Line badValuesLine() {
Line badValuesLine = new Line(badValues);
badValuesLine.setColor(getCol(X.color_bad_values));
badValuesLine.setHasLines(false);
badValuesLine.setPointRadius(pointSize);
badValuesLine.setHasPoints(true);
return badValuesLine;
}
public Line lowValuesLine() {
Line lowValuesLine = new Line(lowValues);
//lowValuesLine.setColor(Color.parseColor("#C30909"));
lowValuesLine.setColor(getCol(X.color_low_values));
lowValuesLine.setHasLines(false);
lowValuesLine.setPointRadius(pointSize);
lowValuesLine.setHasPoints(true);
return lowValuesLine;
}
public Line inRangeValuesLine() {
Line inRangeValuesLine = new Line(inRangeValues);
//inRangeValuesLine.setColor(ChartUtils.COLOR_BLUE);
inRangeValuesLine.setColor(getCol(X.color_inrange_values));
inRangeValuesLine.setHasLines(false);
inRangeValuesLine.setPointRadius(pointSize);
inRangeValuesLine.setHasPoints(true);
return inRangeValuesLine;
}
private Line backFillValuesLine() {
final Line line = new Line(backfillValues);
line.setColor(Color.parseColor("#55338833"));
line.setHasLines(false);
line.setPointRadius(pointSize + 3);
line.setHasPoints(true);
return line;
}
private Line remoteValuesLine() {
final Line line = new Line(remoteValues);
line.setColor(Color.parseColor("#55333388"));
line.setHasLines(false);
line.setPointRadius(pointSize + 4);
line.setHasPoints(true);
return line;
}
public void debugPrintPoints(List<PointValue> mypoints) {
for (PointValue thispoint : mypoints) {
UserError.Log.i(TAG, "Debug Points: " + thispoint.toString());
}
}
// auto split a line - jump thresh in minutes
public ArrayList<Line> autoSplitLine(Line macroline, final float jumpthresh) {
// if (d) Log.d(TAG, "Enter autoSplit Line");
ArrayList<Line> linearray = new ArrayList<Line>();
double lastx = -999999;
List<PointValue> macropoints = macroline.getValues();
List<PointValue> thesepoints = new ArrayList<PointValue>();
if (macropoints.size() > 0) {
final double endmarker = macropoints.get(macropoints.size() - 1).getX();
for (PointValue thispoint : macropoints) {
// a jump too far for a line? make it a new one
if (((lastx != -999999) && (Math.abs(thispoint.getX() - lastx) > jumpthresh))
|| thispoint.getX() == endmarker) {
if (thispoint.getX() == endmarker) {
thesepoints.add(thispoint);
}
Line line = (Line) JoH.cloneObject(macroline); // aieeee
line.setValues(thesepoints);
linearray.add(line);
thesepoints = new ArrayList<PointValue>();
}
lastx = thispoint.getX();
thesepoints.add(thispoint); // grow current line list
}
}
// if (d) Log.d(TAG, "Exit autoSplit Line");
return linearray;
}
// Produce an array of cubic lines, split as needed
public ArrayList<Line> filteredLines() {
ArrayList<Line> linearray = new ArrayList<Line>();
double lastx = -999999; // bogus mark value
double jumpthresh = 15; // in minutes
List<PointValue> thesepoints = new ArrayList<PointValue>();
if (filteredValues.size() > 0) {
final double endmarker = filteredValues.get(filteredValues.size() - 1).getX();
for (PointValue thispoint : filteredValues) {
// a jump too far for a line? make it a new one
if (((lastx != -999999) && (Math.abs(thispoint.getX() - lastx) > jumpthresh))
|| thispoint.getX() == endmarker) {
Line line = new Line(thesepoints);
line.setHasPoints(true);
line.setPointRadius(2);
line.setStrokeWidth(1);
line.setColor(getCol(X.color_filtered));
line.setCubic(true);
line.setHasLines(true);
linearray.add(line);
thesepoints = new ArrayList<PointValue>();
}
lastx = thispoint.getX();
thesepoints.add(thispoint); // grow current line list
}
} else {
UserError.Log.i(TAG, "Raw points size is zero");
}
//UserError.Log.i(TAG, "Returning linearray: " + Integer.toString(linearray.size()));
return linearray;
}
public Line rawInterpretedLine() {
Line line = new Line(rawInterpretedValues);
line.setHasLines(false);
line.setPointRadius(1);
line.setHasPoints(true);
return line;
}
public List<Line> extraLines() {
final List<Line> lines = new ArrayList<>();
Line line = new Line(pluginValues);
line.setHasLines(false);
line.setPointRadius(pluginSize);
line.setHasPoints(true);
line.setColor(getCol(X.color_secondary_glucose_value));
lines.add(line);
Line bloodtest = new Line(bloodTestValues);
bloodtest.setHasLines(false);
bloodtest.setPointRadius(pointSize * 3 / 2);
bloodtest.setHasPoints(true);
bloodtest.setColor(ChartUtils.darkenColor(getCol(X.color_calibration_dot_background)));
bloodtest.setShape(ValueShape.SQUARE);
lines.add(bloodtest);
Line bloodtesti = new Line(bloodTestValues);
bloodtesti.setHasLines(false);
bloodtesti.setPointRadius(pointSize * 3 / 4);
bloodtesti.setHasPoints(true);
bloodtesti.setColor(ChartUtils.darkenColor(getCol(X.color_calibration_dot_foreground)));
bloodtesti.setShape(ValueShape.SQUARE);
lines.add(bloodtesti);
return lines;
}
public Line[] calibrationValuesLine() {
Line[] lines = new Line[2];
lines[0] = new Line(calibrationValues);
lines[0].setColor(getCol(X.color_calibration_dot_background));
lines[0].setHasLines(false);
lines[0].setPointRadius(pointSize * 3 / 2);
lines[0].setHasPoints(true);
lines[1] = new Line(calibrationValues);
lines[1].setColor(getCol(X.color_calibration_dot_foreground));
lines[1].setHasLines(false);
lines[1].setPointRadius(pointSize * 3 / 4);
lines[1].setHasPoints(true);
return lines;
}
public Line[] treatmentValuesLine() {
Line[] lines = new Line[9];
try {
lines[0] = new Line(treatmentValues);
lines[0].setColor(getCol(X.color_treatment_dot_background));
lines[0].setHasLines(false);
lines[0].setPointRadius(pointSize * 5 / 2);
lines[0].setHasPoints(true);
lines[1] = new Line(treatmentValues);
lines[1].setColor(getCol(X.color_treatment_dot_foreground));
lines[1].setHasLines(false);
lines[1].setPointRadius(pointSize * 5 / 4);
lines[1].setHasPoints(true);
lines[1].setShape(ValueShape.DIAMOND);
lines[1].setHasLabels(true);
LineChartValueFormatter formatter = new SimpleLineChartValueFormatter(1);
lines[1].setFormatter(formatter);
// insulin on board
lines[2] = new Line(iobValues);
lines[2].setColor(getCol(X.color_treatment));
// need splitter for cubics
lines[2].setHasLines(true);
lines[2].setCubic(false);
lines[2].setFilled(true);
lines[2].setAreaTransparency(35);
lines[2].setFilled(true);
lines[2].setPointRadius(1);
lines[2].setHasPoints(true);
// lines[2].setShape(ValueShape.DIAMOND);
// lines[2].setHasLabels(true);
// iactivity on board
lines[3] = new Line(activityValues);
lines[3].setColor(getCol(X.color_treatment_dark));
lines[3].setHasLines(false);
lines[3].setCubic(false);
lines[3].setFilled(false);
lines[3].setFilled(false);
lines[3].setPointRadius(1);
lines[3].setHasPoints(true);
// annotations
lines[4] = new Line(annotationValues);
lines[4].setColor(getCol(X.color_treatment_dot_foreground));
lines[4].setHasLines(false);
lines[4].setCubic(false);
lines[4].setFilled(false);
lines[4].setPointRadius(0);
lines[4].setHasPoints(true);
lines[4].setHasLabels(true);
lines[5] = new Line(predictedBgValues);
lines[5].setColor(getCol(X.color_predictive));
lines[5].setHasLines(false);
lines[5].setCubic(false);
lines[5].setStrokeWidth(1);
lines[5].setFilled(false);
lines[5].setPointRadius(2);
lines[5].setHasPoints(true);
lines[5].setHasLabels(false);