forked from ModiaSim/Modia.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeGeneration.jl
More file actions
2091 lines (1746 loc) · 80.6 KB
/
CodeGeneration.jl
File metadata and controls
2091 lines (1746 loc) · 80.6 KB
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
# License for this file: MIT (expat)
# Copyright 2020-2021, DLR Institute of System Dynamics and Control
using OrderedCollections: OrderedDict, OrderedSet
using DataFrames
using OrdinaryDiffEqCore
#=
fieldnames(typeof(integrator)) = (:sol, :u, :du, :k, :t, :dt, :f, :p, :uprev, :uprev2, :duprev, :tprev, :alg,
:dtcache, :dtchangeable, :dtpropose, :tdir, :eigen_est, :EEst, :qold, :q11,
:erracc, :dtacc, :success_iter, :iter, :saveiter, :saveiter_dense, :cache,
:callback_cache, :kshortsize, :force_stepfail, :last_stepfail, :just_hit_tstop,
:do_error_check, :event_last_time, :vector_event_last_time, :last_event_error,
:accept_step, :isout, :reeval_fsal, :u_modified, :reinitialize, :isdae, :opts,
:destats, :initializealg, :fsalfirst, :fsallast)
=#
"""
baseType(T)
Return the base type of a type T, according to the following definition.
```julia
baseType(::Type{T}) where {T} = T
baseType(::Type{Unitful.Quantity{T,D,U}}) where {T,D,U} = T
baseType(::Type{Measurements.Measurement{T}}) where {T} = T
baseType(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T,N} = T
baseType(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T,N} = T
```
# Examples
```
baseType(Float32) # Float32
baseType(Measurement{Float64}) # Float64
```
"""
baseType(::Type{T}) where {T} = T
baseType(::Type{Unitful.Quantity{T,D,U}}) where {T,D,U} = T
baseType(::Type{Measurements.Measurement{T}}) where {T} = T
baseType(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T,N} = T
baseType(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T,N} = T
isQuantity( ::Type{T}) where {T} = T <: Unitful.Quantity || T <: MonteCarloMeasurements.AbstractParticles && baseType(T) <: Unitful.Quantity
isMeasurements( ::Type{T}) where {T} = T <: Measurements.Measurement || T <: Unitful.Quantity && baseType(T) <: Measurements.Measurement
isMonteCarloMeasurements(::Type{T}) where {T} = T <: MonteCarloMeasurements.AbstractParticles
Base.floatmax(::Type{Unitful.Quantity{T,D,U}}) where {T,D,U} = Base.floatmax(T)
Base.floatmax(::Type{Measurements.Measurement{T}}) where {T} = Base.floatmax(T)
Base.floatmax(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T,N} = Base.floatmax(T)
Base.floatmax(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T,N} = Base.floatmax(T)
"""
str = measurementToString(v)
Return variable `v::Measurements.Measurement{FloatType}` or a vector of such variables
in form of a string will the full number of significant digits.
"""
measurementToString(v::Measurements.Measurement{FloatType}) where {FloatType} =
string(Measurements.value(v)) * " ± " * string(Measurements.uncertainty(v))
function measurementToString(v::Vector{Measurements.Measurement{FloatType}}) where {FloatType}
str = string(typeof(v[1])) * "["
for (i,vi) in enumerate(v)
if i > 1
str = str * ", "
end
str = str * measurementToString(vi)
end
str = str * "]"
return str
end
#= No longer needed
function get_x_start!(FloatType, equationInfo, parameters)
x_start = []
startIndex = 1
for xe_info in equationInfo.x_info
xe_info.startIndex = startIndex
# Determine init/start value in m.parameters
xe_value = get_value(parameters, xe_info.x_name)
if ismissing(xe_value)
error("Missing start/init value ", xe_info.x_name)
end
if hasParticles(xe_value)
len = 1
push!(x_start, xe_value)
else
len = length(xe_value)
push!(x_start, xe_value...)
end
if len != xe_info.length
printstyled("Model error: ", bold=true, color=:red)
printstyled("Length of ", xe_info.x_name, " shall be changed from ",
xe_info.length, " to $len\n",
"This is currently not support in Modia.", bold=true, color=:red)
return false
end
startIndex += xe_info.length
end
equationInfo.nx = startIndex - 1
# Temporarily remove units from x_start
# (TODO: should first transform to the var_unit units and then remove)
converted_x_start = convert(Vector{FloatType}, [stripUnit(v) for v in x_start]) # stripUnit.(x_start) does not work for MonteCarloMeasurements
x_start2 = deepcopy(converted_x_start)
return x_start2
end
=#
const BasicSimulationKeywordArguments = OrderedSet{Symbol}(
[:merge, :tolerance, :startTime, :stopTime, :interval, :interp_points, :dtmax, :adaptive, :nlinearMinForDAE,
:log, :logStates, :logEvents, :logProgress, :logTiming, :logParameters, :logEvaluatedParameters,
:requiredFinalStates, :requiredFinalStates_rtol, :requiredFinalStates_atol, :useRecursiveFactorizationUptoSize])
const RegisteredExtraSimulateKeywordArguments = OrderedSet{Symbol}()
function registerExtraSimulateKeywordArguments(keys)::Nothing
for key in keys
if key in BasicSimulationKeywordArguments
@error "registerExtraSimulateKeywordArguments:\nKeyword $key is ignored, since standard keyword of simulate!(..) (use another keyword)\n\n"
end
push!(RegisteredExtraSimulateKeywordArguments, key)
end
return nothing
end
"""
convertTimeVariable(TimeType, t)
If `t` has a unit, it is transformed to u"s", the unit is stripped off,
converted to `TimeType` and returned. Otherwise `t` is converted to `TimeType` and returned.
# Example
```julia
convertTimeVariable(Float32, 2.0u"hr") # = 7200.0f0
```
"""
convertTimeVariable(TimeType, t) = typeof(t) <: Unitful.AbstractQuantity ? convert(TimeType, stripUnit(t)) : convert(TimeType, t)
mutable struct SimulationOptions{FloatType,TimeType}
merge::OrderedDict{Symbol,Any}
tolerance::Float64
startTimeFirstSegment::TimeType # u"s"; startTime of first segment
startTime::TimeType # u"s"; startTime of actual segment
stopTime::TimeType # u"s"
interval::TimeType # u"s"
desiredResultTimeUnit
interp_points::Int
dtmax::Float64
adaptive::Bool
nlinearMinForDAE::Int
log::Bool
logStates::Bool
logEvents::Bool
logProgress::Bool
logTiming::Bool
logParameters::Bool
logEvaluatedParameters::Bool
requiredFinalStates::Union{Missing, Vector{FloatType}}
requiredFinalStates_rtol::Float64
requiredFinalStates_atol::Float64
useRecursiveFactorizationUptoSize::Int
extra_kwargs::OrderedDict{Symbol,Any}
function SimulationOptions{FloatType,TimeType}(merge, errorMessagePrefix=""; _dummy=false, kwargs...) where {FloatType,TimeType}
success = true
adaptive = get(kwargs, :adaptive, true)
tolerance = _dummy ? Inf : get(kwargs, :tolerance, 1e-6)
if tolerance <= 0.0
printstyled(errorMessagePrefix, "tolerance (= $(tolerance)) must be > 0\n\n", bold=true, color=:red)
success = false
elseif tolerance < 100*eps(FloatType) && adaptive
newTolerance = max(tolerance, 100*eps(FloatType))
printstyled("Warning from Modia.simulate!(..):\n"*
"tolerance (= $(tolerance)) is too small for FloatType = $FloatType (eps(FloatType) = $(eps(FloatType))).\n" *
"tolerance changed to $newTolerance.\n\n", bold=true, color=:red)
tolerance = newTolerance
end
startTimeFirstSegment = convertTimeVariable(TimeType, get(kwargs, :startTime, 0.0) )
startTime = startTimeFirstSegment
rawStopTime = get(kwargs, :stopTime, startTime)
stopTime = convertTimeVariable(TimeType, rawStopTime)
interval = convertTimeVariable(TimeType, get(kwargs, :interval , (stopTime - startTime)/500.0) )
dtmax = get(kwargs, :dtmax, 100*getValueOnly(interval))
if ismissing(dtmax) || isnothing(dtmax)
dtmax = 100*getValueOnly(interval)
end
dtmax = convert(Float64, dtmax)
desiredResultTimeUnit = unit(rawStopTime)
interp_points = get(kwargs, :interp_points, 0)
if interp_points < 0
printstyled(errorMessagePrefix, "interp_points (= $(interp_points)) must be > 0\n\n", bold=true, color=:red)
success = false
elseif interp_points == 1
# DifferentialEquations.jl crashes
interp_points = 2
end
nlinearMinForDAE = max(1, get(kwargs, :nlinearMinForDAE, 10)) # >= 10
adaptive = get(kwargs, :adaptive , true)
log = get(kwargs, :log , false)
logStates = get(kwargs, :logStates , false)
logEvents = get(kwargs, :logEvents , false)
logProgress = get(kwargs, :logProgress , false)
logTiming = get(kwargs, :logTiming , false)
logParameters = get(kwargs, :logParameters, false)
logEvaluatedParameters = get(kwargs, :logEvaluatedParameters , false)
requiredFinalStates = get(kwargs, :requiredFinalStates , missing)
if isnothing(requiredFinalStates)
requiredFinalStates = missing
end
requiredFinalStates_rtol = get(kwargs, :requiredFinalStates_rtol, 1e-3)
requiredFinalStates_atol = get(kwargs, :requiredFinalStates_atol, 0.0)
useRecursiveFactorizationUptoSize = get(kwargs, :useRecursiveFactorizationUptoSize, 0)
extra_kwargs = OrderedDict{Symbol,Any}()
for option in kwargs
key = option.first
if key in BasicSimulationKeywordArguments
nothing;
elseif key in RegisteredExtraSimulateKeywordArguments
extra_kwargs[key] = option.second
else
printstyled(errorMessagePrefix, "simulate!(..., $key=$(option.second)): $key is unknown.\n\n", bold=true, color=:red)
success = false
end
end
# obj = new(isnothing(merge) ? NamedTuple() : merge, tolerance, startTime, stopTime, interval, desiredResultTimeUnit, interp_points,
obj = new(ismissing(merge) || isnothing(merge) ? OrderedDict{Symbol,Any}() : merge, tolerance, startTimeFirstSegment, startTime, stopTime, interval, desiredResultTimeUnit, interp_points,
dtmax, adaptive, nlinearMinForDAE, log, logStates, logEvents, logProgress, logTiming, logParameters, logEvaluatedParameters,
requiredFinalStates, requiredFinalStates_rtol, requiredFinalStates_atol, useRecursiveFactorizationUptoSize, extra_kwargs)
return success ? obj : nothing
end
SimulationOptions{FloatType,TimeType}() where {FloatType,TimeType} =
SimulationOptions{FloatType,TimeType}(OrderedDict{Symbol,Any}(); _dummy=true)
end
struct LinearEquationsCopyInfoForDAEMode
ileq::Int # Index of LinearEquations()
index::Vector{Int} # Copy: leq.x[i] = dae_der_x[index[i]]
# dae_residuals[index[i]] = leq.residuals[i]
LinearEquationsCopyInfoForDAEMode(ileq) = new(ileq, Int[])
end
"""
simulationModel = InstantiatedModel{FloatType,TimeType}(
modelModule, modelName, getDerivatives!, equationInfo, x_startValues,
parameters, timeName, w_invariant_names;
vSolvedWithInitValuesAndUnit::OrderedDict{String,Any}(),
vEliminated::Vector{Int}=Int[],
vProperty::Vector{Int}=Int[],
var_name::Function = v->nothing)
# Arguments
- `modelModule`: Module in which `@instantiateModel` is invoked (it is used for `Core.eval(modelModule, ...)`),
that is evaluation of expressions in the environment of the user.
- `modelName::String`: Name of the model
- `getDerivatives::Function`: Function that is used to evaluate the model equations,
typically generated with [`Modia.generate_getDerivatives!`].
- `equationInfo::Modia.EquationInfo`: Information about the states and the equations.
- `x_startValues`:: Deprecated (is no longer used).
- `parameters`: A hierarchical NamedTuple of (key, value) pairs defining the parameter and init/start values.
- `timeName`: Name of time (as Symbol)
- `w_invariant_names`: A vector of variable names (as vector of symbols or Expr)
"""
mutable struct InstantiatedModel{FloatType,TimeType}
# Available before propagateEvaluateAndInstantiate!(..) called (= partiallyInstantedModel)
modelModule::Module
modelName::String
buildDict::OrderedDict{String,Any}
timer::TimerOutputs.TimerOutput
cpuFirst::UInt64 # cpu time of start of simulation
cpuLast::UInt64 # Last time from time_ns()
options::SimulationOptions{FloatType,TimeType}
getDerivatives!::Function
initialEquationInfo::Modia.EquationInfo
linearEquations::Vector{Modia.LinearEquations{FloatType}}
eventHandler::EventHandler{FloatType,TimeType}
vSolvedWithInitValuesAndUnit::OrderedDict{String,Any} # Dictionary of (names, init values with units) for all explicitly solved variables with init-values defined
previous::AbstractVector # previous[i] is the value of previous(...., i)
previous_names::Vector{String} # previous_names[i] is the name of previous-variable i
previous_dict::OrderedDict{String,Int} # previous_dict[name] is the index of previous-variable name
pre::AbstractVector
pre_names::Vector{String}
pre_dict::OrderedDict{String,Int}
hold::AbstractVector
hold_names::Vector{String}
hold_dict::OrderedDict{String,Int}
isInitial::Bool
solve_leq::Bool # = true, if linear equations 0 = A*x-b shall be solved
# = false, if leq.x is provided by DAE solver and leq.residuals is used by the DAE solver.
odeMode::Bool # = false: copy der(x) into linear equation systems that have leq.odeMode=false and do not solve these equation systems
storeResult::Bool
time::TimeType
nf_total::Int # Number of getDerivatives! calls
nf_integrator::Int # Number of getDerivatives! calls from integrator (without zero-crossing calls)
odeIntegrator::Bool # = true , if ODE integrator used
# = false, if DAE integrator used
daeCopyInfo::Vector{LinearEquationsCopyInfoForDAEMode} # Info to efficiently copy between DAE and linear equation systems
algorithmName::Union{String,Missing} # Name of integration algorithm as string (used in default-heading of plot)
sundials::Bool # = true, if algorithm is a Sundials integrator
addEventPointsDueToDEBug::Bool # = true, if event points are explicitly stored for Sundials integrators, due to bug in DifferentialEquations
# (https://github.com/SciML/Sundials.jl/issues/309)
success::Bool # = true, if after first outputs!(..) call and no error was triggered
# = false, either before first outputs!(..) call or at first outputs!(..) after init!(..) and
# an error was triggered and simulate!(..) should be returned with nothing.
unitless::Bool # = true, if simulation is performed without units.
timeName::String
w_invariant_names::Vector{String}
hideResult_names::Vector{String} # Names of hidden variables
vEliminated::Vector{Int}
vProperty::Vector{Int}
var_name::Function
result::Union{Result,Missing} # Result data structure upto current time instant
parameters::OrderedDict{Symbol,Any} # Parameters as provided to InstantiatedModelconstructor
equationInfo::Modia.EquationInfo # Invariant part of equations are available
x_terminate::Vector{FloatType} # States x used at the last terminate!(..) call or [], if terminate!(..) not yet called.
# Available before init!(..) called
statistics::OrderedDict{Symbol,Any} # Statistics of simulation run
# Available after propagateEvaluateAndInstantiate!(..) called
instantiateFunctions::Vector{Tuple{Union{Expr,Symbol},OrderedDict{Symbol,Any},String}}
# All definitions `_initSegmentFunction = Par(functionName = XXX)` in the model to call
# `XXX(instantiatedModel, submodel, submodelPath)` in the order occurring during evaluation
# of the parameters where, instantiatedFunctions[i] = (XXX, submodel, submodelPath)
nsegments::Int # Current simulation segment
evaluatedParameters::OrderedDict{Symbol,Any} # Evaluated parameters
nextPrevious::AbstractVector # nextPrevious[i] is the current value of the variable identified by previous(...., i)
nextPre::AbstractVector
nextHold::AbstractVector
x_vec::Vector{Vector{FloatType}} # x_vec[i] holds the actual values of (visible) state vector element
# equationInfo.x_info[equationInfo.nx_info_fixedLength+i:equationInfo.nx_info_invariant]
x_start::Vector{FloatType} # States x before first event iteration (before initialization)
x_init::Vector{FloatType} # States x after initialization (and before integrator is started)
x_segmented::Vector{FloatType} # A copy of the current segmented states
der_x_invariant::Vector{FloatType} # Derivatives of states x or x_init that correspond to invariant states
# This vector is filled with derivatives of invariants states with appendVariable!(m.der_x_invariant, ...) calls,
# including derivatives of x_vec[i]
der_x_segmented::Vector{FloatType} # Derivatives of states x or x_init that correspond to segmented states (defined in functions and not visible in getDerivatives!(..))
der_x::Vector{FloatType} # Derivatives of states x
function InstantiatedModel{FloatType,TimeType}(modelModule, modelName, buildDict, getDerivatives!, equationInfo,
previousVars, preVars, holdVars,
parameterDefinition, timeName, w_invariant_names, hideResult_names;
unitless::Bool=true,
nz::Int = 0,
nAfter::Int = 0,
vSolvedWithInitValuesAndUnit::AbstractDict = OrderedDict{String,Any}(),
vEliminated::Vector{Int} = Int[],
vProperty::Vector{Int} = Int[],
var_name::Function = v -> nothing) where {FloatType,TimeType}
# Construct data structure for linear equations
linearEquations = Modia.LinearEquations{FloatType}[]
for leq in equationInfo.linearEquations
push!(linearEquations, Modia.LinearEquations{FloatType}(leq...))
end
vSolvedWithInitValuesAndUnit2 = OrderedDict{String,Any}( [(string(key),vSolvedWithInitValuesAndUnit[key]) for key in keys(vSolvedWithInitValuesAndUnit)] )
# Build previous-arrays
previous = Vector{Any}(missing, length(previousVars))
previous_names = string.(previousVars)
previous_dict = OrderedDict{String,Int}(zip(previous_names, 1:length(previousVars)))
# Build pre-arrays
pre = Vector{Any}(missing, length(preVars))
pre_names = string.(preVars)
pre_dict = OrderedDict{String,Int}(zip(pre_names, 1:length(preVars)))
# Build hold-arrays
hold = Vector{Any}(missing, length(holdVars))
hold_names = string.(holdVars)
hold_dict = OrderedDict{String,Int}(zip(hold_names, 1:length(holdVars)))
# Initialize execution flags
eventHandler = EventHandler{FloatType,TimeType}(nz=nz, nAfter=nAfter)
isInitial = true
storeResult = false
solve_leq = true
nf_total = 0
nf_integrator = 0
odeIntegrator = true
daeCopyInfo = LinearEquationsCopyInfoForDAEMode[]
algorithmName = missing
sundials = false
addEventPointsDueToDEBug = false
success = false
w_invariant_names = String[string(name) for name in w_invariant_names]
# Initialize other data
result = missing
instantiateResult = true
newResultSegment = false
parameters = deepcopy(parameterDefinition)
x_terminate = FloatType[]
new(modelModule, modelName, buildDict, TimerOutputs.TimerOutput(), UInt64(0), UInt64(0), SimulationOptions{FloatType,TimeType}(), getDerivatives!,
equationInfo, linearEquations, eventHandler,
vSolvedWithInitValuesAndUnit2,
previous, previous_names, previous_dict,
pre, pre_names, pre_dict,
hold, hold_names, hold_dict,
isInitial, solve_leq, true, storeResult, convert(TimeType, 0), nf_total, nf_integrator,
odeIntegrator, daeCopyInfo, algorithmName, sundials, addEventPointsDueToDEBug, success, unitless,
string(timeName), w_invariant_names, hideResult_names, vEliminated, vProperty, var_name, result,
parameters, equationInfo, x_terminate)
end
#=
function InstantiatedModel{FloatType,TimeType}(m::InstantiatedModel) where {FloatType,TimeType}
# Construct data structure for linear equations
linearEquations = Modia.LinearEquations{FloatType}[]
for leq in m.equationInfo.linearEquations
push!(linearEquations, Modia.LinearEquations{FloatType}(leq...))
end
# Initialize execution flags
eventHandler = EventHandler{FloatType,TimeType}()
eventHandler.initial = true
isInitial = true
storeResult = false
solve_leq = true
nf_total = 0
nf_integrator = 0
odeIntegrator = true
daeCopyInfo = LinearEquationsCopyInfoForDAEMode[]
algorithmName = missing
success = false
nx = m.equationInfo.nx
nxInvariant = m.equationInfo.nxInvariant
nxSegmented = nx-nxInvariant
emptyResult!(m.result)
result = deepcopy(m.result)
nsegments = 1
x_vec = [zeros(FloatType, equationInfo.x_info[i].length) for i in equationInfo.nx_info_fixedLength+1:equationInfo.nx_info_invariant]
x_start = convert(Vector{FloatType}, m.x_start)
x_init = zeros(FloatType, nx)
x_segmented = zeros(FloatType, nxSegmented)
der_x_invariant = zeros(FloatType, nxInvariant)
der_x_segmented = zeros(FloatType, nxSegmented)
der_x = zeros(FloatType, nx)
new(m.modelModule, m.modelName, deepcopy(m.buildDict), TimerOutputs.TimerOutput(), UInt64(0), UInt64(0), deepcopy(m.options), m.getDerivatives!,
deepcopy(m.equationInfo), deepcopy(linearEquations),
deepcopy(eventHandler),
m.vSolvedWithInitValuesAndUnit,
deepcopy(m.previous), m.previous_names, m.previous_dict,
deepcopy(m.pre), m.pre_names, m.pre_dict,
deepcopy(m.hold), m.hold_names, m.hold_dict,
isInitial, solve_leq, true, storeResult, convert(TimeType, 0), nf_total, nf_integrator,
true, LinearEquationsCopyInfoForDAEMode[],
odeIntegrator, daeCopyInfo, m.sundials, m.addEventPointsDueToDEBug, success, m.unitless,
result, nsegments,
deepcopy(m.parameters), deepcopy(m.instantiateFunctions), deepcopy(m.evaluatedParameters),
deepcopy(m.nextPrevious), deepcopy(m.nextPre), deepcopy(m.nextHold),
x_vec, x_start, x_init, x_segmented, der_x_invariant, der_x_segmented, der_x)
end
=#
end
# Default constructors
InstantiatedModel{FloatType}(args...; kwargs...) where {FloatType} = InstantiatedModel{FloatType,FloatType}(args...; kwargs...)
InstantiatedModel{Measurements.Measurement{T},}(args...; kwargs...) where {T} = InstantiatedModel{Measurements.Measurement{T},T}(args...; kwargs...)
InstantiatedModel{MonteCarloMeasurements.Particles{T,N}}(args...; kwargs...) where {T,N,} = InstantiatedModel{MonteCarloMeasurements.Particles{T,N},T}(args...; kwargs...)
InstantiatedModel{MonteCarloMeasurements.StaticParticles{T,N}}(args...; kwargs...) where {T,N} = InstantiatedModel{MonteCarloMeasurements.StaticParticles{T,N},T}(args...; kwargs...)
timeType(m::InstantiatedModel{FloatType,TimeType}) where {FloatType,TimeType} = TimeType
# The following rule is important for DiffEqBase version 6.91.6 and later
# (https://github.com/SciML/DiffEqBase.jl/issues/791)
if Base.isdefined(DiffEqBase, :anyeltypedual)
DiffEqBase.anyeltypedual(::InstantiatedModel) = Any
end
positive(m::InstantiatedModel, args...; kwargs...) = Modia.positive!(m.eventHandler, args...; kwargs...)
negative(m::InstantiatedModel, args...; kwargs...) = Modia.negative!(m.eventHandler, args...; kwargs...)
change( m::InstantiatedModel, args...; kwargs...) = Modia.change!( m.eventHandler, args...; kwargs...)
edge( m::InstantiatedModel, args...; kwargs...) = Modia.edge!( m.eventHandler, args...; kwargs...)
after( m::InstantiatedModel, args...; kwargs...) = Modia.after!( m.eventHandler, args...; kwargs...)
pre( m::InstantiatedModel, i) = m.pre[i]
"""
v_zero = reinit(instantiatedModel, _x, j, v_new, _leqMode; v_threshold=0.01)
Re-initialize state j with v_new, that is set x[i] = v_new, with i = instantiatedModel.equationInfo.x_info[j].startIndex.
If v_new <= v_threshold, set x[i] to the floating point number that is closest to zero, so that x[i] > 0 and return
v_zero = true. Otherwise return v_zero = false.
An error is triggered if the function is not called during an event phase
or if leqMode >= 0 (which means that reinit is called inside the for-loop
to solve a linear equation system - this is not yet supported).
# Implementation notes
At the beginning of getDerivatives!(..), assignments of _x to appropriate variables are performed.
Therefore, setting _x[i] afterwards via reinit, has no immediate effect on this model evaluation.
With reinit, instantiatedModel.eventHandler.newEventIteration = true is set, to force a new
event iteration. At the next event iteration, the new value v_new is copied from _x and therefore
has then an effect.
"""
function reinit(m::InstantiatedModel, x, j, v_new, leqMode; v_threshold=0.01)
if leqMode >= 0
error("reinit(..) of model ", m.modelName, " is called when solving a linear equation system (this is not supported)")
elseif !isEvent(m)
error("reinit(..) of model ", m.modelName, " is called outside of an event phase (this is not allowed)")
end
eh = m.eventHandler
eh.restart = max(eh.restart, Restart)
eh.newEventIteration = true
i = m.equationInfo.x_info[j].startIndex
if v_new <= v_threshold
x[i] = nextfloat(convert(typeof(v_new), 0))
if eh.logEvents
println(" State ", m.equationInfo.x_info[j].x_name, " reinitialized to ", x[i], " (reinit returns true)")
end
return true
else
x[i] = v_new
if eh.logEvents
println(" State ", m.equationInfo.x_info[j].x_name, " reinitialized to ", v_new, " (reinit returns false)")
end
return false
end
end
"""
floatType = getFloatType(simulationModel::InstantiatedModel)
Return the floating point type with which `simulationModel` is parameterized
(for example returns: `Float64, Float32, DoubleFloat, Measurements.Measurement{Float64}`).
"""
getFloatType(m::InstantiatedModel{FloatType,TimeType}) where {FloatType,TimeType} = FloatType
"""
hasParticles(value)
Return true, if `value` is of type `MonteCarloMeasurements.StaticParticles` or
`MonteCarloMeasurements.Particles`.
"""
hasParticles(value) = typeof(value) <: MonteCarloMeasurements.StaticParticles ||
typeof(value) <: MonteCarloMeasurements.Particles
"""
get_value(obj, name::String)
Return the value identified by `name` from the potentially hierarchically
dictionary `obj`. If `name` is not in `obj`, the function returns `missing`.
# Examples
```julia
s1 = Map(a = 1, b = 2, c = 3)
s2 = Map(v1 = s1, v2 = (d = 4, e = 5))
s3 = Map(v3 = s2, v4 = s1)
@show get_value(s3, "v3.v1.b") # returns 2
@show get_value(s3, "v3.v2.e") # returns 5
@show get_value(s3, "v3.v1.e") # returns missing
```
"""
function get_value(obj::OrderedDict, name::String)
if length(name) == 0 || length(obj) == 0
return missing
end
j = findnext('.', name, 1)
if isnothing(j)
key = Symbol(name)
return haskey(obj,key) ? obj[key] : missing
elseif j == 1
return missing
else
key = Symbol(name[1:j-1])
if haskey(obj,key) && typeof(obj[key]) <: OrderedDict && length(name) > j
get_value(obj[key], name[j+1:end])
else
return missing
end
end
end
"""
appendName(path::String, name::Symbol)
Return `path` appended with `.` and `string(name)`.
"""
appendName(path, key) = path == "" ? string(key) : path * "." * string(key)
"""
get_names(obj)
Return `Vector{String}` containing all the names present in `obj`
# Examples
```julia
s1 = Map(a = 1, b = 2, c = 3)
s2 = Map(v1 = s1, v2 = (d = 4, e = 5))
s3 = Map(v3 = s2, v4 = s1)
@show get_names(s3)
```
"""
function get_names(obj) # ::NamedTuple)
names = String[]
get_names!(obj, names, "")
return names
end
function get_names!(obj #= ::NamedTuple =# , names::Vector{String}, path::String)::Nothing
for (key,value) in obj # zip(keys(obj), obj)
if key != :_class
name = appendName(path, key)
if typeof(value) <: OrderedDict
get_names!(value, names, name)
else
push!(names, name)
end
end
end
return nothing
end
"""
getLastValue(model::InstantiatedModel, name::String; unit=true)
Return the last stored value of variable `name` from `model`.
If `unit=true` return the value with its unit, otherwise with stripped unit.
If `name` is not known or no result values yet available, an info message is printed
and the function returns `nothing`.
`name` can be a time-varying variable or a parameter.
"""
function getLastValue(m::InstantiatedModel{FloatType,TimeType}, name::String; unit::Bool=true) where {FloatType,TimeType}
if isnothing(m) || ismissing(m.result)
@info "getLastValue(model,\"$name\"): No results yet available."
return nothing
end
result = m.result
if haskey(result.info, name)
# Time varying variable stored in m.result
resInfo = result.info[name]
if length(result.t) == 0
@info "getLastValue(model,\"$name\"): No results yet available."
return nothing
end
if resInfo.kind == RESULT_ELIMINATED
value = getLastValue(m, resInfo.aliasName, unit=unit)
if resInfo.aliasNegate
value *= -1
end
elseif resInfo.kind == RESULT_CONSTANT
value = resInfo.value
if !unit
value = stripUnit(value)
end
elseif resInfo.kind == RESULT_T
value = result.t[end][end]
if unit && resInfo.unit != ""
value *= uparse(resInfo.unit)
end
elseif resInfo.kind == RESULT_X
id = resInfo.id[end]
segment = id.segment
if segment < length(result.t)
return missing
end
ibeg = id.index
iend = ibeg + prod(id.size) - 1
value = ibeg == iend ? result.x[segment][end][ibeg] : result.x[segment][end][ibeg:iend]
if unit && resInfo.unit != ""
value *= uparse(resInfo.unit)
end
elseif resInfo.kind == RESULT_DER_X
id = resInfo.id[end]
segment = id.segment
if segment < length(result.t)
return missing
end
ibeg = id.index
iend = ibeg + prod(id.size) - 1
value = ibeg == iend ? result.der_x[segment][end][ibeg] : result.der_x[segment][end][ibeg:iend]
if unit && resInfo.unit != ""
value *= uparse(resInfo.unit)
end
elseif resInfo.kind == RESULT_W_INVARIANT
id = resInfo.id[end]
value = result.w_invariant[end][end][id.index]
if !unit
value = stripUnit(value)
end
elseif resInfo.kind == RESULT_W_SEGMENTED
id = resInfo.id[end]
segment = id.segment
if segment < length(result.t)
return missing
end
value = result.w_segmented[segment][end][id.index]
if unit && resInfo.unit != "" && eltype(value) <: AbstractFloat
value *= uparse(resInfo.unit)
end
else
error("Bug in getLastValue(...), name = $name, resInfo.kind = $(resInfo.kind).")
end
else
# Parameter stored in m.evaluatedParameters
value = get_value(m.evaluatedParameters, name)
if ismissing(value)
@info "getLastValue: $name is not known and is ignored."
return nothing;
end
end
return value
end
get_lastValue(m, name; unit=true) = getLastValue(m, name, unit=unit)
"""
get_extraSimulateKeywordArgumentsDict(instantiateModel)
Return the dictionary, in which extra keyword arguments of the last
`simulate!(instantiatedModel,...)` call are stored.
"""
get_extraSimulateKeywordArgumentsDict(m::InstantiatedModel) = m.options.extra_kwargs
"""
terminateEventIteration!(instantiatedModel)
Return true, if event iteration shall be terminated and simulation started.
Return false, if event iteration shall be continued. Reasons for continuing are:
1. pre != nextPre
2. positive(..), negative(..), change(..), edge(..) trigger a new iteration.
3. triggerEventAfterInitial = true
Note
- isInitial:
When simulation shall be started, isInitial = true. When neither (1) nor (2) hold, isInitial = false
and isInitial remains false for the rest of the simulation.
- firstInitialOfAllSegments:
When simulation shall be started, firstInitialOfAllSegments = true. After the first iteration,
this flag is set to false. This flag can be used to initialize devices (e.g. renderer), that should be
initialized once and not several times.
- firstEventIteration:
This flag is true during the first iteration at an event.
- firstEventIterationDirectlyAfterInitial:
This flag is true during the first iteration directly at the time event after initialization
(at simulation startTime).
"""
function terminateEventIteration!(m::InstantiatedModel)::Bool
h = m.eventHandler
h.firstInitialOfAllSegments = false
h.firstEventIteration = false
h.firstEventIterationDirectlyAfterInitial = false
# pre-iteration
pre_iteration = false
for i = 1:length(m.pre)
if m.pre[i] != m.nextPre[i]
if m.options.logEvents
println(" ", m.pre_names[i], " changed from ", m.pre[i], " to ", m.nextPre[i])
end
m.pre[i] = m.nextPre[i]
pre_iteration = true
end
end
if pre_iteration || h.newEventIteration
h.newEventIteration = false
return false # continue event iteration
end
if h.restart == Terminate || h.restart == FullRestart
h.initial = false
return true
elseif h.triggerEventDirectlyAfterInitial
h.triggerEventDirectlyAfterInitial = false
if h.initial
h.firstEventIterationDirectlyAfterInitial = true
end
h.initial = false
return false # continue event iteration
end
h.initial = false
return true
end
function eventIteration!(m::InstantiatedModel, x, t_event)::Nothing
eh = m.eventHandler
# Initialize event iteration
initEventIteration!(eh, t_event)
# Perform event iteration
iter_max = 20
iter = 0
success = false
eh.event = true
while !success && iter <= iter_max
iter += 1
#Base.invokelatest(m.getDerivatives!, m.der_x, x, m, t_event)
invokelatest_getDerivatives_without_der_x!(x, m, t_event)
eh.firstInitialOfAllSegments = false
success = terminateEventIteration!(m)
if eh.firstEventIterationDirectlyAfterInitial
iter = 0 # reset iteration counter, since new event
if m.options.logEvents
println("\n Time event at time = ", eh.time, " s")
end
eh.nTimeEvents += 1
eh.nextEventTime = m.options.stopTime
end
end
eh.event = false
if !success
error("Maximum number of event iterations (= $iter_max) reached")
end
return nothing
end
"""
get_xNames(instantiatedModel)
Return the names of the elements of the x-vector in a Vector{String}.
"""
get_xNames(m::InstantiatedModel) = Modia.get_xNames(m.equationInfo)
"""
isInitial(instantiatedModel)
Return true, if **initialization phase** of simulation
(of the current segment of a segmented simulation).
"""
isInitial(m::InstantiatedModel) = m.eventHandler.initial
initial( m::InstantiatedModel) = m.eventHandler.initial
"""
isFirstInitialOfAllSegments(instantiatedModel)
Return true, if **initialization phase** of simulation of the **first segment**
of a segmented simulation.
"""
isFirstInitialOfAllSegments(m::InstantiatedModel) = m.eventHandler.firstInitialOfAllSegments
"""
isTerminal(instantiatedModel)
Return true, if **terminal phase** of simulation
(of the current segment of a segmented simulation).
"""
isTerminal(m::InstantiatedModel) = m.eventHandler.terminal
terminal( m::InstantiatedModel) = m.eventHandler.terminal
"""
isTerminalOfAllSegments(instantiatedModel)
Return true, if **terminal phase** of simulation of the **last segment**
of a segmented simulation.
"""
isTerminalOfAllSegments(m::InstantiatedModel) = m.eventHandler.terminalOfAllSegments
"""
isEvent(instantiatedModel)
Return true, if **event phase** of simulation (including initialization).
"""
isEvent(m::InstantiatedModel) = m.eventHandler.event
"""
isFirstEventIteration(instantiatedModel)
Return true, if **event phase** of simulation (including initialization) and
during the first iteration of the event iteration.
"""
isFirstEventIteration(m::InstantiatedModel) = m.eventHandler.firstEventIteration
"""
isFirstEventIterationDirectlyAfterInitial(instantiatedModel)
Return true, if first iteration directly after initialization where initial=true
(so at the startTime of the simulation).
"""
isFirstEventIterationDirectlyAfterInitial(m::InstantiatedModel) = m.eventHandler.firstEventIterationDirectlyAfterInitial
"""
isFullRestart(instantiatedModel)
Return true, if **FullRestart event** of a segmented simulation.
"""
isFullRestart(m::InstantiatedModel) = m.eventHandler.fullRestart
"""
isAfterSimulationStart(instantiatedModel)
Return true, if **after start of simulation** (returns false during initialization).
"""
isAfterSimulationStart(m::InstantiatedModel) = m.eventHandler.afterSimulationStart
"""
isZeroCrossing(instantiatedModel)
Return true, if **event indicators (zero crossings) shall be computed**.
"""
isZeroCrossing(m::InstantiatedModel) = m.eventHandler.crossing
"""
storeResults(instantiatedModel)
Return true, if **results shall be stored**.
"""
storeResults(m::InstantiatedModel) = m.storeResult
"""
setNextEvent!(instantiatedModel, nextEventTime)
At an event instant, set the next time event to `nextEventTime`.
"""
setNextEvent!(m::InstantiatedModel{FloatType,TimeType}, nextEventTime) where {FloatType,TimeType} =
setNextEvent!(m.eventHandler, convert(TimeType,nextEventTime))
function setFullRestartEvent!(m::InstantiatedModel)
m.eventHandler.restart = FullRestart
return nothing
end
"""
tCurrent = getTime(instantiatedModel)
Return current simulation time.