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.precache!Method
precache!(a::MetabolicModel)::Nothing

Do whatever is feasible to get the model into a state that can be read from as-quickly-as-possible. This may include e.g. generating helper index structures and loading delayed parts of the model from disk. The model should be modified "transparently" in-place. Analysis functions call this right before applying modifications or converting the model to the optimization model using make_optimization_model; usually on the same machine where the optimizers (and, generally, the core analysis algorithms) will run. The calls are done in a good hope that the performance will be improved.

By default, it should be safe to do nothing.

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_stoichiometryMethod
reaction_stoichiometry(model::MetaboliteModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

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.reaction_stoichiometryMethod
reaction_stoichiometry(model::CoreModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_ind in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

source
COBREXA.reaction_stoichiometryMethod
reaction_stoichiometry(model::CoreModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

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.reaction_stoichiometryMethod
reaction_stoichiometry(model::CoreModelCoupled, rxn_ind::Int)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_ind in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

source
COBREXA.reaction_stoichiometryMethod
reaction_stoichiometry(model::CoreModelCoupled, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

source
COBREXA.FluxSummaryType
FluxSummary

A struct used to store summary information about the solution of a constraint based analysis result.

source
COBREXA.flux_summaryMethod
flux_summary(flux_result::Dict{String, Float64};
            exclude_exchanges = false,
            exchange_prefixes = _constants.exchange_prefixes,
            biomass_strings = _constants.biomass_strings,
            exclude_biomass = false,
            small_flux_bound = 1.0/_constants.default_reaction_bound^2,
            large_flux_bound = _constants.default_reaction_bound,
            keep_unbounded = false,
            )::FluxSummary

Summarize a dictionary of fluxes into small, useful representation of the most important information contained. Useful for pretty-printing and quickly exploring the results. Internally this function uses looks_like_biomass_reaction and looks_like_exchange_reaction. The corresponding keyword arguments passed to these functions. Use this if your model has non-standard ids for reactions. Fluxes smaller than small_flux_bound are not stored, while fluxes larger than large_flux_bound are only stored if keep_unbounded is true.

Example

julia> sol = flux_balance_analysis_dict(model, Tulip.Optimizer)
julia> fr = flux_summary(sol)
Biomass:
  BIOMASS_Ecoli_core_w_GAM: 0.8739
Import:
  EX_o2_e:     -21.7995
  EX_glc__D_e: -10.0
  EX_nh4_e:    -4.7653
  EX_pi_e:     -3.2149
Export:
  EX_h_e:      17.5309
  EX_co2_e:    22.8098
  EX_h2o_e:    29.1758
source
COBREXA.flux_variability_summaryMethod
flux_variability_summary(flux_result::Tuple{Dict{String, Dict{String, Float64}}, Dict{String, Dict{String, Float64}}};
    exclude_exchanges = false,
    exchange_prefixes = _constants.exchange_prefixes,
    biomass_strings = _constants.biomass_strings,
    exclude_biomass = false,
    )::FluxVariabilitySummary

Summarize a dictionary of flux dictionaries obtained eg. from fluxvariabilityanalysisdict. The simplified summary representation is useful for pretty-printing and easily showing the most important results. Internally this function uses [`lookslikebiomassreaction](@ref) and [lookslikeexchange_reaction`](@ref). The corresponding keyword arguments passed to these functions. Use this if your model has non-standard ids for reactions.

Example

julia> sol = flux_variability_analysis_dict(model, Gurobi.Optimizer; bounds = objective_bounds(0.99))
julia> flux_res = flux_variability_summary(sol)
Biomass                     Lower bound   Upper bound
  BIOMASS_Ecoli_core_w_GAM: 0.8652        0.8652
Exchange
  EX_h2o_e:                 28.34         28.34
  EX_co2_e:                 22.0377       22.0377
  EX_o2_e:                  -22.1815      -22.1815
  EX_h_e:                   17.3556       17.3556
  EX_glc__D_e:              -10.0         -10.0
  EX_nh4_e:                 -4.8448       -4.8448
  EX_pi_e:                  -3.2149       -3.2149
  EX_for_e:                 0.0           0.0
  ...                       ...           ...
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.reaction_stoichiometryMethod
reaction_stoichiometry(model::JSONModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

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.reaction_stoichiometryMethod
reaction_stoichiometry(model::MATModel, rxn_index)::Dict{String, Float64}

Return the reaction equation of reaction with index rxn_index in model. The reaction equation maps metabolite ids to their stoichiometric coefficients. Note, rxn_index can be any suitable type that can index into an array.

source
COBREXA.reaction_stoichiometryMethod
reaction_stoichiometry(model::MATModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

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
mutable struct Reaction
    id::String
    name::Maybe{String}
    metabolites::Dict{String,Float64}
    lb::Float64
    ub::Float64
    grr::Maybe{GeneAssociation}
    subsystem::Maybe{String}
    notes::Notes
    annotations::Annotations
    objective_coefficient::Float64
end

A structure for representing a single reaction in a StandardModel.

source
COBREXA.ReactionType
Reaction(
    id = "";
    name = nothing,
    metabolites = Dict{String,Float64}(),
    lb = -_constants.default_reaction_bound,
    ub = _constants.default_reaction_bound,
    grr = nothing,
    subsystem = nothing,
    notes = Notes(),
    annotations = Annotations(),
    objective_coefficient = 0.0,
)

A constructor for Reaction that only takes a reaction id and assigns default/uninformative values to all the fields that are not explicitely assigned.

source
COBREXA.ReactionType
Reaction(
    id::String,
    metabolites::Dict{String,Union{Int, Float64}},
    dir = :bidirectional;
    default_bound = _constants.default_reaction_bound,
)

Convenience constructor for Reaction. The reaction equation is specified using metabolites, which is a dictionary mapping metabolite ids to stoichiometric coefficients. The direcion of the reaction is set through dir which can take :bidirectional, :forward, and :reverse as values. Finally, the default_bound is the value taken to mean infinity in the context of constraint based models, often this is set to a very high flux value like 1000.

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.reaction_stoichiometryMethod
reaction_stoichiometry(model::SBMLModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

source
COBREXA.SerializedType
mutable struct Serialized{M <: MetabolicModel}
    m::Maybe{M}
    filename::String
end

A meta-model that represents a model that is serialized on the disk. The internal model will be loaded on-demand by using any accessor, or by calling precache! directly.

source
COBREXA.precache!Method
precache!(model::Serialized{MetabolicModel})::Nothing

Load the Serialized model from disk in case it's not alreadly loaded.

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_stoichiometryMethod
reaction_stoichiometry(model::StandardModel, rxn_id::String)::Dict{String, Float64}

Return the reaction equation of reaction with id rxn_id in model. The reaction equation maps metabolite ids to their stoichiometric coefficients.

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
COBREXA.set_optmodel_bound!Method
set_optmodel_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

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
Base.showMethod
Base.show(io::IO, ::MIME"text/plain", m::Serialized{M}) where {M}

Show the Serialized model without unnecessarily loading it.

source

Model reconstruction

COBREXA.add_reactionsMethod
add_reactions(m1::CoreModel, m2::CoreModel; check_consistency = false)

Add all reactions from m2 to m1.

source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModel,
    s::V1,
    b::V2,
    c::AbstractFloat,
    xl::AbstractFloat,
    xu::AbstractFloat,
    rxn::String,
    mets::K;
    check_consistency = false,
) where {V1<:VecType,V2<:VecType,K<:StringVecType}
source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModel,
    Sp::M,
    b::V,
    c::V,
    xl::V,
    xu::V,
    rxns::K,
    mets::K;
    check_consistency = false,
) where {M<:MatType,V<:VecType,K<:StringVecType}
source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModel,
    s::V1,
    b::V2,
    c::AbstractFloat,
    xl::AbstractFloat,
    xu::AbstractFloat;
    check_consistency = false,
) where {V1<:VecType,V2<:VecType}

Add reaction(s) to a CoreModel model m.

source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModel,
    Sp::M,
    b::V,
    c::V,
    xl::V,
    xu::V;
    check_consistency = false,
) where {M<:MatType,V<:VecType}
source
COBREXA.remove_metabolitesMethod
remove_metabolites(model::CoreModel, metabolites)

Removes a set of metabolites from the model of type CoreModel and returns a new CoreModel without those metabolites. Here, metabolites can be either a string, a vector of strings, an index or a vector of indices. Also removes any reactions that have no associated metabolites after the metabolites have been removed.

Example

model = load_model(CoreModel, "e_coli_core.json")

m1 = remove_metabolites(model, ["glc__D_e", "for_c"])
m2 = remove_metabolites(model, "glc__D_e")
m3 = remove_metabolites(model, indexin(["glc__D_e", "for_c"], metabolites(model)))
m4 = remove_metabolites(model, first(indexin(["glc__D_e"], metabolites(model))))
source
COBREXA.remove_reactionsMethod
remove_reactions(m::CoreModel, rxns::Vector{Int})

Removes a set of reactions from a CoreModel. Also removes the metabolites not involved in any reaction.

source
COBREXA.verify_consistencyMethod
verify_consistency(
    m::CoreModel,
    Sp::M,
    b::V,
    c::V,
    xl::V,
    xu::V,
    names::K,
    mets::K,
    new_reactions,
    new_metabolites,
) where {M<:MatType,V<:VecType,K<:StringVecType}

Check the consistency of given reactions with existing reactions in m.

TODO: work in progress, doesn't return consistency status.

source
COBREXA.add_coupling_constraints!Method
add_coupling_constraints!(
    m::CoreModelCoupled,
    c::VecType,
    cl::AbstractFloat,
    cu::AbstractFloat,
)

Overload for adding a single coupling constraint.

source
COBREXA.add_coupling_constraints!Method
add_coupling_constraints!(
    m::CoreModelCoupled,
    C::MatType,
    cl::V,
    cu::V,
) where {V<:VecType}

In-place add a single coupling constraint in form

    cₗ ≤ C x ≤ cᵤ
source
COBREXA.add_reactionsMethod
add_reactions(m1::CoreModelCoupled, m2::CoreModel; check_consistency = false)

Add all reactions from m2 to m1.

source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModelCoupled,
    s::V1,
    b::V2,
    c::AbstractFloat,
    xl::AbstractFloat,
    xu::AbstractFloat,
    rxn::String,
    mets::K;
    check_consistency = false,
) where {V1<:VecType,V2<:VecType,K<:StringVecType}
source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModelCoupled,
    Sp::M,
    b::V,
    c::V,
    xl::V,
    xu::V,
    rxns::K,
    mets::K;
    check_consistency = false,
) where {M<:MatType,V<:VecType,K<:StringVecType}
source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModelCoupled,
    s::V1,
    b::V2,
    c::AbstractFloat,
    xl::AbstractFloat,
    xu::AbstractFloat;
    check_consistency = false,
) where {V1<:VecType,V2<:VecType}

Add reaction(s) to a CoreModelCoupled model m.

source
COBREXA.add_reactionsMethod
add_reactions(
    m::CoreModelCoupled,
    Sp::M,
    b::V,
    c::V,
    xl::V,
    xu::V;
    check_consistency = false,
) where {M<:MatType,V<:VecType}
source
COBREXA.change_coupling_bounds!Method
change_coupling_bounds!(
    model::CoreModelCoupled,
    constraints::Vector{Int};
    cl::V = Float64[],
    cu::V = Float64[],
) where {V<:VecType}

Change the lower and/or upper bounds (cl and cu) for the given list of coupling constraints.

source
COBREXA.remove_reactionsMethod
remove_reactions(m::CoreModelCoupled, rxns::Vector{Int})

Remove reaction(s) from a CoreModelCoupled.

Also removes any metabolites not involved in any reaction after the deletion.

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_genes!Method
add_genes!(model::StandardModel, genes::Vector{Gene})

Add genes to model based on gene id.

source
COBREXA.remove_gene!Method
remove_gene!(
    model::StandardModel,
    id::Vector{String};
    knockout_reactions::Bool = false,
)

Remove gene with id from model. If knockout_reactions is true, then also constrain reactions that require the genes to function to carry zero flux.

Example

remove_gene!(model, "g1")
source
COBREXA.remove_genes!Method
remove_genes!(
    model::StandardModel,
    ids::Vector{String};
    knockout_reactions::Bool = false,
)

Remove all genes with ids from model. If knockout_reactions is true, then also constrain reactions that require the genes to function to carry zero flux.

Example

remove_genes!(model, ["g1", "g2"])
source
COBREXA.remove_metabolite!Method
remove_metabolite!(model::StandardModel, id::String)

Remove metabolite with id from model. Warning, this could leave the model inconsistent, e.g. a reaction might require the deleted metabolite, in which case analysis functions will error.

Example

remove_metabolite!(model, "atp_c")
source
COBREXA.remove_metabolites!Method
remove_metabolites!(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, in which case analysis functions will error.

Example

remove_metabolites!(model, ["atp_c", "adp_c"])
source
COBREXA.remove_reaction!Method
remove_reaction!(model::StandardModel, id::String)

Remove reaction with id from model. Note, may result in orphan metabolites.

Example

remove_reaction!(model, "EX_glc__D_e")
source
COBREXA.remove_reactions!Method
remove_reactions!(model::StandardModel, ids::Vector{String})

Remove all reactions with ids from model. Note, may result in orphan metabolites.

Example

remove_reactions!(model, ["EX_glc__D_e", "fba"])
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
COBREXA.add_model_with_exchangesMethod
add_model_with_exchanges(
    community::CoreModel,
    model::MetabolicModel,
    exchange_rxn_ids::Vector{String},
    exchange_met_ids::Vector{String};
    model_name = "unknown_species",
    biomass_id = nothing,
)::CoreModel

Add model to community, which is a pre-existing community model with exchange_rxn_ids and exchange_met_ids. The model_name is appended to each reaction and metabolite, see join_with_exchanges. If biomass_id is specified then a biomass metabolite for model is also added to the resulting model. The column corresponding to the biomass_id reaction then produces this new biomass metabolite with unit coefficient. Note, exchange_rxn_ids and exchange_met_ids must already exist in the community model.

Example

community = add_model_with_exchanges(community, model, exchange_rxn_ids, exchange_met_ids; model_name="species_2", biomass_id="BIOMASS_Ecoli_core_w_GAM")
source
COBREXA.add_objective!Method
add_objective!(
    community::CoreModel,
    objective_mets::Vector{String};
    objective_weights = Float64[],
    objective_column_index = 0,
)

Add an objective to the community model. Supply the string names of the objective metabolites in objective_mets. Optionally specify the weight to assign each metabolite in the objective function, if unassigned then equal weight is assumed. Also, optionally specify whether the objective already exists in the model by assigning objective_column_index. If unassigned then an objective column will be added, otherwise the column at objective_column_index will be updated.

Note, the weights are negated inside the function so that the objective metabolites are seen as reagents/substrates, not products in the reaction equation.

Example

add_objective!(model, ["met1", "met2"]) # adds a new column with weights = [1,1]
add_objective!(model, ["met1", "met2"]; objective_weights=[0.1, 0.9]) # adds a new column
add_objective!(model, ["met1", "met2"]; objective_weights=[0.1, 0.9], objective_column_index=10) # updates column 10
source
COBREXA.join_with_exchangesMethod
join_with_exchanges(models::Vector{M},
    exchange_rxn_ids::Vector{String},
    exchange_met_ids::Vector{String};
    add_biomass_objective=false,
    biomass_ids::Vector{String},
    model_names=String[]
)

Return a CoreModel representing the community model of models joined through their exchange_rxn_ids and exchange_met_ids. These exchange reactions and metabolites link to environmental metabolites and reactions. Optionally specify model_names to append a specific name to each reaction and metabolite of an organism for easier reference (default is species_i for each model index i in models). Note, the bounds of the environmental variables are all set to zero. Thus, to run a simulation you need to constrain them appropriately. All the other bounds are inherited from the models used to construct the community model.

If add_biomass_objective is true then biomass_ids needs to be supplied as well. This creates a model with an extra reaction added to the end of the stoichiometric matrix (last column) that can be assigned as the objective reaction. It also creates biomass "metabolites" that can be used in this objective reaction. Note, this reaction is unspecified, further action needs to be taken to specify it, e.g. assign weights to the last column of the stoichiometric matrix in the rows corresponding to the biomass metabolites.

To further clarify how this join works. Suppose you have 2 organisms with stoichiometric matrices S₁ and S₂ and you want to link them with exchange_met_ids = [em₁, em₂, em₃, ...] and exchange_rxn_ids = [er₁, er₂, er₃, ...]. Then a new community stoichiometric matrix is constructed that looks like this:

            _      er₁  er₂  er₃  ...  b_
           |S₁                           |
           |   S₂                        |
        em₁|                             |
S   =   em₂|                             |
        em₃|                             |
        ...|                             |
        bm₁|                             |
        bm₂|_                           _|

The exchange reactions in each model get linked to environmental metabolites, emᵢ, and these get linked to environmental exchanges, erᵢ. These erᵢ behave like normal single organism exchange reactions. When add_biomass_objective is true each model's biomass becomes a pseudo-metabolite (bmᵢ). These can be weighted in column b, called the community_biomass reaction in the community model, if desired. Refer to the tutorial if this is unclear.

Example

m1 = load_model(core_model_path)
m2 = load_model(CoreModel, core_model_path)

# need to list ALL the exchanges that will form part of the entire model
exchange_rxn_ids = filter(looks_like_exchange_reaction, reactions(m1))
exchange_met_ids = [first(keys(reaction_stoichiometry(m1, ex_rxn))) for ex_rxn in exchange_rxn_ids]

biomass_ids = ["BIOMASS_Ecoli_core_w_GAM", "BIOMASS_Ecoli_core_w_GAM"]

community = join_with_exchanges(
    [m1, m2],
    exchange_rxn_ids,
    exchange_met_ids;
    add_biomass_objective = true,
    biomass_ids = biomass_ids,
)
source

Model variant specifications

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("e_coli_core.json")
solution = flux_balance_analysis(model, GLPK.optimizer)
value.(solution[:x])  # extract flux steady state from the optimizer

biomass_reaction_id = findfirst(model.reactions, "BIOMASS_Ecoli_core_w_GAM")

modified_solution = flux_balance_analysis(model, GLPK.optimizer;
    modifications=[change_objective(biomass_reaction_id)])
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 for a related analysis, also for explanation of the modifications argument).

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. By default, it calls and returns the value of JuMP.objective_value. More information can be extracted e.g. by setting it to a function that returns a more elaborate data structure; such as 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 checked with is_solved; nothing is returned if the optimization failed for any reason.

Example

model = load_model("e_coli_core.json")
flux_variability_analysis(model, [1, 2, 3, 42], GLPK.optimizer)
source
COBREXA.flux_variability_analysis_dictMethod
flux_variability_analysis_dict(
    model::MetabolicModel,
    optimizer;
    kwargs...
)

A variant of flux_variability_analysis that returns the individual maximized and minimized fluxes of all reactions as two dictionaries (of dictionaries). All keyword arguments except ret are passed through.

Example

mins, maxs = flux_variability_analysis_dict(
    model,
    Tulip.Optimizer;
    bounds = objective_bounds(0.99),
    modifications = [
        change_optimizer_attribute("IPM_IterationsLimit", 500),
        change_constraint("EX_glc__D_e", -10, -10),
        change_constraint("EX_o2_e", 0.0, 0.0),
    ],
)
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. See the documentation of fluxbalanceanalysis for usage examples of modifications.

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

model = load_model("e_coli_core.json")
optmodel = parsimonious_flux_balance_analysis(model, biomass, Gurobi.Optimizer)
value.(solution[:x])  # extract the flux from the optimizer
source
COBREXA.screenMethod
function screen(
    model::MetabolicModel;
    variants::Maybe{Array{V,N}} = nothing,
    analysis,
    args::Maybe{Array{T,N}} = nothing,
    workers = [myid()],
)::Array where {V<:AbstractVector, T<:Tuple,N}

Take an array of model-modifying function vectors in variants, and execute the function analysis on all variants of the model specified by variants. The computation is distributed over worker IDs in workers. If args are supplied (as an array of the same size as the variants), they are forwarded as arguments to the corresponding analysis function calls.

The array of variants must contain vectors of single-parameter functions, these are applied to model in order. The functions must not modify the model, but rather return a modified copy. The copy should be made as shallow as possible, to increase memory efficiency of the process. Variant generators that modify the argument model in-place will cause unpredictable results. Refer to the definition of screen_variant for details.

The function analysis will receive a single argument (the modified model), together with an expanded tuple of arguments from args.

The modification and analysis functions are transferred to workers as-is; all packages required to run them (e.g. the optimization solvers) must be loaded there. Typically, you want to use the macro @everywhere using MyFavoriteSolver from Distributed package for loading the solvers.

Return value

The results of running analysis are collected in to the resulting array, in a way that preserves the shape of the variants, similarly as with pmap.

The results of analysis function must be serializable, preferably made only from pure Julia structures, because they may be transferred over the network between the computation nodes. For that reason, functions that return whole JuMP models that contain pointers to allocated C structures (such as flux_balance_analysis used with GLPK or Gurobi otimizers) will generally not in this context.

Example

function reverse_reaction(i::Int)
    (model::CoreModel) -> begin
        mod = copy(model)
        mod.S[:,i] .*= -1   # this is unrealistic but sufficient for demonstration
        mod
    end
end

m = load_model(CoreModel, "e_coli_core.xml")

screen_variants(m,
           [
               [reverse_reaction(5)],
               [reverse_reaction(3), reverse_reaction(6)]
           ],
           mod -> mod.S[:,3])  # observe the changes in S

screen_variants(m,
    [
        [reverse_reaction(5)],
        [reverse_reaction(3), reverse_reaction(6)]
    ],
    mod -> flux_balance_analysis_vec(mod, GLPK.Optimizer))  # run analysis
source
COBREXA.screen_variantFunction
screen_variant(model::MetabolicModel, variant::Vector, analysis, args = ())

Helper function for screen that applies all single-argument functions in variant to the model (in order from "first" to "last"), and executes analysis on the result.

Can be used to test model variants locally.

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._affine_hit_and_run_chainMethod
_affine_hit_and_run_chain(warmup, lbs, ubs, iters, chain)

Internal helper function for computing a single affine hit-and-run chain. The number of the chain is passed for possible future initialization of stable RNGs.

source
COBREXA.affine_hit_and_runMethod
function affine_hit_and_run(
    warmup_points::Matrix{Float64},
    lbs::Vector{Float64},
    ubs::Vector{Float64};
    sample_iters = 100 .* (1:5),
    workers = [myid()],
    chains = length(workers),
)

Run a hit-and-run style sampling that starts from warmup_points and uses their affine combinations for generating the run directions to sample the space delimited by lbs and ubs. The points that represent fluxes in warmup_points should be organized in columns, i.e. warmup_points[:,1] is the first warmup flux.

There are total chains of hit-and-run runs, each on a batch of size(warmup_points, 2) points. The runs are scheduled on workers, for good load balancing chains should be ideally much greater than length(workers).

Each run continues for maximum(sample_iters) iterations; the numbers in sample_iters represent the iterations at which the whole "current" batch of points is collected for output. For example, sample_iters=[1,4,5] causes the process run for 5 iterations, returning the sample batch that was produced by 1st, 4th and last (5th) iteration.

Returns a matrix of sampled fluxes (in columns), with all collected samples horizontally concatenated. The total number of samples (columns) will be size(warmup_points,2) * chains * length(sample_iters).

Example

using COBREXA
using Tulip

model = load_model(StandardModel, model_path)

warmup, lbs, ubs = warmup_from_variability(model, Tulip.Optimizer, 100)
samples = affine_hit_and_run(warmup, lbs, ubs, sample_iters = 1:3)
source
COBREXA.warmup_from_variabilityFunction
function warmup_from_variability(
    model::MetabolicModel,
    optimizer,
    min_reactions::Vector{Int}=1:n_reactions(model),
    max_reactions::Vector{Int}=1:n_reactions(model);
    modifications = [],
    workers::Vector{Int} = [myid()],
)::Tuple{Matrix{Float64}, Vector{Float64}, Vector{Float64}}

Generate FVA-like warmup points for samplers, by minimizing and maximizing the specified reactions. The result is returned as a matrix, each point occupies as single column in the result.

source
COBREXA.warmup_from_variabilityMethod
warmup_from_variability(
    model::MetabolicModel,
    optimizer,
    n_points::Int;
    kwargs...
)

Generates FVA-like warmup points for samplers, by selecting random points by minimizing and maximizing reactions. Can not return more than 2 times the number of reactions in the model.

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.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.serialize_modelMethod
serialize_model(model::MM, filename::String)::Serialized{MM} where {MM<:MetabolicModel}

Serialize the model to file filename, returning a Serialized model that is able to load itself back automatically upon precaching by precache!.

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

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.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.metabolite_fluxesMethod
metabolite_fluxes(model::MetabolicModel, flux_dict::Dict{String, Float64})

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

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
COBREXA.looks_like_biomass_reactionMethod
looks_like_biomass_reaction(rxn_id::String;
    exclude_exchanges = false,
    exchange_prefixes = _constants.exchange_prefixes,
    biomass_strings = _constants.biomass_strings,
)::Bool

A predicate that matches reaction identifiers that look like biomass reactions. Biomass reactions are identified by looking for occurences of biomass_strings in the reaction id. If exclude_exchanges is set, the strings that look like exchanges (from looks_like_exchange_reaction) will not match.

Example

filter(looks_like_biomass_reaction, reactions(model)) # returns strings
findall(looks_like_biomass_reaction, reactions(model)) # returns indices
source
COBREXA.looks_like_exchange_metaboliteMethod
looks_like_exchange_metabolite(rxn_id::String;
    exchange_suffixes = _constants.exchange_suffixes,
    )::Bool

A predicate that matches metabolite identifiers that look like involved in exchange reactions. Exchange metabolites are identified by exchange_suffixes at the end of the metabolite id.

Example

filter(looks_like_exchange_metabolite, metabolites(model)) # returns strings
findall(looks_like_exchange_metabolite, metabolites(model)) # returns indices
source
COBREXA.looks_like_exchange_reactionMethod
looks_like_exchange_reaction(rxn_id::String;
    exclude_biomass = false,
    biomass_strings = _constants.biomass_strings,
    exchange_prefixes = _constants.exchange_prefixes,
)

A predicate that matches reaction identifiers that look like exchange or biomass reactions, given the usual naming schemes in common model repositories. Exchange reactions are identified based on matching prefixes in the set exchange_prefixes and biomass reactions are identified by looking for occurences of biomass_strings in the reaction id.

Also see find_exchange_reactions.

Example

findall(looks_like_exchange_reaction, reactions(model)) # returns indices
filter(looks_like_exchange_reaction, reactions(model)) # returns Strings

# to use the optional arguments you need to expand the function's arguments
# using an anonymous function
findall(x -> looks_like_exchange_reaction(x; exclude_biomass=true), reactions(model)) # returns indices
filter(x -> looks_like_exchange_reaction(x; exclude_biomass=true), reactions(model)) # returns Strings
source
COBREXA.change_bound!Method
change_bound!(
    model::CoreModel,
    rxn_idx::Int;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model in-place.

Example

new_model = change_bound!(model, 123, lower=-21.15, upper=42.3)
source
COBREXA.change_bound!Method
change_bound!(
    model::CoreModel,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model in-place.

Example

new_model = change_bound!(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_bound!Method
change_bound!(
    model::CoreModelCoupled,
    rxn_idx::Int;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model in-place.

Example

new_model = change_bound!(model, 123, lower=-21.15, upper=42.3)
source
COBREXA.change_bound!Method
change_bound!(
    model::CoreModelCoupled,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model in-place.

Example

new_model = change_bound!(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_bound!Method
change_bound!(
    model::StandardModel,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model in-place.

Example

new_model = change_bound!(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_boundMethod
change_bound(
    model::CoreModel,
    rxn_idx::Int;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model and return the modified model.

Example

change_bound(model, 123, lower=-21.15, upper=42.3)
source
COBREXA.change_boundMethod
change_bound(
    model::CoreModel,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model and return the modified model.

Example

change_bound(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_boundMethod
change_bound(
    model::CoreModelCoupled,
    rxn_idx::Int;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model and return the modified model.

Example

change_bound(model, 123, lower=-21.15, upper=42.3)
source
COBREXA.change_boundMethod
change_bound(
    model::CoreModelCoupled,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model and return the modified model.

Example

change_bound(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_boundMethod
change_bound(
    model::StandardModel,
    rxn_id::String;
    lower = nothing,
    upper = nothing,
)

Change the specified reaction flux bound in the model and return the modified model.

Example

change_bound(model, "ReactionB", lower=-21.15, upper=42.3)
source
COBREXA.change_bounds!Method
change_bounds!(
    model::CoreModel,
    rxn_idxs::AbstractVector{Int64};
    lower = (nothing for _ = rxn_idxs),
    upper = (nothing for _ = rxn_idxs),
)

Change the specified reaction flux bounds in the model in-place.

Example

new_model = change_bounds!(model, [123, 234], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_bounds!Method
change_bounds!(
    model::CoreModel,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model in-place.

Example

new_model = change_bounds!(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_bounds!Method
change_bounds!(
    model::CoreModelCoupled,
    rxn_idxs::AbstractVector{Int64};
    lower = (nothing for _ = rxn_idxs),
    upper = (nothing for _ = rxn_idxs),
)

Change the specified reaction flux bounds in the model in-place.

Example

new_model = change_bounds!(model, [123, 234], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_bounds!Method
change_bounds!(
    model::CoreModelCoupled,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model in-place.

Example

new_model = change_bounds!(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_bounds!Method
change_bounds!(
    model::StandardModel,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model in-place.

Example

new_model = change_bounds!(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_boundsMethod
change_bounds(
    model::CoreModel,
    rxn_idxs::AbstractVector{Int64};
    lower = (nothing for _ = rxn_idxs),
    upper = (nothing for _ = rxn_idxs),
)

Change the specified reaction flux bounds in the model and return the modified model.

Example

change_bounds(model, [123, 234], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_boundsMethod
change_bounds(
    model::CoreModel,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model and return the modified model.

Example

change_bounds(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_boundsMethod
change_bounds(
    model::CoreModelCoupled,
    rxn_idxs::AbstractVector{Int64};
    lower = (nothing for _ = rxn_idxs),
    upper = (nothing for _ = rxn_idxs),
)

Change the specified reaction flux bounds in the model and return the modified model.

Example

change_bounds(model, [123, 234], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_boundsMethod
change_bounds(
    model::CoreModelCoupled,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model and return the modified model.

Example

change_bounds(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
source
COBREXA.change_boundsMethod
change_bounds(
    model::StandardModel,
    rxn_ids::AbstractVector{String};
    lower = (nothing for _ = rxn_ids),
    upper = (nothing for _ = rxn_ids),
)

Change the specified reaction flux bounds in the model and return the modified model.

Example

change_bounds(model, ["ReactionA", "ReactionC"], lower=[-2.1, -50.05], upper=[4.2, 100.1])
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