Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check new remake version #1186

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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.64"
NetworkLayout = "0.4.7"
Parameters = "0.12"
Reexport = "0.2, 1.0"
Expand Down
93 changes: 47 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 All @@ -877,6 +877,7 @@ function cache_conservationlaw_eqs!(rn::ReactionSystem, N::AbstractMatrix, col_o
nps.depspecs = Set(depspecs)
nps.conservedeqs = conservedeqs
nps.constantdefs = constantdefs
nps.conservedconst = constants

nothing
end
Expand Down Expand Up @@ -922,7 +923,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 +939,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 +948,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 +957,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 +1003,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 +1051,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 +1177,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 +1212,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 +1235,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 +1257,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 +1269,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
2 changes: 2 additions & 0 deletions src/reactionsystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ Base.@kwdef mutable struct NetworkProperties{I <: Integer, V <: BasicSymbolic{Re
depspecs::Set{V} = Set{V}()
conservedeqs::Vector{Equation} = Equation[]
constantdefs::Vector{Equation} = Equation[]
conservedconst::BasicSymbolic{Real} = MT.unwrap(only(@parameters __UNINITIALIZED))
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)
Expand Down Expand Up @@ -126,6 +127,7 @@ function reset!(nps::NetworkProperties{I, V}) where {I, V}
empty!(nps.col_order)
nps.rank = 0
nps.nullity = 0
nps.conservedconst = only(@parameters __UNINITIALIZED)
empty!(nps.indepspecs)
empty!(nps.depspecs)
empty!(nps.conservedeqs)
Expand Down
6 changes: 1 addition & 5 deletions src/reactionsystem_conversions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,8 @@ function addconstraints!(eqs, rs::ReactionSystem, ists, ispcs; remove_conserved
nps = get_networkproperties(rs)

# add the conservation constants as parameters and set their values
ps = vcat(ps, collect(eq.lhs for eq in nps.constantdefs))
ps = push!(ps, nps.conservedconst)
defs = copy(MT.defaults(rs))
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 +500,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