Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
f0f7b32
initi
TorkelE Feb 17, 2025
1121ce7
don't provide system level conservation law defaults
TorkelE Feb 17, 2025
82ecb25
Update Project.toml
isaacsas Feb 18, 2025
7005533
use vector conservation law constant in ps only
isaacsas Feb 18, 2025
ac0222b
unwrap
isaacsas Feb 18, 2025
a9c2d7d
MT.unwrap
isaacsas Feb 18, 2025
8008a98
mtk update documentation
isaacsas Feb 25, 2025
af91bfa
updates
isaacsas Feb 26, 2025
3f1f19f
more test updates
isaacsas Feb 26, 2025
80540fe
more test fixes
isaacsas Feb 26, 2025
1d376f0
more fixes
isaacsas Feb 27, 2025
ae8c524
finish fixing DSL tests
isaacsas Feb 27, 2025
da09d93
more fixes
isaacsas Feb 27, 2025
d8ce691
fix isequivalent test
isaacsas Feb 27, 2025
ebe63a8
fixes
isaacsas Feb 28, 2025
002da5f
uncomment disabled error
isaacsas Mar 3, 2025
edc289c
update - tests should work
TorkelE Mar 15, 2025
b625247
Merge branch 'master' into mtk_update
TorkelE Mar 15, 2025
78b35fd
up
TorkelE Mar 15, 2025
2888107
some broken tests are no longer broken
TorkelE Mar 15, 2025
99c2e29
fix another broken test
TorkelE Mar 15, 2025
99cea55
update document mtk version
TorkelE Mar 16, 2025
df6496b
doc update
TorkelE Mar 16, 2025
abe5e00
more doc fixes
TorkelE Mar 16, 2025
319e813
up
TorkelE Mar 16, 2025
9f8389f
fix system caching
TorkelE Mar 16, 2025
8097557
Update ode_fitting_oscillation.md
TorkelE Mar 16, 2025
f01b6b5
fix osc fitting turorial. add warning to nonlinear solve cons law doc
TorkelE Mar 17, 2025
2d134fa
improve setp function usage in oscilaltion fitting example
TorkelE Mar 17, 2025
c798cbe
mark broken test as broken (known and fix is incoming)
TorkelE Mar 17, 2025
f5be8ef
Update dsl_options.jl
TorkelE Mar 17, 2025
2dcaa39
add missing (sensible) ode solve kwargs
TorkelE Mar 19, 2025
1d4e1d9
add complete dispatch and remove toplevel stuff
isaacsas Mar 19, 2025
456e545
sync to master
isaacsas Mar 19, 2025
36bdae4
Merge branch 'master' into mtk_update
TorkelE Mar 20, 2025
f636dcd
Merge remote-tracking branch 'origin/mtk_update' into mtk_update
isaacsas Mar 20, 2025
7b0a611
more test fixes
isaacsas Mar 20, 2025
6fc3a01
add non-complete check for extend/compose
isaacsas Mar 20, 2025
5e11215
return nothing
isaacsas Mar 20, 2025
9dfa120
refactor
isaacsas Mar 20, 2025
6d9f44c
remove toplevel function
isaacsas Mar 20, 2025
0286912
fix SDE test
isaacsas Mar 20, 2025
af5bf91
update HISTORY
isaacsas Mar 20, 2025
f4264e4
don't flatten
isaacsas Mar 20, 2025
4280a33
Reenable broken test
TorkelE Mar 20, 2025
af72878
test fix
TorkelE Mar 20, 2025
df86144
spatial test fix
TorkelE Mar 21, 2025
1d194c1
testfix
TorkelE Mar 21, 2025
157cb50
Update docs/Project.toml
isaacsas Mar 23, 2025
47c6bca
Update Project.toml
isaacsas Mar 23, 2025
56b494d
bump MTK
isaacsas Mar 26, 2025
84da329
try to fix docs
isaacsas Mar 26, 2025
2fdb32d
more doc fixes
isaacsas Mar 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ JumpProcesses = "9.13.2"
LaTeXStrings = "1.3.0"
Latexify = "0.16.6"
MacroTools = "0.5.5"
ModelingToolkit = "< 9.60"
ModelingToolkit = "9.60"
NetworkLayout = "0.4.7"
Parameters = "0.12"
Reexport = "0.2, 1.0"
Expand Down
92 changes: 46 additions & 46 deletions src/network_analysis.jl
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,8 @@ end
@doc raw"""
laplacianmat(rn::ReactionSystem, pmap=Dict(); sparse=false)

Return the negative of the graph Laplacian of the reaction network. The ODE system of a chemical reaction network can be factorized as ``\frac{dx}{dt} = Y A_k Φ(x)``, where ``Y`` is the [`complexstoichmat`](@ref) and ``A_k`` is the negative of the graph Laplacian, and ``Φ`` is the [`massactionvector`](@ref). ``A_k`` is an n-by-n matrix, where n is the number of complexes, where ``A_{ij} = k_{ij}`` if a reaction exists between the two complexes and 0 otherwise.
Returns a symbolic matrix by default, but will return a numerical matrix if parameter values are specified via pmap.
Return the negative of the graph Laplacian of the reaction network. The ODE system of a chemical reaction network can be factorized as ``\frac{dx}{dt} = Y A_k Φ(x)``, where ``Y`` is the [`complexstoichmat`](@ref) and ``A_k`` is the negative of the graph Laplacian, and ``Φ`` is the [`massactionvector`](@ref). ``A_k`` is an n-by-n matrix, where n is the number of complexes, where ``A_{ij} = k_{ij}`` if a reaction exists between the two complexes and 0 otherwise.
Returns a symbolic matrix by default, but will return a numerical matrix if parameter values are specified via pmap.

**Warning**: Unlike other Catalyst functions, the `laplacianmat` function will return a `Matrix{Num}` in the symbolic case. This is to allow easier computation of the matrix decomposition of the ODEs, and to ensure that multiplying the sparse form of the matrix will work.
"""
Expand Down Expand Up @@ -258,19 +258,19 @@ function fluxmat(::Type{Matrix{T}}, rcmap, rates) where T
nc = length(rcmap)
K = zeros(T, nr, nc)
for (i, (complex, rxs)) in enumerate(rcmap)
for (rx, dir) in rxs
for (rx, dir) in rxs
dir == -1 && (K[rx, i] = rates[rx])
end
end
K
end

function fluxmat(rn::ReactionSystem, pmap::Vector)
function fluxmat(rn::ReactionSystem, pmap::Vector)
pdict = Dict(pmap)
fluxmat(rn, pdict)
end

function fluxmat(rn::ReactionSystem, pmap::Tuple)
function fluxmat(rn::ReactionSystem, pmap::Tuple)
pdict = Dict(pmap)
fluxmat(rn, pdict)
end
Expand Down Expand Up @@ -301,7 +301,7 @@ function massactionvector(rn::ReactionSystem, scmap::Dict = Dict(); combinatoric
!ismassaction(rx, rn) && error("The supplied ReactionSystem has non-mass action reaction $rx. The `massactionvector` can only be constructed for mass action networks.")
end

specs = if isempty(scmap)
specs = if isempty(scmap)
species(rn)
else
substitutevals(rn, scmap, species(rn), species(rn))
Expand Down Expand Up @@ -330,7 +330,7 @@ function massactionvector(rn::ReactionSystem, scmap::Tuple; combinatoric_ratelaw
massactionvector(rn, sdict; combinatoric_ratelaws)
end

function massactionvector(rn::ReactionSystem, scmap::Vector; combinatoric_ratelaws = Catalyst.get_combinatoric_ratelaws(rn))
function massactionvector(rn::ReactionSystem, scmap::Vector; combinatoric_ratelaws = Catalyst.get_combinatoric_ratelaws(rn))
sdict = Dict(scmap)
massactionvector(rn, sdict; combinatoric_ratelaws)
end
Expand Down Expand Up @@ -461,11 +461,11 @@ end
"""
species_reaction_graph(rn::ReactionSystem)

Construct a directed simple graph where there are two types of nodes: species and reactions.
An edge from a species *s* to reaction *r* indicates that *s* is a reactant for *r*, and
an edge from a reaction *r* to a species *s* indicates that *s* is a product of *r*. By
default, the species vertices are listed first, so the first *n* indices correspond to
species nodes.
Construct a directed simple graph where there are two types of nodes: species and reactions.
An edge from a species *s* to reaction *r* indicates that *s* is a reactant for *r*, and
an edge from a reaction *r* to a species *s* indicates that *s* is a product of *r*. By
default, the species vertices are listed first, so the first *n* indices correspond to
species nodes.

Note: this is equivalent to the Petri net representation of a chemical reaction network.

Expand All @@ -477,14 +477,14 @@ sir = @reaction_network SIR begin
end
species_reaction_graph(sir)
"""
function species_reaction_graph(rn::ReactionSystem)
function species_reaction_graph(rn::ReactionSystem)
specs = species(rn)
rxs = reactions(rn)
sm = speciesmap(rn)
s = length(specs)

edgelist = Graphs.Edge[]
for (i, rx) in enumerate(rxs)
for (i, rx) in enumerate(rxs)
for spec in rx.substrates
push!(edgelist, Graphs.Edge(sm[spec], s+i))
end
Expand Down Expand Up @@ -561,7 +561,7 @@ function terminallinkageclasses(rn::ReactionSystem)
nps.terminallinkageclasses
end

# Helper function for terminallinkageclasses. Given a linkage class and a reaction network, say whether the linkage class is terminal,
# Helper function for terminallinkageclasses. Given a linkage class and a reaction network, say whether the linkage class is terminal,
# i.e. all outgoing reactions from complexes in the linkage class produce a complex also in the linkage class
function isterminal(lc::Vector, rn::ReactionSystem)
imat = incidencemat(rn)
Expand All @@ -570,7 +570,7 @@ function isterminal(lc::Vector, rn::ReactionSystem)
# Find the index of the reactant complex for a given reaction
s = findfirst(==(-1), @view imat[:, r])

# If the reactant complex is in the linkage class, check whether the product complex is also in the linkage class. If any of them are not, return false.
# If the reactant complex is in the linkage class, check whether the product complex is also in the linkage class. If any of them are not, return false.
if s in Set(lc)
p = findfirst(==(1), @view imat[:, r])
p in Set(lc) ? continue : return false
Expand Down Expand Up @@ -852,7 +852,7 @@ function cache_conservationlaw_eqs!(rn::ReactionSystem, N::AbstractMatrix, col_o
depidxs = col_order[(r + 1):end]
depspecs = sts[depidxs]
constants = MT.unwrap(only(
@parameters $(CONSERVED_CONSTANT_SYMBOL)[1:nullity] [conserved = true]))
@parameters $(CONSERVED_CONSTANT_SYMBOL)[1:nullity] = missing [conserved = true, guess = ones(nullity)]))

conservedeqs = Equation[]
constantdefs = Equation[]
Expand Down Expand Up @@ -922,7 +922,7 @@ end
isdetailedbalanced(rs::ReactionSystem, parametermap; reltol=1e-9, abstol)

Constructively compute whether a kinetic system (a reaction network with a set of rate constants) will admit detailed-balanced equilibrium
solutions, using the Wegscheider conditions, [Feinberg, 1989](https://www.sciencedirect.com/science/article/pii/0009250989851243). A detailed-balanced solution is one for which the rate of every forward reaction exactly equals its reverse reaction. Accepts a dictionary, vector, or tuple of variable-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].
solutions, using the Wegscheider conditions, [Feinberg, 1989](https://www.sciencedirect.com/science/article/pii/0009250989851243). A detailed-balanced solution is one for which the rate of every forward reaction exactly equals its reverse reaction. Accepts a dictionary, vector, or tuple of variable-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].
"""
function isdetailedbalanced(rs::ReactionSystem, parametermap::Dict; abstol=0, reltol=1e-9)
if length(parametermap) != numparams(rs)
Expand All @@ -938,7 +938,7 @@ function isdetailedbalanced(rs::ReactionSystem, parametermap::Dict; abstol=0, re
pmap = symmap_to_varmap(rs, parametermap)
pmap = Dict(ModelingToolkit.value(k) => v for (k, v) in pmap)

# Construct reaction-complex graph
# Construct reaction-complex graph
complexes, D = reactioncomplexes(rs)
img = incidencematgraph(rs)
undir_img = SimpleGraph(incidencematgraph(rs))
Expand All @@ -947,7 +947,7 @@ function isdetailedbalanced(rs::ReactionSystem, parametermap::Dict; abstol=0, re
spanning_forest = Graphs.kruskal_mst(undir_img)
outofforest_edges = setdiff(collect(edges(undir_img)), spanning_forest)

# Independent Cycle Conditions: for any cycle we create by adding in an out-of-forest reaction, the product of forward reaction rates over the cycle must equal the product of reverse reaction rates over the cycle.
# Independent Cycle Conditions: for any cycle we create by adding in an out-of-forest reaction, the product of forward reaction rates over the cycle must equal the product of reverse reaction rates over the cycle.
for edge in outofforest_edges
g = SimpleGraph([spanning_forest..., edge])
ic = Graphs.cycle_basis(g)[1]
Expand All @@ -956,7 +956,7 @@ function isdetailedbalanced(rs::ReactionSystem, parametermap::Dict; abstol=0, re
isapprox(fwd, rev; atol = abstol, rtol = reltol) ? continue : return false
end

# Spanning Forest Conditions: for non-deficiency 0 networks, we get an additional δ equations. Choose an orientation for each reaction pair in the spanning forest (we will take the one given by default from kruskal_mst).
# Spanning Forest Conditions: for non-deficiency 0 networks, we get an additional δ equations. Choose an orientation for each reaction pair in the spanning forest (we will take the one given by default from kruskal_mst).

if deficiency(rs) > 0
rxn_idxs = [edgeindex(D, Graphs.src(e), Graphs.dst(e)) for e in spanning_forest]
Expand Down Expand Up @@ -1002,9 +1002,9 @@ end
iscomplexbalanced(rs::ReactionSystem, parametermap; sparse = false)

Constructively compute whether a network will have complex-balanced equilibrium
solutions, following the method in van der Schaft et al., [2015](https://link.springer.com/article/10.1007/s10910-015-0498-2#Sec3).
solutions, following the method in van der Schaft et al., [2015](https://link.springer.com/article/10.1007/s10910-015-0498-2#Sec3).

Requires the specification of values for the parameters/rate constants. Accepts a dictionary, vector, or tuple of parameter-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].
Requires the specification of values for the parameters/rate constants. Accepts a dictionary, vector, or tuple of parameter-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].
"""
function iscomplexbalanced(rs::ReactionSystem, parametermap::Dict; sparse = false)
rxns = reactions(rs)
Expand Down Expand Up @@ -1050,16 +1050,16 @@ end
"""
adjacencymat(rs::ReactionSystem, pmap = Dict(); sparse = false)

Given a reaction system with n complexes, outputs an n-by-n matrix where R_{ij} is the rate
constant of the reaction between complex i and complex j. Accepts a dictionary, vector, or tuple
of variable-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].
Given a reaction system with n complexes, outputs an n-by-n matrix where R_{ij} is the rate
constant of the reaction between complex i and complex j. Accepts a dictionary, vector, or tuple
of variable-to-value mappings, e.g. [k1 => 1.0, k2 => 2.0,...].

Equivalent to the adjacency matrix of the weighted graph whose weights are the
reaction rates.
Returns a symbolic matrix by default, but will return a numerical matrix if parameter values are specified via pmap.
Equivalent to the adjacency matrix of the weighted graph whose weights are the
reaction rates.
Returns a symbolic matrix by default, but will return a numerical matrix if parameter values are specified via pmap.

The difference between this matrix and [`fluxmat`](@ref) is quite subtle. The non-zero entries to both matrices are the rate constants. However:
- In `fluxmat`, the rows represent complexes and columns represent reactions, and an entry (c, r) is non-zero if reaction r's source complex is c.
- In `fluxmat`, the rows represent complexes and columns represent reactions, and an entry (c, r) is non-zero if reaction r's source complex is c.
- In `adjacencymat`, the rows and columns both represent complexes, and an entry (c1, c2) is non-zero if there is a reaction c1 --> c2.
"""
function adjacencymat(rn::ReactionSystem, pmap::Dict = Dict(); sparse = false)
Expand Down Expand Up @@ -1176,8 +1176,8 @@ end
"""
cycles(rs::ReactionSystem)

Returns the matrix of a basis of cycles (or flux vectors), or a basis for reaction fluxes for which the system is at steady state.
These correspond to right eigenvectors of the stoichiometric matrix. Equivalent to [`fluxmodebasis`](@ref).
Returns the matrix of a basis of cycles (or flux vectors), or a basis for reaction fluxes for which the system is at steady state.
These correspond to right eigenvectors of the stoichiometric matrix. Equivalent to [`fluxmodebasis`](@ref).
"""
function cycles(rs::ReactionSystem)
nps = get_networkproperties(rs)
Expand Down Expand Up @@ -1211,7 +1211,7 @@ end
"""
fluxvectors(rs::ReactionSystem)

See documentation for [`cycles`](@ref).
See documentation for [`cycles`](@ref).
"""
function fluxvectors(rs::ReactionSystem)
cycles(rs)
Expand All @@ -1234,10 +1234,10 @@ function satisfiesdeficiencyone(rn::ReactionSystem)
lcs = linkageclasses(rn)
tslcs = terminallinkageclasses(rn)

# Check the conditions for the deficiency one theorem:
# 1) the deficiency of each individual linkage class is at most 1;
# 2) the sum of the linkage deficiencies is the total deficiency, and
# 3) there is only one terminal linkage class per linkage class.
# Check the conditions for the deficiency one theorem:
# 1) the deficiency of each individual linkage class is at most 1;
# 2) the sum of the linkage deficiencies is the total deficiency, and
# 3) there is only one terminal linkage class per linkage class.
all(<=(1), δ_l) && (sum(δ_l) == δ) && (length(lcs) == length(tslcs))
end

Expand All @@ -1256,9 +1256,9 @@ end
"""
robustspecies(rn::ReactionSystem)

Return a vector of indices corresponding to species that are concentration robust, i.e. for every positive equilbrium, the concentration of species s will be the same.
Return a vector of indices corresponding to species that are concentration robust, i.e. for every positive equilbrium, the concentration of species s will be the same.

Note: This function currently only works for networks of deficiency one, and is not currently guaranteed to return *all* the concentration-robust species in the network. Any species returned by the function will be robust, but this may not include all of them. Use with caution. Support for higher deficiency networks and necessary conditions for robustness will be coming in the future.
Note: This function currently only works for networks of deficiency one, and is not currently guaranteed to return *all* the concentration-robust species in the network. Any species returned by the function will be robust, but this may not include all of them. Use with caution. Support for higher deficiency networks and necessary conditions for robustness will be coming in the future.
"""
function robustspecies(rn::ReactionSystem)
complexes, D = reactioncomplexes(rn)
Expand All @@ -1268,28 +1268,28 @@ function robustspecies(rn::ReactionSystem)
error("This algorithm currently only checks for robust species in networks with deficiency one.")
end

# A species is concentration robust in a deficiency one network if there are two non-terminal complexes (i.e. complexes
# belonging to a linkage class that is not terminal) that differ only in species s (i.e. their difference is some
# multiple of s. (A + B, A) differ only in B. (A + 2B, B) differ in both A and B, since A + 2B - B = A + B).
# A species is concentration robust in a deficiency one network if there are two non-terminal complexes (i.e. complexes
# belonging to a linkage class that is not terminal) that differ only in species s (i.e. their difference is some
# multiple of s. (A + B, A) differ only in B. (A + 2B, B) differ in both A and B, since A + 2B - B = A + B).

if !nps.checkedrobust
tslcs = terminallinkageclasses(rn)
Z = complexstoichmat(rn)

# Find the complexes that do not belong to a terminal linkage class
# Find the complexes that do not belong to a terminal linkage class
nonterminal_complexes = deleteat!([1:length(complexes);], vcat(tslcs...))
robust_species = Int64[]

for (c_s, c_p) in Combinatorics.combinations(nonterminal_complexes, 2)
# Check the difference of all the combinations of complexes. The support is the set of indices that are non-zero
# Check the difference of all the combinations of complexes. The support is the set of indices that are non-zero
suppcnt = 0
supp = 0
for i in 1:size(Z, 1)
(Z[i, c_s] != Z[i, c_p]) && (suppcnt += 1; supp = i)
(suppcnt > 1) && break
end

# If the support has length one, then they differ in only one species, and that species is concentration robust.
# If the support has length one, then they differ in only one species, and that species is concentration robust.
(suppcnt == 1) && (supp ∉ robust_species) && push!(robust_species, supp)
end
nps.checkedrobust = true
Expand Down
7 changes: 3 additions & 4 deletions src/reactionsystem_conversions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -394,9 +394,9 @@ function addconstraints!(eqs, rs::ReactionSystem, ists, ispcs; remove_conserved
# add the conservation constants as parameters and set their values
ps = vcat(ps, collect(eq.lhs for eq in nps.constantdefs))
defs = copy(MT.defaults(rs))
for eq in nps.constantdefs
defs[eq.lhs] = eq.rhs
end
# for eq in nps.constantdefs
# defs[eq.lhs] = eq.rhs
# end

# add the dependent species as observed
obs = copy(MT.observed(rs))
Expand Down Expand Up @@ -503,7 +503,6 @@ function Base.convert(::Type{<:ODESystem}, rs::ReactionSystem; name = nameof(rs)
eqs = assemble_drift(fullrs, ispcs; combinatoric_ratelaws, remove_conserved,
include_zero_odes)
eqs, us, ps, obs, defs = addconstraints!(eqs, fullrs, ists, ispcs; remove_conserved)

ODESystem(eqs, get_iv(fullrs), us, ps;
observed = obs,
name,
Expand Down
Loading