Exemple #1
0
def opposing_model():
    """
    Generate a toy model with opposing reversible reactions.

    This toy model ensures that two opposing reversible reactions do not
    appear as blocked.

    """
    test_model = cobra.Model("opposing")
    v1 = cobra.Reaction("v1")
    v2 = cobra.Reaction("v2")
    v3 = cobra.Reaction("v3")
    v4 = cobra.Reaction("v4")

    test_model.add_reactions([v1, v2, v3, v4])

    v1.reaction = "-> 2 A"
    v2.reaction = "A -> C"  # Later made reversible via bounds.
    v3.reaction = "D -> C"  # Later made reversible via bounds.
    v4.reaction = "D ->"

    v1.bounds = 0.0, 3.0
    v2.bounds = -3.0, 3.0
    v3.bounds = -3.0, 3.0
    v4.bounds = 0.0, 3.0

    test_model.objective = v4
    return test_model
def create_metamodel(list_of_models, model_id='metamodel'):

    metamodel = cobra.Model(model_id)

    for model in list_of_models:
        metabolites_dictionary = create_metabolites_dictionary(model)
        for m_id, m_dict in metabolites_dictionary.items():
            if m_id in metamodel.metabolites:
                continue
            metabolite = create_metabolite_from_dict(m_dict)
            metamodel.add_metabolites([metabolite])

    all_metabolites_dict = {m.id: m for m in metamodel.metabolites}

    for model in list_of_models:
        reactions_dictionary = create_reactions_dictionary(model)
        for r_id, r_dict in reactions_dictionary.items():
            if r_id in metamodel.reactions:
                r = metamodel.reactions.get_by_id(r_id)
                r.lower_bound = min(r_dict['lower_bound'], r.lower_bound)
                r.upper_bound = max(r_dict['upper_bound'], r.upper_bound)
                r.reversibility = max(r_dict['reversibility'], r.reversibility)
                continue

            reaction = create_reaction_from_dict(r_dict, all_metabolites_dict)
            metamodel.add_reaction(reaction)

    return metamodel
Exemple #3
0
def fusion (bacteries):
    import cobra
    import re
    if type(bacteries) ==list:
        model = cobra.Model('Communautés')
        model= bacteries[0].model.copy()
        
        for i in range(1,len(bacteries)) :
            A=bacteries[i].model.copy()
            for m in A.metabolites:
                if m.compartment != 'C_e':
                    m.compartment=m.compartment+"_B"+str(i)
                    m.id=m.id+"_B"+str(i)
                    
            for r in A.reactions:
                if not re.search("EX_",r.id):
                    r.id = r.id +"_B"+str(i)
                    set_compartiments=r.compartments.copy()
                    r.compartments.clear()
                    for c in set_compartiments :
                        c=c+"_B"+str(i)
                        r.compartments.add(c)        
            model.add_reactions(A.reactions.copy())
            exec("model.reactions.Growth_B"+str(i)+".objective_coefficient=1")
    else :
        model=bacteries.model
    return model
Exemple #4
0
def build_universal_model(template_model_file,
                          clean_exchange_reactions=False,
                          compartments=[0]):
    """

    :param template_model_file: path to file where a template model is saved. e.g. templates/GramNegative.json
    :param compartments: list (usually integers) to be appended to all compounds/reactions indicating model compartments
                         e.g. if compartments = [0], rxn00001_c, rxn00001_c0 will be in the universal model, and will
                         have compounds of the form cpd00001_c, cpd00001_c0 respectively. This is used if your model has
                         multiple compartments or indicates the compartment as 0 e.g. rxn00001_c0 with cpd00001_c0
    :param clean_exchange_reactions: If true, re-formats exchange reactions to cobra form (see below)

    Cleaning Exchange Reactions:
    if a reaction in the template model uses external compounds to indicate exchange reactions, and the clean_exchange_reactions
    flag is set to True, then external compounds are removed to indicate exchange implicitly (CobraPy style)

    Example: "cpd00001_e0 <=> cpd00001_c0" is used to indicate exchange reaction of cpd00001. With the flag, this is
             changed to " <=> cpd00001_c0"
    :return:
    """
    universal = cobra.Model("Universal Reactions")
    template_model = _load_template_file(template_model_file)
    # Creates a dictionary of the reactions from the tab delimited database, storing their ID and the reaction string
    for template_rxn in template_model['reactions']:
        compartments = [str(i) for i in compartments]
        compartments.extend('')
        for suffix in compartments:
            _add_rxn_from_template_rxn(
                universal,
                template_rxn,
                clean_exchange_reactions=clean_exchange_reactions,
                compartment=suffix)
    return universal
Exemple #5
0
 def to_cobra_model(self):
     """
     Returns an instance of cobra.Model without any of the useful project stuff.
     Note, uses the same solver
     :return cobra.Model
     """
     return cobra.Model(id_or_model=self)
Exemple #6
0
def protein_to_gene(WD, model, protein_corres, name):
    """Function to transform the proteins in gene_reaction_rule into its corresponding genes.
    It creates a new model that will be rid of all the proteins.
    
    ARGS:
        WD (str) -- the path where to find the model.
        model (str) -- the model file in json format.
        protein_corres (str) -- the exact path of the csv file of the
        correspondance between a protein and its gene.
        name (str) -- the new name for the new corrected model.
    """

    dico_corres, dico_corres_rev = corres_dico(protein_corres)
    protein_model = cobra.io.load_json_model(WD + model)
    gene_model = cobra.Model(protein_model.id)
    for reaction in protein_model.reactions:
        genes = []
        list_proteins = reaction.gene_reaction_rule.split(" or ")
        for protein in list(
                filter(None, [trans.upper() for trans in list_proteins])):
            try:
                genes.append(dico_corres_rev[protein])
            except KeyError:
                try:
                    dico_corres[protein]
                    genes.append(protein)
                except KeyError:
                    print("No match for : ", protein)
        new_reaction = copy.deepcopy(reaction)
        new_reaction.gene_reaction_rule = " or ".join(set(genes))
        gene_model.add_reactions([new_reaction])
    cobra.io.save_json_model(gene_model,
                             WD + name + protein_model.id + ".json")
Exemple #7
0
def createReverseEXmodel(EXreactions): 
    '''
    This function takes the list of exchange reactions created using the function totalEXRxns and creates a Model object using cobrapy composed of those reactions with the upper bound flux values of 1000, lower bound flux values of -1000, and objective coefficient of 0, and one metabolite as being produced by the reaction (stoichiometric coefficient of 1). This is a model composed solely of exchange reactions. The metabolite information for these reactions will be used to update the metabolites of the exchange reactions for models A and B.

    :param EXreactions: list of reactions that are the output of the function totalEXRxns (above)
    :return exchange_modelRev: cobrapy Model object containing only exchange reactions with the production of their respective metabolites
    '''

    cherrypy.log("Started the function that creates the reverse exchange reactions for the community model")

    exchange_modelRev = cobra.Model('Model with the exchange reactions only with reversed stoi coefficient')

    cherrypy.log("Created the base reverse exchange model object")

    for i in EXreactions: 
        new_i = str(i)
        new_i = new_i[3:]
        new_met = cobra.Metabolite(new_i)
        
        rxn = cobra.Reaction(i)
        rxn.lower_bound = -1000.000
        rxn.upper_bound = 1000.000
        rxn.objective_coefficient = 0.000
        rxn.add_metabolites({new_met:1.0})
        
        exchange_modelRev.add_reaction(rxn)

    cherrypy.log('Finished adding all exchange reactions in reverse exchange model object. There are %d of them' %(len(exchange_modelRev.reactions)))

    return exchange_modelRev
Exemple #8
0
def createEXmodel(EXreactions): 
    '''
    This function takes the list of exchange reactions created using the function totalEXRxns and creates a Model object using cobrapy composed of those reactions with the upper bound flux values of 1000, lower bound flux values of -1000, and objective coefficient of 0, and one metabolite as being uptaken by the reaction (stoichiometric coefficient of -1). This is a model composed solely of exchange reactions and it's the model for the extra compartment created for the full community model

    :param EXreactions: list of reactions that are the output of the function totalEXRxns (above)
    :return exchange_model: cobrapy Model object for the compartment that will serve as an extra compartment in the full community model.
    '''


    cherrypy.log("Started the function that creates the exchange reactions for the community model")

    exchange_model = cobra.Model('Model with the exchange reactions only')

    cherrypy.log("Created the base exchange model object")
    
    for i in EXreactions: 
        new_i = str(i)
        new_i = new_i[3:]
        new_met = cobra.Metabolite(new_i)
        
        rxn = cobra.Reaction(i)
        rxn.lower_bound = -1000.000
        rxn.upper_bound = 1000.000
        rxn.objective_coefficient = 0.000
        rxn.add_metabolites({new_met:-1.0}) 
        
        exchange_model.add_reaction(rxn)


    cherrypy.log('Finished adding all exchange reactions in exchange model object. There are %d of them' %(len(exchange_model.reactions)))

    return exchange_model 
Exemple #9
0
def drafting(model, dico_genes, model_name):
    """Creates the new COBRA model for the subject organism.
    
    ARGS:
        model -- the COBRA model used for the reconstruction.
        dico_genes -- the dictionary containing the correspondance
        between genes of the model and the subject (See select_genes() for the structure).
        model_name (str) -- a name for the new model.
    RETURN:
        new_model -- the new COBRA model automatically generated.
    """

    new_model = cobra.Model(model_name)
    ###Browsing the model reactions and associating the subject's genes to them
    for reac in model.reactions:
        to_add = []
        to_search = reac.gene_reaction_rule.split(" or ")
        for gene in to_search:
            try:
                to_add += dico_genes[gene]
            except KeyError:
                pass
        ###TODO : change the proteins's ID in to_add in corresponding genes
        string_reaction_rule = " or ".join(to_add)
        if string_reaction_rule:
            x = copy.deepcopy(reac)
            x.gene_reaction_rule = string_reaction_rule
            new_model.add_reactions([x])
    return new_model
Exemple #10
0
def change_model_prefix(model_path,
                        save_model=None,
                        suffix=r"__91__(\w)__93__"):
    """
    Function that translate model extracellular metabolites to other 'languages'
    """
    mod = load_model(model_path)
    new_model = cobra.Model()
    new_model.id = mod.id
    p = re.compile(r"(.+)" + suffix)
    pb = re.compile(r"biomass", re.I)
    pdash = re.compile(r"DASH_")
    for i in mod.reactions:
        for reactant in i.metabolites:
            reactant.id = re.sub(pdash, r"", reactant.id)
            reactant.id = re.sub(p, r"\1[\2]", reactant.id)
        for react in i.reaction:
            react = re.sub(p, r"\1[\2]", react)
        new_model.add_reaction(i)
    for reac in new_model.reactions:
        if pb.search(reac.id):
            new_model.objective = [new_model.reactions.get_by_id(reac.id)]
            break
    if save_model != None:
        cobra.io.write_sbml_model(new_model, save_model)
    return new_model
def test_notes(tmp_path):
    """Testing if model notes are written in SBML"""
    path_to_file = join(str(tmp_path), "model_notes.xml")

    # making a minimal cobra model to test notes
    model = cobra.Model("e_coli_core")
    model.notes["Remark"] = "...Model Notes..."
    met = cobra.Metabolite("pyr_c", compartment="c")
    model.add_metabolites([met])
    met.notes["Remark"] = "Note with \n newline"
    rxn = cobra.Reaction("R_ATPM")
    model.add_reactions([rxn])
    rxn.notes["Remark"] = "What about me?"
    model.objective_direction = "max"
    model.objective = rxn
    write_sbml_model(model, path_to_file)

    # reading the model back
    model_after_reading = read_sbml_model(path_to_file)
    met_after_reading = model_after_reading.metabolites.get_by_id("pyr_c")
    reaction_after_reading = model_after_reading.reactions.get_by_id("R_ATPM")

    # checking if notes are written to model
    assert model_after_reading.notes["Remark"] == "...Model Notes..."

    # checking notes for metabolite and reaction
    assert met_after_reading.notes["Remark"] == "Note with \n newline"
    assert reaction_after_reading.notes["Remark"] == "What about me?"
Exemple #12
0
def createEXmodel(EXreactions):
    import cobra
    '''
    @summary: using the cobrapy package, create a brand new model that will contain the exchange reactions. This is the model
    we can manipulate when we want to change the nutrients available to the species. We will do this by changing either the
    upper or lower bounds (I don't remember and have to check). Ultimately we will create a file with a global exchange 
    reactions model that has a different diet associated with it. But this will require going over a whole bunch of models 
    to find all possible exchange reactions, and so I will stick to this approach for now.
    '''

    exchange_model = cobra.Model('Model with the exchange reactions only')

    for i in EXreactions:
        new_i = str(i)
        new_i = new_i[3:]
        new_met = cobra.Metabolite(new_i)

        rxn = cobra.Reaction(i)
        rxn.lower_bound = -1000.000
        rxn.upper_bound = 1000.000
        rxn.objective_coefficient = 0.000
        rxn.add_metabolites({new_met: -1.0})

        exchange_model.add_reaction(rxn)

    return exchange_model
def get_biomass_model(dic_i, observations_list=False):
    '''
    :description : function to get a model contain biomass reactions from a dic
    :param :
        dic_i(dic) : {'met_id': [coefficient, 'pool]}
                    eg. {'10-FORMYL-THF': [-0.000367, 'cofactor'],
                     'AMP': [-0.0046700000000000005, 'cofactor'],
                     'CPD-12125': [-0.000266, 'cofactor'],
                     'CDP': [-0.000251, 'cofactor'],}
        observations_list like:
            eg. ['dna', 'rna', 'protein', 'lipid', 'carbohydrate', 'cofactor', 'ion', 'other']

    :returns: cobra model
    '''

    if observations_list == False:
        observations_list = [
            'dna', 'rna', 'protein', 'lipid', 'carbohydrate', 'cofactor',
            'ion', 'other'
        ]
    observations_list = [i + '_c' for i in observations_list]

    biomass_model = cobra.Model('model')  # get a Model

    # %% <Biomass pool reactions>
    biomass_reactions = [
        cobra.Reaction('Biomass_' + i) for i in observations_list
    ]
    [
        rxn.add_metabolites({cobra.Metabolite(met): 1})
        for rxn, met in zip(biomass_reactions, observations_list)
    ]

    biomass_model.add_reactions(biomass_reactions)

    for k, v in dic_i.items():
        # print(k)
        try:  # build metabolites
            met = biomass_model.metabolites.get_by_id(k)
        except:
            met = cobra.Metabolite(k)
        try:  # build reactions
            reaction_i = biomass_model.reactions.get_by_id('Biomass_' + v[1] +
                                                           '_c')
            reaction_i.add_metabolites({met: v[0]})
        except:
            print(k, v, 'Error')

    # %% <Biomass reaction>
    Biomass = cobra.Reaction('Biomass')
    [
        Biomass.add_metabolites({biomass_model.metabolites.get_by_id(met): -1})
        for met in observations_list
    ]
    Biomass.add_metabolites({cobra.Metabolite('Biomass'): 1})
    biomass_model.add_reactions([Biomass])

    return biomass_model
Exemple #14
0
    def setUp(self):
        self.model = cb.test.create_test_model('salmonella')
        self.salchs4_e = self.model.metabolites.get_by_id('salchs4_e')
        self.pglyc_c = self.model.metabolites.get_by_id('2pglyc_c')

        small_model = cb.Model('small_model')
        for r in self.salchs4_e.reactions:
            small_model.add_reaction(r)

        self.adj = MetabolicAdjMatrix(small_model)

        unconnected_model = cb.Model('unconnected_model')
        for r in self.salchs4_e.reactions:
            unconnected_model.add_reaction(r)

        for r in self.pglyc_c.reactions:
            unconnected_model.add_reaction(r)

        self.unconnected_adj = MetabolicAdjMatrix(unconnected_model)
Exemple #15
0
 def __init__(self):
     self.name = "Unnamed project"
     self.cobra_py_model = cobra.Model()
     self.maps = {}
     self.scen_values: Dict[str, Tuple[float, float]] = {}
     self.clipboard: Dict[str, Tuple[float, float]] = {}
     self.comp_values: Dict[str, Tuple[float, float]] = {}
     self.modes: Dict[str, Tuple[float, float]] = []
     self.compute_color_type = 1
     self.meta_data = {}
Exemple #16
0
def raw_model():
    """Provides a raw model."""
    model = cobra.Model(id_or_model='raw_model', name='raw_model')
    rxn_1 = cobra.Reaction("BIOMASS_TEST")
    rxn_2 = cobra.Reaction("RXN2")
    rxn_3 = cobra.Reaction("RXN3")
    rxn_4 = cobra.Reaction("RXN4")
    model.add_reactions([rxn_1, rxn_2, rxn_3, rxn_4])
    model.objective = rxn_3
    return model
Exemple #17
0
def expected_model():
    """Provides a model with an objective function according to the config."""
    model = cobra.Model(id_or_model='expected_model', name='expected_model')
    rxn_1 = cobra.Reaction("BIOMASS_TEST")
    rxn_2 = cobra.Reaction("RXN2")
    rxn_3 = cobra.Reaction("RXN3")
    rxn_4 = cobra.Reaction("RXN4")
    model.add_reactions([rxn_1, rxn_2, rxn_3, rxn_4])
    model.objective = rxn_1
    return model
Exemple #18
0
def make_cobra_model(met_list, rxn_list, allow_export = True):
    '''
    Given a list of metabolites and reactions, make a COBRApy model 
    representing the corresponding metabolic network
    If allow_export is True, an extra reaction will be added for every
    metabolite that consumes the metabolite and produces nothing to simulate
    secretion of waste products
    '''
    model = cobra.Model('string_chem')
    # start with the metabolites
    # we will need to make a dictionary with the COBRA metabolite objects
    # as keys and stoichiometric coefficients as values, so we'll need a way
    # to look up the COBRA metabolite objects using their names, since
    cobra_mets = [cobra.Metabolite(met, compartment = 'c') for met in met_list]
    met_dict = dict()
    for met in met_list:
        met_dict[met] = cobra.Metabolite(met, compartment = 'c')
    
    # start working on the reactions
    # start by making a dictionary to look up species involved in a reaction
    # using the string notation of that reaction
    rxn_dict = dict()
    for rxn in rxn_list:
        rxn_dict[rxn] = re.split('(\+|\-\>)', rxn)[0::2]

    # start by just making the COBRA reaction objects then add metabolites
    cobra_rxns = [
        # make all reactions reversible by default
        cobra.Reaction(rxn, upper_bound = 1000.0, lower_bound = -1000.0)
        for rxn in rxn_list
    ]
    for rxn in cobra_rxns:
        # find all the COBRA metabolites associated with this reaction
        c_mets = [met_dict[met] for met in rxn_dict[rxn.id]]
        # we know the first metabolite in the list is the reactant
        rxn.add_metabolites({c_mets[0] : -1.0})
        # check if reactant splits into two identical products
        if rxn_dict[rxn.id][1] == rxn_dict[rxn.id][2]:
            rxn.add_metabolites({c_mets[1] : 2.0})
        else:
            rxn.add_metabolites({c_mets[1] : 1.0, c_mets[2] : 1.0})
        # now that the reaction is complete, we can just add it to the model
        model.add_reaction(rxn)

    # add in export reactions for all metabolites if specified
    if allow_export is True:
        for met in cobra_mets:
            out_rxn = cobra.Reaction(
                met.id + '->',
                upper_bound = 1000.0, # only allow exporting
                lower_bound = 0.0
            )
            out_rxn.add_metabolites({met: -1.0})
            model.add_reaction(out_rxn)
    return(model)
Exemple #19
0
    def test_load_network_model(self):
        model = cb.Model()
        loaded_model = load_network_model(model)
        self.assertEqual(model, loaded_model)

        textbook = load_network_model('textbook')
        self.assertEqual(textbook.id, 'e_coli_core')

        recon2 = load_network_model('recon2')
        self.assertGreater(len(recon2.reactions), 1000)
        self.assertGreater(len(recon2.metabolites), 1000)
Exemple #20
0
def make_plantnetwork(WD, metacycPath, reactionsPath):
    """Function to create a subnetwork of Metacyc containing only the Viridiplantae taxon.
    This function revealed itself useless as the output model is way too small,
    and the TAXONOMIC-RANGE field is not maintained anymore.
    
    ARGS:
        WD (str) -- the path to the working directory where to save the new model.
        metacycPath (str) -- the exact path and filename of the Metacyc model.
        reactionsPath (str) the exact path and filename of the reactions.dat file of the organism.  
    """
    reactionsFile = tools.read_file(reactionsPath)
    list_plant = []
    for line in reactionsFile:
        if "UNIQUE-ID" in line:
            try:
                unique_id = re.search('(?<=UNIQUE-ID - )[+-]*\w+(.*\w+)*(-*\w+)*', line).group(0).rstrip()
            except AttributeError:
                print("No match for : ", line)
        if "TAXONOMIC-RANGE" in line and "33090" in line:
            list_plant.append(unique_id)
    
    ###Necessary step for the gathering of short/long IDs
    dico_matching, dico_matching_rev = tools.corres_dico("/home/asa/INRAE/Work/Fusion/MetacycCorresIDs.tsv")
    
    ###Transformation of all IDs in short + long to get them from Metacyc
    new_plant_list = []
    for reac in list_plant:
        try:
            for long_reac in dico_matching[reac]:
                new_plant_list.append(long_reac)
            new_plant_list.append(reac)
        except KeyError:
            try:
                new_plant_list.append(dico_matching_rev[reac])
                new_plant_list.append(reac)
            except KeyError:
                print("No match for reac : ", reac)
    
    ###Fetching the plant reactions
    metacyc = cobra.io.read_sbml_model(metacycPath)
    meta_plant = cobra.Model(name="Metacyc Plant")
    for reac in new_plant_list:
        try:
            plant_reac = copy.deepcopy(metacyc.reactions.get_by_id(reac))
            meta_plant.add_reactions([plant_reac])
        except KeyError:
            try:
                plant_reac = copy.deepcopy(metacyc.reactions.get_by_id(reac))
                meta_plant.add_reactions([plant_reac])
            except KeyError:
                print("Reaction not found in Metacyc : ", reac)
    cobra.io.write_sbml_model(meta_plant, WD + "meta_plant.sbml")
Exemple #21
0
def to_cobrapy(model):
    """ Convert model to a *cobrapy.Model* object

    Arguments:
        model (CBModel): constraint-based model

    Returns:
        cobrapy.Model
    """

    try:
        import cobra as cb
    except ImportError:
        raise RuntimeError("CobraPy is not installed.")

    cb_model = cb.Model(model.id)
    cb_model.compartments = {
        comp.id: comp.name
        for comp in model.compartments.values()
    }

    cb_mets = []
    for met in model.metabolites.values():
        cb_met = cb.Metabolite(id=met.id,
                               name=met.name,
                               compartment=met.compartment,
                               formula=met.metadata.get('FORMULA', ''))
        cb_mets.append(cb_met)
    cb_model.add_metabolites(cb_mets)

    cb_rxns = []
    for rxn in model.reactions.values():
        cb_rxn = cb.Reaction(id=rxn.id,
                             name=rxn.name,
                             lower_bound=rxn.lb,
                             upper_bound=rxn.ub)
        cb_rxns.append(cb_rxn)
    cb_model.add_reactions(cb_rxns)

    for r_id, rxn in model.reactions.items():
        cb_rxn = cb_model.reactions.get_by_id(r_id)

        cb_rxn.add_metabolites(rxn.stoichiometry)
        if rxn.gpr is not None:
            cb_rxn.gene_reaction_rule = str(rxn.gpr)

    cb_model.objective = {
        cb_model.reactions.get_by_id(r_id): coeff
        for r_id, coeff in model.get_objective().items()
    }

    return cb_model
def bare_mini():
    """Define a minimal metabolism with two metabolites."""
    model = cobra.Model()
    met_a = cobra.Metabolite("a_c", name="A", formula="C2")
    met_b = cobra.Metabolite("b_c", name="B", formula="C2")
    model.add_metabolites([met_a, met_b])
    rxn = cobra.Reaction("FORMB")
    rxn.add_metabolites({met_a: -1, met_b: 1})
    model.add_reactions([rxn])
    model.add_boundary(met_a)
    demand = model.add_boundary(met_b, type="demand")
    model.objective = demand
    model.objective_direction = "max"
    return model
Exemple #23
0
def construct_model_from_mat(N, rxn_names, met_names):

    model = cobra.Model('test_model')

    model.add_metabolites(
        [cobra.Metabolite(id=met_name) for met_name in met_names])

    for row, rxn_name in zip(N.T, rxn_names):
        reaction = cobra.Reaction(id=rxn_name)
        model.add_reaction(reaction)
        reaction.add_metabolites({
            met_id: float(stoich)
            for met_id, stoich in zip(met_names, row) if abs(stoich) > 1E-6
        })

    return model
Exemple #24
0
def make_cobra_model(reaction_dict, metab_dict, reactions_in_model,
                     objective_name):
    '''
    Make a cobra model of all reactions in reactions_in_model, 
    using a reaction class instance and a metab dict containing all metabs used in the reactions.
    '''
    #Make cobra metabolites and reaction objects.
    cobra_metabs = make_cobra_metabolites(metab_dict)
    cobra_reactions = [
        make_cobra_reaction(reaction_dict, cobra_metabs, e)
        for e in reactions_in_model
    ]
    #Make cobra model.
    cobra_model = cobra.Model('tempmodel')
    cobra_model.add_reactions(cobra_reactions)
    cobra_model.objective = objective_name
    return cobra_model
Exemple #25
0
    def _create_base_model(self, model_list, base_id='ensemble base'):
        '''
        Creates a base model from a list of universal models. Base models
        contain all reactions present in a list of models. A reaction_diff
        object is also returned, indicating the bounds for any reaction that
        is different across any model in the ensemble.
        '''
        base_model = cobra.Model(base_id)
        for model in model_list:
            rxns_to_add = []
            for reaction in model.reactions:
                if reaction.id not in [rxn.id for rxn in base_model.reactions]:
                    rxns_to_add.append(reaction.copy())
            base_model.add_reactions(rxns_to_add)
            base_model.repair()

        return base_model
def mini_with_cofactors():
    """Define a minimal metabolism with two metabolites and co-factors."""
    model = cobra.Model()
    met_a = cobra.Metabolite("a_c", name="A", formula="C2")
    met_b = cobra.Metabolite("b_c", name="B", formula="C2")
    met_c = cobra.Metabolite("c_c", name="C", formula="O2")
    met_d = cobra.Metabolite("d_c", name="D", formula="CO")
    model.add_metabolites([met_a, met_b])
    rxn = cobra.Reaction("FORMB")
    rxn.add_metabolites({met_a: -1, met_b: 1})
    model.add_reactions([rxn])
    model.add_boundary(met_a)
    model.add_boundary(met_c)
    model.add_boundary(met_d)
    demand = model.add_boundary(met_b, type="demand")
    model.objective = demand
    model.objective_direction = "max"
    return model
Exemple #27
0
    def as_pathway_model(self):
        """
        Loads a cobra model with just the reactions present in this design
        Can be useful for the cobra.Model methods

        # TODO: add full metabolite info from parent model (optional, as it will be slower)
        :return: mdl instance of cobra.Model
        """

        if self._p_model is not None:
            return self._p_model

        mdl = cobra.Model()
        mdl.id = ''
        mdl = self.add_to_model(mdl, add_missing=True)
        self._p_model = mdl

        return self._p_model
def test_validator():
    """ Check models validate properly """
    with FakeProjectContext() as ctx:
        # Valid model
        model = ctx.project.model
        result = validate_model(model)
        assert len(result['errors']) == 0

        # Model that can't grow
        for re in model.exchanges:
            re.lower_bound = 0

        result = validate_model(model)
        assert len(result['errors']) == 1

        # model without constraints
        model = cobra.Model()
        result = validate_model(model)
        # Should issue warning, this assertion makes sure
        assert len(result['warnings']) == 1
def make_json_pathways(ref_model):

    pathway_dict = {
        "Bafilomycin": create_baf_pathway,
        "Difficidin": create_difficidin_pathway,
        "Anabaenopeptin": create_anabaenopeptin_pathway,
        "Tolaasin": create_tolaasin_pathway,
        "Leupyrrin": create_leupyrrin_pathway,
        "Geldanamycin": create_geldanamycin_pathway,
        "Oocydin": create_oocydin_pathway,
        "Oxazolomycin": create_oxazolo_pathway
    }
    folder = Path("../Data/validation_pathways")
    folder.mkdir(exist_ok=True)

    for key, value in pathway_dict.items():
        fn = folder / "{0}.json".format(key)
        model = cobra.Model()
        reactions = value(ref_model)
        model.add_reactions(reactions)
        cobra.io.save_json_model(model, str(fn))
    def InitializeMetabacterium(self):
        #Define LP problem object
        metabact = cobra.Model('metabacterium')
        reactions = list()
        metabolites = list()

        #Define all metabolites
        for i in range(len(self.metabolites)):
            met = self.metabolites[i]
            metabolites.append(
                cobra.Metabolite(met))  #Add cobra metabolite object
            if met == 'crowding_coeff':  #the sum of crowding coefficients should be < VProt
                metabolites[
                    i]._bound = self.VProt  #for all other metabolites, _bound == 0.
                metabolites[
                    i]._constraint_sense = "L"  # "L" specifies "lower than"

        #Define all reactions, their stoichiometric coefficients per metabolite, upper bounds, lower bounds
        #and objective coefficient (z)
        for i in range(len(self.rxns)):
            rxn = self.rxns[i]
            reactions.append(cobra.Reaction(rxn))  #Add cobra reaction object
            for j in range(len(metabolites)):
                met = metabolites[j]
                s_coeff = self.S[self.metabolites[j]][
                    rxn]  #Obtain the stoichiometric coefficients
                reactions[i].add_metabolites({met: s_coeff
                                              })  #Store for every reaction

            reactions[i].lower_bound = self.rxnBounds[rxn][
                'lb']  #Set reaction lower- (lb) and upper bounds (ub)
            reactions[i].upper_bound = self.rxnBounds[rxn]['ub']
            reactions[i].objective_coefficient = self.Z[
                rxn]  #Set coefficients of objective function (Z) for every reaction
            #Currently every index is 0, except for 'biomass_LPL6.0', which is 1.
            metabact.add_reaction(
                reactions[i]
            )  #Add all reactions incl. metabolites to metabact object

        return (metabact)