How to use the cobra.Model function in cobra

To help you get started, we’ve selected a few cobra examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github resendislab / corda / tests / test_all.py View on Github external
def model():
    A = Metabolite("A")
    B = Metabolite("B")
    C = Metabolite("C")
    r1 = Reaction("r1")
    r1.add_metabolites({A: -1, C: 1})
    r2 = Reaction("r2")
    r2.add_metabolites({B: -1, C: 1})
    r3 = Reaction("EX_A")
    r3.add_metabolites({A: 1})
    r4 = Reaction("EX_B")
    r4.add_metabolites({B: 1})
    r5 = Reaction("EX_C")
    r5.add_metabolites({C: -1})
    mod = Model("test model")
    mod.add_reactions([r1, r2, r3, r4, r5])
    conf = {"r1": 1, "r2": -1, "EX_A": 1, "EX_B": 1, "EX_C": 1}

    return (mod, conf)
github resendislab / corda / tests / tests.py View on Github external
def setUp(self):
        A = Metabolite("A")
        B = Metabolite("B")
        C = Metabolite("C")
        r1 = Reaction("r1")
        r1.add_metabolites({A: -1, C: 1})
        r2 = Reaction("r2")
        r2.add_metabolites({B: -1, C: 1})
        r3 = Reaction("EX_A")
        r3.add_metabolites({A: 1})
        r4 = Reaction("EX_B")
        r4.add_metabolites({B: 1})
        r5 = Reaction("EX_C")
        r5.add_metabolites({C: -1})
        model = Model("test model")
        model.add_reactions([r1, r2, r3, r4, r5])
        conf = {"r1": 1, "r2": -1, "EX_A": 1, "EX_B": 1, "EX_C": 1}

        self.model = model
        self.conf = conf
        self.opt = CORDA(self.model, self.conf, met_prod=["C"])
github SBRG / bigg_models / bigg2 / load / model_database / databaseio.py View on Github external
def databasetomodel(modelversion_id, modelname=False):
    #1. takes a modelid and builds a cobra model object.
    #2. requires modelversion_id as an argument and optionally a model name

    config = {}
    execfile("config", config) 
    
    model_name = "m_" +str(modelversion_id)
    cobra_model = Model(model_name)  

    if modelname:
     print modelname, "Name feature not yet implemented"
     sys.exit()
     #to do: get model by name
         
    conn_string = "host='%s' dbname='%s' user='%s' password='%s'"%(config['host'], config['dbname'], config['user'], config['password'])
    
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
    
    modelversion=modelversion_id
    countreactants=0
    countdeleted=0
    countmetabolite=0
github opencobra / cobrapy / cobra / oven / ali-ebrahim / legacyIO.py View on Github external
to_remove = ["__globals__", "__header__", "__version__"]
        to_pop = []
        for name in possible_names:
            if name in to_remove:
                to_pop.append(name)
        for i in to_pop:
            possible_names.pop(i)
        possible_names = possible_names.keys()
    for possible_name in possible_names:
        m = data[possible_name]  # TODO: generalize
        if m.dtype.names is None:
            continue
        if not set(["rxns", "mets", "S", "lb", "ub"]) \
                <= set(m.dtype.names):
            continue
        model = cobra.Model()
        model.id = m["description"][0, 0][0]
        model.description = model.id
        for i, name in enumerate(m["mets"][0, 0]):
            new_metabolite = cobra.Metabolite()
            new_metabolite.id = name[0][0]#.encode("ascii", "replace")
            try:
                new_metabolite.name = m["metNames"][0, 0][i][0][0]
                new_metabolite.formula = m["metFormulas"][0][0][i][0][0]
            except:
                pass
            model.add_metabolites([new_metabolite])
        for i, name in enumerate(m["rxns"][0, 0]):
            new_reaction = cobra.Reaction()
            new_reaction.id = name[0][0]#.encode("ascii", "replace")
            new_reaction.lower_bound = m["lb"][0, 0][i][0]
            new_reaction.upper_bound = m["ub"][0, 0][i][0]
github biosustain / cameo / scripts / parse_metanetx.py View on Github external
reaction.add_metabolites(stoichiometry)
            try:
                if len(reaction.check_mass_balance()) != 0:
                    continue
            except (AttributeError, ValueError) as e:
                logger.debug(str(e))
                continue
            if row.Balance:
                reaction.lower_bound = -1 * reaction.upper_bound
            reaction.name = row['Source']
            row = row.fillna("")
            rest = row.to_dict()
            reaction.annotation = dict((key, rest[key]) for key in rest if key in ('EC', 'Description'))
            reactions.append(reaction)

    model = Model('metanetx_universal_model_' + '_'.join(list_of_db_prefixes))
    model.add_reactions(reactions)
    # Add demands for all metabolites
    for metabolite in model.metabolites:
        model.add_boundary(metabolite, type='demand')
    return model
github opencobra / cobrapy / cobra / oven / aliebrahim / gapAnalysis.py View on Github external
import cobra
from cobra import Model, Reaction, Metabolite


class SUXModelMILP(cobra.Model):
    """Model with additional Universal and Exchange reactions.
    Adds corresponding dummy reactions and dummy metabolites for each added
    reaction which are used to impose MILP constraints to minimize the
    total number of added reactions. See the figure for more
    information on the structure of the matrix.
    """
    def __init__(self, model, Universal=None, threshold=0.05,
            penalties={"Universal": 1, "Exchange": 1, "Demand": 1},
            dm_rxns=False, ex_rxns=True):
        cobra.Model.__init__(self, "")
        # store parameters
        self.threshold = threshold
        self.penalties = penalties
        # want to only operate on a copy of Universal so as not to mess up
        # is this necessary?
        if Universal is None:
github SBRG / cobrame / cobrame / io / jsonme.py View on Github external
Filename of the JSON ME-model

    Returns
    -------
    :class:`cobra.core.model.Model`
        COBRA Model representation of the ME-model. This will not include
        all of the functionality of a :class:`~cobrame.core.model.MEModel` but
        will solve identically compared to the full model.
    """
    if isinstance(file_name, string_types):
        with open(file_name, 'r') as f:
            obj = json.load(f)
    else:
        obj = file_name

    model = cobra.Model()

    # If cannot import SymbolicParameter, assume using cobrapy
    # versions <= 0.5.11. If versions >= 0.8.0 are used, a ME-model interface
    # must be assigned as the solver interface
    try:
        from optlang.interface import SymbolicParameter
    except ImportError:
        pass
    else:
        model.solver = me_model_interface

    default_reactions = [i.id for i in model.reactions]

    for k, v in iteritems(obj):
        if k in {'id', 'name'}:
            setattr(model, k, v)
github biosustain / cameo / cameo / strain_design / pathway_prediction / pathway_predictor.py View on Github external
def __init__(self, model, universal_model=None, mapping=None, compartment_regexp=None):
        """"""
        self.original_model = model
        if compartment_regexp is None:
            compartments_tally = Counter(metabolite.compartment for metabolite in self.original_model.metabolites)
            most_common_compartment = compartments_tally.most_common(n=1)[0][0]
            compartment_regexp = re.compile('^' + most_common_compartment + '$')
        else:
            compartment_regexp = re.compile(compartment_regexp)

        if universal_model is None:
            logger.debug("Loading default universal model.")
            self.universal_model = models.universal.metanetx_universal_model_bigg
        elif isinstance(universal_model, Model):
            self.universal_model = universal_model
        else:
            raise ValueError('Provided universal_model %s is not a model.' % universal_model)
        self.products = self.universal_model.metabolites

        if mapping is None:
            self.mapping = metanetx.all2mnx
        else:
            self.mapping = mapping

        self.model = model.copy()

        try:
            logger.info('Trying to set solver to cplex to speed up pathway predictions.')
            self.model.solver = 'cplex'
        except SolverNotFound:
github opencobra / cobrapy / cobra / oven / ali-ebrahim / keggIO.py View on Github external
if metabolite_id in used_metabolites:
                used_metabolites[metabolite_id] = coefficients[i]
            else:
                # use a new metabolite
                new_metabolite = cobra.Metabolite(metabolite_id)
                used_metabolites[metabolite_id] = new_metabolite
                metabolite_dict[cobra.Metabolite(metabolite_id)] = \
                    coefficients[i]
        reaction.add_metabolites(metabolite_dict)
        reaction.notes["temporary_gapfilling_type"] = "Universal"
        # because the model will be converted to irreversible
        reaction.lower_bound = -1 * reaction.upper_bound
        cobra_reactions.append(reaction)
    keggfile.close()
    # add all of the reactions to a cobra model
    Universal = cobra.Model("Kegg_Universal_Reactions")
    Universal.add_reactions(cobra_reactions)
    return Universal
if __name__ == "__main__":