-
Notifications
You must be signed in to change notification settings - Fork 0
/
OptimizationWindow.cpp
1573 lines (1237 loc) · 52.5 KB
/
OptimizationWindow.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 "OptimizationWindow.h"
#include "MobiView2.h"
#include "support/dlib_optimization.h"
#include "support/effect_indexes.h"
/*
#ifdef _WIN32
#include <winsock2.h> //NOTE: For some reason dlib includes some windows headers in an order that upp's clang setup doesn't like
#endif
*/
#define IMAGECLASS IconImg4
#define IMAGEFILE <MobiView2/images.iml>
#include <Draw/iml.h>
using namespace Upp;
OptimizationParameterSetup::OptimizationParameterSetup() {
CtrlLayout(*this);
}
OptimizationTargetSetup::OptimizationTargetSetup() {
CtrlLayout(*this);
}
OptimizationRunSetup::OptimizationRunSetup() {
CtrlLayout(*this);
}
MCMCRunSetup::MCMCRunSetup() {
CtrlLayout(*this);
}
SensitivityRunSetup::SensitivityRunSetup() {
CtrlLayout(*this);
}
OptimizationWindow::OptimizationWindow(MobiView2 *parent) : parent(parent) {
SetRect(0, 0, 740, 740);
Title("MobiView optimization and MCMC setup").Sizeable().Zoomable();
par_setup.parameter_view.AddColumn(Id("__name"), "Name");
par_setup.parameter_view.AddColumn(Id("__indexes"), "Indexes");
par_setup.parameter_view.AddColumn(Id("__min"), "Min");
par_setup.parameter_view.AddColumn(Id("__max"), "Max");
par_setup.parameter_view.AddColumn(Id("__unit"), "Unit");
par_setup.parameter_view.AddColumn(Id("__sym"), "Symbol");
par_setup.parameter_view.AddColumn(Id("__expr"), "Expression");
par_setup.parameter_view.AddColumn(Id("__idx"), "Index");
par_setup.parameter_view.HeaderObject().HideTab(7);
par_setup.parameter_view.Moving(true);
target_setup.target_view.AddColumn(Id("__resultname"), "Result name");
target_setup.target_view.AddColumn(Id("__resultindexes"), "Result idxs.");
target_setup.target_view.AddColumn(Id("__inputname"), "Input name");
target_setup.target_view.AddColumn(Id("__inputindexes"), "Input idxs.");
target_setup.target_view.AddColumn(Id("__targetstat"), "Statistic");
target_setup.target_view.AddColumn(Id("__errparam"), "Error param(s).");
target_setup.target_view.AddColumn(Id("__weight"), "Weight");
target_setup.target_view.AddColumn(Id("__start"), "Start");
target_setup.target_view.AddColumn(Id("__end"), "End");
target_setup.edit_timeout.SetData(-1);
par_setup.push_add_parameter.WhenPush = THISBACK(add_parameter_clicked);
par_setup.push_add_group.WhenPush = THISBACK(add_group_clicked);
par_setup.push_remove_parameter.WhenPush = THISBACK(remove_parameter_clicked);
par_setup.push_clear_parameters.WhenPush = THISBACK(clear_parameters_clicked);
par_setup.push_add_virtual.WhenPush = THISBACK(add_virtual_clicked);
par_setup.push_add_parameter.SetImage(IconImg4::Add());
par_setup.push_add_group.SetImage(IconImg4::AddGroup());
par_setup.push_remove_parameter.SetImage(IconImg4::Remove());
par_setup.push_clear_parameters.SetImage(IconImg4::RemoveGroup());
par_setup.push_add_virtual.SetImage(IconImg4::Add());
target_setup.push_add_target.WhenPush = THISBACK(add_target_clicked);
target_setup.push_remove_target.WhenPush = THISBACK(remove_target_clicked);
target_setup.push_clear_targets.WhenPush = THISBACK(clear_targets_clicked);
target_setup.push_display.WhenPush = THISBACK(display_clicked);
target_setup.push_add_target.SetImage(IconImg4::Add());
target_setup.push_remove_target.SetImage(IconImg4::Remove());
target_setup.push_clear_targets.SetImage(IconImg4::RemoveGroup());
target_setup.push_display.SetImage(IconImg4::ViewMorePlots());
run_setup.push_run.WhenPush = [&](){ run_clicked(0); };
run_setup.push_run.SetImage(IconImg4::Run());
run_setup.edit_max_evals.Min(1);
run_setup.edit_max_evals.SetData(1000);
run_setup.edit_epsilon.Min(0.0);
run_setup.edit_epsilon.SetData(0.0);
run_setup.option_show_progress.SetData(true);
mcmc_setup.push_run.WhenPush = [this](){ run_clicked(1); };
mcmc_setup.push_run.SetImage(IconImg4::Run());
mcmc_setup.push_view_chains.WhenPush << [this]() { if(!this->parent->mcmc_window.IsOpen()) this->parent->mcmc_window.Open(); };
mcmc_setup.push_view_chains.SetImage(IconImg4::ViewMorePlots());
mcmc_setup.push_extend_run.WhenPush = [this](){ run_clicked(2); };
mcmc_setup.push_extend_run.Disable();
mcmc_setup.push_extend_run.SetImage(IconImg4::Run());
mcmc_setup.edit_steps.Min(10);
mcmc_setup.edit_steps.SetData(1000);
mcmc_setup.edit_walkers.Min(10);
mcmc_setup.edit_walkers.SetData(50);
mcmc_setup.initial_type_switch.SetData(0);
mcmc_setup.sampler_param_view.AddColumn("Name");
mcmc_setup.sampler_param_view.AddColumn("Value");
mcmc_setup.sampler_param_view.AddColumn("Description");
mcmc_setup.sampler_param_view.ColumnWidths("3 2 5");
mcmc_setup.select_sampler.Add((int)MCMC_Sampler::affine_stretch, "Affine stretch (recommended)");
mcmc_setup.select_sampler.Add((int)MCMC_Sampler::affine_walk, "Affine walk");
mcmc_setup.select_sampler.Add((int)MCMC_Sampler::differential_evolution, "Differential evolution");
mcmc_setup.select_sampler.Add((int)MCMC_Sampler::metropolis_hastings, "Metropolis-Hastings (independent chains)");
mcmc_setup.select_sampler.GoBegin();
mcmc_setup.select_sampler.WhenAction << THISBACK(sampler_method_selected);
sampler_method_selected(); //To set the sampler parameters for the initial selection
sensitivity_setup.edit_sample_size.Min(10);
sensitivity_setup.edit_sample_size.SetData(1000);
sensitivity_setup.push_run.WhenPush = [this](){ run_clicked(3); };
sensitivity_setup.push_view_results.WhenPush = [this]() { if(!this->parent->variance_window.IsOpen()) this->parent->variance_window.Open(); };
sensitivity_setup.push_run.SetImage(IconImg4::Run());
sensitivity_setup.push_view_results.SetImage(IconImg4::ViewMorePlots());
sensitivity_setup.select_method.Add(0, "Latin hypercube");
sensitivity_setup.select_method.Add(1, "Independent uniform");
sensitivity_setup.select_method.GoBegin();
AddFrame(tool);
tool.Set(THISBACK(sub_bar));
target_setup.optimizer_type_tab.Add(run_setup.SizePos(), "Optimizer");
target_setup.optimizer_type_tab.Add(mcmc_setup.SizePos(), "MCMC");
target_setup.optimizer_type_tab.Add(sensitivity_setup.SizePos(), "Variance based sensitivity");
target_setup.optimizer_type_tab.WhenSet << THISBACK(tab_change);
main_vertical.Vert();
main_vertical.Add(par_setup);
main_vertical.Add(target_setup);
Add(main_vertical.SizePos());
auto font = GetStdFont();
target_setup.error_label.SetFont(font.Bold());
target_setup.error_label.SetInk(Red());
}
void OptimizationWindow::set_error(const String &err_str) {
target_setup.error_label.SetText(err_str);
}
void OptimizationWindow::sub_bar(Bar &bar) {
bar.Add(IconImg4::Open(), THISBACK(read_from_json)).Tip("Load setup from file");
bar.Add(IconImg4::Save(), THISBACK(write_to_json)).Tip("Save setup to file");
}
bool OptimizationWindow::add_single_parameter(Indexed_Parameter parameter, bool lookup_default) {
if(!is_valid(parameter.id) && !parameter.virt) return false; //TODO: Some kind of error message explaining how to use the feature?
auto app = parent->app;
Parameter_Registration *par;
if(!parameter.virt) {
par = app->model->parameters[parameter.id];
if(par->decl_type != Decl_Type::par_real) return false; //TODO: Dlib has provision for allowing integer parameters
}
int overwrite_row = -1;
int row = 0;
if(!parameter.virt) {
for(Indexed_Parameter &other_par : parameters) {
if(parameter_is_subset_of(parameter, other_par)) return false;
if(parameter_is_subset_of(other_par, parameter)) {
other_par = parameter;
overwrite_row = row;
}
++row;
}
}
String index_str = "";
if(!parameter.virt)
index_str = make_parameter_index_string(&app->parameter_structure, ¶meter);
if(overwrite_row < 0) {
double min = Null;
double max = Null;
String name = "(virtual)";
String unit = "";
String sym = parameter.symbol.data();
String expr = parameter.expr.data();
if(!parameter.virt) {
min = par->min_val.val_real;
max = par->max_val.val_real;
if(is_valid(par->unit))
unit = app->model->units[par->unit]->data.to_utf8();
name = par->name.data();
if(lookup_default)
sym = app->model->get_symbol(parameter.id).data();
}
parameter.symbol = sym.ToStd();
parameters.push_back(std::move(parameter));
//int row = parameters.size()-1;
int idx = parameters.size()-1;
int row = par_setup.parameter_view.GetCount();
par_setup.parameter_view.Add(name, index_str, min, max, unit, sym, expr, idx);
edit_min_ctrls.Create<EditDoubleNotNull>();
edit_max_ctrls.Create<EditDoubleNotNull>();
par_setup.parameter_view.SetCtrl(row, 2, edit_min_ctrls.Top());
par_setup.parameter_view.SetCtrl(row, 3, edit_max_ctrls.Top());
edit_sym_ctrls.Create<EditField>();
edit_expr_ctrls.Create<EditField>();
par_setup.parameter_view.SetCtrl(row, 5, edit_sym_ctrls.Top());
par_setup.parameter_view.SetCtrl(row, 6, edit_expr_ctrls.Top());
edit_sym_ctrls.Top().WhenAction << [this, row](){ symbol_edited(row); };
edit_expr_ctrls.Top().WhenAction << [this, row](){ expr_edited(row); };
}
else
par_setup.parameter_view.Set(overwrite_row, 1, index_str);
return true;
}
void OptimizationWindow::symbol_edited(int row) {
int idx = par_setup.parameter_view.Get(row, "__idx");
parameters[idx].symbol = par_setup.parameter_view.Get(row, "__sym").ToStd();
}
void OptimizationWindow::expr_edited(int row) {
int idx = par_setup.parameter_view.Get(row, "__idx");
parameters[idx].expr = par_setup.parameter_view.Get(row, "__expr").ToStd();
}
void OptimizationWindow::add_parameter_clicked() {
Indexed_Parameter &par = parent->params.get_selected_parameter();
add_single_parameter(par);
}
void OptimizationWindow::add_virtual_clicked() {
Indexed_Parameter par(parent->model);
par.virt = true;
add_single_parameter(par);
}
void OptimizationWindow::add_group_clicked() {
auto pars = parent->params.get_all_parameters();
for(Indexed_Parameter &par : pars)
add_single_parameter(par);
}
void OptimizationWindow::remove_parameter_clicked() {
int sel_row = par_setup.parameter_view.GetCursor();
if(sel_row < 0) return;
//int idx = par_setup.parameter_view.Get(sel_row, "__idx");
par_setup.parameter_view.Remove(sel_row);
//parameters.erase(parameters.begin()+idx); // NOTE: We can't do this, because then we
// invalidate the indexes that are stored in the row for the rest of them...
edit_min_ctrls.Remove(sel_row);
edit_max_ctrls.Remove(sel_row);
edit_sym_ctrls.Remove(sel_row);
edit_expr_ctrls.Remove(sel_row);
}
void OptimizationWindow::clear_parameters_clicked() {
par_setup.parameter_view.Clear();
parameters.clear();
edit_min_ctrls.Clear();
edit_max_ctrls.Clear();
edit_sym_ctrls.Clear();
edit_expr_ctrls.Clear();
}
void OptimizationWindow::add_optimization_target(Optimization_Target &target) {
targets.push_back(target);
auto app = parent->app;
//get_storage_and_var(&app->data, target.sim_id, &sim_data, &var_sim);
auto *sim_data = &app->data.get_storage(target.sim_id.type);
auto var_sim = app->vars[target.sim_id];
String sim_index_str = make_index_string(sim_data->structure, target.indexes, target.sim_id);
Data_Storage<double, Var_Id> *obs_data;
State_Var *var_obs;
String obs_index_str;
String obs_name;
if(is_valid(target.obs_id)) {
//get_storage_and_var(&app->data, target.obs_id, &obs_data, &var_obs);
obs_data = &app->data.get_storage(target.obs_id.type);
var_obs = app->vars[target.obs_id];
obs_index_str = make_index_string(obs_data->structure, target.indexes, target.obs_id);
obs_name = var_obs->name.data();
}
target_stat_ctrls.Create<DropList>();
DropList &sel_stat = target_stat_ctrls.Top();
int tab = target_setup.optimizer_type_tab.Get();
if(tab == 2) {
#define SET_STATISTIC(handle, name) sel_stat.Add((int)Stat_Type::handle, name);
#include "support/stat_types.incl"
#undef SET_STATISTIC
}
if(tab == 0 || tab == 2) {
#define SET_RESIDUAL(handle, name, type) if(type != -1) sel_stat.Add((int)Residual_Type::handle, name);
#include "support/residual_types.incl"
#undef SET_RESIDUAL
}
if(tab == 0 || tab == 1)
{
#define SET_LOG_LIKELIHOOD(handle, name, n_resid_par) sel_stat.Add((int)LL_Type::handle, name);
#include "support/log_likelihood_types.incl"
#undef SET_LOG_LIKELIHOOD
}
target_setup.target_view.Add(var_sim->name.data(), sim_index_str, obs_name, obs_index_str, target.stat_type, "", target.weight,
convert_time(target.start), convert_time(target.end));
int row = target_setup.target_view.GetCount()-1;
int col = target_setup.target_view.GetPos(Id("__targetstat"));
target_setup.target_view.SetCtrl(row, col, sel_stat);
sel_stat.WhenAction << [this, row]() { stat_edited(row); };
if(target.stat_type >= 0 && target.stat_type <= (int)LL_Type::end)
sel_stat.SetData(target.stat_type);
else
sel_stat.GoBegin();
target_err_ctrls.Create<EditField>();
EditField &err_ctrl = target_err_ctrls.Top();
col = target_setup.target_view.GetPos(Id("__errparam"));
target_setup.target_view.SetCtrl(row, col, err_ctrl);
err_ctrl.WhenAction << [this, row](){ err_sym_edited(row); };
target_weight_ctrls.Create<EditDoubleNotNull>();
EditDoubleNotNull &edit_wt = target_weight_ctrls.Top();
edit_wt.Min(0.0);
col = target_setup.target_view.GetPos(Id("__weight"));
target_setup.target_view.SetCtrl(row, col, edit_wt);
edit_wt.WhenAction << [this, row](){ weight_edited(row); };
target_start_ctrls.Create<EditTimeNotNull>();
EditTimeNotNull &edit_start = target_start_ctrls.Top();
col = target_setup.target_view.GetPos(Id("__start"));
target_setup.target_view.SetCtrl(row, col, edit_start);
edit_start.WhenAction << [this, row](){ start_edited(row); };
target_end_ctrls.Create<EditTimeNotNull>();
EditTimeNotNull &edit_end = target_end_ctrls.Top();
col = target_setup.target_view.GetPos(Id("__end"));
target_setup.target_view.SetCtrl(row, col, edit_end);
edit_end.WhenAction << [this, row](){ end_edited(row); };
}
void OptimizationWindow::stat_edited(int row) {
targets[row].stat_type = (int)target_stat_ctrls[row].GetData();
//PromptOK(Format("Set stat to %d", targets[row].stat_type));
}
void OptimizationWindow::err_sym_edited(int row) {
// NOTE: we don't update the stored err params here, instead we do it right before the run.
}
void OptimizationWindow::weight_edited(int row) {
targets[row].weight = (double)target_setup.target_view.Get(row, "__weight");
}
void OptimizationWindow::start_edited(int row) {
targets[row].start = convert_time((Time)target_setup.target_view.Get(row, "__start"));
}
void OptimizationWindow::end_edited(int row) {
targets[row].end = convert_time((Time)target_setup.target_view.Get(row, "__end"));
}
void OptimizationWindow::add_target_clicked() {
Plot_Setup setup;
parent->plotter.get_plot_setup(setup);
if(setup.selected_results.size() != 1 || setup.selected_series.size() > 1) {
set_error("Can only add a target that has a single selected result series and at most one input series.");
return;
}
for(int idx = 0; idx < setup.selected_indexes.size(); ++idx) {
if(setup.selected_indexes[idx].size() != 1 && setup.index_set_is_active[idx]) {
set_error("Can only add a target with one single selected index per index set.");
return;
}
}
Optimization_Target target(parent->model);
target.sim_id = setup.selected_results[0];
target.obs_id = setup.selected_series.empty() ? invalid_var : setup.selected_series[0];
get_single_indexes(parent->app, target.indexes, setup);
// TODO: We should set index to invalid in target.indexes if this particular target does
// not depend on it.
target.weight = 1.0;
int tab = target_setup.optimizer_type_tab.Get();
//NOTE: Defaults.
if(tab == 0) target.stat_type = (int)Residual_Type::offset + 2; // +1 selects "mean error", which can't be optimized.
else if(tab == 1) target.stat_type = (int)LL_Type::offset + 1;
else if(tab == 2) target.stat_type = (int)Stat_Type::offset + 1;
Time start_setting = parent->calib_start.GetData();
Time end_setting = parent->calib_end.GetData();
Date_Time result_start = parent->app->data.get_start_date_parameter();
Date_Time result_end = parent->app->data.get_end_date_parameter();
target.start = IsNull(start_setting) ? result_start : convert_time(start_setting);
target.end = IsNull(end_setting) ? result_end : convert_time(end_setting);
add_optimization_target(target);
}
Plot_Setup
target_to_plot_setup(Optimization_Target &target, Model_Application *app) {
Plot_Setup setup = {};
setup.selected_indexes.resize(app->model->index_sets.count());
setup.index_set_is_active.resize(app->model->index_sets.count());
setup.mode = Plot_Mode::regular;
setup.aggregation_period = Aggregation_Period::none;
setup.scatter_inputs = true;
setup.selected_results.push_back(target.sim_id);
if(is_valid(target.obs_id))
setup.selected_series.push_back(target.obs_id);
for(int idx = 0; idx < app->model->index_sets.count(); ++idx) {
if(is_valid(target.indexes.indexes[idx]))
setup.selected_indexes[idx].push_back(target.indexes.indexes[idx]);
}
// TODO: not that clean to have this as a function on the Plot_Ctrl...
register_if_index_set_is_active(setup, app);
return setup;
}
void OptimizationWindow::display_clicked() {
if(targets.empty()) {
set_error("There are no targets to display the plots of");
return;
}
if(!parent->model_is_loaded()) return;
set_error("");
std::vector<Plot_Setup> plot_setups;
for(auto &target : targets)
plot_setups.push_back(target_to_plot_setup(target, parent->app));
//TODO: Same issue as for sensitivity view. Would like to zoom it to the area of the result
//series only, not the entire input data span.
parent->additional_plots.set_all(plot_setups);
parent->open_additional_plots();
}
void OptimizationWindow::remove_target_clicked() {
int sel_row = target_setup.target_view.GetCursor();
if(sel_row < 0) return;
target_setup.target_view.Remove(sel_row);
targets.erase(targets.begin()+sel_row);
target_weight_ctrls.Remove(sel_row);
target_stat_ctrls.Remove(sel_row);
target_err_ctrls.Remove(sel_row);
target_start_ctrls.Remove(sel_row);
target_end_ctrls.Remove(sel_row);
}
void OptimizationWindow::clear_targets_clicked() {
target_setup.target_view.Clear();
targets.clear();
target_weight_ctrls.Clear();
target_stat_ctrls.Clear();
target_err_ctrls.Clear();
target_start_ctrls.Clear();
target_end_ctrls.Clear();
}
void OptimizationWindow::clean() {
clear_parameters_clicked();
clear_targets_clicked();
}
void OptimizationWindow::sampler_method_selected() {
//TODO
MCMC_Sampler method = (MCMC_Sampler)(int)mcmc_setup.select_sampler.GetData();
mcmc_setup.sampler_param_view.Clear();
mcmc_sampler_param_ctrls.Clear();
switch(method) {
case MCMC_Sampler::affine_stretch : {
mcmc_setup.sampler_param_view.Add("a", 2.0, "Max. stretch factor");
} break;
case MCMC_Sampler::affine_walk : {
mcmc_setup.sampler_param_view.Add("|S|", 10.0, "Size of sub-ensemble. Has to be between 2 and NParams/2.");
} break;
case MCMC_Sampler::differential_evolution : {
mcmc_setup.sampler_param_view.Add("γ", -1.0, "Stretch factor. If negative, will be set to default of 2.38/sqrt(2*dim)");
mcmc_setup.sampler_param_view.Add("b", 1e-3, "Max. random walk step (multiplied by |max - min| for each par.)");
mcmc_setup.sampler_param_view.Add("CR", 1.0, "Crossover probability");
} break;
case MCMC_Sampler::metropolis_hastings : {
mcmc_setup.sampler_param_view.Add("b", 0.02, "Std. dev. of random walk step (multiplied by |max - min| for each par.)");
} break;
}
int rows = mcmc_setup.sampler_param_view.GetCount();
mcmc_sampler_param_ctrls.InsertN(0, rows);
for(int row = 0; row < rows; ++row)
mcmc_setup.sampler_param_view.SetCtrl(row, 1, mcmc_sampler_param_ctrls[row]);
}
struct
MCMC_Run_Data {
MC_Data *data;
std::vector<Optimization_Model> optim_models;
double *min_bound;
double *max_bound;
};
struct
MCMC_Callback_Data {
MobiView2 *parent_win;
MCMCResultWindow *result_win;
};
bool
mcmc_callback(void *callback_data, int step) {
auto *cbd = (MCMC_Callback_Data *)callback_data;
//if(CBD->ParentWindow->MCMCResultWin.HaltWasPushed)
// return false;
// TODO!
//GuiLock lock;
cbd->result_win->refresh_plots(step);
cbd->parent_win->ProcessEvents();
return true;
}
double
mcmc_ll_eval(void *run_data_0, int walker, int step) {
MCMC_Run_Data *run_data = (MCMC_Run_Data *)run_data_0;
MC_Data *data = run_data->data;
std::vector<double> pars(data->n_pars);
for(int par = 0; par < data->n_pars; ++par) {
double val = (*data)(walker, par, step);
if(val < run_data->min_bound[par] || val > run_data->max_bound[par])
return -std::numeric_limits<double>::infinity();
pars[par] = val;
}
return run_data->optim_models[walker].evaluate(pars);
}
bool
OptimizationWindow::run_mcmc_from_window(MCMC_Sampler method, double *sampler_params, int n_walkers, int n_pars, int n_steps, Optimization_Model *optim,
std::vector<double> &initial_values, std::vector<double> &min_bound, std::vector<double> &max_bound, int init_type, int callback_interval, int run_type)
{
int init_step = 0;
MCMCResultWindow *result_win = &parent->mcmc_window;
result_win->clean();
{
GuiLock lock;
if(!result_win->IsOpen())
result_win->Open();
if(run_type == 2) { // NOTE RunType==2 means extend the previous run.
if(mc_data.n_steps == 0) {
set_error("Can't extend a run before the model has been run once");
return false;
}
if(mc_data.n_steps >= n_steps) {
set_error(Format("To extend the run, you must set a higher number of timesteps than previously. Previous was %d.", (int)mc_data.n_steps));
return false;
}
if(mc_data.n_walkers != n_walkers) {
set_error("To extend the run, you must have the same amount of walkers as before.");
return false;
}
//TODO
/*
if(ResultWin->Parameters != Parameters || ResultWin->Targets != Targets) {
//TODO: Could alternatively let you continue with the old parameter set.
SetError("You can't extend the run since the parameters or targets have changed.");
return false;
}
*/
init_step = mc_data.n_steps - 1;
mc_data.extend_steps(n_steps);
} else {
mc_data.free_data();
mc_data.allocate(n_walkers, n_pars, n_steps);
}
//NOTE: These have to be cached so that we don't have to rely on the optimization window
//not being edited (and going out of sync with the data)
result_win->expr_pars.copy(expr_pars);
result_win->targets = targets;
result_win->choose_plots_tab.Set(0);
result_win->begin_new_plots(mc_data, min_bound, max_bound, run_type);
//parent->ProcessEvents();
if(run_type == 1) {
// For a completely new run, initialize the walkers randomly
std::mt19937_64 gen;
for(int walker = 0; walker < n_walkers; ++walker) {
for(int par = 0; par < n_pars; ++par) {
double initial = initial_values[par];
double draw = initial;
if(init_type == 0) {
//Initializing walkers to a gaussian ball around the initial parameter values.
double std_dev = (max_bound[par] - min_bound[par])/400.0; //TODO: How to choose scaling coefficient?
std::normal_distribution<double> distr(initial, std_dev);
draw = distr(gen);
draw = std::max(min_bound[par], draw);
draw = std::min(max_bound[par], draw);
} else if(init_type == 1) {
std::uniform_real_distribution<double> distr(min_bound[par], max_bound[par]);
draw = distr(gen);
} else
PromptOK("Internal error, wrong intial type");
mc_data(walker, par, 0) = draw;
}
}
}
}
parent->ProcessEvents();
std::vector<double> scales(n_pars);
for(int par = 0; par < n_pars; ++par)
scales[par] = max_bound[par] - min_bound[par];
//TODO: We really only need a set of optim models that is the size of a
//partial ensemble, which is about half of the total ensemble.
MCMC_Run_Data run_data;
for(int walker = 0; walker < n_walkers; ++walker) {
Optimization_Model opt = *optim;
opt.data = optim->data->copy(false);
run_data.optim_models.push_back(opt);
}
run_data.data = &mc_data;
run_data.min_bound = min_bound.data();
run_data.max_bound = max_bound.data();
MCMC_Callback_Data callback_data;
callback_data.parent_win = parent;
callback_data.result_win = result_win;
//TODO: We should check the sampler_params for correctness somehow!
bool finished = false;
#if CATCH_ERRORS
try {
#endif
finished =
run_mcmc(method, sampler_params, scales.data(), mcmc_ll_eval, &run_data, mc_data, mcmc_callback, &callback_data, callback_interval, init_step);
#if CATCH_ERRORS
} catch(int) {
}
#endif
parent->log_warnings_and_errors();
// Clean up copied data.
for(int walker = 0; walker < n_walkers; ++walker)
delete run_data.optim_models[walker].data;
return finished;
}
struct Sensitivity_Target_State {
std::vector<Optimization_Model> optim_models;
};
double
sensitivity_target_fun(void *state, int worker, const std::vector<double> &values) {
auto target_state = static_cast<Sensitivity_Target_State *>(state);
double result = target_state->optim_models[worker].evaluate(values);
return result;
}
struct Sensitivity_Callback_State {
VarianceSensitivityWindow *result_window;
MobiView2 *parent;
};
bool
sensitivity_callback(void *state, int cb_type, int par_or_sample, double main_ei, double total_ei) {
auto callback_state = static_cast<Sensitivity_Callback_State *>(state);
if(cb_type == 0) {
auto &sp = callback_state->result_window->show_progress;
sp.Set(par_or_sample);
} else {
double prec = callback_state->parent->stat_settings.display_settings.decimal_precision;
int par = par_or_sample;
callback_state->result_window->result_data.Set(par, "__main", FormatDouble(main_ei, prec));
callback_state->result_window->result_data.Set(par, "__total", FormatDouble(total_ei, prec));
}
callback_state->parent->ProcessEvents();
return true;
}
bool
OptimizationWindow::run_variance_based_sensitivity(int n_samples, int sample_method, Optimization_Model *optim, double *min_bound, double *max_bound) {
int n_pars = optim->initial_pars.size();
auto n_threads = std::thread::hardware_concurrency();
int n_workers = std::max(32, (int)n_threads);
Sensitivity_Target_State target_state;
for(int worker = 0; worker < n_workers; ++worker) {
Optimization_Model opt = *optim;
opt.data = optim->data->copy(false);
target_state.optim_models.push_back(opt);
}
auto win = &parent->variance_window;
win->clean();
Sensitivity_Callback_State callback_state;
callback_state.result_window = win;
callback_state.parent = parent;
int callback_interval = 10*n_workers; //TODO: Make the caller set this. Note, it must be a multiple of 2*n_workers
int total_samples = n_samples*(2 + n_pars);
win->show_progress.Set(0, total_samples);
win->show_progress.Show();
// TODO: Actually need one more type of callback for just regular progress update.
int idx = 0;
for(Indexed_Parameter &par : optim->parameters->parameters) {
if(!optim->parameters->exprs[idx])
win->result_data.Add(par.symbol.data(), Null, Null);
}
parent->ProcessEvents();
std::vector<double> samples;
compute_effect_indexes(n_samples, n_pars, n_workers, sample_method, min_bound, max_bound,
sensitivity_target_fun, &target_state, sensitivity_callback, &callback_state, callback_interval, samples);
// Clean up copied data.
for(int worker = 0; worker < n_workers; ++worker)
delete target_state.optim_models[worker].data;
std::vector<double> xs(samples.size());
win->plot.series_data.Create<Data_Source_Owns_XY>(&xs, &samples);
auto *data = &win->plot.series_data.Top();
int n_bins_histogram = add_histogram(&win->plot, data, data->MinY(), data->MaxY(), data->GetCount(), Null, Null, win->plot.colors.next());
format_axes(&win->plot, Plot_Mode::histogram, n_bins_histogram, {}, {});
win->plot.ShowLegend(false);
win->plot.Refresh();
win->show_progress.Hide();
//TODO: Maybe error handling
return true;
}
VarianceSensitivityWindow::VarianceSensitivityWindow() {
CtrlLayout(*this, "MobiView2 variance based sensitivity results");
MinimizeBox().Sizeable().Zoomable();
show_progress.Set(0, 1);
show_progress.Hide();
result_data.AddColumn("__par", "Parameter");
result_data.AddColumn("__main", "First-order sensitivity coefficient");
result_data.AddColumn("__total", "Total effect index");
plot.SetLabels("Combined statistic", "Frequency");
}
void
VarianceSensitivityWindow::clean() {
result_data.Clear();
plot.clean();
}
bool
OptimizationWindow::err_sym_fixup() {
std::unordered_map<std::string, std::pair<int,int>> sym_row;
// TODO: Should not give error if "Enable expressions" is not checked.
int active_idx = 0;
for(int row = 0; row < expr_pars.parameters.size(); ++row) {
auto ¶meter = expr_pars.parameters[row];
if(!parameter.symbol.empty()) {
if(sym_row.find(parameter.symbol) != sym_row.end()) {
set_error(Format("The parameter symbol %s appears twice", parameter.symbol.data()));
return false;
}
sym_row[parameter.symbol] = {row, active_idx};
}
if(!expr_pars.exprs[row].get())
++active_idx;
}
int row = 0;
for(Optimization_Target &target : targets) {
target.err_par_idx.clear();
String syms = target_setup.target_view.Get(row++, Id("__errparam"));
Vector<String> symbols = Split(syms, ',', true);
auto stat_class = is_stat_class(target.stat_type);
if(stat_class == Stat_Class::log_likelihood) {
for(String &sym : symbols) { sym = TrimLeft(TrimRight(sym)); }
#define SET_LOG_LIKELIHOOD(handle, name, n_err) \
else if((LL_Type)target.stat_type == LL_Type::handle && symbols.size() != n_err) {\
set_error(Format("The error structure %s requires %d error parameters. Only %d were provided. Provide them as a comma-separated list of parameter symbols", name, n_err, symbols.size())); \
return false; \
}
if(false) {}
#include "support/log_likelihood_types.incl"
#undef SET_LOG_LIKELIHOOD
for(String &sym0 : symbols) {
std::string sym = sym0.ToStd();
if(sym_row.find(sym) == sym_row.end()) {
set_error(Format("The error parameter symbol '%s' is not the symbol of a parameter in the parameter list.", sym.data()));
return false;
}
int par_sym_row = sym_row[sym].first;
Indexed_Parameter &par = expr_pars.parameters[par_sym_row];
if(!par.virt) {
set_error(Format("Only virtual parameters can be error parameters. The parameter with symbol '%s' is not virtual", sym.data()));
return false;
}
if(expr_pars.exprs[par_sym_row].get()) {
set_error(Format("Error parameters can not be results of expressions. The parameter with symbol '%s' was set as an error parameter, but also has an expression", sym.data()));
return false;
}
target.err_par_idx.push_back(sym_row[sym].second);
}
} else if(!symbols.empty()) {
set_error("An error symbol was provided for a stat does not use one");
return false;
}
}
return true;
}
void OptimizationWindow::run_clicked(int run_type)
{
//RunType:
// 0 = Optimizer
// 1 = New MCMC
// 2 = Extend MCMC
// 3 = Variance based sensitivity
set_error("");
int n_rows = par_setup.parameter_view.GetCount();
if(!n_rows) {
set_error("At least one parameter must be added before running");
ProcessEvents();
return;
}
if(targets.empty()) {
set_error("There must be at least one optimization target.");
return;
}
int cl = 1;
if(parent->params.changed_since_last_save)
cl = PromptYesNo("The main parameter set has been edited since the last save. If run the optimizer now it will overwrite these changes. Do you still want to run the optimizer?");
if(!cl)
return;
auto app = parent->app;
std::vector<Indexed_Parameter> sorted_params;
for(int row = 0; row < n_rows; ++row) {
int idx = par_setup.parameter_view.Get(row, "__idx");
sorted_params.push_back(parameters[idx]);
}
bool error = false;
#if CATCH_ERRORS
try {
#endif
// NOTE: Must set the expr_pars before we call err_sym_fixup() !
expr_pars.set(app, sorted_params);
#if CATCH_ERRORS
} catch (int) {
set_error("There was an error. See the main log window.");
error = true;
}
#endif
parent->log_warnings_and_errors();
if(error) return;
bool success = err_sym_fixup();
if(!success) return;
Model_Data *data = app->data.copy(); //TODO: more granular spec on what parts to copy.
std::vector<double> initial_pars, min_vals, max_vals;
int active_idx = 0;
for(int row = 0; row < n_rows; ++row) {
if(expr_pars.exprs[row].get()) continue; // Don't check for parameters that have expressions.
auto &par = expr_pars.parameters[row];
double min = (double)par_setup.parameter_view.Get(row, Id("__min"));
double max = (double)par_setup.parameter_view.Get(row, Id("__max"));
double init;
if(par.virt) {
init = (max - min)*0.5; //TODO: we should have a system for allowing you to set the initial value.
} else {
if(!is_valid(par.id)) { // This should technically not be possible
set_error("Somehow we got an invalid parameter id for one of the parameters in the setup.");
return;
}
s64 offset = data->parameters.structure->get_offset(par.id, par.indexes);
Parameter_Value val = *data->parameters.get_value(offset);
init = val.val_real; // We already checked that the parameter was of type real when we added it.
}
String name = par_setup.parameter_view.Get(row, Id("__name"));
if(min >= max) {
set_error(Format("The parameter \"%s\" has a min value %f that is larger than or equal to the max value %f", name, min, max));
return;
}
if(init < min) {
set_error(Format("The parameter \"%s\" has an initial value %f that is smaller than the min value %f", name, init, min));
return;
}
if(init > max) {
set_error(Format("The parameter \"%s\" has an initial value %f that is larger than the max value %f", name, init, max));
return;
}
if((run_type==1 || run_type==2 || run_type==3) && par.symbol == "") {
set_error("You should provide a symbol for all the parameters that don't have an expression.");