forked from NIVANorge/Mobius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmobius_model.cpp
1834 lines (1585 loc) · 71.8 KB
/
mobius_model.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
static mobius_model *
BeginModelDefinition(const char *Name = "(unnamed model)", const char *Version = "0.0")
{
mobius_model *Model = new mobius_model {};
Model->DefinitionTimer = BeginTimer();
Model->Name = Name;
Model->Version = Version;
//NOTE: Reserve Handle 0 as an error / unused value.
Model->FirstUnusedInputHandle = 1;
Model->FirstUnusedParameterHandle = 1;
Model->FirstUnusedEquationHandle = 1;
Model->FirstUnusedIndexSetHandle = 1; //NOTE: IndexSet 0 is the "global"/"system" index set, for parameters that don't have any other index sets.
Model->IndexSetSpecs.push_back({});
Model->FirstUnusedParameterGroupHandle = 1;
Model->FirstUnusedSolverHandle = 1;
Model->FirstUnusedUnitHandle = 1;
return Model;
}
static void
PrintPartialDependencyTrace(mobius_model *Model, equation_h Equation, bool First = false)
{
if(!First)
{
MOBIUS_PARTIAL_ERROR("<- ");
}
else
{
MOBIUS_PARTIAL_ERROR(" ");
}
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(IsValid(Spec.Solver))
{
MOBIUS_PARTIAL_ERROR("\"" << GetName(Model, Spec.Solver) << "\" (");
}
MOBIUS_PARTIAL_ERROR("\"" << GetName(Model, Equation) << "\"");
if(IsValid(Spec.Solver))
{
MOBIUS_PARTIAL_ERROR(")")
}
MOBIUS_PARTIAL_ERROR(std::endl);
}
static bool
TopologicalSortEquationsVisit(mobius_model *Model, equation_h Equation, std::vector<equation_h>& PushTo)
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
solver_spec &SolverSpec = Model->SolverSpecs[Spec.Solver.Handle];
//NOTE: We have to short-circuit out all equations that belong to a particular solver since they always have to be grouped together in a batch, and ODE equations within a batch are allowed to have circular references since they work differently. They have to be sorted as a block later.
bool &Visited = IsValid(Spec.Solver) ? SolverSpec.Visited : Spec.Visited;
bool &TempVisited = IsValid(Spec.Solver) ? SolverSpec.TempVisited : Spec.TempVisited;
if(Visited) return true;
if(TempVisited)
{
MOBIUS_PARTIAL_ERROR("ERROR: There is a circular dependency between the equations :" << std::endl);
PrintPartialDependencyTrace(Model, Equation, true);
return false;
}
TempVisited = true;
std::set<equation_h> &DirectResultDependencies = IsValid(Spec.Solver) ? SolverSpec.DirectResultDependencies : Spec.DirectResultDependencies;
for(equation_h Dependency : DirectResultDependencies)
{
equation_spec &DepSpec = Model->EquationSpecs[Dependency.Handle];
if(IsValid(Spec.Solver) && IsValid(DepSpec.Solver) && Spec.Solver == DepSpec.Solver) continue; //NOTE: We ignore dependencies of the solver on itself for now.
bool Success = TopologicalSortEquationsVisit(Model, Dependency, PushTo);
if(!Success)
{
PrintPartialDependencyTrace(Model, Equation);
return false;
}
}
Visited = true;
PushTo.push_back(Equation);
return true;
}
static bool
TopologicalSortEquationsInSolverVisit(mobius_model *Model, equation_h Equation, std::vector<equation_h>& PushTo)
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(Spec.Visited) return true;
if(Spec.TempVisited)
{
MOBIUS_PARTIAL_ERROR("ERROR: There is a circular dependency between the non-ode equations within a solver :" << std::endl);
PrintPartialDependencyTrace(Model, Equation, true);
return false;
}
Spec.TempVisited = true;
for(equation_h Dependency : Spec.DirectResultDependencies)
{
equation_spec &DepSpec = Model->EquationSpecs[Dependency.Handle];
if(DepSpec.Type == EquationType_ODE || DepSpec.Solver != Spec.Solver) continue; //NOTE: We are only interested sorting non-ode equations belonging to this solver.
bool Success = TopologicalSortEquationsInSolverVisit(Model, Dependency, PushTo);
if(!Success)
{
PrintPartialDependencyTrace(Model, Equation);
return false;
}
}
Spec.Visited = true;
PushTo.push_back(Equation);
return true;
}
static bool
TopologicalSortEquationsInitialValueVisit(mobius_model *Model, equation_h Equation, std::vector<equation_h>& PushTo)
{
equation_h EquationToLookUp = Equation;
equation_spec &OriginalSpec = Model->EquationSpecs[Equation.Handle];
equation_h InitialValueEq = OriginalSpec.InitialValueEquation;
if(IsValid(InitialValueEq))
{
EquationToLookUp = InitialValueEq;
}
equation_spec &Spec = Model->EquationSpecs[EquationToLookUp.Handle];
if(Spec.Visited) return true;
if(Spec.TempVisited)
{
MOBIUS_PARTIAL_ERROR("ERROR: There is a circular dependency between the initial value of the equations :" << std::endl);
PrintPartialDependencyTrace(Model, Equation, true);
return false;
}
Spec.TempVisited = true;
//std::cout << "Initial value sort for " << GetName(Model, EquationToLookUp) << std::endl;
if(!IsValid(OriginalSpec.InitialValue) && !OriginalSpec.HasExplicitInitialValue) //NOTE: If the equation has one type of explicit initial value or other, we don't evaluate it during the initial value run, and so we don't care what its dependencies are for this sort.
{
for(equation_h Dependency : Spec.DirectResultDependencies)
{
bool Success = TopologicalSortEquationsInitialValueVisit(Model, Dependency, PushTo);
if(!Success)
{
PrintPartialDependencyTrace(Model, Equation);
return false;
}
}
}
Spec.Visited = true;
PushTo.push_back(Equation);
return true;
}
typedef bool topological_sort_equations_visit(mobius_model *Model, equation_h Equation, std::vector<equation_h>& PushTo);
static void
TopologicalSortEquations(mobius_model *Model, std::vector<equation_h> &Equations, topological_sort_equations_visit *Visit)
{
std::vector<equation_h> Temporary;
Temporary.reserve(Equations.size());
for(equation_h Equation : Equations)
{
bool Success = Visit(Model, Equation, Temporary);
if(!Success)
{
MOBIUS_FATAL_ERROR("");
}
}
for(size_t Idx = 0; Idx < Equations.size(); ++Idx)
{
Equations[Idx] = Temporary[Idx];
}
}
struct equation_batch_template
{
equation_batch_type Type;
std::vector<equation_h> Equations;
std::vector<equation_h> EquationsODE;
std::set<index_set_h> IndexSetDependencies;
solver_h Solver;
};
static bool
IsTopIndexSetForThisDependency(std::vector<index_set_h> &IndexSetDependencies, std::vector<index_set_h> &BatchGroupIndexSets, size_t IndexSetLevel)
{
index_set_h CurrentLevelIndexSet = BatchGroupIndexSets[IndexSetLevel];
bool DependsOnCurrentLevel = (std::find(IndexSetDependencies.begin(), IndexSetDependencies.end(), CurrentLevelIndexSet) != IndexSetDependencies.end());
if(!DependsOnCurrentLevel) return false;
for(size_t LevelAbove = IndexSetLevel + 1; LevelAbove < BatchGroupIndexSets.size(); ++LevelAbove)
{
index_set_h IndexSetAtLevelAbove = BatchGroupIndexSets[LevelAbove];
if(std::find(IndexSetDependencies.begin(), IndexSetDependencies.end(), IndexSetAtLevelAbove) != IndexSetDependencies.end())
{
return false;
}
}
return true;
}
static bool
WeDependOnBatch(std::set<equation_h> &Dependencies, std::set<equation_h> &CrossDependencies, equation_batch_template &Batch)
{
bool DependOnBatch = false;
for(equation_h EquationInBatch : Batch.Equations)
{
if(!Dependencies.empty() && std::find(Dependencies.begin(), Dependencies.end(), EquationInBatch) != Dependencies.end())
{
DependOnBatch = true;
break;
}
if(!CrossDependencies.empty() && std::find(CrossDependencies.begin(), CrossDependencies.end(), EquationInBatch) != CrossDependencies.end())
{
DependOnBatch = true;
break;
}
}
if(Batch.Type == BatchType_Solver && !DependOnBatch)
{
for(equation_h EquationInBatch : Batch.EquationsODE)
{
if(!Dependencies.empty() && std::find(Dependencies.begin(), Dependencies.end(), EquationInBatch) != Dependencies.end())
{
DependOnBatch = true;
break;
}
if(!CrossDependencies.empty() && std::find(CrossDependencies.begin(), CrossDependencies.end(), EquationInBatch) != CrossDependencies.end())
{
DependOnBatch = true;
break;
}
}
}
return DependOnBatch;
}
#if !defined(MOBIUS_PRINT_TIMING_INFO)
#define MOBIUS_PRINT_TIMING_INFO 0
#endif
static void
EndModelDefinition(mobius_model *Model)
{
if(Model->Finalized)
{
MOBIUS_FATAL_ERROR("ERROR: Called EndModelDefinition twice on the same model." << std::endl);
}
///////////// Find out what index sets each parameter depends on /////////////
for(entity_handle ParameterHandle = 1; ParameterHandle < Model->FirstUnusedParameterHandle; ++ParameterHandle)
{
const parameter_spec &Spec = Model->ParameterSpecs[ParameterHandle];
parameter_group_h CurrentGroup = Spec.Group;
std::vector<index_set_h>& Dependencies = Model->ParameterSpecs[ParameterHandle].IndexSetDependencies;
while(IsValid(CurrentGroup))
{
parameter_group_spec *GroupSpec = &Model->ParameterGroupSpecs[CurrentGroup.Handle];
if(IsValid(GroupSpec->IndexSet)) //NOTE: We never insert index set 0 as a dependency. If this is a global parameter, we want to register it as having no dependencies.
{
Dependencies.insert(Dependencies.begin(), GroupSpec->IndexSet);
}
CurrentGroup = GroupSpec->ParentGroup;
}
}
/////////////////////// Find all dependencies of equations on parameters, inputs and other results /////////////////////
value_set_accessor ValueSet(Model);
for(entity_handle EquationHandle = 1; EquationHandle < Model->FirstUnusedEquationHandle; ++EquationHandle)
{
equation_spec &Spec = Model->EquationSpecs[EquationHandle];
if(Spec.Type == EquationType_Cumulative)
{
//NOTE: Cumulative equations depend on the equations they cumulate.
Spec.DirectResultDependencies.insert(Spec.Cumulates);
continue;
}
if(!Model->EquationSpecs[EquationHandle].EquationIsSet)
{
MOBIUS_FATAL_ERROR("ERROR: The equation body for the registered equation " << GetName(Model, equation_h {EquationHandle}) << " has not been defined." << std::endl);
}
// Clear dependency registrations from evaluation of previous equation.
ValueSet.Clear();
//Call the equation. Since we are in ValueSet.Running==false mode, the equation will register which values it tried to access.
Model->Equations[EquationHandle](&ValueSet);
//std::cout << GetName(Model, equation {EquationHandle}) << std::endl;
Spec.IndexSetDependencies.insert(ValueSet.DirectIndexSetDependencies.begin(), ValueSet.DirectIndexSetDependencies.end());
for(dependency_registration ParameterDependency : ValueSet.ParameterDependencies)
{
entity_handle ParameterHandle = ParameterDependency.Handle;
parameter_spec &ParSpec = Model->ParameterSpecs[ParameterHandle];
std::vector<index_set_h>& IndexSetDependencies = ParSpec.IndexSetDependencies;
if(ParameterDependency.NumExplicitIndexes > IndexSetDependencies.size())
{
MOBIUS_FATAL_ERROR("ERROR: In equation " << Spec.Name << ". The parameter " << ParSpec.Name << " is referenced with more explicit indexes than the number of index sets this parameter depends on." << std::endl);
}
size_t NumImplicitIndexes = IndexSetDependencies.size() - ParameterDependency.NumExplicitIndexes;
if(NumImplicitIndexes > 0)
{
Spec.IndexSetDependencies.insert(IndexSetDependencies.begin(), IndexSetDependencies.begin() + NumImplicitIndexes);
}
if(ParameterDependency.NumExplicitIndexes == 0)
{
//NOTE: We only store the parameters that should be hotloaded at the start of the batch in this vector: For various reasons we can't do that with parameters that are referred to by explicit indexing.
//TODO: We should maybe store a cross-index parameter dependency list for easy referencing later (during debugging etc.).
Spec.ParameterDependencies.insert(ParameterHandle);
}
}
for(dependency_registration InputDependency : ValueSet.InputDependencies)
{
//TODO: This block has to be updated to match the parameter registration above if we later allow for explicitly indexed inputs.
entity_handle InputHandle = InputDependency.Handle;
std::vector<index_set_h>& IndexSetDependencies = Model->InputSpecs[InputHandle].IndexSetDependencies;
Spec.IndexSetDependencies.insert(IndexSetDependencies.begin(), IndexSetDependencies.end());
Spec.InputDependencies.insert(input_h {InputHandle});
}
//NOTE: Every equation always depends on its initial value parameter if it has one.
//TODO: We should have a specialized system for this, because this currently causes the initial value parameter to be loaded into the CurParameters buffer at each step (instead of just during the initial value step), which is unnecessary.
if(IsValid(Spec.InitialValue))
{
std::vector<index_set_h>& IndexSetDependencies = Model->ParameterSpecs[Spec.InitialValue.Handle].IndexSetDependencies;
Spec.IndexSetDependencies.insert(IndexSetDependencies.begin(), IndexSetDependencies.end());
Spec.ParameterDependencies.insert(Spec.InitialValue.Handle);
}
for(const result_dependency_registration &ResultDependency : ValueSet.ResultDependencies)
{
entity_handle DepResultHandle = ResultDependency.Handle;
if(Model->EquationSpecs[DepResultHandle].Type == EquationType_InitialValue)
{
std::cout << "ERROR: The equation " << GetName(Model, equation_h {EquationHandle}) << " depends explicitly on the result of the equation " << GetName(Model, equation_h {DepResultHandle}) << " which is an EquationInitialValue. This is not allowed, instead it should depend on the result of the equation that " << GetName(Model, equation_h {DepResultHandle}) << " is an initial value for." << std::endl;
}
if(ResultDependency.Indexes.size() == 0)
{
Spec.DirectResultDependencies.insert(equation_h {DepResultHandle});
}
else
{
Spec.CrossIndexResultDependencies.insert(equation_h {DepResultHandle}); //TODO: Do we really need to keep this separately?
Spec.IndexedResultAndLastResultDependencies.push_back(ResultDependency); //TODO: Maybe don't store these on the result spec? They are only needed in this algorithm..
}
}
for(const result_dependency_registration &ResultDependency : ValueSet.LastResultDependencies)
{
entity_handle DepResultHandle = ResultDependency.Handle;
if(Model->EquationSpecs[DepResultHandle].Type == EquationType_InitialValue)
{
std::cout << "ERROR: The equation " << GetName(Model, equation_h {EquationHandle}) << " depends explicitly on the result of the equation " << GetName(Model, equation_h {DepResultHandle}) << " which is an EquationInitialValue. This is not allowed, instead it should depend on the result of the equation that " << GetName(Model, equation_h {DepResultHandle}) << " is an initial value for." << std::endl;
}
if(ResultDependency.Indexes.size() == 0)
{
Spec.DirectLastResultDependencies.insert(equation_h {DepResultHandle});
}
else
{
Spec.IndexedResultAndLastResultDependencies.push_back(ResultDependency);
}
}
//NOTE: Every equation always depends on its initial value equation if it has one.
//TODO: Right now we register it as a LastResultDependency, which is not technically correct, but it should give the desired result.
//TODO: Figure out if this may break somehting, and if we need a specialized system for this?
equation_h EqInitialValue = Model->EquationSpecs[EquationHandle].InitialValueEquation;
if(IsValid(EqInitialValue))
{
Spec.DirectLastResultDependencies.insert(EqInitialValue);
}
}
{
//NOTE: Check for computed parameters if their equation satisfies the requirements:
for(entity_handle ParameterHandle = 1; ParameterHandle < Model->FirstUnusedParameterHandle; ++ParameterHandle)
{
parameter_spec &Spec = Model->ParameterSpecs[ParameterHandle];
equation_h Equation = Spec.IsComputedBy;
if(IsValid(Equation))
{
equation_spec &EqSpec = Model->EquationSpecs[Equation.Handle];
if(
!EqSpec.DirectResultDependencies.empty()
|| !EqSpec.DirectLastResultDependencies.empty()
|| !EqSpec.IndexedResultAndLastResultDependencies.empty()
|| !EqSpec.InputDependencies.empty()
)
{
MOBIUS_FATAL_ERROR("ERROR: The initial value equation " << EqSpec.Name << " assigned to compute the parameter " << Spec.Name << " depends on either a result of an equation or an input. This is not allowed for computed parameters." << std::endl);
}
}
}
}
///////////////////// Resolve indirect dependencies of equations on index sets.
//TODO: This is probably an inefficient way to do it, we should instead use some kind of graph traversal, but it is tricky. We need a way to do it properly with collapsing the dependency graph (including both results and lastresults) by its strongly connected components, then resolving the dependencies between the components.
//NOTE: We stop the iteraton at 1000 so that if the dependencies are unresolvable, we don't go in an infinite loop. (they can probably never become unresolvable though??)
bool DependenciesWereResolved = false;
for(size_t It = 0; It < 1000; ++It)
{
bool Changed = false;
for(entity_handle EquationHandle = 1; EquationHandle < Model->FirstUnusedEquationHandle; ++EquationHandle)
{
equation_spec &Spec = Model->EquationSpecs[EquationHandle];
size_t DependencyCount = Spec.IndexSetDependencies.size();
if(Spec.Type == EquationType_Cumulative)
{
equation_spec &DepSpec = Model->EquationSpecs[Spec.Cumulates.Handle];
for(index_set_h IndexSet : DepSpec.IndexSetDependencies)
{
if(IndexSet != Spec.CumulatesOverIndexSet) Spec.IndexSetDependencies.insert(IndexSet);
}
parameter_spec &WeightSpec = Model->ParameterSpecs[Spec.CumulationWeight.Handle];
for(index_set_h IndexSet : WeightSpec.IndexSetDependencies)
{
if(IndexSet != Spec.CumulatesOverIndexSet) Spec.IndexSetDependencies.insert(IndexSet);
}
}
else
{
for(equation_h ResultDependency : Spec.DirectResultDependencies)
{
equation_spec &DepSpec = Model->EquationSpecs[ResultDependency.Handle];
Spec.IndexSetDependencies.insert(DepSpec.IndexSetDependencies.begin(), DepSpec.IndexSetDependencies.end());
}
for(equation_h ResultDependency : Spec.DirectLastResultDependencies)
{
equation_spec &DepSpec = Model->EquationSpecs[ResultDependency.Handle];
Spec.IndexSetDependencies.insert(DepSpec.IndexSetDependencies.begin(), DepSpec.IndexSetDependencies.end());
}
for(const result_dependency_registration &ResultDependency : Spec.IndexedResultAndLastResultDependencies)
{
equation_spec &DepSpec = Model->EquationSpecs[ResultDependency.Handle];
const std::set<index_set_h> &IndexSetDependencies = DepSpec.IndexSetDependencies;
for(index_set_h IndexSet : IndexSetDependencies)
{
bool ExplicitlyIndexed = false;
for(index_t Index : ResultDependency.Indexes)
{
if(Index.IndexSetHandle == IndexSet.Handle)
{
ExplicitlyIndexed = true;
break;
}
}
if(!ExplicitlyIndexed) Spec.IndexSetDependencies.insert(IndexSet);
}
}
}
if(DependencyCount != Spec.IndexSetDependencies.size()) Changed = true;
}
if(!Changed)
{
DependenciesWereResolved = true;
//std::cout << "Dependencies resolved at " << It + 1 << " iterations." << std::endl;
break;
}
}
if(!DependenciesWereResolved)
{
MOBIUS_FATAL_ERROR("ERROR: We were unable to resolve all equation dependencies!" << std::endl);
}
/////////////// Sorting the equations into equation batches ///////////////////////////////
std::vector<equation_h> EquationsToSort;
bool *SolverHasBeenHitOnce = AllocClearedArray(bool, Model->FirstUnusedSolverHandle);
for(entity_handle EquationHandle = 1; EquationHandle < Model->FirstUnusedEquationHandle; ++EquationHandle)
{
equation_spec &Spec = Model->EquationSpecs[EquationHandle];
solver_h Solver = Spec.Solver;
if(Spec.Type == EquationType_InitialValue) continue; //NOTE: initial value equations should not be a part of the result structure.
if(IsValid(Solver))
{
solver_spec &SolverSpec = Model->SolverSpecs[Solver.Handle];
SolverSpec.IndexSetDependencies.insert(Spec.IndexSetDependencies.begin(), Spec.IndexSetDependencies.end());
SolverSpec.DirectResultDependencies.insert(Spec.DirectResultDependencies.begin(), Spec.DirectResultDependencies.end());
SolverSpec.CrossIndexResultDependencies.insert(Spec.CrossIndexResultDependencies.begin(), Spec.CrossIndexResultDependencies.end());
SolverSpec.EquationsToSolve.push_back(equation_h {EquationHandle});
if(!SolverHasBeenHitOnce[Solver.Handle])
{
EquationsToSort.push_back(equation_h {EquationHandle}); //NOTE: We only put one equation into the sorting vector as a stand-in for the solver. This is because all equations belonging to a solver have to be solved together.
}
SolverHasBeenHitOnce[Solver.Handle] = true;
}
else
{
if(Spec.Type == EquationType_ODE)
{
MOBIUS_FATAL_ERROR("ERROR: The equation " << GetName(Model, equation_h {EquationHandle}) << " is registered as an ODE equation, but it has not been given a solver." << std::endl);
}
EquationsToSort.push_back(equation_h {EquationHandle});
}
}
free(SolverHasBeenHitOnce);
TopologicalSortEquations(Model, EquationsToSort, TopologicalSortEquationsVisit);
std::vector<equation_batch_template> BatchBuild;
for(equation_h Equation : EquationsToSort)
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(IsValid(Spec.Solver))
{
//TODO: Instead of always pushing this at the end, could we try to insert it earlier if it is possible to place it next to another batch with the same index set dependencies?
solver_spec &SolverSpec = Model->SolverSpecs[Spec.Solver.Handle];
//NOTE: There is only one stand-in equation for the whole solver in the EquationsToSort vector. We create a new batch containing all of the equations and put it at the end of the batch build list.
equation_batch_template Batch = {};
Batch.Type = BatchType_Solver;
Batch.Solver = Spec.Solver;
Batch.IndexSetDependencies = SolverSpec.IndexSetDependencies; //Important: Should be the dependencies of the solver, not of the one equation.
//NOTE: Add all equations and sort the non-ode equations among themselves.
//NOTE: We don't sort the ODE equations since they ARE allowed to have circular dependencies on each other.
for(equation_h SolverEquation : SolverSpec.EquationsToSolve)
{
equation_spec &SolverResultSpec = Model->EquationSpecs[SolverEquation.Handle];
if(SolverResultSpec.Type == EquationType_Basic) Batch.Equations.push_back(SolverEquation);
else if(SolverResultSpec.Type == EquationType_ODE) Batch.EquationsODE.push_back(SolverEquation);
else assert(0);
}
TopologicalSortEquations(Model, Batch.Equations, TopologicalSortEquationsInSolverVisit);
s32 EarliestSuitableBatchIdx = BatchBuild.size();
//size_t FirstBatchWeDependOn = BatchBuild.size();
for(s32 BatchIdx = BatchBuild.size() - 1; BatchIdx >= 0; --BatchIdx)
{
equation_batch_template &NeighborBatch = BatchBuild[BatchIdx];
if(NeighborBatch.IndexSetDependencies == Batch.IndexSetDependencies)
{
EarliestSuitableBatchIdx = BatchIdx;
}
//FirstBatchWeDependOn = BatchIdx;
bool DependOnBatch = WeDependOnBatch(SolverSpec.DirectResultDependencies, SolverSpec.CrossIndexResultDependencies, NeighborBatch);
//if(DependOnBatch) std::cout << SolverSpec.Name << " depend on " << BatchIdx << std::endl;
if(DependOnBatch) break; //We have to enter after this batch.
}
if(EarliestSuitableBatchIdx == (s32)BatchBuild.size())
{
BatchBuild.push_back(Batch);
}
else
{
//NOTE: This inserts the new batch right after the earliest suitable one.
BatchBuild.insert(BatchBuild.begin() + EarliestSuitableBatchIdx + 1, Batch);
}
}
else
{
//NOTE: put non-solver equations in the first batch that suits it. A batch is suitable if it has the same index set dependencies as the equation and if no batch after it have equations that this equation depends on.
s32 EarliestSuitableBatchIdx = BatchBuild.size();
bool EarliestSuitableIsSolver = false;
for(s32 BatchIdx = (s32)BatchBuild.size() - 1; BatchIdx >= 0; --BatchIdx)
{
equation_batch_template &Batch = BatchBuild[BatchIdx];
if(Batch.IndexSetDependencies == Spec.IndexSetDependencies)
{
EarliestSuitableBatchIdx = BatchIdx;
EarliestSuitableIsSolver = (Batch.Type == BatchType_Solver);
}
bool DependOnBatch = WeDependOnBatch(Spec.DirectResultDependencies, Spec.CrossIndexResultDependencies, Batch);
if(DependOnBatch) break; // We can not enter a batch that is earlier than this
//NOTE: We don't have to check equations in the batch depends on us, because all equations that depend on us have been sorted so that they are processed after us, and so have not been put in the batches yet.
}
bool PushNewBatch = false;
if(EarliestSuitableBatchIdx == (s32)BatchBuild.size())
{
PushNewBatch = true;
}
else if(EarliestSuitableIsSolver)
{
//This equation does not belong to a solver, so we can not add it to the solver batch. Try to add it immediately after, either by adding it to the next batch if it is suitable or by creating a new batch.
bool CouldInsertInNext = false;
if(EarliestSuitableBatchIdx + 1 != (s32)BatchBuild.size())
{
equation_batch_template &NextBatch = BatchBuild[EarliestSuitableBatchIdx + 1];
if(NextBatch.IndexSetDependencies == Spec.IndexSetDependencies)
{
NextBatch.Equations.push_back(Equation);
CouldInsertInNext = true;
}
}
if(!CouldInsertInNext)
{
equation_batch_template Batch = {};
Batch.Type = BatchType_Regular;
Batch.Equations.push_back(Equation);
Batch.IndexSetDependencies = Spec.IndexSetDependencies;
BatchBuild.insert(BatchBuild.begin() + EarliestSuitableBatchIdx + 1, Batch);
}
}
else
{
BatchBuild[EarliestSuitableBatchIdx].Equations.push_back(Equation);
}
if(PushNewBatch)
{
equation_batch_template Batch = {};
Batch.Type = BatchType_Regular;
Batch.Equations.push_back(Equation);
Batch.IndexSetDependencies = Spec.IndexSetDependencies;
if(Spec.DirectResultDependencies.empty() && Spec.CrossIndexResultDependencies.empty())
{
BatchBuild.insert(BatchBuild.begin(), Batch); //NOTE: If we had no dependencies at all, just insert us at the beginning rather than at the end. This makes it less likely to screw up later structure, and is for instance good for INCA-N.
}
else
{
BatchBuild.push_back(Batch);
}
}
}
}
#if 0
for(auto& BatchTemplate : BatchBuild)
{
for(index_set IndexSet : BatchTemplate.IndexSetDependencies)
{
std::cout << "[" << GetName(Model, IndexSet) << "]";
}
std::cout << "Type: " << BatchTemplate.Type << " Solver: " << BatchTemplate.Solver.Handle << std::endl;
FOR_ALL_BATCH_EQUATIONS(BatchTemplate,
std::cout << "\t" << GetName(Model, Equation) << std::endl;
)
}
#endif
//NOTE: We do a second pass to see if some equations can be shifted to a later batch. This may ultimately reduce the amount of batch groups and speed up execution. It will also make sure that cross indexing between results is more likely to be correct.
// (TODO: this needs a better explanation, but for instance SimplyP gets a more fragmented run structure without this second pass).
//TODO: Maaybe this could be done in the same pass as above, but I haven't figured out how. The problem is that while we are building the batches above, we don't know about any of the batches that will appear after the current batch we are building.
#if 1
for(size_t It = 0; It < 2; ++It) //NOTE: In the latest version of INCA-N we have to do this twice to get a good structure.
{
{
size_t BatchIdx = 0;
for(equation_batch_template &Batch : BatchBuild)
{
if(Batch.Type != BatchType_Solver)
{
s64 EquationIdx = Batch.Equations.size() - 1;
while(EquationIdx >= 0)
{
equation_h ThisEquation = Batch.Equations[EquationIdx];
equation_spec &Spec = Model->EquationSpecs[ThisEquation.Handle];
bool Continue = false;
for(size_t EquationBehind = EquationIdx + 1; EquationBehind < Batch.Equations.size(); ++EquationBehind)
{
equation_h ResultBehind = Batch.Equations[EquationBehind];
equation_spec &SpecBehind = Model->EquationSpecs[ResultBehind.Handle];
//If somebody behind us in this batch depend on us, we are not allowed to move.
if(std::find(SpecBehind.DirectResultDependencies.begin(), SpecBehind.DirectResultDependencies.end(), ThisEquation) != SpecBehind.DirectResultDependencies.end())
{
Continue = true;
break;
}
}
if(Continue)
{
EquationIdx--;
continue;
}
size_t LastSuitableBatch = BatchIdx;
for(size_t BatchBehind = BatchIdx + 1; BatchBehind < BatchBuild.size(); ++BatchBehind)
{
equation_batch_template &NextBatch = BatchBuild[BatchBehind];
if(NextBatch.Type != BatchType_Solver && Spec.IndexSetDependencies == NextBatch.IndexSetDependencies) //This batch suits us
{
LastSuitableBatch = BatchBehind;
}
bool BatchDependsOnUs = false;
FOR_ALL_BATCH_EQUATIONS(NextBatch,
equation_spec &CheckSpec = Model->EquationSpecs[Equation.Handle];
if(std::find(CheckSpec.DirectResultDependencies.begin(), CheckSpec.DirectResultDependencies.end(), ThisEquation) != CheckSpec.DirectResultDependencies.end())
{
BatchDependsOnUs = true;
break; //UGH, since this is a loop macro that loops over two things, this break will not break out of the second loop if it happens in the first...
}
)
if(BatchBehind == BatchBuild.size() - 1 || BatchDependsOnUs)
{
if(LastSuitableBatch != BatchIdx)
{
//Move to the front of that batch.
equation_batch_template &InsertToBatch = BatchBuild[LastSuitableBatch];
InsertToBatch.Equations.insert(InsertToBatch.Equations.begin(), ThisEquation);
Batch.Equations.erase(Batch.Equations.begin() + EquationIdx);
}
break;
}
}
EquationIdx--;
}
}
++BatchIdx;
}
}
//NOTE: Erase Batch templates that got all their equations removed
{
s64 BatchIdx = BatchBuild.size()-1;
while(BatchIdx >= 0)
{
equation_batch_template &Batch = BatchBuild[BatchIdx];
if(Batch.Type != BatchType_Solver && Batch.Equations.empty())
{
BatchBuild.erase(BatchBuild.begin() + BatchIdx);
}
--BatchIdx;
}
}
}
#endif
/////////////// Process the batches into a finished result structure ////////////////////////
size_t *EquationBelongsToBatchGroup = AllocClearedArray(size_t, Model->FirstUnusedEquationHandle);
{
//NOTE: We have to clear sorting flags from previous sortings since we have to do a new sorting for the initial value equations.
for(entity_handle EquationHandle = 1; EquationHandle < Model->FirstUnusedEquationHandle; ++EquationHandle)
{
Model->EquationSpecs[EquationHandle].TempVisited = false;
Model->EquationSpecs[EquationHandle].Visited = false;
}
size_t *Counts = AllocClearedArray(size_t, Model->FirstUnusedIndexSetHandle);
for(auto& BatchTemplate : BatchBuild)
{
for(index_set_h IndexSet : BatchTemplate.IndexSetDependencies)
{
Counts[IndexSet.Handle]++;
}
}
Model->EquationBatches.resize(BatchBuild.size(), {});
size_t BatchIdx = 0;
size_t BatchGroupIdx = 0;
while(BatchIdx != BatchBuild.size())
{
Model->BatchGroups.push_back({});
equation_batch_group &BatchGroup = Model->BatchGroups[Model->BatchGroups.size() - 1];
equation_batch_template &FirstBatchOfGroup = BatchBuild[BatchIdx];
std::set<index_set_h> IndexSets = FirstBatchOfGroup.IndexSetDependencies; //NOTE: set copy.
BatchGroup.IndexSets.insert(BatchGroup.IndexSets.end(), IndexSets.begin(), IndexSets.end());
std::sort(BatchGroup.IndexSets.begin(), BatchGroup.IndexSets.end(),
[Counts] (index_set_h A, index_set_h B) { return ((Counts[A.Handle] == Counts[B.Handle]) ? (A.Handle > B.Handle) : (Counts[A.Handle] > Counts[B.Handle])); }
);
BatchGroup.FirstBatch = BatchIdx;
while(BatchIdx != BatchBuild.size() && BatchBuild[BatchIdx].IndexSetDependencies == IndexSets)
{
equation_batch_template &BatchTemplate = BatchBuild[BatchIdx];
equation_batch &Batch = Model->EquationBatches[BatchIdx];
Batch.Type = BatchTemplate.Type;
Batch.Equations = BatchTemplate.Equations; //NOTE: vector copy
if(Batch.Type == BatchType_Solver)
{
Batch.EquationsODE = BatchTemplate.EquationsODE;
Batch.Solver = BatchTemplate.Solver;
}
FOR_ALL_BATCH_EQUATIONS(Batch,
EquationBelongsToBatchGroup[Equation.Handle] = BatchGroupIdx;
)
//NOTE: In this setup of initial values, we get a problem if an initial value of an equation in batch A depends on the (initial) value of an equation in batch B and batch A is before batch B. If we want to allow this, we need a completely separate batch structure for the initial value equations.... Hopefully that won't be necessary.
//TODO: We should report an error if that happens!
//NOTE: Currently we only allow for initial value equations to be sorted differently than their parent equations within the same batch (this was needed in some of the example models).
FOR_ALL_BATCH_EQUATIONS(Batch,
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(IsValid(Spec.InitialValueEquation) || IsValid(Spec.InitialValue) || Spec.HasExplicitInitialValue) //NOTE: We only care about equations that have an initial value (or that are depended on by an initial value equation, but they are added recursively inside the visit)
{
TopologicalSortEquationsInitialValueVisit(Model, Equation, Batch.InitialValueOrder);
}
)
++BatchIdx;
}
BatchGroup.LastBatch = BatchIdx - 1;
++BatchGroupIdx;
}
free(Counts);
}
///////////////// Find out which parameters, results and last_results that need to be hotloaded into the CurParameters, CurInputs etc. buffers in the value_set_accessor at each iteration stage during model run. /////////////////
{
size_t BatchGroupIdx = 0;
for(equation_batch_group &BatchGroup : Model->BatchGroups)
{
std::set<entity_handle> AllParameterDependenciesForBatchGroup;
std::set<equation_h> AllResultDependenciesForBatchGroup;
std::set<equation_h> AllLastResultDependenciesForBatchGroup;
std::set<input_h> AllInputDependenciesForBatchGroup;
for(size_t BatchIdx = BatchGroup.FirstBatch; BatchIdx <= BatchGroup.LastBatch; ++BatchIdx)
{
equation_batch &Batch = Model->EquationBatches[BatchIdx];
FOR_ALL_BATCH_EQUATIONS(Batch,
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(Spec.Type != EquationType_Cumulative) //NOTE: We don't have to load in dependencies for cumulative equations since these get their data directly from the DataSet.
{
AllParameterDependenciesForBatchGroup.insert(Spec.ParameterDependencies.begin(), Spec.ParameterDependencies.end());
AllInputDependenciesForBatchGroup.insert(Spec.InputDependencies.begin(), Spec.InputDependencies.end());
AllResultDependenciesForBatchGroup.insert(Spec.DirectResultDependencies.begin(), Spec.DirectResultDependencies.end());
AllLastResultDependenciesForBatchGroup.insert(Spec.DirectLastResultDependencies.begin(), Spec.DirectLastResultDependencies.end());
//TODO: The following is a quick fix so that initial value equations get their parameters set correctly. However it causes unneeded parameters to be loaded at each step for the main execution. We should make a separate system for initial value equations.
if(IsValid(Spec.InitialValueEquation))
{
equation_spec &InitSpec = Model->EquationSpecs[Spec.InitialValueEquation.Handle];
AllParameterDependenciesForBatchGroup.insert(InitSpec.ParameterDependencies.begin(), InitSpec.ParameterDependencies.end());
}
}
)
}
BatchGroup.IterationData.resize(BatchGroup.IndexSets.size(), {});
for(size_t IndexSetLevel = 0; IndexSetLevel < BatchGroup.IndexSets.size(); ++IndexSetLevel)
{
//NOTE: Gather up all the parameters that need to be updated at this stage of the execution tree. By updated we mean that they need to be read into the CurParameters buffer during execution.
//TODO: We do a lot of redundant checks here. We could store temporary information to speed this up.
for(entity_handle ParameterHandle : AllParameterDependenciesForBatchGroup)
{
std::vector<index_set_h> &ThisParDependsOn = Model->ParameterSpecs[ParameterHandle].IndexSetDependencies;
if(IsTopIndexSetForThisDependency(ThisParDependsOn, BatchGroup.IndexSets, IndexSetLevel))
{
BatchGroup.IterationData[IndexSetLevel].ParametersToRead.push_back(ParameterHandle);
}
}
for(input_h Input : AllInputDependenciesForBatchGroup)
{
std::vector<index_set_h> &ThisInputDependsOn = Model->InputSpecs[Input.Handle].IndexSetDependencies;
if(IsTopIndexSetForThisDependency(ThisInputDependsOn, BatchGroup.IndexSets, IndexSetLevel))
{
BatchGroup.IterationData[IndexSetLevel].InputsToRead.push_back(Input);
}
}
for(equation_h Equation : AllResultDependenciesForBatchGroup)
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(Spec.Type != EquationType_InitialValue) //NOTE: Initial values are handled separately in an initial setup run.
{
size_t ResultBatchGroupIndex = EquationBelongsToBatchGroup[Equation.Handle];
if(ResultBatchGroupIndex < BatchGroupIdx) //NOTE: Results in the current batch group will be correct any way, and by definition we can not depend on any batches that are after this one.
{
std::vector<index_set_h> &ThisResultDependsOn = Model->BatchGroups[ResultBatchGroupIndex].IndexSets;
if(IsTopIndexSetForThisDependency(ThisResultDependsOn, BatchGroup.IndexSets, IndexSetLevel))
{
BatchGroup.IterationData[IndexSetLevel].ResultsToRead.push_back(Equation);
}
}
}
}
for(equation_h Equation : AllLastResultDependenciesForBatchGroup)
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(Spec.Type != EquationType_InitialValue) //NOTE: Initial values are handled separately in an initial setup run.
{
size_t ResultBatchGroupIndex = EquationBelongsToBatchGroup[Equation.Handle];
if(ResultBatchGroupIndex != BatchGroupIdx) //NOTE: LAST_RESULTs in the current batch group are loaded using a different mechanism.
{
std::vector<index_set_h> &ThisResultDependsOn = Model->BatchGroups[ResultBatchGroupIndex].IndexSets;
if(IsTopIndexSetForThisDependency(ThisResultDependsOn, BatchGroup.IndexSets, IndexSetLevel))
{
BatchGroup.IterationData[IndexSetLevel].LastResultsToRead.push_back(Equation);
}
}
}
}
}
for(equation_h Equation : AllLastResultDependenciesForBatchGroup) //NOTE: We need a separate system for last_results with no index set dependencies, unfortunately.
{
equation_spec &Spec = Model->EquationSpecs[Equation.Handle];
if(Spec.Type != EquationType_InitialValue) //NOTE: Initial values are handled separately in an initial setup run.
{
size_t ResultBatchGroupIndex = EquationBelongsToBatchGroup[Equation.Handle];
if(ResultBatchGroupIndex != BatchGroupIdx) //NOTE: LAST_RESULTs in the current batch group are loaded using a different mechanism.
{
std::vector<index_set_h> &ThisResultDependsOn = Model->BatchGroups[ResultBatchGroupIndex].IndexSets;
if(ThisResultDependsOn.empty())
{
BatchGroup.LastResultsToReadAtBase.push_back(Equation);
}
}
}
}
++BatchGroupIdx;
}
}
free(EquationBelongsToBatchGroup);
//////////////////////// Gather about (in-) direct equation dependencies to be used by the Jacobian estimation used by some implicit solvers //////////////////////////////////
BuildJacobianInfo(Model);
Model->Finalized = true;
#if MOBIUS_PRINT_TIMING_INFO
u64 Duration = GetTimerMilliseconds(&Model->DefinitionTimer);
std::cout << "Model definition time: " << Duration << " milliseconds." << std::endl;
#endif
}
//NOTE: It is kind of superfluous to both provide the batch group and the batch group index... But it does probably not harm either?
#define INNER_LOOP_BODY(Name) void Name(mobius_data_set *DataSet, value_set_accessor *ValueSet, const equation_batch_group &BatchGroup, size_t BatchGroupIdx, s32 CurrentLevel)
typedef INNER_LOOP_BODY(mobius_inner_loop_body);
static void
ModelLoop(mobius_data_set *DataSet, value_set_accessor *ValueSet, mobius_inner_loop_body InnerLoopBody)
{
const mobius_model *Model = DataSet->Model;
size_t BatchGroupIdx = 0;
for(const equation_batch_group &BatchGroup : Model->BatchGroups)
{
if(BatchGroup.IndexSets.empty())
{
InnerLoopBody(DataSet, ValueSet, BatchGroup, BatchGroupIdx, -1);
BatchGroupIdx++;
continue;
}
s32 BottomLevel = (s32)BatchGroup.IndexSets.size() - 1;
s32 CurrentLevel = 0;