-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimizationWindow.cpp
2382 lines (1855 loc) · 72.2 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
#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 DLIB_NO_GUI_SUPPORT //NOTE: Turns off dlib's own GUI since we are using upp.
#include "dlib/optimization.h"
#include "dlib/global_optimization.h"
#include "MobiView.h"
#include <unordered_map>
#define IMAGECLASS IconImg4
#define IMAGEFILE <MobiView/images.iml>
#include <Draw/iml.h>
OptimizationParameterSetup::OptimizationParameterSetup()
{
CtrlLayout(*this);
}
OptimizationTargetSetup::OptimizationTargetSetup()
{
CtrlLayout(*this);
}
OptimizationRunSetup::OptimizationRunSetup()
{
CtrlLayout(*this);
}
MCMCRunSetup::MCMCRunSetup()
{
CtrlLayout(*this);
}
SensitivityRunSetup::SensitivityRunSetup()
{
CtrlLayout(*this);
}
target_stat_class
GetStatClass(optimization_target &Target)
{
target_stat_class Result = StatClass_Unknown;
int Stat = (int)Target.Stat;
if(Stat > (int)StatType_Offset && Stat < (int)StatType_End)
Result = StatClass_Stat;
else if(Stat > (int)ResidualType_Offset && Stat < (int)ResidualType_End)
Result = StatClass_Residual;
else if(Stat > (int)MCMCError_Offset && Stat < (int)MCMCError_End)
Result = StatClass_LogLikelihood;
return Result;
}
OptimizationWindow::OptimizationWindow()
{
SetRect(0, 0, 740, 740);
Title("MobiView optimization and MCMC setup").Sizeable().Zoomable();
ParSetup.ParameterView.AddColumn(Id("__name"), "Name");
ParSetup.ParameterView.AddColumn(Id("__indexes"), "Indexes");
ParSetup.ParameterView.AddColumn(Id("__min"), "Min");
ParSetup.ParameterView.AddColumn(Id("__max"), "Max");
ParSetup.ParameterView.AddColumn(Id("__unit"), "Unit");
ParSetup.ParameterView.AddColumn(Id("__sym"), "Symbol");
ParSetup.ParameterView.AddColumn(Id("__expr"), "Expression");
ParSetup.OptionUseExpr.Set((int)false);
ParSetup.OptionUseExpr.WhenAction = THISBACK(EnableExpressionsClicked);
ParSetup.ParameterView.HeaderObject().HideTab(5);
ParSetup.ParameterView.HeaderObject().HideTab(6);
TargetSetup.TargetView.AddColumn(Id("__resultname"), "Result name");
TargetSetup.TargetView.AddColumn(Id("__resultindexes"), "Result idxs.");
TargetSetup.TargetView.AddColumn(Id("__inputname"), "Input name");
TargetSetup.TargetView.AddColumn(Id("__inputindexes"), "Input idxs.");
TargetSetup.TargetView.AddColumn(Id("__targetstat"), "Statistic");
TargetSetup.TargetView.AddColumn(Id("__errparam"), "Error param(s).");
TargetSetup.TargetView.AddColumn(Id("__weight"), "Weight");
TargetSetup.TargetView.AddColumn(Id("__begin"), "Begin");
TargetSetup.TargetView.AddColumn(Id("__end"), "End");
//TargetSetup.TargetView.HeaderObject().HideTab(5);
TargetSetup.EditTimeout.SetData(-1);
ParSetup.PushAddParameter.WhenPush = THISBACK(AddParameterClicked);
ParSetup.PushAddGroup.WhenPush = THISBACK(AddGroupClicked);
ParSetup.PushRemoveParameter.WhenPush = THISBACK(RemoveParameterClicked);
ParSetup.PushClearParameters.WhenPush = THISBACK(ClearParametersClicked);
ParSetup.PushAddVirtual.WhenPush = THISBACK(AddVirtualClicked);
ParSetup.PushAddParameter.SetImage(IconImg4::Add());
ParSetup.PushAddGroup.SetImage(IconImg4::AddGroup());
ParSetup.PushRemoveParameter.SetImage(IconImg4::Remove());
ParSetup.PushClearParameters.SetImage(IconImg4::RemoveGroup());
ParSetup.PushAddVirtual.SetImage(IconImg4::Add());
ParSetup.PushAddVirtual.Disable();
ParSetup.PushAddVirtual.Hide();
TargetSetup.PushAddTarget.WhenPush = THISBACK(AddTargetClicked);
TargetSetup.PushRemoveTarget.WhenPush = THISBACK(RemoveTargetClicked);
TargetSetup.PushClearTargets.WhenPush = THISBACK(ClearTargetsClicked);
TargetSetup.PushDisplay.WhenPush = THISBACK(DisplayClicked);
TargetSetup.PushAddTarget.SetImage(IconImg4::Add());
TargetSetup.PushRemoveTarget.SetImage(IconImg4::Remove());
TargetSetup.PushClearTargets.SetImage(IconImg4::RemoveGroup());
TargetSetup.PushDisplay.SetImage(IconImg4::ViewMorePlots());
RunSetup.PushRun.WhenPush = [&](){ RunClicked(0); };
RunSetup.PushRun.SetImage(IconImg4::Run());
RunSetup.EditMaxEvals.Min(1);
RunSetup.EditMaxEvals.SetData(1000);
RunSetup.EditEpsilon.Min(0.0);
RunSetup.EditEpsilon.SetData(0.0);
RunSetup.OptionShowProgress.SetData(true);
MCMCSetup.PushRun.WhenPush = [&](){ RunClicked(1); };
MCMCSetup.PushRun.SetImage(IconImg4::Run());
MCMCSetup.PushViewChains.WhenPush << [&]() { if(!ParentWindow->MCMCResultWin.IsOpen()) ParentWindow->MCMCResultWin.Open(); };
MCMCSetup.PushViewChains.SetImage(IconImg4::ViewMorePlots());
MCMCSetup.PushExtendRun.WhenPush = [&](){ RunClicked(2); };
MCMCSetup.PushExtendRun.Disable();
MCMCSetup.PushExtendRun.SetImage(IconImg4::Run());
MCMCSetup.EditSteps.Min(10);
MCMCSetup.EditSteps.SetData(1000);
MCMCSetup.EditWalkers.Min(10);
MCMCSetup.EditWalkers.SetData(25);
MCMCSetup.InitialTypeSwitch.SetData(0);
MCMCSetup.SamplerParamView.AddColumn("Name");
MCMCSetup.SamplerParamView.AddColumn("Value");
MCMCSetup.SamplerParamView.AddColumn("Description");
MCMCSetup.SamplerParamView.ColumnWidths("3 2 5");
MCMCSetup.SelectSampler.Add((int)MCMCMethod_AffineStretch, "Affine stretch (recommended)");
MCMCSetup.SelectSampler.Add((int)MCMCMethod_AffineWalk, "Affine walk");
MCMCSetup.SelectSampler.Add((int)MCMCMethod_DifferentialEvolution, "Differential evolution");
MCMCSetup.SelectSampler.Add((int)MCMCMethod_MetropolisHastings, "Metropolis-Hastings (independent chains)");
MCMCSetup.SelectSampler.GoBegin();
MCMCSetup.SelectSampler.WhenAction << THISBACK(SamplerMethodSelected);
SamplerMethodSelected(); //To set the sampler parameters for the initial selection
SensitivitySetup.EditSampleSize.Min(10);
SensitivitySetup.EditSampleSize.SetData(1000);
SensitivitySetup.PushRun.WhenPush = [&](){ RunClicked(3); };
SensitivitySetup.PushViewResults.WhenPush = [&]() { if(!ParentWindow->VarSensitivityWin.IsOpen()) ParentWindow->VarSensitivityWin.Open(); };
SensitivitySetup.PushRun.SetImage(IconImg4::Run());
SensitivitySetup.PushViewResults.SetImage(IconImg4::ViewMorePlots());
SensitivitySetup.SelectMethod.Add(0, "Latin hypercube");
SensitivitySetup.SelectMethod.Add(1, "Independent uniform");
SensitivitySetup.SelectMethod.GoBegin();
AddFrame(Tool);
Tool.Set(THISBACK(SubBar));
TargetSetup.OptimizerTypeTab.Add(RunSetup.SizePos(), "Optimizer");
TargetSetup.OptimizerTypeTab.Add(MCMCSetup.SizePos(), "MCMC");
TargetSetup.OptimizerTypeTab.Add(SensitivitySetup.SizePos(), "Variance based sensitivity");
TargetSetup.OptimizerTypeTab.WhenSet << THISBACK(TabChange);
MainVertical.Vert();
MainVertical.Add(ParSetup);
MainVertical.Add(TargetSetup);
Add(MainVertical.SizePos());
}
void OptimizationWindow::SetError(const String &ErrStr)
{
TargetSetup.ErrorLabel.SetText(ErrStr);
}
void OptimizationWindow::SubBar(Bar &bar)
{
bar.Add(IconImg4::Open(), THISBACK(LoadFromJson)).Tip("Load setup from file");
bar.Add(IconImg4::Save(), THISBACK(WriteToJson)).Tip("Save setup to file");
}
void OptimizationWindow::EnableExpressionsClicked()
{
bool Value = (bool)ParSetup.OptionUseExpr.Get();
if(Value)
{
ParSetup.ParameterView.HeaderObject().ShowTab(5);
ParSetup.ParameterView.HeaderObject().ShowTab(6);
ParSetup.PushAddVirtual.Enable();
ParSetup.PushAddVirtual.Show();
}
else
{
ParSetup.ParameterView.HeaderObject().HideTab(5);
ParSetup.ParameterView.HeaderObject().HideTab(6);
ParSetup.PushAddVirtual.Disable();
ParSetup.PushAddVirtual.Hide();
}
}
bool OptimizationWindow::AddSingleParameter(indexed_parameter &Parameter, int SourceRow, bool ReadAdditionalData)
{
if(SourceRow == -1) return false;
if(Parameter.Type != ParameterType_Double) return false; //TODO: Dlib has provision for allowing integer parameters
int OverrideRow = -1;
int Row = 0;
if(!Parameter.Virtual)
{
for(indexed_parameter &Par2 : Parameters)
{
if(ParameterIsSubsetOf(Parameter, Par2)) return false;
if(ParameterIsSubsetOf(Par2, Parameter))
{
Par2 = Parameter;
OverrideRow = Row;
}
++Row;
}
}
String Indexes = MakeParameterIndexString(Parameter);
if(OverrideRow < 0)
{
//TODO: Maybe min and max should be put on the indexed_parameter, but that is pretty superfluous
//for the other purposes this struct is used for.
double Min = Null;
double Max = Null;
String ParUnit = "";
String Symbol = Parameter.Symbol.data();
String Expr = Parameter.Expr.data();
if(ReadAdditionalData)
{
Min = ParentWindow->Params.ParameterView.Get(SourceRow, Id("__min"));
Max = ParentWindow->Params.ParameterView.Get(SourceRow, Id("__max"));
ParUnit = ParentWindow->Params.ParameterView.Get(SourceRow, Id("__unit"));
Symbol = ParentWindow->ModelDll.GetParameterShortName(ParentWindow->DataSet, Parameter.Name.data());
}
Parameter.Symbol = Symbol.ToStd();
Parameters.push_back(Parameter);
ParSetup.ParameterView.Add(Parameter.Name.data(), Indexes, Min, Max, ParUnit, Symbol, Expr);
int Row = Parameters.size()-1;
EditMinCtrls.Create<EditDoubleNotNull>();
EditMaxCtrls.Create<EditDoubleNotNull>();
ParSetup.ParameterView.SetCtrl(Row, 2, EditMinCtrls[Row]);
ParSetup.ParameterView.SetCtrl(Row, 3, EditMaxCtrls[Row]);
EditSymCtrls.Create<EditField>();
EditExprCtrls.Create<EditField>();
ParSetup.ParameterView.SetCtrl(Row, 5, EditSymCtrls[Row]);
ParSetup.ParameterView.SetCtrl(Row, 6, EditExprCtrls[Row]);
EditSymCtrls[Row].WhenAction << [this, Row](){ SymbolEdited(Row); };
EditExprCtrls[Row].WhenAction << [this, Row](){ ExprEdited(Row); };
}
else
{
ParSetup.ParameterView.Set(OverrideRow, 1, Indexes);
}
return true;
}
void OptimizationWindow::SymbolEdited(int Row)
{
String Symbol = ParSetup.ParameterView.Get(Row, "__sym");
Parameters[Row].Symbol = Symbol.ToStd();
}
void OptimizationWindow::ExprEdited(int Row)
{
String Expr = ParSetup.ParameterView.Get(Row, "__expr");
Parameters[Row].Expr = Expr.ToStd();
}
void OptimizationWindow::AddParameterClicked()
{
int SelectedRow = ParentWindow->FindSelectedParameterRow();
indexed_parameter &Parameter = ParentWindow->CurrentSelectedParameter;
if(SelectedRow==-1 || !Parameter.Valid) return; //TODO: Some kind of error message explaining how to use the feature?
AddSingleParameter(Parameter, SelectedRow);
}
void OptimizationWindow::AddVirtualClicked()
{
indexed_parameter Parameter = {};
Parameter.Name = "(virtual)";
Parameter.Valid = true;
Parameter.Virtual = true;
Parameter.Type = ParameterType_Double;
AddSingleParameter(Parameter, 0, false);
}
void OptimizationWindow::AddGroupClicked()
{
int RowCount = ParentWindow->Params.ParameterView.GetCount();
for(int Row = 0; Row < RowCount; ++Row)
{
indexed_parameter Parameter = ParentWindow->GetParameterAtRow(Row);
if(Parameter.Valid)
AddSingleParameter(Parameter, Row);
}
}
void OptimizationWindow::RemoveParameterClicked()
{
int SelectedRow = -1;
for(int Row = 0; Row < ParSetup.ParameterView.GetCount(); ++Row)
{
if(ParSetup.ParameterView.IsSel(Row))
{
SelectedRow = Row;
break;
}
}
if(SelectedRow == -1) return;
ParSetup.ParameterView.Remove(SelectedRow);
Parameters.erase(Parameters.begin()+SelectedRow);
EditMinCtrls.Remove(SelectedRow);
EditMaxCtrls.Remove(SelectedRow);
EditSymCtrls.Remove(SelectedRow);
EditExprCtrls.Remove(SelectedRow);
}
void OptimizationWindow::ClearParametersClicked()
{
ParSetup.ParameterView.Clear();
Parameters.clear();
EditMinCtrls.Clear();
EditMaxCtrls.Clear();
EditSymCtrls.Clear();
EditExprCtrls.Clear();
}
void OptimizationWindow::AddOptimizationTarget(optimization_target &Target)
{
Targets.push_back(Target);
String InputIndexStr = MakeIndexString(Target.InputIndexes);
String ResultIndexStr = MakeIndexString(Target.ResultIndexes);
int TargetStat = (int)Target.Stat;;
TargetSetup.TargetView.Add(Target.ResultName.data(), ResultIndexStr, Target.InputName.data(), InputIndexStr, TargetStat, Target.ErrParSym.data(), Target.Weight, Target.Begin.data(), Target.End.data());
TargetStatCtrls.Create<DropList>();
DropList &SelectStat = TargetStatCtrls.Top();
TargetErrCtrls.Create<EditField>();
EditField &ErrCtrl = TargetErrCtrls.Top();
int TabNum = TargetSetup.OptimizerTypeTab.Get();
if(TabNum == 2)
{
#define SET_SETTING(Handle, Name, Type) SelectStat.Add((int)StatType_##Handle, Name);
#define SET_RES_SETTING(Handle, Name, Type)
#include "SetStatSettings.h"
#undef SET_SETTING
#undef SET_RES_SETTING
}
if(TabNum == 0 || TabNum == 2)
{
#define SET_SETTING(Handle, Name, Type)
#define SET_RES_SETTING(Handle, Name, Type) if(Type != -1) SelectStat.Add((int)ResidualType_##Handle, Name);
#include "SetStatSettings.h"
#undef SET_SETTING
#undef SET_RES_SETTING
}
if(TabNum == 0 || TabNum == 1)
{
#define SET_LL_SETTING(Handle, Name, NumErr) SelectStat.Add((int)MCMCError_##Handle, Name);
#include "LLSettings.h"
#undef SET_LL_SETTING
}
int Row = TargetSetup.TargetView.GetCount() - 1;
int Col = TargetSetup.TargetView.GetPos(Id("__targetstat"));
TargetSetup.TargetView.SetCtrl(Row, Col, SelectStat);
SelectStat.WhenAction << [this, Row](){ StatEdited(Row); };
Col = TargetSetup.TargetView.GetPos(Id("__errparam"));
TargetSetup.TargetView.SetCtrl(Row, Col, ErrCtrl);
ErrCtrl.WhenAction << [this, Row](){ ErrSymEdited(Row); };
TargetWeightCtrls.Create<EditDoubleNotNull>();
EditDoubleNotNull &EditWt = TargetWeightCtrls.Top();
EditWt.Min(0.0);
Col = TargetSetup.TargetView.GetPos(Id("__weight"));
TargetSetup.TargetView.SetCtrl(Row, Col, EditWt);
EditWt.WhenAction << [this, Row](){ WeightEdited(Row); };
TargetBeginCtrls.Create<EditTimeNotNull>();
EditTimeNotNull &EditBegin = TargetBeginCtrls.Top();
Col = TargetSetup.TargetView.GetPos(Id("__begin"));
TargetSetup.TargetView.SetCtrl(Row, Col, EditBegin);
EditBegin.WhenAction << [this, Row](){ BeginEdited(Row); };
TargetEndCtrls.Create<EditTimeNotNull>();
EditTimeNotNull &EditEnd = TargetEndCtrls.Top();
Col = TargetSetup.TargetView.GetPos(Id("__end"));
TargetSetup.TargetView.SetCtrl(Row, Col, EditEnd);
EditEnd.WhenAction << [this, Row](){ EndEdited(Row); };
}
void OptimizationWindow::StatEdited(int Row)
{
int IntValue = (int)TargetSetup.TargetView.Get(Row, "__targetstat");
if(IntValue > (int)StatType_Offset && IntValue < (int)StatType_End)
Targets[Row].Stat = (stat_type)IntValue;
else if(IntValue > (int)ResidualType_Offset && IntValue < (int)ResidualType_End)
Targets[Row].ResidualStat = (residual_type)IntValue;
else if(IntValue > (int)MCMCError_Offset && IntValue < (int)MCMCError_End)
Targets[Row].ErrStruct = (mcmc_error_structure)IntValue;
}
void OptimizationWindow::ErrSymEdited(int Row)
{
Targets[Row].ErrParSym = TargetSetup.TargetView.Get(Row, "__errparam").ToStd();
}
void OptimizationWindow::WeightEdited(int Row)
{
Targets[Row].Weight = (double)TargetSetup.TargetView.Get(Row, "__weight");
}
void OptimizationWindow::BeginEdited(int Row)
{
Targets[Row].Begin = TargetSetup.TargetView.Get(Row, "__begin").ToString().ToStd();
}
void OptimizationWindow::EndEdited(int Row)
{
Targets[Row].End = TargetSetup.TargetView.Get(Row, "__end").ToString().ToStd();
}
void OptimizationWindow::AddTargetClicked()
{
plot_setup PlotSetup;
ParentWindow->Plotter.GatherCurrentPlotSetup(PlotSetup);
if(PlotSetup.SelectedResults.size() != 1 || PlotSetup.SelectedInputs.size() > 1)
{
SetError("This only works with a single selected result series and at most one input series.");
return;
}
for(int Idx = 0; Idx < PlotSetup.SelectedIndexes.size(); ++Idx)
{
if(PlotSetup.SelectedIndexes[Idx].size() != 1 && PlotSetup.IndexSetIsActive[Idx])
{
SetError("This currently only works with a single selected index combination");
return;
}
}
optimization_target Target = {};
Target.ResultName = PlotSetup.SelectedResults[0];
std::vector<char *> ResultIndexes;
bool Success = ParentWindow->GetSelectedIndexesForSeries(PlotSetup, ParentWindow->DataSet, Target.ResultName, 0, ResultIndexes);
if(!Success) return;
//Ugh, super annoying to have to convert back and forth between char* and string to ensure
//storage...
for(const char *Idx : ResultIndexes)
Target.ResultIndexes.push_back(std::string(Idx));
if(PlotSetup.SelectedInputs.size() == 1)
{
Target.InputName = PlotSetup.SelectedInputs[0];
std::vector<char *> InputIndexes;
bool Success = ParentWindow->GetSelectedIndexesForSeries(PlotSetup, ParentWindow->DataSet, Target.InputName, 1, InputIndexes);
if(!Success) return;
for(const char *Idx : InputIndexes)
Target.InputIndexes.push_back(std::string(Idx));
}
int TabNum = TargetSetup.OptimizerTypeTab.Get();
//NOTE: Defaults.
if(TabNum == 0) Target.ResidualStat = ResidualType_MAE;
else if(TabNum == 1) Target.ErrStruct = MCMCError_NormalHet1; //This is the easiest one to start with maybe. Or should we just do Normal?
else if(TabNum == 2) Target.Stat = StatType_Mean;
Target.Weight = 1.0;
//NOTE for you to be able to add a target, the model has to have been run once any way, so
//there is no problem using these time stamps for that.
char TimeStr[256];
uint64 ResultTimesteps = ParentWindow->ModelDll.GetTimesteps(ParentWindow->DataSet);
ParentWindow->ModelDll.GetStartDate(ParentWindow->DataSet, TimeStr);
Time ResultStartTime;
StrToTime(ResultStartTime, TimeStr);
Time GofStartTime, GofEndTime;
int64 GofOffset, GofTimesteps;
ParentWindow->GetGofOffsets(ResultStartTime, ResultTimesteps, GofStartTime, GofEndTime, GofOffset, GofTimesteps);
Target.Begin = Format(GofStartTime).ToStd();
Target.End = Format(GofEndTime).ToStd();
AddOptimizationTarget(Target);
}
void OptimizationWindow::TargetsToPlotSetups(std::vector<optimization_target> &Targets, std::vector<plot_setup> &PlotSetups)
{
PlotSetups.clear();
PlotSetups.reserve(Targets.size());
for(optimization_target &Target : Targets)
{
plot_setup PlotSetup = {};
PlotSetup.SelectedIndexes.resize(MAX_INDEX_SETS);
PlotSetup.IndexSetIsActive.resize(MAX_INDEX_SETS);
PlotSetup.MajorMode = MajorMode_Regular;//MajorMode_Residuals;
PlotSetup.AggregationPeriod = Aggregation_None;
PlotSetup.ScatterInputs = true;
std::vector<char *> IndexSets;
if(Target.InputName != "")
{
PlotSetup.SelectedInputs.push_back(Target.InputName);
bool Success = ParentWindow->GetIndexSetsForSeries(ParentWindow->DataSet, Target.InputName, 1, IndexSets);
if(!Success) return;
for(int IdxIdx = 0; IdxIdx < IndexSets.size(); ++IdxIdx)
{
size_t Id = ParentWindow->IndexSetNameToId[IndexSets[IdxIdx]];
PlotSetup.IndexSetIsActive[Id] = true;
PlotSetup.SelectedIndexes[Id].push_back(Target.InputIndexes[IdxIdx]);
}
}
PlotSetup.SelectedResults.push_back(Target.ResultName);
IndexSets.clear();
bool Success = ParentWindow->GetIndexSetsForSeries(ParentWindow->DataSet, Target.ResultName, 0, IndexSets);
if(!Success) return;
for(int IdxIdx = 0; IdxIdx < IndexSets.size(); ++IdxIdx)
{
size_t Id = ParentWindow->IndexSetNameToId[IndexSets[IdxIdx]];
PlotSetup.IndexSetIsActive[Id] = true;
PlotSetup.SelectedIndexes[Id].push_back(Target.ResultIndexes[IdxIdx]);
}
PlotSetups.push_back(PlotSetup);
}
}
void OptimizationWindow::DisplayClicked()
{
if(!ParentWindow->DataSet || !ParentWindow->ModelDll.IsLoaded())
{
SetError("Can't display plots before a model is loaded");
return;
}
if(Targets.empty())
{
SetError("There are no targets to display the plots of");
return;
}
SetError("");
std::vector<plot_setup> PlotSetups;
TargetsToPlotSetups(Targets, PlotSetups);
AdditionalPlotView *Plots = &ParentWindow->OtherPlots;
Plots->SetAll(PlotSetups);
if(!Plots->IsOpen())
Plots->Open();
}
void OptimizationWindow::RemoveTargetClicked()
{
int SelectedRow = -1;
for(int Row = 0; Row < TargetSetup.TargetView.GetCount(); ++Row)
{
if(TargetSetup.TargetView.IsSel(Row))
{
SelectedRow = Row;
break;
}
}
if(SelectedRow == -1) return;
TargetSetup.TargetView.Remove(SelectedRow);
Targets.erase(Targets.begin()+SelectedRow);
TargetWeightCtrls.Remove(SelectedRow);
TargetStatCtrls.Remove(SelectedRow);
TargetErrCtrls.Remove(SelectedRow);
TargetBeginCtrls.Remove(SelectedRow);
TargetEndCtrls.Remove(SelectedRow);
}
void OptimizationWindow::ClearTargetsClicked()
{
TargetSetup.TargetView.Clear();
Targets.clear();
TargetWeightCtrls.Clear();
TargetStatCtrls.Clear();
TargetErrCtrls.Clear();
TargetBeginCtrls.Clear();
TargetEndCtrls.Clear();
}
void OptimizationWindow::ClearAll()
{
ClearParametersClicked();
ClearTargetsClicked();
}
void OptimizationWindow::SamplerMethodSelected()
{
mcmc_sampler_method Method = (mcmc_sampler_method)(int)MCMCSetup.SelectSampler.GetData();
MCMCSetup.SamplerParamView.Clear();
MCMCSamplerParamCtrls.Clear();
switch(Method)
{
case MCMCMethod_AffineStretch :
{
MCMCSetup.SamplerParamView.Add("a", 2.0, "Max. stretch factor");
} break;
case MCMCMethod_AffineWalk :
{
MCMCSetup.SamplerParamView.Add("|S|", 10.0, "Size of sub-ensemble. Has to be between 2 and NParams/2.");
} break;
case MCMCMethod_DifferentialEvolution :
{
MCMCSetup.SamplerParamView.Add("\u03B3", -1.0, "Stretch factor. If negative, will be set to default of 2.38/sqrt(2*dim)");
MCMCSetup.SamplerParamView.Add("b", 1e-3, "Max. random walk step (multiplied by |max - min| for each par.)");
MCMCSetup.SamplerParamView.Add("CR", 1.0, "Crossover probability");
} break;
case MCMCMethod_MetropolisHastings :
{
MCMCSetup.SamplerParamView.Add("b", 0.02, "Std. dev. of random walk step (multiplied by |max - min| for each par.)");
} break;
}
int Rows = MCMCSetup.SamplerParamView.GetCount();
MCMCSamplerParamCtrls.InsertN(0, Rows);
for(int Row = 0; Row < Rows; ++Row)
MCMCSetup.SamplerParamView.SetCtrl(Row, 1, MCMCSamplerParamCtrls[Row]);
}
typedef dlib::matrix<double,0,1> column_vector;
inline int
SetParameters(void *DataSet, std::vector<indexed_parameter> *Parameters, const column_vector& Par, bool UseExpr, model_dll_interface &ModelDll)
{
//NOTE: The length of Par has to be equal to the length of Parameters - ExprCount
if(!UseExpr)
{
int ParIdx = 0;
for(indexed_parameter &Param : *Parameters)
{
if(!Param.Virtual)
SetParameterValue(Param, DataSet, Par(ParIdx), ModelDll);
++ParIdx;
}
}
else
{
EvalExpr Expression;
Expression.SetErrorUndefined(true); //NOTE: Necessary for it to return Null when encountering an undefined variable
int ParIdx = 0;
int ActiveIdx = 0;
for(indexed_parameter &Param : *Parameters)
{
double Val;
if(Param.Expr != "")
{
auto Res = Expression.Eval(Param.Expr.data());
if(IsNull(Res)) return ParIdx;
Val = Res.val;
}
else
{
Val = Par(ActiveIdx);
++ActiveIdx;
}
if(Param.Symbol != "")
{
auto Res = Expression.AssignVariable(Param.Symbol.data(), Val);
if(IsNull(Res)) return ParIdx;
}
if(!Param.Virtual)
SetParameterValue(Param, DataSet, Val, ModelDll);
++ParIdx;
}
}
return -1;
}
double ComputeLLValue(double *Obs, double *Sim, size_t Timesteps, const std::vector<double> &ErrParam, mcmc_error_structure ErrStruct);
struct optimization_model
{
MobiView *ParentWindow;
Label *ProgressLabel;
std::vector<indexed_parameter> *Parameters;
std::vector<optimization_target> *Targets;
bool ValuesLoadedOnce = false;
std::vector<std::vector<double>> InputData;
std::vector<int64> GofOffsets;
std::vector<int64> GofTimesteps;
int ExprCount;
int FreeParCount;
int64 RunTimeout = -1;
int64 Timeouts = 0;
int64 NumEvals = 0;
double InitialScore, BestScore;
bool IsMaximizing = true;
int UpdateStep = 100;
void *DataSetBase = nullptr;
optimization_model(MobiView *ParentWindow, std::vector<indexed_parameter> *Parameters, std::vector<optimization_target> *Targets,
Label *ProgressLabel, void *DataSetBase, int64 RunTimeout)
{
this->ParentWindow = ParentWindow;
this->Parameters = Parameters;
this->Targets = Targets;
this->ProgressLabel = ProgressLabel;
this->RunTimeout = RunTimeout;
ExprCount = 0;
for(indexed_parameter &Parameter : *Parameters)
if(Parameter.Expr != "")
ExprCount++;
FreeParCount = Parameters->size() - ExprCount;
this->DataSetBase = DataSetBase;
}
double EvaluateObjectives(void *DataSet, const column_vector &Par)
{
SetParameters(DataSet, Parameters, Par, ExprCount > 0, ParentWindow->ModelDll);
bool RunFinished = ParentWindow->ModelDll.RunModel(DataSet, RunTimeout);
// Extract result and input values to compute them.
if(!ValuesLoadedOnce)
{
uint64 Timesteps = ParentWindow->ModelDll.GetTimesteps(DataSet);
InputData.resize(Targets->size());
GofOffsets.resize(Targets->size());
GofTimesteps.resize(Targets->size());
char TimeStr[256];
ParentWindow->ModelDll.GetStartDate(DataSet, TimeStr);
Time ResultStartTime;
StrToTime(ResultStartTime, TimeStr);
for(int Obj = 0; Obj < Targets->size(); ++Obj)
{
optimization_target &Target = (*Targets)[Obj];
InputData[Obj].resize(Timesteps); //TODO: This is sometimes unnecessary, but the size is used below.
if(Target.InputName != "")
{
std::vector<const char *> InputIndexes(Target.InputIndexes.size());
for(int Idx = 0; Idx < InputIndexes.size(); ++Idx)
InputIndexes[Idx] = Target.InputIndexes[Idx].data();
//NOTE: The final 'true' signifies that we align with the result series, so that it
//is in fact safe to use the result timesteps for the size here.
ParentWindow->ModelDll.GetInputSeries(DataSet, Target.InputName.data(), (char**)InputIndexes.data(), InputIndexes.size(), InputData[Obj].data(), true);
}
Time Begin;
Time End;
StrToTime(Begin, Target.Begin.data());
StrToTime(End, Target.End.data());
GofOffsets[Obj] = TimestepsBetween(ResultStartTime, Begin, ParentWindow->TimestepSize);
GofTimesteps[Obj] = TimestepsBetween(Begin, End, ParentWindow->TimestepSize) + 1; //NOTE: if start time = end time, there is still one timestep.
//PromptOK(Format("Begin: %s, end: %s, Gof offset: %d, gof timesteps: %d", Format(Begin), Format(End), GofOffsets[Obj], GofTimesteps[Obj]));
}
ValuesLoadedOnce = true;
}
if(!RunFinished)
{
Timeouts++;
return IsMaximizing ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
}
double Aggregate = 0.0;
//NOTE: We have to allocate this for each call, for thread safety.
std::vector<double> ResultData(InputData[0].size());
for(int Obj = 0; Obj < Targets->size(); ++Obj)
{
optimization_target &Target = (*Targets)[Obj];
std::vector<const char *> ResultIndexes(Target.ResultIndexes.size());
for(int Idx = 0; Idx < ResultIndexes.size(); ++Idx)
ResultIndexes[Idx] = Target.ResultIndexes[Idx].data();
ParentWindow->ModelDll.GetResultSeries(DataSet, Target.ResultName.data(), (char**)ResultIndexes.data(), ResultIndexes.size(), ResultData.data());
double Value;
switch(GetStatClass(Target))
{
case StatClass_Stat:
{
timeseries_stats Stats;
ComputeTimeseriesStats(Stats, ResultData.data() + GofOffsets[Obj], GofTimesteps[Obj], ParentWindow->StatSettings, false);
if(false){}
#define SET_SETTING(Handle, Name, Type) \
else if(Target.Stat == StatType_##Handle) Value = Stats.Handle;
#define SET_RES_SETTING(Handle, Name, Type)
#include "SetStatSettings.h"
#undef SET_SETTING
#undef SET_RES_SETTING
} break;
case StatClass_Residual:
{
//NOTE: It may seem a little wasteful to compute all of them, but it is a bit messy to
//untangle their computations.
residual_stats ResidualStats;
ComputeResidualStats(ResidualStats, InputData[Obj].data() + GofOffsets[Obj], ResultData.data() + GofOffsets[Obj], GofTimesteps[Obj]);
if(false){}
#define SET_SETTING(Handle, Name, Type)
#define SET_RES_SETTING(Handle, Name, Type) \
else if(Target.ResidualStat == ResidualType_##Handle) Value = ResidualStats.Handle; //TODO: Could do this with an array lookup, but would be a little hacky
#include "SetStatSettings.h"
#undef SET_SETTING
#undef SET_RES_SETTING
} break;
case StatClass_LogLikelihood:
{
std::vector<double> ErrParam(Target.ErrParNum.size());
for(int Idx = 0; Idx < ErrParam.size(); ++Idx) ErrParam[Idx] = Par(Target.ErrParNum[Idx]);
Value = ComputeLLValue(InputData[Obj].data() + GofOffsets[Obj], ResultData.data() + GofOffsets[Obj], GofTimesteps[Obj], ErrParam, Target.ErrStruct);
} break;
default :
assert(!"Unknown stat class!");
}
Aggregate += Value*Target.Weight;
}
return Aggregate;
}
double operator()(const column_vector& Par)
{
//NOTE: This one is for use by the Dlib optimizer
//NOTE: Since the optimizer is not multithreaded, there is no reason to do an
//additional copy each run.
//If we ever do get threading to work for this, we have to have a separate copy per
//paralell run.
//void *DataSetCopy = ParentWindow->ModelDll.CopyDataSet(DataSetBase, false);
void *DataSetCopy = DataSetBase;
double Value = EvaluateObjectives(DataSetCopy, Par);
// NOTE: The following is about updating the UI during optimization
// It is not thread safe, so should be turned off if we
// eventually are able to run the optimizer multi-threaded:
++NumEvals;
/////////// BEGIN UI UPDATE
if(IsMaximizing)
BestScore = std::max(BestScore, Value);
else
BestScore = std::min(BestScore, Value);
AdditionalPlotView *View = &ParentWindow->OtherPlots;
if(ProgressLabel && View->IsOpen() && BestScore==Value)
ParentWindow->ModelDll.CopyData(DataSetCopy, ParentWindow->DataSet, true, false, true); //Copy over parameter and result data.
if(ProgressLabel && (NumEvals%UpdateStep==0))
{
GuiLock Lock;
ProgressLabel->SetText(Format("Current evaluations: %d, timeouts: %d, best score: %g (initial: %g)", NumEvals, Timeouts, BestScore, InitialScore));
if(View->IsOpen())
View->BuildAll(true);
ParentWindow->ProcessEvents();
}
////////// END UI UPDATE
//NOTE: See note about threading above
//ParentWindow->ModelDll.DeleteDataSet(DataSetCopy);
return IsMaximizing ? Value : -Value;
}
};
void OptimizationWindow::SetParameterValues(void *DataSet, double *ParVal, size_t NPars, std::vector<indexed_parameter> &Parameters)
{
//NOTE: This one is only here to be used by the MCMC result window when it wants to write
//back parameter sets. TODO: This may not be the best way of organizing it...
int ExprCount = 0;
for(indexed_parameter &Parameter : Parameters)
if(Parameter.Expr != "") ++ExprCount;
column_vector ParVal2(NPars);
for(int Par = 0; Par < NPars; ++Par) ParVal2(Par) = ParVal[Par];
SetParameters(DataSet, &Parameters, ParVal2, ExprCount > 0, ParentWindow->ModelDll);
}
struct mcmc_run_data
{
optimization_model *Model;
mcmc_data *Data;
std::vector<void *> DataSets;
double *MinBound;
double *MaxBound;