-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
reactionsystem.jl
2009 lines (1732 loc) · 78.8 KB
/
reactionsystem.jl
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
# Catalyst specific symbolics to support SBML
struct ParameterConstantSpecies end
struct VariableBCSpecies end
struct VariableSpecies end
Symbolics.option_to_metadata_type(::Val{:isconstantspecies}) = ParameterConstantSpecies
Symbolics.option_to_metadata_type(::Val{:isbcspecies}) = VariableBCSpecies
Symbolics.option_to_metadata_type(::Val{:isspecies}) = VariableSpecies
"""
Catalyst.isconstant(s)
Tests if the given symbolic variable corresponds to a constant species.
"""
isconstant(s::Num) = isconstant(MT.value(s))
function isconstant(s)
MT.getmetadata(s, ParameterConstantSpecies, false)
end
"""
Catalyst.isbc(s)
Tests if the given symbolic variable corresponds to a boundary condition species.
"""
isbc(s::Num) = isbc(MT.value(s))
function isbc(s)
MT.getmetadata(s, VariableBCSpecies, false)
end
"""
isspecies(s)
Tests if the given symbolic variable corresponds to a chemical species.
"""
isspecies(s::Num) = isspecies(MT.value(s))
function isspecies(s)
MT.getmetadata(s, VariableSpecies, false)
end
"""
tospecies(s)
Convert the given symbolic variable to be a species by adding the isspecies metadata.
Notes:
- Will error if passed a parameter.
"""
function tospecies(s)
MT.isparameter(s) &&
error("Parameters can not be converted to species. Please pass a variable.")
MT.setmetadata(s, VariableSpecies, true)
end
# true for species which shouldn't change from the reactions, including non-species
# variables
drop_dynamics(s) = isconstant(s) || isbc(s) || (!isspecies(s))
"""
$(TYPEDEF)
One chemical reaction.
# Fields
$(FIELDS)
# Examples
```julia
using Catalyst
t = default_t()
@parameters k[1:20]
@species A(t) B(t) C(t) D(t)
rxs = [Reaction(k[1], nothing, [A]), # 0 -> A
Reaction(k[2], [B], nothing), # B -> 0
Reaction(k[3],[A],[C]), # A -> C
Reaction(k[4], [C], [A,B]), # C -> A + B
Reaction(k[5], [C], [A], [1], [2]), # C -> A + A
Reaction(k[6], [A,B], [C]), # A + B -> C
Reaction(k[7], [B], [A], [2], [1]), # 2B -> A
Reaction(k[8], [A,B], [A,C]), # A + B -> A + C
Reaction(k[9], [A,B], [C,D]), # A + B -> C + D
Reaction(k[10], [A], [C,D], [2], [1,1]), # 2A -> C + D
Reaction(k[11], [A], [A,B], [2], [1,1]), # 2A -> A + B
Reaction(k[12], [A,B,C], [C,D], [1,3,4], [2, 3]), # A+3B+4C -> 2C + 3D
Reaction(k[13], [A,B], nothing, [3,1], nothing), # 3A+B -> 0
Reaction(k[14], nothing, [A], nothing, [2]), # 0 -> 2A
Reaction(k[15]*A/(2+A), [A], nothing; only_use_rate=true), # A -> 0 with custom rate
Reaction(k[16], [A], [B]; only_use_rate=true), # A -> B with custom rate.
Reaction(k[17]*A*exp(B), [C], [D], [2], [1]), # 2C -> D with non constant rate.
Reaction(k[18]*B, nothing, [B], nothing, [2]), # 0 -> 2B with non constant rate.
Reaction(k[19]*t, [A], [B]), # A -> B with non constant rate.
Reaction(k[20]*t*A, [B,C], [D],[2,1],[2]) # 2A +B -> 2C with non constant rate.
]
```
Notes:
- `nothing` can be used to indicate a reaction that has no reactants or no products.
In this case the corresponding stoichiometry vector should also be set to `nothing`.
- The three-argument form assumes all reactant and product stoichiometric coefficients
are one.
"""
struct Reaction{S, T}
"""The rate function (excluding mass action terms)."""
rate::Any
"""Reaction substrates."""
substrates::Vector
"""Reaction products."""
products::Vector
"""The stoichiometric coefficients of the reactants."""
substoich::Vector{T}
"""The stoichiometric coefficients of the products."""
prodstoich::Vector{T}
"""The net stoichiometric coefficients of all species changed by the reaction."""
netstoich::Vector{Pair{S, T}}
"""
`false` (default) if `rate` should be multiplied by mass action terms to give the rate law.
`true` if `rate` represents the full reaction rate law.
"""
only_use_rate::Bool
"""
Contain additional data, such whenever the reaction have a specific noise-scaling expression for
the chemical Langevin equation.
"""
metadata::Vector{Pair{Symbol, Any}}
end
"""
isvalidreactant(s)
Test if a species is valid as a reactant (i.e. a species variable or a constant parameter).
"""
isvalidreactant(s) = MT.isparameter(s) ? isconstant(s) : (isspecies(s) && !isconstant(s))
function Reaction(rate, subs, prods, substoich, prodstoich;
netstoich = nothing, metadata = Pair{Symbol, Any}[],
only_use_rate = metadata_only_use_rate_check(metadata), kwargs...)
(isnothing(prods) && isnothing(subs)) &&
throw(ArgumentError("A reaction requires a non-nothing substrate or product vector."))
(isnothing(prodstoich) && isnothing(substoich)) &&
throw(ArgumentError("Both substrate and product stochiometry inputs cannot be nothing."))
if isnothing(subs)
prodtype = typeof(value(first(prods)))
subs = Vector{prodtype}()
!isnothing(substoich) &&
throw(ArgumentError("If substrates are nothing, substrate stoichiometries have to be so too."))
substoich = typeof(prodstoich)()
else
subs = value.(subs)
end
allunique(subs) ||
throw(ArgumentError("Substrates can not be repeated in the list provided to `Reaction`, please modify the stoichiometry for any repeated substrates instead."))
S = eltype(substoich)
if isnothing(prods)
prods = Vector{eltype(subs)}()
!isnothing(prodstoich) &&
throw(ArgumentError("If products are nothing, product stoichiometries have to be so too."))
prodstoich = typeof(substoich)()
else
prods = value.(prods)
end
allunique(prods) ||
throw(ArgumentError("Products can not be repeated in the list provided to `Reaction`, please modify the stoichiometry for any repeated products instead."))
T = eltype(prodstoich)
# try to get a common type for stoichiometry, using Any if have Syms
stoich_type = promote_type(S, T)
if stoich_type <: Num
stoich_type = Any
substoich′ = Any[value(s) for s in substoich]
prodstoich′ = Any[value(p) for p in prodstoich]
else
substoich′ = (S == stoich_type) ? substoich : convert.(stoich_type, substoich)
prodstoich′ = (T == stoich_type) ? prodstoich : convert.(stoich_type, prodstoich)
end
if !(all(isvalidreactant, subs) && all(isvalidreactant, prods))
badsts = union(filter(!isvalidreactant, subs), filter(!isvalidreactant, prods))
throw(ArgumentError("""To be a valid substrate or product, non-constant species must be declared via @species, while constant species must be parameters with the isconstantspecies metadata. The following reactants do not follow this convention:\n $badsts"""))
end
ns = if netstoich === nothing
get_netstoich(subs, prods, substoich′, prodstoich′)
else
(netstoich_stoichtype(netstoich) != stoich_type) ?
convert.(stoich_type, netstoich) : netstoich
end
# Check that all metadata entries are unique. (cannot use `in` since some entries may be symbolics).
if !allunique(entry[1] for entry in metadata)
error("Repeated entries for the same metadata encountered in the following metadata set: $([entry[1] for entry in metadata]).")
end
# Deletes potential `:only_use_rate => ` entries from the metadata.
if any(:only_use_rate == entry[1] for entry in metadata)
deleteat!(metadata, findfirst(:only_use_rate == entry[1] for entry in metadata))
end
# Ensures metadata have the correct type.
metadata = convert(Vector{Pair{Symbol, Any}}, metadata)
Reaction(value(rate), subs, prods, substoich′, prodstoich′, ns, only_use_rate, metadata)
end
# Checks if a metadata input has an entry :only_use_rate => true
function metadata_only_use_rate_check(metadata)
only_use_rate_idx = findfirst(:only_use_rate == entry[1] for entry in metadata)
isnothing(only_use_rate_idx) && return false
return Bool(metadata[only_use_rate_idx][2])
end
# three argument constructor assumes stoichiometric coefs are one and integers
function Reaction(rate, subs, prods; kwargs...)
sstoich = isnothing(subs) ? nothing : ones(Int, length(subs))
pstoich = isnothing(prods) ? nothing : ones(Int, length(prods))
Reaction(rate, subs, prods, sstoich, pstoich; kwargs...)
end
function print_rxside(io::IO, specs, stoich)
# reactants/substrates
if isempty(specs)
print(io, "∅")
else
for (i, spec) in enumerate(specs)
prspec = (MT.isparameter(spec) || (MT.operation(spec) == getindex)) ?
spec : MT.operation(spec)
if isequal(stoich[i], one(stoich[i]))
print(io, prspec)
elseif istree(stoich[i])
print(io, "(", stoich[i], ")*", prspec)
else
print(io, stoich[i], "*", prspec)
end
(i < length(specs)) && print(io, " + ")
end
end
nothing
end
function Base.show(io::IO, rx::Reaction)
print(io, rx.rate, ", ")
print_rxside(io, rx.substrates, rx.substoich)
arrow = rx.only_use_rate ? "⇒" : "-->"
print(io, " ", arrow, " ")
print_rxside(io, rx.products, rx.prodstoich)
end
function apply_if_nonempty(f, v)
isempty(v) && return v
s = similar(v)
map!(f, s, v)
s
end
function ModelingToolkit.namespace_equation(rx::Reaction, name; kw...)
f = Base.Fix2(namespace_expr, name)
rate = f(rx.rate)
subs = apply_if_nonempty(f, rx.substrates)
prods = apply_if_nonempty(f, rx.products)
substoich = apply_if_nonempty(f, rx.substoich)
prodstoich = apply_if_nonempty(f, rx.prodstoich)
netstoich = if isempty(rx.netstoich)
rx.netstoich
else
ns = similar(rx.netstoich)
map!(n -> f(n[1]) => f(n[2]), ns, rx.netstoich)
end
Reaction(rate, subs, prods, substoich, prodstoich, netstoich, rx.only_use_rate, rx.metadata)
end
netstoich_stoichtype(::Vector{Pair{S, T}}) where {S, T} = T
# calculates the net stoichiometry of a reaction as a vector of pairs (sub,substoich)
function get_netstoich(subs, prods, sstoich, pstoich)
# stoichiometry as a Dictionary
nsdict = Dict{Any, eltype(sstoich)}(sub => -sstoich[i] for (i, sub) in enumerate(subs))
for (i, p) in enumerate(prods)
coef = pstoich[i]
@inbounds nsdict[p] = haskey(nsdict, p) ? nsdict[p] + coef : coef
end
# stoichiometry as a vector
[el for el in nsdict if !_iszero(el[2])]
end
"""
isbcbalanced(rx::Reaction)
True if any BC species in `rx` appears as a substrate and product with the same
stoichiometry.
"""
function isbcbalanced(rx::Reaction)
# any substrate BC must be a product with the same stoichiometry
for (sidx, sub) in enumerate(rx.substrates)
if isbc(sub)
pidx = findfirst(Base.Fix1(isequal, sub), rx.products)
(pidx === nothing) && return false
isequal(rx.prodstoich[pidx], rx.substoich[sidx]) || return false
end
end
for prod in rx.products
if isbc(prod)
any(Base.Fix1(isequal, prod), rx.substrates) || return false
end
end
true
end
### Reaction Acessor Functions ###
# Overwrites functions in ModelingToolkit to give the correct input.
ModelingToolkit.is_diff_equation(rx::Reaction) = false
ModelingToolkit.is_alg_equation(rx::Reaction) = false
################################## Reaction Complexes ####################################
"""
$(TYPEDEF)
One reaction complex element
# Fields
$(FIELDS)
"""
struct ReactionComplexElement{T}
"""The integer id of the species representing this element."""
speciesid::Int
"""The stoichiometric coefficient of this species."""
speciesstoich::T
end
"""
$(TYPEDEF)
One reaction complex.
# Fields
$(FIELDS)
"""
struct ReactionComplex{V <: Integer} <: AbstractVector{ReactionComplexElement{V}}
"""The integer ids of all species participating in this complex."""
speciesids::Vector{Int}
"""The stoichiometric coefficients of all species participating in this complex."""
speciesstoichs::Vector{V}
function ReactionComplex{V}(speciesids::Vector{Int},
speciesstoichs::Vector{V}) where {V <: Integer}
new{V}(speciesids, speciesstoichs)
end
end
function ReactionComplex(speciesids::Vector{Int},
speciesstoichs::Vector{V}) where {V <: Integer}
(length(speciesids) == length(speciesstoichs)) ||
error("Creating a complex with different number of species ids and associated stoichiometries.")
ReactionComplex{V}(speciesids, speciesstoichs)
end
function (==)(a::ReactionComplex{V}, b::ReactionComplex{V}) where {V <: Integer}
(a.speciesids == b.speciesids) &&
(a.speciesstoichs == b.speciesstoichs)
end
function hash(rc::ReactionComplex, h::UInt)
Base.hash(rc.speciesids, Base.hash(rc.speciesstoichs, h))
end
Base.size(rc::ReactionComplex) = size(rc.speciesids)
Base.length(rc::ReactionComplex) = length(rc.speciesids)
function Base.getindex(rc::ReactionComplex, i...)
ReactionComplexElement(getindex(rc.speciesids, i...), getindex(rc.speciesstoichs, i...))
end
function Base.setindex!(rc::ReactionComplex, t::ReactionComplexElement, i...)
(setindex!(rc.speciesids, t.speciesid, i...);
setindex!(rc.speciesstoichs,
t.speciesstoich, i...);
rc)
end
function Base.isless(a::ReactionComplexElement, b::ReactionComplexElement)
isless(a.speciesid, b.speciesid)
end
Base.Sort.defalg(::ReactionComplex) = Base.DEFAULT_UNSTABLE
############################### Network Properties ####################################
#! format: off
# Internal cache for various ReactionSystem calculated properties
Base.@kwdef mutable struct NetworkProperties{I <: Integer, V <: BasicSymbolic{Real}}
isempty::Bool = true
netstoichmat::Union{Matrix{Int}, SparseMatrixCSC{Int, Int}} = Matrix{Int}(undef, 0, 0)
conservationmat::Matrix{I} = Matrix{I}(undef, 0, 0)
col_order::Vector{Int} = Int[]
rank::Int = 0
nullity::Int = 0
indepspecs::Set{V} = Set{V}()
depspecs::Set{V} = Set{V}()
conservedeqs::Vector{Equation} = Equation[]
constantdefs::Vector{Equation} = Equation[]
speciesmap::Dict{V, Int} = Dict{V, Int}()
complextorxsmap::OrderedDict{ReactionComplex{Int}, Vector{Pair{Int, Int}}} = OrderedDict{ReactionComplex{Int},Vector{Pair{Int,Int}}}()
complexes::Vector{ReactionComplex{Int}} = Vector{ReactionComplex{Int}}(undef, 0)
incidencemat::Union{Matrix{Int}, SparseMatrixCSC{Int, Int}} = Matrix{Int}(undef, 0, 0)
complexstoichmat::Union{Matrix{Int}, SparseMatrixCSC{Int, Int}} = Matrix{Int}(undef, 0, 0)
complexoutgoingmat::Union{Matrix{Int}, SparseMatrixCSC{Int, Int}} = Matrix{Int}(undef, 0, 0)
incidencegraph::Graphs.SimpleDiGraph{Int} = Graphs.DiGraph()
linkageclasses::Vector{Vector{Int}} = Vector{Vector{Int}}(undef, 0)
deficiency::Int = 0
end
#! format: on
function Base.show(io::IO, nps::NetworkProperties)
if (nps.conservationmat !== nothing)
println(io, "Conserved Equations: ")
foreach(eq -> println(io, eq), nps.conservedeqs)
println()
end
end
Base.isempty(nps::NetworkProperties) = getfield(nps, :isempty)
function Base.setproperty!(nps::NetworkProperties, sym::Symbol, x)
(sym !== :isempty) && setfield!(nps, :isempty, false)
setfield!(nps, sym, x)
end
function reset!(nps::NetworkProperties{I, V}) where {I, V}
nps.isempty && return
nps.netstoichmat = Matrix{Int}(undef, 0, 0)
nps.conservationmat = Matrix{I}(undef, 0, 0)
empty!(nps.col_order)
nps.rank = 0
nps.nullity = 0
empty!(nps.indepspecs)
empty!(nps.depspecs)
empty!(nps.conservedeqs)
empty!(nps.constantdefs)
empty!(nps.speciesmap)
empty!(nps.complextorxsmap)
empty!(nps.complexes)
nps.incidencemat = Matrix{Int}(undef, 0, 0)
nps.complexstoichmat = Matrix{Int}(undef, 0, 0)
nps.complexoutgoingmat = Matrix{Int}(undef, 0, 0)
nps.incidencegraph = Graphs.DiGraph()
empty!(nps.linkageclasses)
nps.deficiency = 0
# this needs to be last due to setproperty! setting it to false
nps.isempty = true
nothing
end
############################### Reaction Systems ####################################
const CatalystEqType = Union{Reaction, Equation}
"""
$(TYPEDEF)
A system of chemical reactions.
# Fields
$(FIELDS)
# Example
Continuing from the example in the [`Reaction`](@ref) definition:
```julia
# simple constructor that infers species and parameters
@named rs = ReactionSystem(rxs, t)
# allows specification of species and parameters
@named rs = ReactionSystem(rxs, t, [A,B,C,D], k)
```
Keyword Arguments:
- `observed::Vector{Equation}`, equations specifying observed variables.
- `systems::Vector{AbstractSystems}`, vector of sub-systems. Can be `ReactionSystem`s,
`ODESystem`s, or `NonlinearSystem`s.
- `name::Symbol`, the name of the system (must be provided, or `@named` must be used).
- `defaults::Dict`, a dictionary mapping parameters to their default values and species to
their default initial values.
- `checks = true`, boolean for whether to check units.
- `networkproperties = NetworkProperties()`, cache for network properties calculated via API
functions.
- `combinatoric_ratelaws = true`, sets the default value of `combinatoric_ratelaws` used in
calls to `convert` or calling various problem types with the `ReactionSystem`.
- `balanced_bc_check = true`, sets whether to check that BC species appearing in reactions
are balanced (i.e appear as both a substrate and a product with the same stoichiometry).
Notes:
- ReactionSystems currently do rudimentary unit checking, requiring that all species have
the same units, and all reactions have rate laws with units of (species units) / (time
units). Unit checking can be disabled by passing the keyword argument `checks=false`.
"""
struct ReactionSystem{V <: NetworkProperties} <:
MT.AbstractTimeDependentSystem
"""The equations (reactions and algebraic/differential) defining the system."""
eqs::Vector{CatalystEqType}
"""The Reactions defining the system. """
rxs::Vector{Reaction}
"""Independent variable (usually time)."""
iv::BasicSymbolic{Real}
"""Spatial independent variables"""
sivs::Vector{BasicSymbolic{Real}}
"""All dependent (unknown) variables, species and non-species. Must not contain the
independent variable."""
unknowns::Vector{BasicSymbolic{Real}}
"""Dependent unknown variables representing species"""
species::Vector{BasicSymbolic{Real}}
"""Parameter variables. Must not contain the independent variable."""
ps::Vector{Any}
"""Maps Symbol to corresponding variable."""
var_to_name::Dict{Symbol, Any}
"""Equations for observed variables."""
observed::Vector{Equation}
"""The name of the system"""
name::Symbol
"""Internal sub-systems"""
systems::Vector
"""
The default values to use when initial conditions and/or
parameters are not supplied in `ODEProblem`.
"""
defaults::Dict
"""Type of the system"""
connection_type::Any
"""`NetworkProperties` object that can be filled in by API functions. INTERNAL -- not
considered part of the public API."""
networkproperties::V
"""Sets whether to use combinatoric scalings in rate laws. true by default."""
combinatoric_ratelaws::Bool
"""
continuous_events: A `Vector{SymbolicContinuousCallback}` that model events.
The integrator will use root finding to guarantee that it steps at each zero crossing.
"""
continuous_events::Vector{MT.SymbolicContinuousCallback}
"""
discrete_events: A `Vector{SymbolicDiscreteCallback}` that models events. Symbolic
analog to `SciMLBase.DiscreteCallback` that executes an affect when a given condition is
true at the end of an integration step.
"""
discrete_events::Vector{MT.SymbolicDiscreteCallback}
"""
Metadata for the system, to be used by downstream packages.
"""
metadata::Any
"""
complete: if a model `sys` is complete, then `sys.x` no longer performs namespacing.
"""
complete::Bool
# inner constructor is considered private and may change between non-breaking releases.
function ReactionSystem(eqs, rxs, iv, sivs, unknowns, spcs, ps, var_to_name, observed,
name, systems, defaults, connection_type, nps, cls, cevs, devs,
metadata = nothing, complete = false; checks::Bool = true)
# Checks that all parameters have the appropriate Symbolics type.
for p in ps
(p isa Symbolics.BasicSymbolic) || error("Parameter $p is not a `BasicSymbolic`. This is required.")
end
# Filters away any potential obervables from `states` and `spcs`.
obs_vars = [obs_eq.lhs for obs_eq in observed]
unknowns = filter(state -> !any(isequal(state, obs_var) for obs_var in obs_vars), unknowns)
spcs = filter(spc -> !any(isequal(spc, obs_var) for obs_var in obs_vars), spcs)
# unit checks are for ODEs and Reactions only currently
nonrx_eqs = Equation[eq for eq in eqs if eq isa Equation]
if checks && isempty(sivs)
check_variables(unknowns, iv)
check_parameters(ps, iv)
nonrx_eqs = Equation[eq for eq in eqs if eq isa Equation]
!isempty(nonrx_eqs) && check_equations(nonrx_eqs, iv)
!isempty(cevs) && check_equations(equations(cevs), iv)
end
if isempty(sivs) && (checks == true || (checks & MT.CheckUnits) > 0)
if !all(u == 1.0 for u in ModelingToolkit.get_unit([unknowns; ps; iv]))
for eq in eqs
(eq isa Equation) && check_units(eq)
end
end
end
rs = new{typeof(nps)}(eqs, rxs, iv, sivs, unknowns, spcs, ps, var_to_name, observed,
name, systems, defaults, connection_type, nps, cls, cevs,
devs, metadata, complete)
checks && validate(rs)
rs
end
end
function get_speciestype(iv, unknowns, systems)
T = Nothing
!isempty(unknowns) && (T = typeof(first(unknowns)))
if !isempty(systems)
for sys in Iterators.filter(s -> s isa ReactionSystem, systems)
sts = MT.unknowns(sys)
if !isempty(sts)
T = typeof(first(sts))
break
end
end
end
if T <: Nothing
@variables A($iv)
T = typeof(MT.unwrap(A))
end
T
end
eqsortby(eq::CatalystEqType) = eq isa Reaction ? 1 : 2
function ReactionSystem(eqs, iv, unknowns, ps;
observed = Equation[],
systems = [],
name = nothing,
default_u0 = Dict(),
default_p = Dict(),
defaults = _merge(Dict(default_u0), Dict(default_p)),
connection_type = nothing,
checks = true,
networkproperties = nothing,
combinatoric_ratelaws = true,
balanced_bc_check = true,
spatial_ivs = nothing,
continuous_events = nothing,
discrete_events = nothing,
metadata = nothing)
# Error checks
if name === nothing
throw(ArgumentError("The `name` keyword must be provided. Please consider using the `@named` macro"))
end
sysnames = nameof.(systems)
(length(unique(sysnames)) == length(sysnames)) || throw(ArgumentError("System names must be unique."))
# Handle defaults values provided via optional arguments.
if !(isempty(default_u0) && isempty(default_p))
Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :ReactionSystem, force = true)
end
defaults = MT.todict(defaults)
defaults = Dict{Any, Any}(value(k) => value(v) for (k, v) in pairs(defaults))
# Extracts independent variables (iv and sivs), dependent variables (species and variables)
# and parameters. Sorts so that species comes before variables in unknowns vector.
iv′ = value(iv)
sivs′ = if spatial_ivs === nothing
Vector{typeof(iv′)}()
else
value.(MT.scalarize(spatial_ivs))
end
unknowns′ = sort!(value.(MT.scalarize(unknowns)), by = !isspecies)
spcs = filter(isspecies, unknowns′)
ps′ = value.(MT.scalarize(ps))
# Checks that no (by Catalyst) forbidden symbols are used.
allsyms = Iterators.flatten((ps′, unknowns′))
if !all(sym -> getname(sym) ∉ forbidden_symbols_error, allsyms)
error("Catalyst reserves the symbols $forbidden_symbols_error for internal use. Please do not use these symbols as parameters or unknowns/species.")
end
# Handles reactions and equations. Sorts so that reactions are before equaions in the equations vector.
eqs′ = CatalystEqType[eq for eq in eqs]
sort!(eqs′; by = eqsortby)
rxs = Reaction[rx for rx in eqs if rx isa Reaction]
# Additional error checks.
if any(MT.isparameter, unknowns′)
psts = filter(MT.isparameter, unknowns′)
throw(ArgumentError("Found one or more parameters among the unknowns; this is not allowed. Move: $psts to be parameters."))
end
if any(isconstant, unknowns′)
csts = filter(isconstant, unknowns′)
throw(ArgumentError("Found one or more constant species among the unknowns; this is not allowed. Move: $csts to be parameters."))
end
# If there are BC species, check they are balanced in their reactions.
if balanced_bc_check && any(isbc, unknowns′)
for rx in eqs
if (rx isa Reaction) && !isbcbalanced(rx)
throw(ErrorException("BC species must be balanced, appearing as a substrate and product with the same stoichiometry. Please fix reaction: $rx"))
end
end
end
# Adds all unknowns/parameters to the `var_to_name` vector.
# Adds their (potential) default values to the defaults vector.
var_to_name = Dict()
MT.process_variables!(var_to_name, defaults, unknowns′)
MT.process_variables!(var_to_name, defaults, ps′)
MT.collect_var_to_name!(var_to_name, eq.lhs for eq in observed)
# Computes network properties.
nps = if networkproperties === nothing
NetworkProperties{Int, get_speciestype(iv′, unknowns′, systems)}()
else
networkproperties
end
# Creates the continious and discrete callbacks.
ccallbacks = MT.SymbolicContinuousCallbacks(continuous_events)
dcallbacks = MT.SymbolicDiscreteCallbacks(discrete_events)
ReactionSystem(eqs′, rxs, iv′, sivs′, unknowns′, spcs, ps′, var_to_name, observed, name,
systems, defaults, connection_type, nps, combinatoric_ratelaws,
ccallbacks, dcallbacks, metadata; checks = checks)
end
function ReactionSystem(rxs::Vector, iv = Catalyst.DEFAULT_IV; kwargs...)
make_ReactionSystem_internal(rxs, iv, Vector{Num}(), Vector{Num}(); kwargs...)
end
# search the symbolic expression for parameters or unknowns
# and save in ps and us respectively. vars is used to cache results
function findvars!(ps, us, exprtosearch, ivs, vars)
MT.get_variables!(vars, exprtosearch)
for var in vars
(var ∈ ivs) && continue
if MT.isparameter(var)
push!(ps, var)
else
push!(us, var)
end
end
empty!(vars)
end
# Special dispatch for equations, applied `findvars!` to left-hand and right-hand sides.
function findvars!(ps, us, eq_to_search::Equation, ivs, vars)
findvars!(ps, us, eq_to_search.lhs, ivs, vars)
findvars!(ps, us, eq_to_search.rhs, ivs, vars)
end
# Special dispatch for Vectors (applies it to each vector element).
function findvars!(ps, us, exprs_to_search::Vector, ivs, vars)
foreach(exprtosearch -> findvars!(ps, us, exprtosearch, ivs, vars), exprs_to_search)
end
# Called internally (whether DSL-based or programmtic model creation is used).
# Creates a sorted reactions + equations vector, also ensuring reaction is first in this vector.
# Extracts potential species, variables, and parameters from the input (if not provided as part of
# the model creation) and creates the corresponding vectors.
# While species are ordered before variables in the unknowns vector, this ordering is not imposed here,
# but carried out at a later stage.
function make_ReactionSystem_internal(rxs_and_eqs::Vector, iv, us_in, ps_in; spatial_ivs = nothing,
continuous_events = [], discrete_events = [], kwargs...)
# Creates a combined iv vector (iv and sivs). This is used later in the function (so that
# independent variables can be exluded when encountered quantities are added to `us` and `ps`).
t = value(iv)
ivs = Set([t])
if (spatial_ivs !== nothing)
for siv in (MT.scalarize(spatial_ivs))
push!(ivs, value(siv))
end
end
# Initialises the new unknowns and parameter vectors.
# Preallocates the `vars` set, which is used by `findvars!`
us = OrderedSet{eltype(us_in)}(us_in)
ps = OrderedSet{eltype(ps_in)}(ps_in)
vars = OrderedSet()
# Extracts the reactions and equations from the combined reactions + equations input vector.
all(eq -> eq isa Union{Reaction, Equation}, rxs_and_eqs)
rxs = Reaction[eq for eq in rxs_and_eqs if eq isa Reaction]
eqs = Equation[eq for eq in rxs_and_eqs if eq isa Equation]
# Loops through all reactions, adding encountered quantities to the unknown and parameter vectors.
for rx in rxs
# Loops through all reaction substrates and products, extracting these.
for reactants in (rx.substrates, rx.products), spec in reactants
MT.isparameter(spec) ? push!(ps, spec) : push!(us, spec)
end
# Adds all quantitites encountered in the reaction's rate.
findvars!(ps, us, rx.rate, ivs, vars)
# Extracts all quantitites encountered within stoichiometries.
for stoichiometry in (rx.substoich, rx.prodstoich), sym in stoichiometry
(sym isa Symbolic) && findvars!(ps, us, sym, ivs, vars)
end
# Will appear here: add stuff from nosie scaling.
end
# Extracts any species, variables, and parameters that occur in (non-reaction) equations.
# Creates the new reactions + equations vector, `fulleqs` (sorted reactions first, equations next).
if !isempty(eqs)
osys = ODESystem(eqs, iv; name = gensym())
fulleqs = CatalystEqType[rxs; equations(osys)]
union!(us, unknowns(osys))
union!(ps, parameters(osys))
else
fulleqs = rxs
end
# Loops through all events, adding encountered quantities to the unknwon and parameter vectors.
find_event_vars!(ps, us, continuous_events, ivs, vars)
find_event_vars!(ps, us, discrete_events, ivs, vars)
# Converts the found unknowns and parameters to vectors.
usv = collect(us)
psv = collect(ps)
# Passes the processed input into the next `ReactionSystem` call.
ReactionSystem(fulleqs, t, usv, psv; spatial_ivs, continuous_events, discrete_events, kwargs...)
end
function ReactionSystem(iv; kwargs...)
ReactionSystem(Reaction[], iv, [], []; kwargs...)
end
# Loops through all events in an supplied event vector, adding all unknowns and parameters found in
# its condition and affect functions to their respective vectors (`ps` and `us`).
function find_event_vars!(ps, us, events::Vector, ivs, vars)
foreach(event -> find_event_vars!(ps, us, event, ivs, vars), events)
end
# For a single event, adds quantitites from its condition and affect expression(s) to `ps` and `us`.
# Applies `findvars!` to the event's condition (`event[1])` and affec (`event[2]`).
function find_event_vars!(ps, us, event, ivs, vars)
findvars!(ps, us, event[1], ivs, vars)
findvars!(ps, us, event[2], ivs, vars)
end
"""
remake_ReactionSystem_internal(rs::ReactionSystem;
default_reaction_metadata::Vector{Pair{Symbol, T}} = Vector{Pair{Symbol, Any}}()) where {T}
Takes a `ReactionSystem` and remakes it, returning a modified `ReactionSystem`. Modifications depend
on which additional arguments are provided. The input `ReactionSystem` is not mutated. Updating
default reaction metadata is currently the only supported feature.
Arguments:
- `rs::ReactionSystem`: The `ReactionSystem` which you wish to remake.
- `default_reaction_metadata::Vector{Pair{Symbol, T}}`: A vector with default `Reaction` metadata values.
Each metadata in each `Reaction` of the updated `ReactionSystem` will have the value desiganted in
`default_reaction_metadata` (however, `Reaction`s that already have that metadata designated will not
have their value updated).
"""
function remake_ReactionSystem_internal(rs::ReactionSystem; default_reaction_metadata = [])
rs = set_default_metadata(rs; default_reaction_metadata)
return rs
end
# For a `ReactionSystem`, updates all `Reaction`'s default metadata.
function set_default_metadata(rs::ReactionSystem; default_reaction_metadata = [])
# Updates reaction metadata for for reactions in this specific system.
eqtransform(eq) = eq isa Reaction ? set_default_metadata(eq, default_reaction_metadata) : eq
updated_equations = map(eqtransform, get_eqs(rs))
@set! rs.eqs = updated_equations
@set! rs.rxs = Reaction[rx for rx in updated_equations if rx isa Reaction]
# Updates reaction metadata for all its subsystems.
new_sub_systems = similar(get_systems(rs))
for (i, sub_system) in enumerate(get_systems(rs))
new_sub_systems[i] = set_default_metadata(sub_system; default_reaction_metadata)
end
@set! rs.systems = new_sub_systems
# Returns the updated system.
return rs
end
# For a `Reaction`, adds missing default metadata values. Equations are passed back unmodified.
function set_default_metadata(rx::Reaction, default_metadata)
missing_metadata = filter(md -> !in(md[1], entry[1] for entry in rx.metadata), default_metadata)
updated_metadata = vcat(rx.metadata, missing_metadata)
updated_metadata = convert(Vector{Pair{Symbol, Any}}, updated_metadata)
return @set rx.metadata = updated_metadata
end
set_default_metadata(eq::Equation, default_metadata) = eq
"""
set_default_noise_scaling(rs::ReactionSystem, noise_scaling)
Creates an updated `ReactionSystem`. This is the old `ReactionSystem`, but each `Reaction` that does
not have a `noise_scaling` metadata have its noise_scaling metadata updated. The input `ReactionSystem`
is not mutated. Any subsystems of `rs` have their `noise_scaling` metadata updated as well.
Arguments:
- `rs::ReactionSystem`: The `ReactionSystem` which you wish to remake.
- `noise_scaling`: The updated noise scaling terms
"""
function set_default_noise_scaling(rs::ReactionSystem, noise_scaling)
return remake_ReactionSystem_internal(rs, default_reaction_metadata = [:noise_scaling => noise_scaling])
end
"""
isspatial(rn::ReactionSystem)
Returns whether `rn` has any spatial independent variables (i.e. is a spatial network).
"""
isspatial(rn::ReactionSystem) = !isempty(get_sivs(rn))
####################### ModelingToolkit inherited accessors #############################
"""
get_species(sys::ReactionSystem)
Return the current dependent variables that represent species in `sys` (toplevel system
only).
"""
get_species(sys::ReactionSystem) = getfield(sys, :species)
has_species(sys::ReactionSystem) = isdefined(sys, :species)
"""
get_rxs(sys::ReactionSystem)
Return the system's `Reaction` vector (toplevel system only).
"""
get_rxs(sys::ReactionSystem) = getfield(sys, :rxs)
has_rxs(sys::ReactionSystem) = isdefined(sys, :rxs)
"""
get_sivs(sys::ReactionSystem)
Return the current spatial ivs, if the system is non-spatial returns an empty vector.
"""
get_sivs(sys::ReactionSystem) = getfield(sys, :sivs)
has_sivs(sys::ReactionSystem) = isdefined(sys, :sivs)
"""
get_networkproperties(sys::ReactionSystem)
Return the current network properties of `sys`.
"""
get_networkproperties(sys::ReactionSystem) = getfield(sys, :networkproperties)
"""
get_combinatoric_ratelaws(sys::ReactionSystem)
Returns true if the default for the system is to rescale ratelaws, see
https://docs.sciml.ai/Catalyst/stable/introduction_to_catalyst/introduction_to_catalyst/#Reaction-rate-laws-used-in-simulations
for details. Can be overriden via passing `combinatoric_ratelaws` to `convert` or the
`*Problem` functions.
"""
get_combinatoric_ratelaws(sys::ReactionSystem) = getfield(sys, :combinatoric_ratelaws)
MT.get_continuous_events(sys::ReactionSystem) = getfield(sys, :continuous_events)
# need a custom equations since ReactionSystem.eqs are a mix of Reactions and Equations
function MT.equations(sys::ReactionSystem)
ivs = independent_variables(sys)
eqs = get_eqs(sys)
systems = get_systems(sys)
if !isempty(systems)
eqs = CatalystEqType[eqs;
reduce(vcat, MT.namespace_equations.(systems, (ivs,));
init = Any[])]
return sort!(eqs; by = eqsortby)
end
return eqs
end
function MT.unknowns(sys::ReactionSystem)
sts = get_unknowns(sys)
systems = get_systems(sys)
if !isempty(systems)
sts = unique!([sts; reduce(vcat, namespace_variables.(systems))])
sort!(sts; by = !isspecies)
return sts
end
return sts
end
"""
combinatoric_ratelaws(sys::ReactionSystem)
Returns the effective (default) `combinatoric_ratelaw` value for a compositional system,
calculated by taking the logical or of each component `ReactionSystem`. Can be overriden
during calls to `convert` of problem constructors.
"""
function combinatoric_ratelaws(sys::ReactionSystem)
crl = get_combinatoric_ratelaws(sys)
subsys = Iterators.filter(s -> s isa ReactionSystem, get_systems(sys))
mapreduce(combinatoric_ratelaws, |, subsys; init = crl)
end
# get the non-bc, independent unknown variables and independent species, preserving their
# relative order in get_unknowns(rs). ASSUMES system has been validated to have no constant
# species as unknowns and is flattened.
function get_indep_sts(rs::ReactionSystem, remove_conserved = false)
sts = get_unknowns(rs)
nps = get_networkproperties(rs)
indepsts = if remove_conserved
filter(s -> ((s ∈ nps.indepspecs) || (!isspecies(s))) && (!isbc(s)), sts)
else
filter(s -> !isbc(s), sts)
end
indepsts, filter(isspecies, indepsts)
end
######################## Other accessors ##############################
"""
has_noise_scaling(reaction::Reaction)
Checks whether a specific reaction has the metadata field `noise_scaing`. If so, returns `true`, else
returns `false`.