Functions

Base Types

COBREXA._defaultMethod
_default(d::T, x::Maybe{T})::T where {T}

Fold the Maybe{T} down to T by defaulting.

source
COBREXA.AnnotationsType
Annotations = Dict{String,Vector{String}}

Dictionary used to store (possible multiple) standardized annotations of something, such as a Metabolite and a Reaction.

Example

Annotations("PubChem" => ["CID12345", "CID54321"])
source
COBREXA.GeneAssociationType
GeneAssociation = Vector{Vector{String}}

An association to genes, represented as a logical formula in a positive disjunctive normal form (DNF). (The 2nd-level vectors of strings are connected by "and" to form conjunctions, and the 1st-level vectors of these conjunctions are connected by "or" to form the DNF.)

source
COBREXA.MetabolicModelType
abstract type MetabolicModel end

A helper supertype that wraps everything usable as a linear-like model for COBREXA functions.

If you want your model type to work with COBREXA, add the MetabolicModel as its supertype, and implement the accessor functions. Accessors reactions, metabolites, stoichiometry, bounds and objective must be implemented; others are not mandatory and default to safe "empty" values.

source
COBREXA.NotesType
Notes = Dict{String,Vector{String}}

Free-form notes about something (e.g. a Gene), categorized by "topic".

source
COBREXA.balanceMethod
balance(a::MetabolicModel)::SparseVec

Get the sparse balance vector of a model (ie. the b from S x = b).

source
COBREXA.boundsMethod
bounds(a::MetabolicModel)::Tuple{SparseVec,SparseVec}

Get the lower and upper flux bounds of a model.

source
COBREXA.couplingMethod
coupling(a::MetabolicModel)::SparseMat

Get a matrix of coupling constraint definitions of a model. By default, there is no coupling in the models.

source
COBREXA.coupling_boundsMethod
coupling_bounds(a::MetabolicModel)::Tuple{SparseVec,SparseVec}

Get the lower and upper bounds for each coupling bound in a model, as specified by coupling. By default, the model does not have any coupling bounds.

source
COBREXA.gene_annotationsMethod
gene_annotations(a::MetabolicModel, gene_id::String)::Annotations

Return standardized names that identify the corresponding gene or product. The dictionary assigns vectors of possible identifiers to identifier system names, e.g. "PDB" => ["PROT01"].

source
COBREXA.gene_notesMethod
gene_notes(model::MetabolicModel, gene_id::String)::Notes

Return the notes associated with the gene gene_id in model.

source
COBREXA.genesMethod
genes(a::MetabolicModel)::Vector{String}

Return identifiers of all genes contained in the model. By default, there are no genes.

In SBML, these are usually called "gene products" but we write genes for simplicity.

source
COBREXA.metabolite_annotationsMethod
metabolite_annotations(a::MetabolicModel, metabolite_id::String)::Annotations

Return standardized names that may help to reliably identify the metabolite. The dictionary assigns vectors of possible identifiers to identifier system names, e.g. "ChEMBL" => ["123"] or "PubChem" => ["CID123", "CID654645645"].

source
COBREXA.metabolite_chargeMethod

metabolitecharge(model::MetabolicModel, metaboliteid::String)::Maybe{Int}

Return the charge associated with metabolite metabolite_id in model. Returns nothing if charge not present.

source
COBREXA.metabolite_compartmentMethod
metabolite_compartment(model::MetabolicModel, metabolite_id::String)::Maybe{String}

Return the compartment of metabolite metabolite_id in model if it is assigned. If not, return nothing.

source
COBREXA.metabolite_formulaMethod
metabolite_formula(
    a::MetabolicModel,
    metabolite_id::String,
)::Maybe{MetaboliteFormula}

Return the formula of metabolite metabolite_id in model. Return nothing in case the formula is not known or irrelevant.

source
COBREXA.metabolite_notesMethod
metabolite_notes(model::MetabolicModel, metabolite_id::String)::Notes

Return the notes associated with metabolite reaction_id in model.

source
COBREXA.metabolitesMethod
metabolites(a::MetabolicModel)::Vector{String}

Return a vector of metabolite identifiers in a model.

source
COBREXA.n_genesMethod
n_genes(a::MetabolicModel)::Int

Return the number of genes in the model (as returned by genes). If you just need the number of the genes, this may be much more efficient than calling genes and measuring the array.

source
COBREXA.reaction_annotationsMethod
reaction_annotations(a::MetabolicModel, reaction_id::String)::Annotations

Return standardized names that may help identifying the reaction. The dictionary assigns vectors of possible identifiers to identifier system names, e.g. "Reactome" => ["reactomeID123"].

source
COBREXA.reaction_gene_associationMethod
reaction_gene_association(a::MetabolicModel, gene_id::String)::Maybe{GeneAssociation}

Returns the sets of genes that need to be present so that the reaction can work (technically, a DNF on gene availability, with positive atoms only).

For simplicity, nothing may be returned, meaning that the reaction always takes place. (in DNF, that would be equivalent to returning [[]].)

source
COBREXA.reaction_notesMethod
reaction_notes(model::MetabolicModel, reaction_id::String)::Notes

Return the notes associated with reaction reaction_id in model.

source
COBREXA.reaction_subsystemMethod
reaction_subsystem(model::MetabolicModel, reaction_id::String)::Maybe{String}

Return the subsystem of reaction reaction_id in model if it is assigned. If not, return nothing.

source
COBREXA.reactionsMethod
reactions(a::MetabolicModel)::Vector{String}

Return a vector of reaction identifiers in a model.

source

Model types and contents

COBREXA.CoreModelType
struct CoreModel <: MetabolicModel

A "bare bones" core linear optimization problem of the form, with reaction and metabolite names.

min c^T x
s.t. S x = b
      xₗ ≤ x ≤ xᵤ
source
Base.convertMethod
Base.convert(::Type{CoreModel}, m::M) where {M <: MetabolicModel}

Make a CoreModel out of any compatible model type.

source
COBREXA.boundsMethod
bounds(a::CoreModel)::Tuple{SparseVec,SparseVec}

CoreModel flux bounds.

source
COBREXA.CoreModelCoupledType
struct CoreModelCoupled <: MetabolicModel

The linear model with additional coupling constraints in the form

    cₗ ≤ C x ≤ cᵤ
source
Base.convertMethod
Base.convert(::Type{CoreModelCoupled}, mm::MetabolicModel)

Make a CoreModelCoupled out of any compatible model type.

source
COBREXA.couplingMethod
coupling(a::CoreModelCoupled)::SparseMat

Coupling constraint matrix for a CoreModelCoupled.

source
COBREXA.GeneType

Gene struct.

Fields

id :: String
name :: Union{String, Nothing}
notes :: Dict{String, Vector{String}}
annotation :: Dict{String, Union{Vector{String}, String}}
source
COBREXA.JSONModelType
struct JSONModel <: MetabolicModel
    json::Dict{String,Any}
end

A struct used to store the contents of a JSON model, i.e. a model read from a file ending with .json. These model files typically store all the model parameters in arrays of JSON objects (i.e. Julia dictionaries).

Usually, not all of the fields of the input JSON can be easily represented when converting to other models, care should be taken to avoid losing information.

Direct work on this precise model type is not very efficient, as the accessor functions need to repeatedly find the information in the JSON tree. This gets very slow especially if calling many accessor functions sequentially. To avoid that, convert to e.g. StandardModel as soon as possible.

Example

model = load_json_model("some_model.json")
model.json # see the actual underlying JSON
reactions(model) # see the list of reactions
source
COBREXA.boundsMethod
bounds(model::JSONModel)

Get the bounds for reactions, assuming the information is stored in .lower_bound and .upper_bound.

source
COBREXA.objectiveMethod
objective(model::JSONModel)

Collect .objective_coefficient keys from model reactions.

source
COBREXA.reactionsMethod
reactions(model::JSONModel)

Extract reaction names (stored as .id) from JSON model.

source
COBREXA.stoichiometryMethod
stoichiometry(model::JSONModel)

Get the stoichiometry. Assuming the information is stored in reaction object under key .metabolites.

source
COBREXA.MATModelType
struct MATModel

Wrapper around the models loaded in dictionaries from the MATLAB representation.

source
Base.convertMethod
Base.convert(::Type{MATModel}, m::MetabolicModel)

Convert any metabolic model to MATModel.

source
COBREXA.balanceMethod
balance(m::MATModel)

Extracts balance from the MAT model, defaulting to zeroes if not present.

source
COBREXA.boundsMethod
bounds(m::MATModel)

Extracts bounds from the MAT file, saved under lb and ub.

source
COBREXA.coupling_boundsMethod
coupling_bounds(m::MATModel)

Extracts the coupling constraints. Currently, there are several accepted ways to store these in MATLAB models; this takes the constraints from vectors cl and cu.

source
COBREXA.genesMethod
genes(m::MATModel)

Extracts the possible gene list from genes key.

source
COBREXA.metabolitesMethod
metabolites(m::MATModel)::Vector{String}

Extracts metabolite names from mets key in the MAT file.

source
COBREXA.objectiveMethod
objective(m::MATModel)

Extracts the objective from the MAT model (defaults to zeroes).

source
COBREXA.reactionsMethod
reactions(m::MATModel)::Vector{String}

Extracts reaction names from rxns key in the MAT file.

source
COBREXA.MetaboliteType

Metabolite structure.

Fields

id :: String
name :: String
formula :: String
charge :: Int
compartment :: String
notes :: Dict{String, Vector{String}}
annotation :: Dict{String, Union{Vector{String}, String}}
source
COBREXA.ReactionType

Reaction struct.

Fields

id :: String
name :: String
metabolites :: Dict{Metabolite, Float64}
lb :: Float64
ub :: Float64
grr :: Vector{Vector{Gene}}
subsystem :: String
notes :: Dict{String, Vector{String}}
annotation :: Dict{String, Union{Vector{String}, String}}
objective_coefficient :: Float64
source
COBREXA.SBMLModelType
struct SBMLModel

Thin wrapper around the model from SBML.jl library. Allows easy conversion from SBML to any other model format.

source
COBREXA.boundsMethod
bounds(model::SBMLModel)::Tuple{SparseVec,SparseVec}

Get the lower and upper flux bounds of model SBMLModel. Throws DomainError in case if the SBML contains mismatching units.

source
COBREXA.StandardModelType
mutable struct StandardModel

StandardModel is used to store a constraint based metabolic model with meta-information. Meta-information is defined as annotation details, which include gene-reaction-rules, formulas, etc.

This model type seeks to keep as much meta-information as possible, as opposed to CoreModel and CoreModelCoupled, which keep the bare neccessities only. When merging models and keeping meta-information is important, use this as the model type. If meta-information is not important, use the more efficient core model types. See CoreModel and CoreModelCoupled for comparison.

In this model, reactions, metabolites, and genes are stored in ordered dictionaries indexed by each struct's id field. For example, model.reactions["rxn1_id"] returns a Reaction where the field id equals "rxn1_id". This makes adding and removing reactions efficient.

Note that the stoichiometric matrix (or any other core data, e.g. flux bounds) is not stored directly as in CoreModel. When this model type is used in analysis functions, these core data structures are built from scratch each time an analysis function is called. This can cause performance issues if you run many small analysis functions sequentially. Consider using the core model types if performance is critical.

See also: Reaction, Metabolite, Gene

Fields

id :: String
reactions :: OrderedDict{String, Reaction}
metabolites :: OrderedDict{String, Metabolite}
genes :: OrderedDict{String, Gene}

Example

model = load_model(StandardModel, "model_location")
source
Base.convertMethod

Base.convert(::Type{StandardModel}, model::MetabolicModel)

Convert any MetabolicModel into a StandardModel. Note, some data loss may occur since only the generic interface is used during the conversion process.

source
COBREXA.balanceMethod
balance(model::StandardModel)

Return the balance of the linear problem, i.e. b in Sv = 0 where S is the stoichiometric matrix and v is the flux vector.

source
COBREXA.boundsMethod
bounds(model::StandardModel)

Return the lower and upper bounds, respectively, for reactions in model. Order matches that of the reaction ids returned in reactions().

source
COBREXA.gene_annotationsMethod
gene_annotations(model::StandardModel, id::String)::Annotations

Return the annotation associated with gene id in model. Return an empty Dict if not present.

source
COBREXA.gene_notesMethod
gene_notes(model::StandardModel, id::String)::Notes

Return the notes associated with gene id in model. Return an empty Dict if not present.

source
COBREXA.genesMethod
genes(model::StandardModel)

Return a vector of gene id strings in model.

source
COBREXA.lower_boundsMethod
lower_bounds(model::StandardModel)

Return the lower bounds for all reactions in model in sparse format.

source
COBREXA.metabolite_annotationsMethod
metabolite_annotations(model::StandardModel, id::String)::Annotations

Return the annotation associated with metabolite id in model. Return an empty Dict if not present.

source
COBREXA.metabolite_chargeMethod
metabolite_charge(model::StandardModel, id::String)

Return the charge associated with metabolite id in model. Return nothing if not present.

source
COBREXA.metabolite_compartmentMethod
metabolite_compartment(model::StandardModel, id::String)

Return compartment associated with metabolite id in model. Return nothing if not present.

source
COBREXA.metabolite_formulaMethod
metabolite_formula(model::StandardModel, id::String)

Return the formula of reaction id in model. Return nothing if not present.

source
COBREXA.metabolite_notesMethod
metabolite_notes(model::StandardModel, id::String)::Notes

Return the notes associated with metabolite id in model. Return an empty Dict if not present.

source
COBREXA.metabolitesMethod
metabolites(model::StandardModel)

Return a vector of metabolite id strings contained in model. The order of metabolite strings returned here matches the order used to construct the stoichiometric matrix.

source
COBREXA.reaction_annotationsMethod
reaction_annotations(model::StandardModel, id::String)::Annotations

Return the annotation associated with reaction id in model. Return an empty Dict if not present.

source
COBREXA.reaction_gene_associationMethod
reaction_gene_association(model::StandardModel, id::String)

Return the gene reaction rule in string format for reaction with id in model. Return nothing if not available.

source
COBREXA.reaction_notesMethod
reaction_notes(model::StandardModel, id::String)::Notes

Return the notes associated with reaction id in model. Return an empty Dict if not present.

source
COBREXA.reaction_subsystemMethod
reaction_subsystem(id::String, model::StandardModel)

Return the subsystem associated with reaction id in model. Return nothing if not present.

source
COBREXA.reactionsMethod
reactions(model::StandardModel)

Return a vector of reaction id strings contained in model. The order of reaction ids returned here matches the order used to construct the stoichiometric matrix.

source
COBREXA.stoichiometryMethod
stoichiometry(model::StandardModel)

Return the stoichiometric matrix associated with model in sparse format.

source
COBREXA.upper_boundsMethod
upper_bounds(model::StandardModel)

Return the upper bounds for all reactions in model in sparse format. Order matches that of the reaction ids returned in reactions().

source

Base functions

COBREXA._constantsConstant

A named tuple that contains the magic values that are used globally for whatever purposes.

source
COBREXA.is_solvedMethod
is_solved(optmodel)

Return true if optmodel solved successfully (solution is optimal or locally optimal). Return false if any other termination status is reached. Termination status is defined in the documentation of JuMP.

source
COBREXA.make_optimization_modelMethod
make_optimization_model(
    model::MetabolicModel,
    optimizer;
    sense = MOI.MAX_SENSE,
)

Convert MetabolicModels to a JuMP model, place objectives and the equality constraint.

source
COBREXA.optimize_modelMethod
optimize_model(
    model::MetabolicModel,
    optimizer;
    sense = MOI.MIN_SENSE,
)

Use JuMP to solve an instance of CoreModel

source

File I/O and serialization

COBREXA.load_modelMethod
load_model(file_name::String)::MetabolicModel

Generic function for loading models that chooses a specific loader function from the file_name extension, or throws an error.

Currently, these model types are supported:

source
COBREXA.load_modelMethod
load_model(type::Type{T}, file_name::String)::T where T

Helper function tht loads the model using load_model and return it converted to type.

Example:

load_model(CoreModel, "mySBMLModel.xml")
source
COBREXA.save_modelMethod
save_model(model::MetabolicModel, file_name::String)

Generic function for saving models that chooses a specific writer function from the file_name extension, or throws an error.

Currently, these model types are supported:

source
COBREXA.load_json_modelMethod
load_json_model(filename::String)::JSONModel

Load and return a JSON-formatted model that is stored in file_name.

source
COBREXA.save_json_modelMethod
save_json_model(model::MetabolicModel, file_name::String)

Save a JSONModel in model to a JSON file file_name.

In case the model is not JSONModel, it will be converted automatically.

source
COBREXA.load_mat_modelMethod
load_mat_model(file_name::String)

Load and return a MATLAB file file_name that contains a COBRA-compatible model.

source
COBREXA.save_mat_modelMethod
save_mat_model(model::MetabolicModel, file_name::String; model_name::String="model")

Save a MATModel in model to a MATLAB file file_name in a format compatible with other MATLAB-based COBRA software.

In case the model is not MATModel, it will be converted automatically.

model_name is the identifier name for the whole model written to the MATLAB file; defaults to just "model".

source

Pretty printing

Base.showMethod

Pretty printing of everything metabolic-modelish.

source

Model reconstruction

COBREXA.find_exchange_metabolitesMethod

Returns indices of exchanged metabolites, ie, the outermost metabolites in the network In practice returns the metabolites consumed by the reactions given by find_exchange_reactions and if called with the same arguments, the two outputs correspond.

source
COBREXA.add_coupling_constraintsMethod

Add constraints of the following form to a CoreModelCoupled and return a modified one.

The arguments are same as for in-place add_coupling_constraints!.

source
COBREXA.remove_coupling_constraintsMethod

Remove coupling constraints from the linear model and return the modified model.

Arguments are the same as for in-place version remove_coupling_constraints!.

source
COBREXA.:⟵Method
⟵(
    substrates::Union{
        Nothing,
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient},
    },
    products::Union{
        Nothing,
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient}
    },
)

Make a reverse-only Reaction from substrates and products. An equivalent alternative is .

source
COBREXA.:⟶Method
⟶(
    substrates::Union{
        Nothing,
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient},
    },
    products::Union{
        Nothing, 
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient}
    },
)

Make a forward-only Reaction from substrates and products. An equivalent alternative is .

source
COBREXA.:⟷Method
⟷(
    substrates::Union{
        Nothing,
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient},
    },
    products::Union{
        Nothing,
        Metabolite,
        MetaboliteWithCoefficient,
        Vector{MetaboliteWithCoefficient}
    },
)

Make a bidirectional (reversible) Reaction from substrates and products. An equivalent alternative is .

source
COBREXA.add!Method
add!(model::StandardModel, genes::Union{Vector{Gene}, Gene})

Add gene(s) to model if they are not already present based on gene id.

source
COBREXA.add!Method
add!(model::StandardModel, mets::Union{Vector{Metabolite}, Metabolite})

Add met(s) to model if they are not already present, based on metabolite id.

source
COBREXA.add!Method
add!(model::StandardModel, rxns::Union{Vector{Reaction}, Reaction})

Add rxn(s) to model if they are not already present based on reaction id.

source
COBREXA.rm!Method
rm!(::Type{Gene}, model::StandardModel, ids::Vector{String})

Remove all genes with ids from model.

Example

rm!(Gene, model, ["g1", "g2"]) rm!(Gene, model, "g1")

source
COBREXA.rm!Method
rm!(::Type{Metabolite}, model::StandardModel, ids::Vector{String})

Remove all metabolites with ids from model. Warning, this could leave the model inconsistent, e.g. a reaction might require the deleted metabolite.

Example

rm!(Metabolite, model, ["atpc", "adpc"]) rm!(Metabolite, model, "atp_c")

source
COBREXA.rm!Method
rm!(::Type{Reaction}, model::StandardModel, ids::Vector{String})

Remove all reactions with ids from model.

Example

rm!(Reaction, model, ["EXglc__De", "fba"]) rm!(Reaction, model, "EXglc__De")

source
COBREXA.@add_reactions!Macro
@add_reactions!(model::Symbol, ex::Expr)

Shortcut to add multiple reactions and their lower and upper bounds

Call variants

@add_reactions! model begin
    reaction_name, reaction
end

@add_reactions! model begin
    reaction_name, reaction, lower_bound
end

@add_reactions! model begin
    reaction_name, reaction, lower_bound, upper_bound
end

Examples

@add_reactions! model begin
    "v1", nothing ⟶ A, 0, 500
    "v2", A ⟷ B + C, -500
    "v3", B + C ⟶ nothing
end
source

Analysis functions

COBREXA.flux_balance_analysisMethod
flux_balance_analysis(
    model::M,
    optimizer;
    modifications = [],
) where {M<:MetabolicModel}

Run flux balance analysis (FBA) on the model optionally specifying modifications to the problem. Basically, FBA solves this optimization problem:

max cᵀx
s.t. S x = b
     xₗ ≤ x ≤ xᵤ

See "Orth, J., Thiele, I. & Palsson, B. What is flux balance analysis?. Nat Biotechnol 28, 245–248 (2010). https://doi.org/10.1038/nbt.1614" for more information.

The optimizer must be set to a JuMP-compatible optimizer, such as GLPK.Optimizer or Tulip.Optimizer

Optionally, you may specify one or more modifications to be applied to the model before the analysis, such as change_optimizer_attribute,change_objective, and change_sense.

Returns an optimized JuMP model.

Example

model = load_model(StandardModel, "e_coli_core.json")
biomass = findfirst(model.reactions, "BIOMASS_Ecoli_core_w_GAM")
solution = flux_balance_analysis(model, GLPK.optimizer; modifications=[change_objective(biomass)])
source
COBREXA._FVA_add_constraintMethod
_FVA_add_constraint(model, c, x, Z)

Internal helper function for adding constraints to a model. Exists mainly because for avoiding namespace problems on remote workers.

source
COBREXA.flux_variability_analysisMethod
flux_variability_analysis(
    model::MetabolicModel,
    reactions::Vector{Int},
    optimizer;
    modifications = [],
    workers = [myid()],
    bounds = z -> (z,z),
    ret = objective_value,
)::Matrix{Float64}

Flux variability analysis solves a pair of optimization problems in model for each flux listed in reactions:

 min,max xᵢ
s.t. S x = b
    xₗ ≤ x ≤ xᵤ
     cᵀx ≥ bounds(Z₀)[1]
     cᵀx ≤ bounds(Z₀)[2]

where Z₀:= cᵀx₀ is the objective value of an optimal solution of the associated FBA problem (see flux_balance_analysis). See "Gudmundsson, S., Thiele, I. Computationally efficient flux variability analysis. BMC Bioinformatics 11, 489 (2010). https://doi.org/10.1186/1471-2105-11-489" for more information.

The bounds is a user-supplied function that specifies the objective bounds for the variability optimizations, by default it restricts the flux objective value to the precise optimum reached in FBA. It can return -Inf and Inf in first and second pair to remove the limit. Use gamma_bounds and objective_bounds for simple bounds.

optimizer must be set to a JuMP-compatible optimizer. The computation of the individual optimization problems is transparently distributed to workers (see Distributed.workers()).

ret is a function used to extract results from optimized JuMP models of the individual reactions. More detailed information can be extracted e.g. by setting it to m -> (JuMP.objective_value(m), JuMP.value.(m[:x])).

Returns a matrix of extracted ret values for minima and maxima, of total size length(reactions)×2. The optimizer result status is not checked by default, instead ret function can access the JuMP.termination_status of the model and react accordingly, depending on user decision.

source
COBREXA.parsimonious_flux_balance_analysisMethod
parsimonious_flux_balance_analysis(
    model::MetabolicModel,
    optimizer;
    modifications = [],
    qp_modifications = [],
    relax_bounds=[1.0, 0.999999, 0.99999, 0.9999, 0.999, 0.99],
)

Run parsimonious flux balance analysis (pFBA) on the model. In short, pFBA runs two consecutive optimization problems. The first is traditional FBA:

max cᵀx = μ
s.t. S x = b
     xₗ ≤ x ≤ xᵤ

And the second is a quadratic optimization problem:

min Σᵢ xᵢ²
s.t. S x = b
     xₗ ≤ x ≤ xᵤ
     μ = μ⁰

Where the optimal solution of the FBA problem, μ⁰, has been added as an additional constraint. See "Lewis, Nathan E, Hixson, Kim K, Conrad, Tom M, Lerman, Joshua A, Charusanti, Pep, Polpitiya, Ashoka D, Adkins, Joshua N, Schramm, Gunnar, Purvine, Samuel O, Lopez‐Ferrer, Daniel, Weitz, Karl K, Eils, Roland, König, Rainer, Smith, Richard D, Palsson, Bernhard Ø, (2010) Omic data from evolved E. coli are consistent with computed optimal growth from genome‐scale models. Molecular Systems Biology, 6. 390. doi: accession:10.1038/msb.2010.47" for more details.

pFBA gets the model optimum by standard FBA (using flux_balance_analysis with optimizer and modifications), then finds a minimal total flux through the model that still satisfies the (slightly relaxed) optimum. This is done using a quadratic problem optimizer. If the original optimizer does not support quadratic optimization, it can be changed using the callback in qp_modifications, which are applied after the FBA.

Thhe optimum relaxation sequence can be specified in relax parameter, it defaults to multiplicative range of [1.0, 0.999999, ..., 0.99] of the original bound.

Returns an optimized model that contains the pFBA solution; or nothing if the optimization failed.

Example

optimizer = Gurobi.Optimizer
atts = Dict("OutputFlag" => 0)
model = load_model(StandardModel, "iJO1366.json")
biomass = findfirst(model.reactions, "BIOMASS_Ec_iJO1366_WT_53p95M")
sol = pfba(model, biomass, Gurobi.optimizer)
source

Analysis modifications

COBREXA._do_knockoutMethod
_do_knockout(model::MetabolicModel, opt_model)

Internal helper for knockouts on generic MetabolicModels. This can be overloaded so that the knockouts may work differently (more efficiently) with other models.

source
COBREXA.knockoutMethod
knockout(gene_ids::Vector{String})

A modification that zeroes the bounds of all reactions that would be knocked out by the specified genes (effectively disables the reactions).

source
COBREXA.change_objectiveMethod
change_objective(new_objective::Union{String,Vector{String}}; weights=[], sense=MOI.MAX_SENSE)

Modification that changes the objective function used in a constraint based analysis function. new_objective can be a single reaction identifier, or an array of reactions identifiers.

Optionally, the objective can be weighted by a vector of weights, and a optimization sense can be set.

source
COBREXA.change_optimizer_attributeMethod
change_optimizer_attribute(attribute_key, value)

Change a JuMP optimizer attribute. The attributes are optimizer-specific, refer to the JuMP documentation and the documentation of the specific optimizer for usable keys and values.

source
COBREXA.change_senseMethod
change_sense(objective_sense)

Change the objective sense of optimization. Possible arguments are MOI.MAX_SENSE and MOI.MIN_SENSE.

If you want to change the objective and sense at the same time, use change_objective instead to do both at once.

source

Flux sampling

COBREXA.hit_and_runMethod
hit_and_run(
    N::Int,
    opt_model;
    keepevery = 100,
    samplesize = 1000,
    random_objective = false,
)

Perform a basic hit and run sampling for N iterations on a constrained JuMP model in opt_model. See "Robert L. Smith Efficient Monte Carlo Procedures for Generating Points Uniformly Distributed over Bounded Regions. Operations Research 32 (6) 1296-1308 https://doi.org/10.1287/opre.32.6.1296" for more details.

The process generates samplesize samples, and logs the sample state each keepevery iterations.

Warm up points are generated by minimizing and maximizing reactions as in flux_variability_analysis, unless the random_objective is true, in which case a randomly weighted objective is used for warmup.

Note that N needs to be greater than sample size, and should be greater than the dimensionality of the sampled space (i.e., at least same as the number of reactions).

Example

using COBREXA
using JuMP
using Tulip

model = load_model(StandardModel, "e_coli_core.json")
biomass = findfirst(model.reactions, "BIOMASS_Ecoli_core_w_GAM")
glucose = findfirst(model.reactions, "EX_glc__D_e")

opt_model = flux_balance_analysis(model, Tulip.Optimizer; 
    modifications=[change_objective(biomass), 
    modify_constraint(glucose, -12, -12), 
    change_optimizer_attribute("IPM_IterationsLimit", 500)])

biomass_index = model[biomass]
λ = JuMP.value(opt_model[:x][biomass_index])
modify_constraint(biomass, 0.99*λ, λ)(model, opt_model)

samples = hit_and_run(100_000, opt_model; keepevery=10, samplesize=5000)
source
COBREXA._get_warmup_pointsMethod
_get_warmup_points(cbm; random_objective=false, numstop=Inf)

Generate warmup points for all reactions in the model that are not fixed. Assumes that the input JuMP model in cbm is already constrained.

The warmup points are sampled randomly from all possibilities until numstop is reached; by default all points are generated.

By default, the warmup points are generated as in FVA by minimizing and maximizing all reactions; random_objective switches this to completely random objectives.

source

Miscellaneous utilities

COBREXA.ambiguously_identified_itemsMethod
ambiguously_identified_items(
    index::Dict{String,Dict{String,[String]}},
)::Vector{String}

Find items (genes, metabolites, ...) from the annotation index that are identified non-uniquely by at least one of their annotations.

This often indicates that the items are duplicate or miscategorized.

source
COBREXA.annotation_indexMethod
annotation_index(
    xs::AbstractDict{String};
    annotations = _annotations,
)::Dict{String,Dict{String,[String]}}

Extract annotations from a dictionary of items xs and build an index that maps annotation "kinds" (e.g. "PubChem") to the mapping from the annotations (e.g. "COMPOUND_12345") to item IDs that carry the annotations.

Function annotations is used to access the Annotations object in the dictionary values.

This is extremely useful for finding items by annotation data.

source
COBREXA.get_atomsMethod
get_atoms(met::Metabolite)::MetaboliteFormula

Simple wrapper for getting the atom dictionary count out of a Metabolite.

source
COBREXA.check_duplicate_reactionMethod
check_duplicate_reaction(rxn::Reaction, rxns::Dict{String, Reaction}; only_metabolites=true)

Check if rxn already exists in rxns but has another id. If only_metabolites is true then only the metabolite ids are checked. Otherwise, compares metabolite ids and the absolute value of their stoichiometric coefficients to those of rxn. If rxn has the same reaction equation as another reaction in rxns, the return the id. Otherwise return nothing.

See also: is_mass_balanced

source
COBREXA.is_boundaryMethod
is_boundary(rxn::Reaction)

Return true if reaction is a boundary reaction, otherwise return false. Checks if boundary by inspecting number of metabolites in reaction equation. Boundary reactions have only one metabolite, e.g. an exchange reaction, or a sink/demand reaction.

source
COBREXA.atom_exchangeMethod
atom_exchange(flux_dict::Dict{String, Float64}, model::StandardModel)

Return a dictionary mapping the flux of atoms across the boundary of the model given flux_dict (the solution of a constraint based analysis) of reactions in model.

source
COBREXA.exchange_reactionsMethod
get_exchanges(flux_dict::Dict{String, Float64}; top_n=Inf, ignorebound=_constants.default_reaction_bound, verbose=true)

Display the top_n producing and consuming exchange fluxes. If top_n is not specified (by an integer), then all are displayed. Ignores infinite (problem upper/lower bound) fluxes (set with ignorebound). When verbose is false, the output is not printed out. Return these reactions (id => ) in two dictionaries: consuming, producing

source
COBREXA.metabolite_fluxesMethod
metabolite_fluxes(flux_dict::Dict{String, Float64}, model::StandardModel)

Return two dictionaries of metabolite ids mapped to reactions that consume or produce them given the flux distribution supplied in fluxdict.

source
COBREXA.set_boundMethod
set_bound(index, optimization_model;
    ub=_constants.default_reaction_rate,
    lb=-_constants.default_reaction_rate)

Helper function to set the bounds of variables. The JuMP set_normalized_rhs function is a little confusing, so this function simplifies setting constraints. In short, JuMP uses a normalized right hand side representation of constraints, which means that lower bounds have their sign flipped. This function does this for you, so you don't have to remember to do this whenever you change the constraints.

Just supply the constraint index and the JuMP model (opt_model) that will be solved, and the variable's bounds will be set to ub and lb.

source
COBREXA.gamma_boundsMethod
gamma_bounds(gamma)

A bounds-generating function for flux_variability_analysis that limits the objective value to be at least gamma*Z₀, as usual in COBRA packages. Use as the bounds argument:

flux_variability_analysis(model, some_optimizer; bounds = gamma_bounds(0.9))
source
COBREXA._parse_grrMethod
_parse_grr(gpa::SBML.GeneProductAssociation)::GeneAssociation

Parse SBML.GeneProductAssociation structure to the simpler GeneAssociation. The input must be (implicitly) in a positive DNF.

source
COBREXA._parse_grrMethod
_parse_grr(s::String)::GeneAssociation

Parse a DNF gene association rule in format (YIL010W and YLR043C) or (YIL010W and YGR209C) to GeneAssociation. Also acceptsOR,|,||,AND,&, and&&`.

Example

julia> _parse_grr("(YIL010W and YLR043C) or (YIL010W and YGR209C)")
2-element Array{Array{String,1},1}:
 ["YIL010W", "YLR043C"]
 ["YIL010W", "YGR209C"]
source
COBREXA._unparse_grrMethod
_unparse_grr(
    ::Type{SBML.GeneProductAssociation},
    x::GeneAssociation,
)::SBML.GeneAssociation

Convert a GeneAssociation to the corresponding SBML.jl structure.

source
COBREXA._unparse_grrMethod
unparse_grr(grr::Vector{Vector{Gene}}

Converts a nested string gene reaction array back into a gene reaction rule string.

Example

julia> _unparse_grr(String, [["YIL010W", "YLR043C"], ["YIL010W", "YGR209C"]])
"(YIL010W and YLR043C) or (YIL010W and YGR209C)"
source
COBREXA._guesskeyMethod
_guesskey(ks, possibilities)

Unfortunately, many model types that contain dictionares do not have standardized field names, so we need to try a few possibilities and guess the best one. The keys used to look for valid field names should be ideally specified as constants in src/base/constants.jl.

source

Logging and debugging helpers

COBREXA.log_ioFunction
log_io(enable::Bool=true)

Enable (default) or disable (by passing false) output of messages and warnings from model input/output.

source
COBREXA.log_modelsFunction
log_models(enable::Bool=true)

Enable (default) or disable (by passing false) output of model-related messages.

source
COBREXA.log_perfFunction
log_perf(enable::Bool=true)

Enable (default) or disable (by passing false) output of performance-related tracing information.

source
COBREXA.@_make_logging_tagMacro
macro _make_logging_group(sym::Symbol, doc::String)

This creates a group of functions that allow masking out topic-related logging actions. A call that goes as follows:

@_make_logging_tag XYZ

creates the following tools:

  • global variable _XYZ_log_enabled defaulted to false
  • function log_XYZ that can be called to turn the logging on/off
  • a masking macro @_XYZ_log that can be prepended to commands that should only happen if the logging of tag XYZ is enabled.

The masking macro is then used as follows:

@_XYZ_log @info "This is the extra verbose information you wanted!" a b c

The user can direct logging with these:

log_XYZ()
log_XYZ(false)

doc should be a name of the stuff that is being printed if the corresponding log_XYZ() is enabled – it is used to create a friendly documentation for the logging switch. In this case it could say "X, Y and Z-related messages".

source