Commit 73774a74 authored by Miroslav Kratochvil's avatar Miroslav Kratochvil
Browse files

efficient stoichiometry building from StandardModel

parent 939d677b
Pipeline #45546 passed with stages
in 13 minutes and 2 seconds
......@@ -108,24 +108,39 @@ n_genes(model::StandardModel)::Int = length(model.genes)
Return the stoichiometric matrix associated with `model` in sparse format.
"""
function stoichiometry(model::StandardModel)::SparseMat
S = SparseArrays.spzeros(n_metabolites(model), n_reactions(model))
mets = metabolites(model) # vector of metabolite ids
n_entries = 0
for (_, r) in model.reactions
for _ in r.metabolites
n_entries += 1
end
end
MI = Vector{Int}()
RI = Vector{Int}()
SV = Vector{Float64}()
sizehint!(MI, n_entries)
sizehint!(RI, n_entries)
sizehint!(SV, n_entries)
# establish the ordering
rxns = reactions(model)
for (i, rid) in enumerate(rxns) # column, in order
met_idx = Dict(mid => i for (i, mid) in enumerate(metabolites(model)))
# fill the matrix entries
for (ridx, rid) in enumerate(rxns)
for (mid, coeff) in model.reactions[rid].metabolites
j = findfirst(==(mid), mets) # row
if isnothing(j)
throw(
DomainError(
mid,
"Metabolite $(mid) not found in model but occurs in stoichiometry of $(rid)",
),
)
end
S[j, i] = coeff
haskey(met_idx, mid) || throw(
DomainError(
mid,
"Metabolite $(mid) not found in model but occurs in stoichiometry of $(rid)",
),
)
push!(MI, met_idx[mid])
push!(RI, ridx)
push!(SV, coeff)
end
end
return S
return SparseArrays.sparse(MI, RI, SV, n_metabolites(model), n_reactions(model))
end
"""
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment