-
-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathsystem.jl
More file actions
1790 lines (1591 loc) · 64.2 KB
/
Copy pathsystem.jl
File metadata and controls
1790 lines (1591 loc) · 64.2 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
struct Schedule
var_sccs::Vector{Vector{Int}}
"""
Mapping of `Differential`s of variables to corresponding derivative expressions.
"""
dummy_sub::Dict{SymbolicT, SymbolicT}
end
function Base.copy(sched::Schedule)
return Schedule(copy(sched.var_sccs), copy(sched.dummy_sub))
end
const MetadataT = Base.ImmutableDict{DataType, Any}
abstract type MutableCacheKey end
const MutableCacheT = Dict{DataType, Any}
"""
$TYPEDEF
Utility metadata key for adding miscellaneous/one-off metadata to systems.
"""
abstract type MiscSystemData end
"""
$TYPEDEF
Metadata key used to mark a system as incompatible with symbolic automatic differentiation.
When set on a system via `setmetadata(sys, SymbolicADDisallowed, reason)`, any attempt to
perform symbolic AD on the equations of that system (e.g. via `calculate_jacobian`,
`calculate_tgrad`, `linearize_symbolic`, or during structural simplification) will throw
an error. The value associated with this key should be a descriptive `String` explaining
why symbolic AD is unsupported, or `true` if no explanation is available.
See also: [`check_symbolic_ad_allowed`](@ref).
"""
abstract type SymbolicADDisallowed end
"""
check_symbolic_ad_allowed(sys::AbstractSystem)
Check whether `sys` supports symbolic automatic differentiation. Throws an `ArgumentError`
if the system has been marked with [`SymbolicADDisallowed`](@ref).
"""
function check_symbolic_ad_allowed(sys::AbstractSystem)
return if SymbolicUtils.hasmetadata(sys, SymbolicADDisallowed)
reason = SymbolicUtils.getmetadata(sys, SymbolicADDisallowed, nothing)
msg = "System $(nameof(sys)) does not support symbolic automatic differentiation."
if reason isa AbstractString && !isempty(reason)
msg *= " $reason"
end
throw(ArgumentError(msg))
end
end
__new_irstructure() = IRStructure{VartypeT}()
__new_irstructure_tlv() = TaskLocalValue{IRStructure{VartypeT}}(__new_irstructure)
const IRStructureTLVT = typeof(__new_irstructure_tlv())
__new_mutable_cache() = MutableCacheT()
__new_mutable_cache_tlv() = TaskLocalValue{MutableCacheT}(__new_mutable_cache)
const MutableCacheTLVT = typeof(__new_mutable_cache_tlv())
"""
$(TYPEDEF)
A symbolic representation of a numerical system to be solved. This is a recursive
tree-like data structure - each system can contain additional subsystems. As such,
it implements the `AbstractTrees.jl` interface to enable exploring the hierarchical
structure.
# Fields
$(TYPEDFIELDS)
"""
struct System <: IntermediateDeprecationSystem
"""
$INTERNAL_FIELD_WARNING
A unique integer tag for the system.
"""
tag::UInt
"""
The equations of the system.
"""
eqs::Vector{Equation}
# nothing - no noise
# vector - diagonal noise
# matrix - generic form
# column matrix - scalar noise
"""
The noise terms for each equation of the system. This field is only used for flattened
systems. To represent noise in a hierarchical system, use brownians. In a system with
`N` equations and `K` independent brownian variables, this should be an `N x K`
matrix. In the special case where `N == K` and each equation has independent noise,
this noise matrix is diagonal. Diagonal noise can be specified by providing an `N`
length vector. If this field is `nothing`, the system does not have noise.
"""
noise_eqs::Union{Nothing, Vector{SymbolicT}, Matrix{SymbolicT}}
"""
Jumps associated with the system. Each jump can be a `VariableRateJump`,
`ConstantRateJump` or `MassActionJump`. See `JumpProcesses.jl` for more information.
`MassActionJump`s must use `scale_rates = false` (pre-scaled rate expressions); see
[`SymbolicMassActionJump`](@ref).
"""
jumps::Vector{JumpType}
"""
The constraints of the system. This can be used to represent the constraints in an
optimal-control problem or boundary-value differential equation, or the constraints
in a constrained optimization.
"""
constraints::Vector{Union{Equation, Inequality}}
"""
The costs of the system. This can be the cost in an optimal-control problem, or the
loss of an optimization problem. Scalar loss values must also be provided as a single-
element vector.
"""
costs::Vector{SymbolicT}
"""
A function which combines costs into a scalar value. This should take two arguments,
the `costs` of this system and the consolidated costs of all subsystems in the order
they are present in the `systems` field. It should return a scalar cost that combines
all of the individual values. This defaults to a function that simply sums all cost
values.
"""
consolidate::Any
"""
The variables being solved for by this system. For example, in a differential equation
system, this contains the dependent variables.
"""
unknowns::Vector{SymbolicT}
"""
The parameters of the system. Parameters can either be variables that parameterize the
problem being solved for (e.g. the spring constant of a mass-spring system) or
additional unknowns not part of the main dynamics of the system (e.g. discrete/clocked
variables in a hybrid ODE).
"""
ps::Vector{SymbolicT}
"""
The brownian variables of the system, created via `@brownians`. Each brownian variable
represents an independent noise. A system with brownians cannot be simulated directly.
It needs to be compiled using `mtkcompile` into `noise_eqs`.
"""
brownians::Vector{SymbolicT}
"""
The poissonian variables of the system, created via `@poissonians`. Each poissonian
variable represents an independent Poisson counting process with an associated rate.
A system with poissonians cannot be simulated directly. It needs to be compiled using
`mtkcompile` which converts poissonians into jump equations.
"""
poissonians::Vector{SymbolicT}
"""
The independent variable for a time-dependent system, or `nothing` for a time-independent
system.
"""
iv::Union{Nothing, SymbolicT}
"""
Equations that compute variables of a system that have been eliminated from the set of
unknowns by `mtkcompile`. More generally, this contains all variables that can be
computed from the unknowns and parameters and do not need to be solved for. Such
variables are termed as "observables". Each equation must be of the form
`observable ~ expression` and observables cannot appear on the LHS of multiple
equations. Equations must be sorted such that every observable appears on
the left hand side of an equation before it appears on the right hand side of any other
equation.
"""
observed::Vector{Equation}
"""
$INTERNAL_FIELD_WARNING
A mapping from the name of a variable to the actual symbolic variable in the system.
This is used to enable `getproperty` syntax to access variables of a system.
"""
var_to_name::Dict{Symbol, SymbolicT}
"""
The name of the system.
"""
name::Symbol
"""
An optional description for the system.
"""
description::String
"""
Binding relations for variables/parameters. The bound variable (key) is completely
determined by the binding (value). Providing an initial condition for a bound variable
is an error. Bindings for variables (ones created via `@variables` and `@discretes`)
are treated as initial conditions.
"""
bindings::ROSymmapT
"""
Initial conditions for variables (unknowns/observables/parameters) which can be
changed/overridden. When constructing a numerical problem from the system.
"""
initial_conditions::SymmapT
"""
Guess values for variables of a system that are solved for during initialization.
"""
guesses::SymmapT
"""
A list of subsystems of this system. Used for hierarchically building models.
"""
systems::Vector{System}
"""
Equations that must be satisfied during initialization of the numerical problem created
from this system. For time-dependent systems, these equations are not valid after the
initial time.
"""
initialization_eqs::Vector{Equation}
"""
Symbolic representation of continuous events in a dynamical system. See
[`SymbolicContinuousCallback`](@ref).
"""
continuous_events::Vector{SymbolicContinuousCallback}
"""
Symbolic representation of discrete events in a dynamica system. See
[`SymbolicDiscreteCallback`](@ref).
"""
discrete_events::Vector{SymbolicDiscreteCallback}
"""
$INTERNAL_FIELD_WARNING
If this system is a connector, the type of connector it is.
"""
connector_type::Any
"""
A map from expressions that must be through throughout the solution process to an
associated error message. By default these assertions cause the generated code to
output `NaN`s if violated, but can be made to error using `debug_system`.
"""
assertions::Dict{SymbolicT, String}
"""
The metadata associated with this system, as a `Base.ImmutableDict`. This follows
the same interface as SymbolicUtils.jl. Metadata can be queried and updated using
`SymbolicUtils.getmetadata` and `SymbolicUtils.setmetadata` respectively.
"""
metadata::MetadataT
"""
$INTERNAL_FIELD_WARNING
Metadata added by the `@mtkmodel` macro.
"""
gui_metadata::Any # ?
"""
Whether the system contains delay terms. This is inferred from the equations, but
can also be provided explicitly.
"""
is_dde::Bool
"""
Extra time points for the integrator to stop at. These can be numeric values,
or expressions of parameters and time.
"""
tstops::Vector{Any}
"""
$INTERNAL_FIELD_WARNING
The list of input variables of the system.
"""
inputs::OrderedSet{SymbolicT}
"""
$INTERNAL_FIELD_WARNING
The list of output variables of the system.
"""
outputs::OrderedSet{SymbolicT}
"""
The `TearingState` of the system post-simplification with `mtkcompile`.
"""
tearing_state::Any
"""
Whether the system namespaces variables accessed via `getproperty`. `complete`d systems
do not namespace, but this flag can be toggled independently of `complete` using
`toggle_namespacing`.
"""
namespacing::Bool
"""
Whether the system is marked as "complete". Completed systems cannot be used as
subsystems.
"""
complete::Bool
"""
$INTERNAL_FIELD_WARNING
For systems simplified or completed with `split = true` (the default) this contains an
`IndexCache` which aids in symbolic indexing. If this field is `nothing`, the system is
either not completed, or completed with `split = false`.
"""
index_cache::Union{Nothing, IndexCache}
"""
$INTERNAL_FIELD_WARNING
Contains the dependency graph of bound parameters to avoid excessive duplicated work
during code generation.
"""
parameter_bindings_graph::Union{Nothing, ParameterBindingsGraph}
"""
$INTERNAL_FIELD_WARNING
Connections that should be ignored because they were removed by an analysis point
transformation. The first element of the tuple contains all such "standard" connections
(ones between connector systems) and the second contains all such causal variable
connections.
"""
ignored_connections::Union{Nothing, Vector{Connection}}
"""
`SymbolicUtils.Code.Assignment`s to prepend to all code generated from this system.
"""
preface::Any
"""
After simplification with `mtkcompile`, this field contains the unsimplified system
with the hierarchical structure. There may be multiple levels of `parent`s. The root
parent is used for accessing variables via `getproperty` syntax.
"""
parent::Union{Nothing, System}
"""
A custom initialization system to use if no initial conditions are provided for the
unknowns or observables of this system.
"""
initializesystem::Union{Nothing, System}
"""
Whether the current system is an initialization system.
"""
is_initializesystem::Bool
is_discrete::Bool
"""
State priorities for variables. Used in structural simplification algorithms.
"""
state_priorities::AtomicMapT{Int}
"""
Variables marked as irreducible for simplification.
"""
irreducibles::AtomicSetT
"""
Expressions which may be zero and should be given special consideration during simplification.
"""
maybe_zeros::AtomicSetT
"""
$INTERNAL_FIELD_WARNING
The `IRStructure` used for efficient symbolic manipulation, stored in a `TaskLocalValue`.
"""
irstructure_tlv::TaskLocalValue{IRStructure{VartypeT}}
"""
$INTERNAL_FIELD_WARNING
Whether the system has been simplified by `mtkcompile`.
"""
isscheduled::Bool
"""
$INTERNAL_FIELD_WARNING
The `Schedule` containing additional information about the simplified system.
"""
schedule::Union{Schedule, Nothing}
function System(
tag, eqs, noise_eqs, jumps, constraints, costs, consolidate, unknowns, ps,
brownians, poissonians, iv, observed, var_to_name, name, description, bindings,
initial_conditions, guesses, systems, initialization_eqs, continuous_events,
discrete_events, connector_type, assertions = Dict{SymbolicT, String}(),
metadata = MetadataT(), gui_metadata = nothing, is_dde = false, tstops = [],
inputs = Set{SymbolicT}(), outputs = Set{SymbolicT}(),
tearing_state = nothing, namespacing = true,
complete = false, index_cache = nothing, parameter_bindings_graph = nothing,
ignored_connections = nothing,
preface = nothing, parent = nothing, initializesystem = nothing,
is_initializesystem = false, is_discrete = false, state_priorities = AtomicMapT{Int}(),
irreducibles = AtomicSetT(), maybe_zeros = AtomicSetT(),
irstructure_tlv = __new_irstructure_tlv(), isscheduled = false, schedule = nothing;
checks::Union{Bool, Int} = true
)
if is_initializesystem && iv !== nothing
throw(
ArgumentError(
"""
Expected initialization system to be time-independent. Found independent
variable $iv.
"""
)
)
end
@assert iv === nothing || symtype(iv) === Real
if (checks isa Bool && checks === true || checks isa Int && (checks & CheckComponents) > 0) && iv !== nothing
check_independent_variables((iv,))
check_variables(unknowns, iv)
check_parameters(ps, iv)
check_equations(eqs, iv)
Neq = length(eqs)
if noise_eqs isa Matrix{SymbolicT}
N1 = size(noise_eqs, 1)
elseif noise_eqs isa Vector{SymbolicT}
N1 = length(noise_eqs)
elseif noise_eqs === nothing
N1 = Neq
else
error()
end
N1 == Neq || throw(IllFormedNoiseEquationsError(N1, Neq))
if noise_eqs !== nothing && !isempty(brownians)
throw(
ArgumentError(
"A system cannot have both `noise_eqs` and `brownians` specified. " *
"Use either `noise_eqs` (a matrix of noise coefficients) or " *
"`brownians` (symbolic brownian variables in equations), but not both."
)
)
end
check_equations(equations(continuous_events), iv)
check_subsystems(systems)
end
if checks == true || (checks & CheckUnits) > 0
u = __get_unit_type(unknowns, ps, iv)
if noise_eqs === nothing
check_units(u, eqs)
else
check_units(u, eqs, noise_eqs)
end
if iv !== nothing
check_units(u, jumps, iv)
end
isempty(constraints) || check_units(u, constraints)
end
return new(
tag, eqs, noise_eqs, jumps, constraints, costs,
consolidate, unknowns, ps, brownians, poissonians, iv,
observed, var_to_name, name, description, bindings, initial_conditions,
guesses, systems, initialization_eqs, continuous_events, discrete_events,
connector_type, assertions, metadata, gui_metadata, is_dde,
tstops, inputs, outputs, tearing_state, namespacing,
complete, index_cache, parameter_bindings_graph, ignored_connections,
preface, parent, initializesystem, is_initializesystem, is_discrete,
state_priorities, irreducibles, maybe_zeros, irstructure_tlv,
isscheduled, schedule
)
end
end
_sum_costs(costs::Vector{SymbolicT}) = SU.add_worker(VartypeT, costs)
_sum_costs(costs::Vector{Num}) = SU.add_worker(VartypeT, costs)
# `reduce` instead of `sum` because the rrule for `sum` doesn't
# handle the `init` kwarg.
_sum_costs(costs::Vector) = reduce(+, costs; init = 0.0)
function default_consolidate(costs, subcosts)
return _sum_costs(costs) + _sum_costs(subcosts)
end
unwrap_vars(x) = unwrap_vars(collect(x))
unwrap_vars(vars::AbstractArray{SymbolicT}) = vars
function unwrap_vars(vars::AbstractArray)
result = similar(vars, SymbolicT)
for i in eachindex(vars)
result[i] = SU.Const{VartypeT}(vars[i])
end
return result
end
defsdict(x::SymmapT) = x
defsdict(x::Vector{Any}) = isempty(x) ? SymmapT() : defsdict(Dict(x))
function defsdict(x::Union{AbstractDict, AbstractArray{<:Pair}})
result = SymmapT()
for (k, v) in x
result[unwrap(k)] = SU.Const{VartypeT}(v)
end
return result
end
as_atomicmap(::Type{T}, x::AtomicMapT{T}) where {T} = x
function as_atomicmap(::Type{T}, x::Union{AbstractDict, AbstractArray{<:Pair}}) where {T}
result = AtomicMapT{T}()
for (k, v) in x
result[unwrap(k)] = convert(T, v)
end
return result
end
parse_atomicset(x::AtomicSetT) = x
function parse_atomicset(vars)
result = AtomicSetT()
for var in vars
push!(result, unwrap(var))
end
return result
end
function __get_new_tag()
return Threads.atomic_add!(SYSTEM_COUNT, UInt(1))
end
"""
$(TYPEDSIGNATURES)
Construct a system using the given equations `eqs`, independent variable `iv` (`nothing`)
for time-independent systems, unknowns `dvs`, parameters `ps` and brownian variables
`brownians`.
## Keyword Arguments
- `discover_from_metadata`: Whether to parse metadata of unknowns and parameters of the
system to obtain bindings, initial conditions and/or guesses.
- `checks`: Whether to perform sanity checks on the passed values.
All other keyword arguments are named identically to the corresponding fields in
[`System`](@ref).
"""
function System(
eqs::Vector{Equation}, iv, dvs, ps, brownians = SymbolicT[];
poissonians = SymbolicT[],
constraints = Union{Equation, Inequality}[], noise_eqs = nothing, jumps = JumpType[],
costs = SymbolicT[], consolidate = default_consolidate,
# `@nospecialize` is only supported on the first 32 arguments. Keep this early.
@nospecialize(preface = nothing), @nospecialize(tstops = []),
observed = Equation[], bindings = SymmapT(), initial_conditions = SymmapT(),
guesses = SymmapT(), systems = System[], initialization_eqs = Equation[],
continuous_events = SymbolicContinuousCallback[], discrete_events = SymbolicDiscreteCallback[],
connector_type = nothing, assertions = Dict{SymbolicT, String}(),
metadata = MetadataT(), gui_metadata = nothing,
is_dde = nothing, inputs = OrderedSet{SymbolicT}(),
outputs = OrderedSet{SymbolicT}(), tearing_state = nothing,
ignored_connections = nothing, parent = nothing, state_priorities = AtomicMapT{Int}(),
irreducibles = AtomicSetT(), maybe_zeros = AtomicSetT(),
description = "", name = nothing, discover_from_metadata = true,
initializesystem = nothing, is_initializesystem = false, is_discrete = false,
irstructure = IRStructure{VartypeT}(), irstructure_tlv = nothing,
checks = true, __legacy_defaults__ = nothing
)
name === nothing && throw(NoNameError())
if __legacy_defaults__ !== nothing
Base.depwarn(
"""
The `@mtkmodel` macro is deprecated. Please use the functional form with \
`@components` instead.
""", :mtkmodel
)
initial_conditions = __legacy_defaults__
end
if !(systems isa Vector{System})
systems = Vector{System}(systems)
end
if !(eqs isa Vector{Equation})
eqs = Equation[eqs]
end
eqs = eqs::Vector{Equation}
iv = unwrap(iv)
ps = vec(unwrap_vars(ps))
dvs = vec(unwrap_vars(dvs))
if iv !== nothing
filter!(!Base.Fix2(_is_unknown_delay_or_evalat, iv), dvs)
end
brownians = unwrap_vars(brownians)
poissonians = unwrap_vars(poissonians)
if noise_eqs !== nothing
noise_eqs = unwrap_vars(noise_eqs)
end
costs = vec(unwrap_vars(costs))
if !(inputs isa OrderedSet{SymbolicT})
inputs = unwrap.(inputs)
inputs = OrderedSet{SymbolicT}(inputs)
end
if !(outputs isa OrderedSet{SymbolicT})
outputs = unwrap.(outputs)
outputs = OrderedSet{SymbolicT}(outputs)
end
for subsys in systems
for var in get_inputs(subsys)
push!(inputs, renamespace(subsys, var))
end
for var in get_outputs(subsys)
push!(outputs, renamespace(subsys, var))
end
end
var_to_name = Dict{Symbol, SymbolicT}()
bindings = defsdict(bindings)
initial_conditions = defsdict(initial_conditions)
guesses = defsdict(guesses)
all_dvs = as_atomic_array_set(dvs)
if iv === nothing
for k in keys(bindings)
k in all_dvs || continue
throw(
ArgumentError(
"""
Bindings for variables are enforced during initialization. Since \
time-independent systems only perform parameter initialization, \
bindings for variables in such systems are invalid. $k was found to have \
a binding in the system $name.
"""
)
)
end
end
let initial_conditions = discover_from_metadata ? initial_conditions : SymmapT(),
bindings = discover_from_metadata ? bindings : SymmapT(),
guesses = discover_from_metadata ? guesses : SymmapT(),
inputs = discover_from_metadata ? inputs : OrderedSet{SymbolicT}(),
outputs = discover_from_metadata ? outputs : OrderedSet{SymbolicT}()
process_variables!(var_to_name, initial_conditions, bindings, guesses, dvs)
process_variables!(var_to_name, initial_conditions, bindings, guesses, ps)
buffer = SymbolicT[]
for eq in observed
push!(buffer, eq.lhs)
if !(iv isa SymbolicT && _is_unknown_delay_or_evalat(eq.rhs, iv)) &&
!iscalledparameter(eq.rhs)
push!(buffer, eq.rhs)
end
end
process_variables!(var_to_name, initial_conditions, bindings, guesses, buffer)
for var in dvs
if isinput(var)
push!(inputs, var)
elseif isoutput(var)
push!(outputs, var)
end
end
end
state_priorities = as_atomicmap(Int, state_priorities)
irreducibles = parse_atomicset(irreducibles)
if discover_from_metadata
collect_metadata!(VariableStatePriority, state_priorities, dvs)
collect_metadata!(VariableIrreducible, irreducibles, dvs)
end
maybe_zeros = as_atomic_array_set(maybe_zeros)
filter!(!(Base.Fix1(===, COMMON_NOTHING) ∘ last), initial_conditions)
filter!(!(Base.Fix1(===, COMMON_NOTHING) ∘ last), bindings)
filter!(!(Base.Fix1(===, COMMON_NOTHING) ∘ last), guesses)
if iv === nothing
move_variable_bindings_to_ics!(all_dvs, initial_conditions, bindings)
end
check_bindings(ps, bindings)
bindings = ROSymmapT(bindings)
if !allunique(map(nameof, systems))
nonunique_subsystems(systems)
end
continuous_events,
discrete_events = create_symbolic_events(
continuous_events, discrete_events
)
if iv === nothing && (!isempty(continuous_events) || !isempty(discrete_events))
throw(EventsInTimeIndependentSystemError(continuous_events, discrete_events))
end
if is_dde === nothing
is_dde = _check_if_dde(eqs, iv, systems)
end
_assertions = Dict{SymbolicT, String}()
for (k, v) in assertions
_assertions[unwrap(k)::SymbolicT] = v
end
assertions = _assertions
if isempty(metadata)
metadata = MetadataT()
elseif metadata isa MetadataT
metadata = metadata
else
meta = MetadataT()
for kvp in metadata
meta = Base.ImmutableDict(meta, kvp)
end
metadata = meta
end
metadata = refreshed_metadata(metadata)
jumps = Vector{JumpType}(jumps)
# MTK requires symbolic MassActionJumps to have pre-scaled rate expressions.
# JumpProcesses must not re-apply factorial scaling on parameter updates.
for j in jumps
if j isa MassActionJump && j.rescale_rates_on_update
throw(
ArgumentError(
"MassActionJump with rescale_rates_on_update = true is not supported " *
"in Systems with jumps or JumpSystems. Rate expressions must be pre-scaled (e.g. " *
"k/factorial(n) for n-th order reactions). Use SymbolicMassActionJump " *
"or pass scale_rates = false when constructing the MassActionJump."
)
)
end
end
if irstructure_tlv === nothing
irstructure_tlv = __new_irstructure_tlv()
if !iszero(length(irstructure))
irstructure_tlv[] = irstructure
end
end
return System(
__get_new_tag(), eqs, noise_eqs, jumps, constraints,
costs, consolidate, dvs, ps, brownians, poissonians, iv, observed,
var_to_name, name, description, bindings, initial_conditions, guesses, systems, initialization_eqs,
continuous_events, discrete_events, connector_type, assertions, metadata, gui_metadata, is_dde,
tstops, inputs, outputs, tearing_state, true, false,
nothing, nothing, ignored_connections, preface, parent,
initializesystem, is_initializesystem, is_discrete, state_priorities, irreducibles,
maybe_zeros, irstructure_tlv; checks
)
end
function _is_unknown_delay_or_evalat(x::SymbolicT, iv::SymbolicT)
x = split_indexed_var(x)[1]
return Moshi.Match.@match x begin
BSImpl.Term(; f, args) && if f isa SymbolicT end => begin
!isequal(args[1], iv) && Moshi.Match.@match args[1] begin
BSImpl.Term(; f = f2) => !(f2 isa SymbolicT) || SU.is_function_symbolic(f2)
_ => true
end
end
BSImpl.Term(; f, args) && if f === real || f === imag end => begin
_is_unknown_delay_or_evalat(args[1], iv)
end
BSImpl.Term(; f, args) && if f isa Differential end => begin
_is_unknown_delay_or_evalat(args[1], iv)
end
_ => false
end
end
@noinline function nonunique_subsystems(systems)
sysnames = nameof.(systems)
unique_sysnames = Set(sysnames)
throw(NonUniqueSubsystemsError(sysnames, unique_sysnames))
end
SymbolicIndexingInterface.getname(x::AbstractSystem) = nameof(x)
"""
$(TYPEDSIGNATURES)
Create a time-independent [`System`](@ref) with the given equations `eqs`, unknowns `dvs`
and parameters `ps`.
"""
function System(eqs::Vector{Equation}, dvs, ps; kwargs...)
return System(eqs, nothing, dvs, ps; kwargs...)
end
"""
$(TYPEDSIGNATURES)
Create a time-dependent system with the given equations `eqs` and independent variable `iv`.
Discover variables, parameters and brownians in the system by parsing the equations and
other symbolic expressions passed to the system.
"""
function System(eqs::Vector{Equation}, iv; kwargs...)
iv === nothing && return System(eqs; kwargs...)
diffvars = OrderedSet{SymbolicT}()
othervars = OrderedSet{SymbolicT}()
ps = OrderedSet{SymbolicT}()
diffeqs = Equation[]
othereqs = Equation[]
iv = unwrap(iv)
for eq in eqs
collect_vars!(othervars, ps, eq, iv)
if iscall(eq.lhs) && operation(eq.lhs) isa Differential
var, _ = var_from_nested_derivative(eq.lhs)
if var in diffvars
throw(
ArgumentError(
"""
The differential variable $var is not unique in the system of \
equations.
"""
)
)
end
# this check ensures var is correctly scoped, since `collect_vars!` won't pick
# it up if it belongs to an ancestor system.
if var in othervars
push!(diffvars, var)
end
push!(diffeqs, eq)
else
push!(othereqs, eq)
end
end
allunknowns = union(diffvars, othervars)
eqs = [diffeqs; othereqs]
brownians = Set{SymbolicT}()
poissonians = Set{SymbolicT}()
for x in allunknowns
x = unwrap(x)
if getvariabletype(x) == BROWNIAN
push!(brownians, x)
elseif getvariabletype(x) == POISSONIAN
push!(poissonians, x)
end
end
setdiff!(allunknowns, brownians)
setdiff!(allunknowns, poissonians)
# Extract variables and parameters from poissonian rate expressions
for p in poissonians
rate = getpoissonianrate(p)
if rate !== nothing
collect_vars!(allunknowns, ps, rate, iv)
end
end
cstrs = Vector{Union{Equation, Inequality}}(get(kwargs, :constraints, []))
_cstrunknowns, cstrps = process_constraint_system(cstrs, allunknowns, ps, iv)
cstrunknowns = empty(_cstrunknowns)
for var in _cstrunknowns
op, inner = Moshi.Match.@match var begin
BSImpl.Term(; f, args) && if f isa Differential end => (f, args[1])
_ => begin
push!(cstrunknowns, var)
continue
end
end
Moshi.Match.@match inner begin
BSImpl.Term(; f, args) && if f isa SymbolicT && SU.isconst(args[1]) end => begin
push!(cstrunknowns, op(f(iv)))
end
_ => push!(cstrunknowns, var)
end
end
union!(allunknowns, cstrunknowns)
union!(ps, cstrps)
for ssys in get(kwargs, :systems, System[])
collect_scoped_vars!(allunknowns, ps, ssys, iv)
end
costs = get(kwargs, :costs, nothing)
if costs !== nothing
costunknowns, costps = process_costs(costs, allunknowns, ps, iv)
union!(allunknowns, costunknowns)
union!(ps, costps)
end
for v in allunknowns
isdelay(v, iv) || continue
collect_vars!(allunknowns, ps, arguments(v)[1], iv)
end
for pair in get(kwargs, :initial_conditions, ())
collect_vars!(allunknowns, ps, pair, iv)
end
for pair in get(kwargs, :bindings, ())
collect_vars!(allunknowns, ps, pair, iv)
end
new_ps = gather_array_params(ps)
noiseeqs = get(kwargs, :noise_eqs, nothing)
if noiseeqs !== nothing
# validate noise equations
noisedvs = OrderedSet{SymbolicT}()
noiseps = OrderedSet{SymbolicT}()
collect_vars!(noisedvs, noiseps, noiseeqs, iv)
for dv in noisedvs
dv ∈ allunknowns ||
throw(ArgumentError(lazy"Variable $dv in noise equations is not an unknown of the system."))
end
end
return System(
eqs, iv, collect(allunknowns), collect(new_ps), collect(brownians);
poissonians = collect(poissonians), kwargs...
)
end
"""
$(TYPEDSIGNATURES)
Create a time-independent system with the given equations `eqs`. Discover variables and
parameters in the system by parsing the equations and other symbolic expressions passed to
the system.
"""
function System(eqs::Vector{Equation}; kwargs...)
eqs = collect(eqs)
allunknowns = OrderedSet{SymbolicT}()
ps = OrderedSet{SymbolicT}()
for eq in eqs
collect_vars!(allunknowns, ps, eq, nothing)
end
for ssys in get(kwargs, :systems, System[])
collect_scoped_vars!(allunknowns, ps, ssys, nothing)
end
costs = get(kwargs, :costs, [])
for val in costs
collect_vars!(allunknowns, ps, val, nothing)
end
cstrs = Vector{Union{Equation, Inequality}}(get(kwargs, :constraints, []))
for eq in cstrs
collect_vars!(allunknowns, ps, eq, nothing)
end
for pair in get(kwargs, :initial_conditions, ())
collect_vars!(allunknowns, ps, pair, nothing)
end
for pair in get(kwargs, :bindings, ())
collect_vars!(allunknowns, ps, pair, nothing)
end
new_ps = gather_array_params(ps)
return System(eqs, nothing, collect(allunknowns), collect(new_ps); kwargs...)
end
"""
$(TYPEDSIGNATURES)
Create a `System` with a single equation `eq`.
"""
System(eq::Equation, args...; kwargs...) = System([eq], args...; kwargs...)
function gather_array_params(ps::AbstractSet{SymbolicT})
new_ps = OrderedSet{SymbolicT}()
for p in ps
arr, isarr = split_indexed_var(p)
sh = SU.shape(arr)
if isarr
if !(sh isa SU.Unknown) && all(in(ps) ∘ Base.Fix1(getindex, arr), SU.stable_eachindex(arr))
push!(new_ps, arr)
else
push!(new_ps, p)
end
else
if sh isa SU.ShapeVecT && !isempty(sh)
for i in SU.stable_eachindex(arr)
delete!(new_ps, arr[i])
end
end
push!(new_ps, p)
end
end
return new_ps
end
struct ConstraintValidator
innervars::Set{SymbolicT}
end
ConstraintValidator() = ConstraintValidator(Set{SymbolicT}())
function (cv::ConstraintValidator)(x::SymbolicT)
Moshi.Match.@match x begin
BSImpl.Term(; f, args) && if f isa SymbolicT && !SU.is_function_symbolic(f) end => begin
empty!(cv.innervars)
SU.search_variables!(cv.innervars, args[1])
for var in cv.innervars
Moshi.Match.@match var begin
BSImpl.Term() => throw(
ArgumentError(
"""
Arguments of a delayed or evaluated (via `EvalAt`) variable \
cannot be other dependent variables. Found $x which \
contains $var.
"""
)
)
_ => nothing
end
end
end
_ => nothing
end
return false
end
"""
Process variables in constraints of the (ODE) System.
"""
function process_constraint_system(
constraints::Vector{Union{Equation, Inequality}}, sts, ps, iv; validate = true,
)
isempty(constraints) && return OrderedSet{SymbolicT}(), OrderedSet{SymbolicT}()
constraintsts = OrderedSet{SymbolicT}()
constraintps = OrderedSet{SymbolicT}()
validator = ConstraintValidator()
for cons in constraints
collect_vars!(constraintsts, constraintps, cons, iv)
union!(constraintsts, collect_applied_operators(cons, Differential))
SU.query(validator, cons.lhs)
SU.query(validator, cons.rhs)
end
# Validate the states.
if validate
validate_vars_and_find_ps!(constraintsts, constraintps, sts, iv)
end
return constraintsts, constraintps
end
"""
Process the costs for the constraint system.
"""
function process_costs(costs::Vector, sts, ps, iv)
coststs = OrderedSet{SymbolicT}()
costps = OrderedSet{SymbolicT}()
for cost in costs