-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyPlot.cpp
1467 lines (1217 loc) · 53.8 KB
/
MyPlot.cpp
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
#include "PlotCtrl.h"
#include "MobiView2.h"
#include "Statistics.h"
using namespace Upp;
std::vector<Color> Plot_Colors::colors = {{0, 130, 200}, {230, 25, 75}, {245, 130, 48}, {145, 30, 180}, {60, 180, 75},
{70, 240, 240}, {240, 50, 230}, {210, 245, 60}, {250, 190, 190}, {0, 128, 128}, {230, 190, 255},
{170, 110, 40}, {128, 0, 0}, {170, 255, 195}, {128, 128, 0}, {255, 215, 180}, {0, 0, 128}, {255, 225, 25}};
MyPlot::MyPlot() {
//SetFastViewX(true); Can't be used with scatter plot data since it combines points.
//SetSequentialXAll(true); // NOTE: with this on, lines that clip the plot area to the left
//are culled :( . Doesn't seem to matter that much to speed though, so just leave it off?
Size plot_reticle_size = GetTextSize("00000000", GetReticleFont());
Size plot_unit_size = GetTextSize("[dummy]", GetLabelsFont());
SetPlotAreaLeftMargin(plot_reticle_size.cx + plot_unit_size.cy + 20);
SetPlotAreaBottomMargin(plot_reticle_size.cy*2 + plot_unit_size.cy + 20);
SetGridDash("");
Color grey(180, 180, 180);
SetGridColor(grey);
RemoveMouseBehavior(ScatterCtrl::ZOOM_WINDOW);
RemoveMouseBehavior(ScatterCtrl::SHOW_INFO);
AddMouseBehavior(true, false, false, true, false, 0, false, ScatterCtrl::SHOW_INFO);
AddMouseBehavior(false, false, false, true, false, 0, false, ScatterCtrl::SCROLL);
AddMouseBehavior(false, false, false, false, true, 0, false, ScatterCtrl::SCROLL);
SetRainbowPalettePos({50, 10});
}
void MyPlot::clean(bool full_clean) {
//TODO
RemoveAllSeries();
RemoveSurf();
colors.reset();
x_data.clear();
data_stacked.clear();
profile.clear();
profile2D.clear();
profile2Dt.clear();
profile2D_is_timed = false;
histogram.Clear();
series_data.Clear();
SetTitle("");
SetLabelX(" ");
SetLabelY(" ");
labels.Clear();
labels2.Clear();
if(full_clean)
was_auto_resized = false;
}
void MyPlot::compute_x_data(Date_Time start, s64 steps, Time_Step_Size ts_size) {
x_data.resize(steps);
Expanded_Date_Time dt(start, ts_size);
for(s64 step = 0; step < steps; ++step) {
x_data[step] = (double)(dt.date_time.seconds_since_epoch - start.seconds_since_epoch);
dt.advance();
}
}
void format_plot(MyPlot *draw, Var_Id::Type type, DataSource *data, Color &color, String &legend, String &unit) {
draw->Legend(legend).Units(unit);
bool scatter = false;
if(type != Var_Id::Type::state_var && draw->setup.scatter_inputs) {
bool prev_prev_valid = false;
bool prev_valid = false;
// See if there are any isolated points.
for(int64 id = 0; id < data->GetCount(); ++id) {
double y = data->y(id);
bool valid = std::isfinite(y);
bool edge = id==0 || id==data->GetCount()-1;
if(!valid && prev_valid && (edge || !prev_prev_valid)) {
scatter = true;
break;
}
prev_prev_valid = prev_valid;
prev_valid = valid;
}
}
if(!scatter)
draw->NoMark().Stroke(1.5, color).Dash("");
else {
draw->MarkBorderColor(color).Stroke(0.0, color).Opacity(0.5).MarkStyle<CircleMarkPlot>();
int index = draw->GetCount()-1;
draw->SetMarkColor(index, Null); //NOTE: Calling draw->MarkColor(Null) does not make it transparent, so we have to do it like this.
}
}
bool add_single_plot(MyPlot *draw, Model_Data *md, Model_Application *app, Var_Id var_id, Indexes &indexes,
s64 ts, Date_Time ref_x_start, Date_Time start, double *x_data, s64 gof_offset, s64 gof_ts, Color &color, bool stacked,
const String &legend_prefix, bool always_copy_y) {
if(!app->index_data.are_in_bounds(indexes)) return true;
if(draw->GetCount() == 100) {
draw->SetTitle("Warning: only displaying the 100 first selected series");
return false;
}
auto *data = &md->get_storage(var_id.type);
auto var = app->vars[var_id];
s64 offset = data->structure->get_offset(var_id, indexes);
String unit_str;
if(draw->setup.y_axis_mode == Y_Axis_Mode::normalized)
unit_str = "(normalized)";
else {
auto unit = var->unit;
if(draw->setup.aggregation_type == Aggregation_Type::sum)
unit = unit_of_sum(var->unit, app->time_step_unit, draw->setup.aggregation_period);
unit_str = unit.to_utf8();
}
String legend = String(var->name) + " " + make_index_string(data->structure, indexes, var_id) + "[" + unit_str + "]";
if(!IsNull(legend_prefix))
legend = legend_prefix + legend;
// Don't plot a nonexisting series. TODO: This didn't work as intended Have to start scan at
// between ref start and start?
// Also can be annoying for the user if they click a series and nothing happens. Better if
// it was just blank, but that is bugged.
/*bool found = false;
for(s64 t = 0; t < ts; ++t) {
if(std::isfinite(*data->get_value(offset, t))) {
found = true;
break;
}
}
if(!found) return true;
*/
draw->series_data.Create<Agg_Data_Source>(data, offset, ts, x_data, ref_x_start, start, app->time_step_size, &draw->setup, always_copy_y);
if(stacked) {
draw->data_stacked.Add(draw->series_data.Top());
draw->AddSeries(draw->data_stacked.top()).Fill(color);
} else
draw->AddSeries(draw->series_data.Top());
format_plot(draw, var_id.type, &draw->series_data.Top(), color, legend, unit_str);
if(draw->plot_info) {
Time_Series_Stats stats;
compute_time_series_stats(&stats, &draw->parent->stat_settings.settings, data, offset, gof_offset, gof_ts);
display_statistics(draw->plot_info, &draw->parent->stat_settings.display_settings, &stats, color, legend);
}
return true;
}
std::vector<Index_T> *
get_selected_indexes(Mobius_Model *model, Plot_Setup *setup, Entity_Id index_set_id) {
if(setup->index_set_is_active[index_set_id.id])
return &setup->selected_indexes[index_set_id.id];
auto index_set = model->index_sets[index_set_id];
for(auto other_id : index_set->union_of) {
if(setup->index_set_is_active[other_id.id])
return &setup->selected_indexes[other_id.id];
}
return nullptr;
}
void
get_single_indexes(Model_Application *app, Indexes &indexes, Plot_Setup &setup) {
if(indexes.lookup_ordered)
fatal_error(Mobius_Error::internal, "Can't use get_single_indexes with lookup ordered indexes");
//indexes.clear(); // Probably unnecessary since we only use it for newly constructed ones
for(auto id : app->model->index_sets) {
auto selected = get_selected_indexes(app->model, &setup, id);
if(selected && !selected->empty()) {
auto index = (*selected)[0];
if(id != index.index_set)
index = app->index_data.raise(index, id);
indexes.set_index(index);
}
}
}
bool add_plot_recursive(MyPlot *draw, Model_Application *app, Var_Id var_id, Indexes &indexes, int level,
Date_Time ref_x_start, Date_Time start, s64 time_steps, double *x_data, const std::vector<Entity_Id> &index_sets, s64 gof_offset, s64 gof_ts, Plot_Mode mode, int found_count = 0) {
if(level == indexes.indexes.size() || found_count == index_sets.size()) {
bool stacked = var_id.type == Var_Id::Type::state_var && (mode == Plot_Mode::stacked || mode == Plot_Mode::stacked_share);
Color &graph_color = draw->colors.next();
bool success = add_single_plot(draw, &app->data, app, var_id, indexes, time_steps,
ref_x_start, start, x_data, gof_offset, gof_ts, graph_color, stacked);
return success;
} else {
auto index_set_id = Entity_Id {Reg_Type::index_set, (s16)level };
auto selected = get_selected_indexes(app->model, &draw->setup, index_set_id);
bool loop = false;
if(selected && !selected->empty())
loop = std::find(index_sets.begin(), index_sets.end(), index_set_id) != index_sets.end();
if(!loop) {
indexes.indexes[level] = invalid_index;
return add_plot_recursive(draw, app, var_id, indexes, level+1, ref_x_start, start, time_steps, x_data, index_sets, gof_offset, gof_ts, mode, found_count);
} else {
for(Index_T index : *selected) {
//log_print("Index set is ", app->model->index_sets[index.index_set]->name, "\n");
if(index.index_set != index_set_id)
index = app->index_data.raise(index, index_set_id); // Have to make it relative to the union.
indexes.set_index(index, true);
//log_print("Setting index for ", app->vars[var_id]->name, " ", app->model->index_sets[index.index_set]->name, " ", index.index, "\n");
bool success = add_plot_recursive(draw, app, var_id, indexes, level+1, ref_x_start, start, time_steps, x_data, index_sets, gof_offset, gof_ts, mode, found_count+1);
if(!success) return false;
}
}
}
return true;
}
void
set_round_grid_line_positions(ScatterDraw *plot, int axis) {
//TODO: This should take Y axis mode into account (if axis is 1)
double min;
double range;
if(axis == 0) {
min = plot->GetXMin();
range = plot->GetXRange();
} else {
min = plot->GetYMin();
range = plot->GetYRange();
}
double log_range = std::log10(range);
double int_part;
double frac_part = std::modf(log_range, &int_part);
if(range < 1.0) int_part -= 1.0;
double order_of_mag = std::pow(10.0, int_part);
double stretch = range / order_of_mag;
constexpr int ref_ticks = 10; //TODO: Should depend on plot size.
//TODO: Document this implementation better?
static double stride_factors[8] = {0.1, 0.2, 0.25, 0.5, 1.0, 2.0, 2.5, 5.0};
double stride = order_of_mag * stride_factors[0];
for(int idx = 1; idx < 8; ++idx) {
double n_ticks = std::floor(range / stride);
if((int)n_ticks <= ref_ticks) break;
stride = order_of_mag * stride_factors[idx];
}
double min2 = std::floor(min / stride)*stride;
range += min-min2;
//MainPlot.SetMinUnits(Null, Min); //We would prefer to do this, but for some reason it works
//poorly when there are negative values...
if(axis == 0) {
plot->SetXYMin(min2, Null);
plot->SetRange(range, Null);
plot->SetMajorUnits(stride, Null);
} else {
plot->SetXYMin(Null, min2);
plot->SetRange(Null, range);
plot->SetMajorUnits(Null, stride);
}
}
int round_step_10(int step) {
//TODO: hmm, could this be unified with what is done in the above function somehow?
int log_10 = (int)std::log10((double)step);
int order_of_mag = (int)std::pow(10.0, log_10);
int stretch = step / order_of_mag;
if(stretch == 1) return order_of_mag;
if(stretch == 2) return order_of_mag*2;
if(stretch <= 5) return order_of_mag*5;
return order_of_mag*10;
}
int round_step_60(int step) {
//TODO: lookup table?
if(step == 3) step = 2;
else if(step == 4) step = 5;
else if(step == 6 || step == 7) step = 5;
else if(step >= 8 && step <= 12) step = 10;
else if(step >= 13 && step <= 17) step = 15;
else if(step >= 18 && step <= 26) step = 20;
else if(step >= 27 && step <= 40) step = 30;
return step;
}
int round_step_24(int step) {
//TODO: lookup table?
if(step == 3) step = 2;
if(step == 5) step = 4;
if(step == 7 || step == 8) step = 6;
if(step >= 9 && step <= 14) step = 12;
return step;
}
int round_step_31(int step) {
// TODO: lookup table?
if(step == 3) step = 2;
else if(step == 4) step = 5;
else if(step == 6 || step == 7) step = 5;
else if(step == 8 || step == 9) step = 10;
else if(step > 2 && step < 20) step = 15;
return step;
}
void set_date_grid_line_positions_x(double x_min, double x_range, Vector<double> &pos, Date_Time input_start, int res_type) {
constexpr int n_grid_lines = 10; //TODO: Make it sensitive to plot size
s64 sec_range = (s64)x_range;
s64 first = input_start.seconds_since_epoch + (s64)x_min;
s64 last = first + sec_range;
//NOTE: res_type denotes the unit that we try to use for spacing the grid lines. 0=seconds, 1=minutes, 2=hours, 3=days,
//4=months, 5=years
s64 step;
s64 iter_time = first;
if(res_type == 0) {
step = sec_range / n_grid_lines + 1;
step = round_step_60(step);
if(step > 30) res_type = 1; //The plot is too wide to do secondly resolution, try minutely instead
else
iter_time -= (iter_time % step); //TODO: may not work if iter_time is negative. Likewise for the next two. Fix this. (make round_down_by function.)
}
if(res_type == 1) {
s64 min_range = sec_range / 60;
s64 min_step = min_range / n_grid_lines + 1;
min_step = round_step_60(min_step);
if(min_step > 30) res_type = 2; //The plot is too wide to do minutely resolution, try hourly instead
else {
iter_time -= (iter_time % 60);
iter_time -= 60*((iter_time/60) % min_step);
step = 60*min_step;
}
}
if(res_type == 2) {
s64 hr_range = sec_range / 3600;
s64 hr_step = hr_range / n_grid_lines + 1;
hr_step = round_step_24(hr_step);
if(hr_step > 12) res_type = 3; //The plot is too wide to do hourly resolution, try daily instead
else {
iter_time -= (iter_time % 3600);
iter_time -= 3600*((iter_time / 3600) % hr_step);
step = 3600*hr_step;
}
}
if(res_type <= 2) {
if(step <= 0) //NOTE: should not happen. Just so that it doesn't crash if there is a bug.
return;
for(; iter_time <= last; iter_time += step) {
double x = (double)((iter_time - input_start.seconds_since_epoch)) - x_min;
if(x > 0.0 && x < x_range)
pos << x;
}
return;
}
// TODO: The date algorithms used here are very slow when the year is large. Either improve
// datetime.h or do some approximation here in that case.
Date_Time first_d;
first_d.seconds_since_epoch = first;
Date_Time last_d;
last_d.seconds_since_epoch = last;
s32 fy, fm, fd, ly, lm, ld;
first_d.year_month_day(&fy, &fm, &fd);
last_d.year_month_day(&ly, &lm, &ld);
if(res_type == 3) {
s64 day_range = sec_range / 86400; // +1 ??
s64 day_step = day_range / n_grid_lines + 1;
day_step = round_step_31(day_step);
if(day_step >= 20) res_type = 4; //The plot is too wide to do daily resolution, try monthly instead;
else {
s32 d = fd;
d -= (d - 1) % day_step;
s32 m = fm;
s32 y = fy;
// TODO: use Expanded_Date_Time here instead?
while(true) {
if(y > ly ||
(y == ly && (m > lm ||
(m == lm && d > ld)))) break;
s32 dom = month_length(y, m);
if(d > dom || (day_step != 1 && (dom - d < day_step/2))) { //TODO: I forgot why rightmost part of the condition is here. Figure it out and explain it in comment.
d = 1; m++;
if(m > 12) { m = 1; y++; }
}
Date_Time iter_date(y, m, d);
double x = (double)((iter_date.seconds_since_epoch - input_start.seconds_since_epoch)) - x_min;
if(x > 0.0 && x < x_range)
pos << x;
d += day_step;
}
return;
}
}
s64 mon_step;
if(res_type == 4) {
int mon_range = lm - fm + 12*(ly - fy);
mon_step = mon_range / n_grid_lines + 1;
if(mon_step >= 10) res_type = 5; //The plot is too wide to do monthly resolution, try yearly instead
else {
if(mon_step == 4) mon_step = 3;
else if(mon_step == 5 || (mon_step > 6 && mon_step <= 9)) mon_step = 6;
int surp = (fm-1) % mon_step;
fm -= surp; //NOTE: This should not result in fm being negative.
}
}
int yr_step = 0;
if(res_type == 5) {
int yr_range = ly - fy;
yr_step = yr_range / n_grid_lines + 1;
yr_step = round_step_10(yr_step);
fy -= (fy % yr_step);
fm = 1;
mon_step = 12*yr_step;
}
if(mon_step <= 0) return; //NOTE: should not happen. Just so that it doesn't crash if there is a bug.
if(yr_step > 1000) return; //TODO: Can remove this if we speed up the datetime algorithms.
Expanded_Date_Time iter_date(Date_Time(fy, fm, 1), Time_Step_Size { Time_Step_Size::month, (s32)mon_step} );
while(true) {
if(iter_date.year > ly || (iter_date.year == ly && iter_date.month > lm)) break;
double x = (double)((iter_date.date_time.seconds_since_epoch - input_start.seconds_since_epoch)) - x_min;
if(x > 0.0 && x < x_range)
pos << x;
iter_date.advance();
}
}
int
compute_smallest_step_resolution(Aggregation_Period interval_type, Time_Step_Size ts_size) {
//NOTE: To compute the unit that we try to use for spacing the grid lines.
// 0=seconds, 1=minutes, 2=hours,
// 3=days, 4=months, 5=years
if(interval_type == Aggregation_Period::none) {
//NOTE: The plot does not display aggregated data, so the unit of the grid line step should be
//determined by the model step size.
if(ts_size.unit == Time_Step_Size::second) {
if(ts_size.multiplier < 60) return 0;
else if(ts_size.multiplier < 3600) return 1;
else if(ts_size.multiplier < 86400) return 2;
else return 3;
} else {
if(ts_size.multiplier < 12) return 4;
else return 5;
}
}
else if(interval_type == Aggregation_Period::weekly) return 3;
else if(interval_type == Aggregation_Period::monthly) return 4;
else if(interval_type == Aggregation_Period::yearly) return 5;
return 0;
}
inline void
grid_time_stamp_format(int res_type, Date_Time ref_date, double seconds_since_ref, String &str) {
//static const char *month_names[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
// Testing shorter month names since they some times overlap
static const char *month_names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
//NOTE: Adding 0.5 helps a bit with avoiding flickering when panning, but is not perfect (TODO)
Date_Time d2 = ref_date;
if(seconds_since_ref >= 0.0)
d2.seconds_since_epoch += (s64)(seconds_since_ref + 0.5);
else
d2.seconds_since_epoch += (s64)(seconds_since_ref); // For negatives it will skip a second if we add the 0.5
s32 h, m, s;
if(res_type <= 2) {
d2.hour_minute_second(&h, &m, &s);
if(res_type == 0)
str = Format("%02d:%02d:%02d", h, m, s);
else
str = Format("%02d:%02d", h, m);
}
if(res_type >= 3 || (h==0 && m==0 && s==0)) {
s32 y, mn, d;
d2.year_month_day(&y, &mn, &d); // TODO: Slow when the year is large.
if(res_type <= 3) {
if(res_type <= 2)
str << "\n";
str << Format("%d. ", d);
}
if(d == 1 || res_type >= 4) {
if(res_type <= 4)
str << month_names[mn-1];
if(mn == 1 || res_type >= 5) {
if(res_type <= 4)
str << "\n";
str << Format("%d", y);
}
}
}
}
inline void
time_stamp_format(int res_type, Date_Time ref_date, double seconds_since_ref, String &str) {
Date_Time d2 = ref_date;
d2.seconds_since_epoch += (s64)(seconds_since_ref + 0.5);
s32 y, mn, d, h, m, s;
d2.year_month_day(&y, &mn, &d);
if(res_type <= 2) {
d2.hour_minute_second(&h, &m, &s);
str = Format("%02d-%02d-%02d %02d:%02d:%02d", y, mn, d, h, m, s);
} else
str = Format("%02d-%02d-%02d", y, mn, d);
}
void
format_axes(MyPlot *plot, Plot_Mode mode, int n_bins_histogram, Date_Time input_start, Time_Step_Size ts_size) {
plot->SetGridLinesX.Clear();
plot->cbModifFormatXGridUnits.Clear();
plot->cbModifFormatX.Clear();
plot->cbModifFormatY.Clear();
plot->cbModifFormatYGridUnits.Clear();
plot->SetMinUnits(0, 0);
if(plot->setup.y_axis_mode == Y_Axis_Mode::logarithmic && mode != Plot_Mode::profile2D)
plot->SetLogY(true);
else
plot->SetLogY(false);
if(plot->GetCount() > 0
|| (mode == Plot_Mode::profile2D &&
((!plot->profile2D_is_timed && plot->profile2D.count() > 0) ||
(plot->profile2D_is_timed && plot->profile2Dt.count() > 0))
)) {
if(mode == Plot_Mode::histogram || mode == Plot_Mode::residuals_histogram) {
//NOTE: Histograms require special zooming.
plot->ZoomToFitNonLinked(true, true, 0, 0);
plot->was_auto_resized = false;
double x_range = plot->GetXRange();
double x_min = plot->GetXMin();
//NOTE: The auto-resize cuts out half of each outer bar, so we fix that
double stride = x_range / (double)(n_bins_histogram-1);
x_min -= 0.5*stride;
x_range += stride;
plot->SetXYMin(x_min);
plot->SetRange(x_range);
// Position grid lines at the actual bars.
int line_skip = n_bins_histogram / 30 + 1;
plot->SetGridLinesX << [n_bins_histogram, stride, line_skip](Vector<double> &pos) {
for(int idx = 0; idx < n_bins_histogram; idx+=line_skip)
pos << stride * (double)idx;
};
// Skip some of the numeric labels since they tend to overlap otherwise.
plot->cbModifFormatXGridUnits << [](String &s, int i, double d) {
if(i % 2 == 1)
s = FormatDouble(d, 3);
else
s = "";
};
} else if(mode == Plot_Mode::qq) {
//NOTE: qq plots require special zooming.
plot->ZoomToFitNonLinked(true, true, 0, 0);
plot->was_auto_resized = false;
double y_range = plot->GetYRange();
double y_min = plot->GetYMin();
double x_range = plot->GetXRange();
double x_min = plot->GetXMin();
//NOTE: Make it so that the extremal points are not on the border
double ext_y = y_range * 0.1;
y_range += 2.0 * ext_y;
y_min -= ext_y;
double ext_x = x_range * 0.1;
x_range += 2.0 * ext_x;
x_min -= ext_x;
plot->SetRange(x_range, y_range);
plot->SetXYMin(x_min, y_min);
} else if(mode == Plot_Mode::profile) {
plot->was_auto_resized = false;
double ymin = std::min(0.0, plot->profile.get_min());
double ymax = plot->profile.get_max();
int count = plot->profile.GetCount();
plot->SetRange(Null, ymax - ymin);
// For some reason, the behaviour of this is different depending on whether or not
// you set the units before or after the min and range.....
bool has_x_values = plot->profile.has_x_values();
if(!has_x_values) {
plot->SetXYMin(-0.5, ymin);
plot->SetRange((double)count, Null);
plot->cbModifFormatX << [count, plot](String &s, int i, double d) {
int idx = (int)std::floor(d);
if(idx >= -1 && idx <= count-1 && (idx+1 < plot->labels.size()))
s = plot->labels[idx+1];
else s = "";
};
}
int preferred_max_grid = 15; //TODO: Dynamic size-based ?
int units = std::max(1, count / preferred_max_grid);
plot->SetMajorUnits((double)units);
plot->SetMinUnits(0.0);
if(has_x_values) {
plot->SetXYMin(0, ymin);
double x_max = plot->profile.x(count-1);
plot->SetRange(x_max+0.5, Null);
}
} else if (mode == Plot_Mode::profile2D && plot->profile2D_is_timed) {
plot->ZoomToFitNonLinked(true, true, 0, 0);
plot->was_auto_resized = false;
plot->SetSurfMinZ(plot->profile2Dt.get_min());
plot->SetSurfMaxZ(plot->profile2Dt.get_max());
plot->SetXYMin(0.0, 0.0);
int count_x = plot->profile2Dt.get_dim_x();
int count_y = plot->profile2Dt.get_dim_y();
plot->SetRange((double)count_x, (double)count_y);
int preferred_max_grid = 15; //TODO: Dynamic size-based ?
int units_x = std::max(1, count_x / preferred_max_grid);
int units_y = std::max(1, count_y / preferred_max_grid);
plot->SetMinUnits(0.5, 0.5);
plot->SetMajorUnits((double)units_x, (double)units_y);
plot->cbModifFormatX << [count_x, plot](String &s, int i, double d) {
int idx = (int)d;
if(d >= 0 && d < count_x && (idx < plot->labels2.size())) s = plot->labels2[idx];
};
plot->cbModifFormatY << [count_y, plot](String &s, int i, double d) {
int idx = (int)d;
if(d >= 0 && d < count_y && (idx < plot->labels.size())) s = plot->labels[idx];
};
} else if (!plot->profile2D_is_timed) {
plot->ZoomToFitNonLinked(false, true, 0, 0);
int res_type = compute_smallest_step_resolution(plot->setup.aggregation_period, ts_size);
if(mode == Plot_Mode::profile2D) {
//plot->ZoomToFitZ();
TableData *data = plot->profile2D_is_timed ? static_cast<TableData *>(&plot->profile2Dt) : static_cast<TableData *>(&plot->profile2D);
double minz = data->MinZ();
double maxz = data->MaxZ();
if(maxz < 0.0)
maxz = 0.0;
else if (minz > 0.0)
minz = 0.0;
else { // maxz > 0.0 && minz < 0.0*/
double absmax = std::max(std::abs(maxz), std::abs(minz));
maxz = absmax;
minz = std::max(-0.5*absmax, minz);
}
plot->SetSurfMinZ(minz);
plot->SetSurfMaxZ(maxz);
bool has_y_values = plot->profile2D.has_y_values();
if(has_y_values) {
// This is very hacky, but it is because we have to put the data at
// negative y values to be able to put them from top to bottom without messing up the
// plotting algorithms.
plot->cbModifFormatY <<
[](String &s, int i, double d) {
s = FormatDouble(-d);
};
} else {
int count = plot->profile2D.count();
int preferred_max_grid = 15; //TODO: Dynamic size-based ?
int units = std::max(1, count / preferred_max_grid);
plot->SetMinUnits(Null, 0.5);
plot->SetMajorUnits(Null, units);
plot->cbModifFormatY <<
[plot](String &s, int i, double d) {
int idx = (int)d;
if(d >= 0 && d < plot->labels.size()) s = plot->labels[idx]; // NOTE: We display them from top to bottom
};
}
} else {
// Set the minimum of the y range to be 0 unless the minimum is already below 0
double y_range = plot->GetYRange();
double y_min = plot->GetYMin();
if(y_min > 0.0) {
double new_range = y_range + y_min;
plot->SetRange(Null, new_range);
plot->SetXYMin(Null, 0.0);
}
}
if(!plot->was_auto_resized) {
plot->ZoomToFitNonLinked(true, false, 0, 0);
plot->was_auto_resized = true;
}
// TODO: This is still bug prone!!
// Position of x grid lines
plot->SetGridLinesX << [plot, input_start, res_type](Vector<double> &vec){
double x_min = plot->GetXMin();
double x_range = plot->GetXRange();
set_date_grid_line_positions_x(x_min, x_range, vec, input_start, res_type);
};
// Format to be displayed for x values at grid lines and data view
plot->cbModifFormatXGridUnits << [res_type, input_start] (String &str, int i, double r) {
grid_time_stamp_format(res_type, input_start, r, str);
};
// Format to be displayed in data table
plot->cbModifFormatX << [res_type, input_start] (String &str, int i, double r) {
time_stamp_format(res_type, input_start, r, str);
};
}
// Extend the Y range a bit more to avoid the legend obscuring the plot in the most
// common cases (and to have a nice margin).
if(plot->GetShowLegend() && mode != Plot_Mode::profile && mode != Plot_Mode::profile2D)
plot->SetRange(Null, plot->GetYRange() * 1.15);
if(mode != Plot_Mode::profile2D) {
if(plot->setup.y_axis_mode != Y_Axis_Mode::logarithmic) {
plot->cbModifFormatYGridUnits << [](String &s, int i, double d) {
s = FormatDouble(d, 4);
};
}
set_round_grid_line_positions(plot, 1);
}
if(mode == Plot_Mode::qq)
set_round_grid_line_positions(plot, 0);
}
bool allow_scroll_x = !(mode == Plot_Mode::profile || mode == Plot_Mode::histogram
|| mode == Plot_Mode::residuals_histogram);
bool allow_scroll_y = (mode == Plot_Mode::qq) || (mode == Plot_Mode::profile2D && plot->profile2D_is_timed);
plot->SetMouseHandling(allow_scroll_x, allow_scroll_y);
}
void add_line(MyPlot *plot, double x0, double y0, double x1, double y1, Color color, const String &legend) {
plot->series_data.Create<Data_Source_Line>(x0, y0, x1, y1);
if(IsNull(color)) color = plot->colors.next();
plot->AddSeries(plot->series_data.Top()).NoMark().Stroke(1.5, color).Dash("6 3");
if(!IsNull(legend)) plot->Legend(legend);
else plot->ShowSeriesLegend(false);
}
void add_trend_line(MyPlot *plot, double xy_covar, double x_var, double y_mean, double x_mean, double start_x, double end_x, String &legend) {
double beta = xy_covar / x_var;
double alpha = y_mean - beta*x_mean;
add_line(plot, start_x, alpha + start_x*beta, end_x, alpha + end_x*beta, Null, legend);
}
int add_histogram(MyPlot *plot, DataSource *data, double min, double max, s64 count, const String &legend, const String &unit, const Color &color) {
//n_bins_histogram = 1 + (int)std::ceil(std::log2((double)count)); //NOTE: Sturges' rule.
int n_bins_histogram = 2*(int)(std::ceil(std::cbrt((double)count))); //NOTE: Rice's rule.
plot->histogram.Create(*data, min, max, n_bins_histogram);
plot->histogram.Normalize();
double stride = (max - min)/(double)n_bins_histogram;
double darken = 0.4;
Color border((int)(((double)color.GetR())*darken), (int)(((double)color.GetG())*darken), (int)(((double)color.GetB())*darken));
plot->AddSeries(plot->histogram).Legend(legend).PlotStyle<BarSeriesPlot>().BarWidth(0.5*stride).NoMark().Fill(color).Stroke(1.0, border).Units("", unit);
return n_bins_histogram;
}
void get_gof_offsets(Time &start_setting, Time &end_setting, Date_Time input_start, s64 input_ts, Date_Time result_start, s64 result_ts, Date_Time &gof_start, Date_Time &gof_end,
s64 &input_gof_offset, s64 &result_gof_offset, s64 &gof_ts, Time_Step_Size ts_size, bool has_results) {
Date_Time gof_min = result_start;
s64 max_ts = result_ts;
if(!has_results) {
gof_min = input_start;
max_ts = input_ts;
}
Date_Time gof_max = advance(gof_min, ts_size, max_ts-1);
gof_start = IsNull(start_setting) ? gof_min : convert_time(start_setting);
gof_end = IsNull(end_setting) ? gof_max : convert_time(end_setting);
if(gof_start < gof_min || gof_start > gof_max)
gof_start = gof_min;
if(gof_end < gof_min || gof_end > gof_max || gof_end < gof_start)
gof_end = gof_max;
gof_ts = steps_between(gof_start, gof_end, ts_size) + 1; //NOTE: if start time = end time, there is still one timestep.
result_gof_offset = steps_between(result_start, gof_start, ts_size); //NOTE: this could be negative, but only in the case when has_results=false
input_gof_offset = steps_between(input_start, gof_start, ts_size);
}
void MyPlot::build_plot(bool caused_by_run, Plot_Mode override_mode) {
clean(false);
if(!parent->model_is_loaded()) {
SetTitle("No model is loaded.");
return;
}
int series_count = setup.selected_results.size() + setup.selected_series.size();
if(series_count == 0) {
SetTitle("No time series is selected for plotting.");
return;
}
auto app = parent->app;
Date_Time result_start = app->data.results.start_date;
Date_Time input_start = app->data.series.start_date; // NOTE: Should be same for both type of series (model inputs & additional series)
s64 input_ts = app->data.series.time_steps;
s64 result_ts = app->data.results.time_steps;
if(input_ts == 0) { //NOTE: could happen if there are no input series at all
input_ts = result_ts;
input_start = result_start;
}
s64 result_offset = steps_between(input_start, result_start, app->time_step_size);
if(!setup.selected_results.empty() && result_ts == 0) {
SetTitle("Unable to generate a plot of any result series since the model has not been run.");
return;
}
// NOTE: this should theoretically never happen
if(setup.selected_indexes.empty() && app->model->index_sets.count() > 0) {
SetTitle("No indexes were selected");
return;
}
bool multi_index = false;
for(auto id : app->model->index_sets) {
if(!setup.index_set_is_active[id.id]) continue;
if(setup.selected_indexes[id.id].empty()) {
//parent->log(Format("The index set %s has %d selected indexes.", parent->model->index_sets[id]->name.data(), (int)setup.selected_indexes[id.id].size()));
SetTitle("At least one index has to be selected for each of the active index sets.");
return;
}
if(setup.selected_indexes[id.id].size() > 1)
multi_index = true;
}
bool show_l = true;
if(plot_ctrl) {
show_l = plot_ctrl->show_legend.GetData();
}
ShowLegend(show_l);
plot_info->Clear();
Plot_Mode mode = setup.mode;
if(override_mode != Plot_Mode::none) mode = override_mode;
Date_Time gof_start;
Date_Time gof_end;
s64 input_gof_offset;
s64 result_gof_offset;
s64 gof_ts;
Time gof_start_setting = parent->calib_start.GetData();
Time gof_end_setting = parent->calib_end.GetData();
get_gof_offsets(gof_start_setting, gof_end_setting, input_start, input_ts, result_start, result_ts, gof_start, gof_end,
input_gof_offset, result_gof_offset, gof_ts, app->time_step_size, !setup.selected_results.empty());
bool gof_available = false;
bool want_gof = (bool)parent->gof_option.GetData() || mode == Plot_Mode::residuals || mode == Plot_Mode::residuals_histogram || mode == Plot_Mode::qq;
s64 offset_sim;
s64 offset_obs;
char buf1[64];
char buf2[64];
gof_start.to_string(buf1);
gof_end .to_string(buf2);
plot_info->append(Format("Showing statistics for interval %s to %s&&", buf1, buf2));
#if CATCH_ERRORS
try {
#endif
Residual_Stats residual_stats;
if(want_gof && setup.selected_results.size() == 1 && setup.selected_series.size() == 1 && !multi_index) {
gof_available = true;
bool compute_rcc = parent->stat_settings.display_settings.display_srcc;
Var_Id id_sim = setup.selected_results[0];
Var_Id id_obs = setup.selected_series[0];
Data_Storage<double, Var_Id> *data_sim = &app->data.results;
Data_Storage<double, Var_Id> *data_obs = id_obs.type == Var_Id::Type::series ? &app->data.series : &app->data.additional_series;
Indexes indexes(parent->model);
get_single_indexes(parent->app, indexes, setup);
offset_sim = data_sim->structure->get_offset(id_sim, indexes);
offset_obs = data_obs->structure->get_offset(id_obs, indexes);
compute_residual_stats(&residual_stats, data_sim, offset_sim, result_gof_offset, data_obs, offset_obs, input_gof_offset, gof_ts, compute_rcc);
}
compute_x_data(input_start, input_ts+1, app->time_step_size);
int n_bins_histogram = 0;
if(mode == Plot_Mode::regular || mode == Plot_Mode::stacked || mode == Plot_Mode::stacked_share) {
if(mode != Plot_Mode::regular) {
bool is_share = (mode == Plot_Mode::stacked_share);
data_stacked.set_share(is_share);
}
Indexes indexes(parent->model);
for(auto var_id : setup.selected_results) {
const std::vector<Entity_Id> &index_sets = app->result_structure.get_index_sets(var_id);
add_plot_recursive(this, app, var_id, indexes, 0, input_start, result_start, result_ts, x_data.data(), index_sets, result_gof_offset, gof_ts, mode);
}
for(auto var_id : setup.selected_series) {
const std::vector<Entity_Id> &index_sets = var_id.type == Var_Id::Type::series ? app->series_structure.get_index_sets(var_id) : app->additional_series_structure.get_index_sets(var_id);
add_plot_recursive(this, app, var_id, indexes, 0, input_start, input_start, input_ts, x_data.data(), index_sets, input_gof_offset, gof_ts, mode);
}
} else if (mode == Plot_Mode::histogram) {
if(series_count > 1 || multi_index) {
SetTitle("In histogram mode you can only have one timeseries selected, for one index combination");
return;
}
Indexes indexes(parent->model);
get_single_indexes(parent->app, indexes, setup);
s64 gof_offset;
Var_Id var_id;
// TODO: We should make it very clear that the histogram uses the GOF interval only
// for its data!
if(!setup.selected_results.empty()) {
var_id = setup.selected_results[0];
gof_offset = result_gof_offset;
} else {
var_id = setup.selected_series[0];
gof_offset = input_gof_offset;
}
auto *data = &app->data.get_storage(var_id.type);
auto var = app->vars[var_id];
//TODO: with the new data system, it would be easy to allow aggregation also.
s64 offset = data->structure->get_offset(var_id, indexes);
Time_Series_Stats stats;
compute_time_series_stats(&stats, &parent->stat_settings.settings, data, offset, gof_offset, gof_ts);
series_data.Create<Mobius_Data_Source>(data, offset, gof_ts, x_data.data(), input_start, gof_start, app->time_step_size);
String unit = var->unit.to_utf8();
String legend = String(var->name) + " " + make_index_string(data->structure, indexes, var_id) + "[" + unit + "]";
Color &color = colors.next();
n_bins_histogram = add_histogram(this, &series_data.Top(), stats.min, stats.max, stats.data_points, legend, unit, color);
display_statistics(plot_info, &parent->stat_settings.display_settings, &stats, color, legend);