コード例 #1
0
 def export_model(self,model_id_I,filename_I,filetype_I = 'sbml',ko_list=[],flux_dict={}):
     '''export a cobra model
     INPUT:
     model_id_I = model id
     filename_I = filename
     filetype_I = if specified, the model will be written to the desired filetype
                 default: model file in the database
     '''
     
     # get the model
     cobra_model_sbml = {};
     cobra_model_sbml = self.get_row_modelID_dataStage02IsotopomerModels(model_id_I);
     if not cobra_model_sbml:
         print('model not found');
         return;
     # load the model
     cobra_model = self.writeAndLoad_modelTable(cobra_model_sbml);
     # Constrain the model
     self.constrain_modelModelVariables(cobra_model=cobra_model,ko_list=ko_list,flux_dict=flux_dict);
     # export the model
     if filetype_I == 'sbml':
         cobra_model = self.writeAndLoad_modelTable(cobra_model_sbml);
         #export the model to sbml
         write_cobra_model_to_sbml_file(cobra_model,filename_I);
     elif filetype_I == 'json':
         cobra_model = self.writeAndLoad_modelTable(cobra_model_sbml);
         #export the model to json
         save_json_model(cobra_model,filename_I);
     else:
         print('file_type not supported')
コード例 #2
0
ファイル: iterations.py プロジェクト: yseif/sbaas
def isotopomer_model_iteration1():
    '''iteration 1:
    identification of reactions that can be lumped in pathways outside the model scope'''
    cobra_model = load_ALEWt();
    # Make the model irreversible for downstream manipulations:
    convert_to_irreversible(cobra_model);
    # Add lumped isotopomer reactions
    add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible);
    # Find minimal flux solution:
    pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi');
    # Write pfba solution to file
    with open('data\\iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Flux'])
        for k,v in cobra_model.solution.x_dict.items():
            writer.writerow([k,v]);
    # Read in pfba solution 
    pfba_sol = {};
    with open('data\\iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='r') as infile:
        dictreader = csv.DictReader(infile)
        for r in dictreader:
            pfba_sol[r['Reaction']] = r['Flux'];
    # Make net reactions for pathways outside of the scope
    # of the isotopomer model
    subs = ['Cell Envelope Biosynthesis',
	    'Glycerophospholipid Metabolism',
	    'Lipopolysaccharide Biosynthesis / Recycling',
	    'Membrane Lipid Metabolism',
	    'Murein Biosynthesis'
        'Murein Recycling',
        'Cofactor and Prosthetic Group Biosynthesis',
        #'Transport, Inner Membrane',
        #'Transport, Outer Membrane',
        #'Transport, Outer Membrane Porin',
        'tRNA Charging',
        'Unassigned',
        'Exchange',
        'Inorganic Ion Transport and Metabolism',
        'Nitrogen Metabolism'];
    add_net_reaction_subsystem(cobra_model,pfba_sol,subs);
    remove_noflux_reactions(cobra_model,pfba_sol,['Transport, Outer Membrane Porin','Transport, Inner Membrane','Transport, Outer Membrane'])
    revert_to_reversible(cobra_model);
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model,'data\\iteration1_140407_ijo1366_netrxn_irreversible.xml')
    # Reduce model using FVA:
    reduce_model(cobra_model,"data\\iteration1_140407_ijo1366_reduced.xml")
    # Remove all reactions with 0 flux
    remove_noflux_reactions(cobra_model);
    with open('data\\iteration1_140407_ijo1366_reduced_netrxn_lbub.csv',mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Formula','LB','UB','Subsystem'])
        for r in cobra_model.reactions:
            writer.writerow([r.id,
                             r.build_reaction_string(),
                            r.lower_bound,
                            r.upper_bound,
                            r.subsystem]);
コード例 #3
0
ファイル: iterations.py プロジェクト: SBRG/sbaas
def isotopomer_model_iteration1():
    '''iteration 1:
    identification of reactions that can be lumped in pathways outside the model scope'''
    cobra_model = load_ALEWt();
    # Make the model irreversible for downstream manipulations:
    convert_to_irreversible(cobra_model);
    # Add lumped isotopomer reactions
    add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible);
    # Find minimal flux solution:
    pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi');
    # Write pfba solution to file
    with open('data/iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Flux'])
        for k,v in cobra_model.solution.x_dict.items():
            writer.writerow([k,v]);
    # Read in pfba solution 
    pfba_sol = {};
    with open('data/iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='r') as infile:
        dictreader = csv.DictReader(infile)
        for r in dictreader:
            pfba_sol[r['Reaction']] = r['Flux'];
    # Make net reactions for pathways outside of the scope
    # of the isotopomer model
    subs = ['Cell Envelope Biosynthesis',
	    'Glycerophospholipid Metabolism',
	    'Lipopolysaccharide Biosynthesis / Recycling',
	    'Membrane Lipid Metabolism',
	    'Murein Biosynthesis'
        'Murein Recycling',
        'Cofactor and Prosthetic Group Biosynthesis',
        #'Transport, Inner Membrane',
        #'Transport, Outer Membrane',
        #'Transport, Outer Membrane Porin',
        'tRNA Charging',
        'Unassigned',
        'Exchange',
        'Inorganic Ion Transport and Metabolism',
        'Nitrogen Metabolism'];
    add_net_reaction_subsystem(cobra_model,pfba_sol,subs);
    remove_noflux_reactions(cobra_model,pfba_sol,['Transport, Outer Membrane Porin','Transport, Inner Membrane','Transport, Outer Membrane'])
    revert_to_reversible(cobra_model);
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model,'data/iteration1_140407_ijo1366_netrxn_irreversible.xml')
    # Reduce model using FVA:
    reduce_model(cobra_model,"data/iteration1_140407_ijo1366_reduced.xml")
    # Remove all reactions with 0 flux
    remove_noflux_reactions(cobra_model);
    with open('data/iteration1_140407_ijo1366_reduced_netrxn_lbub.csv',mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Formula','LB','UB','Subsystem'])
        for r in cobra_model.reactions:
            writer.writerow([r.id,
                             r.build_reaction_string(),
                            r.lower_bound,
                            r.upper_bound,
                            r.subsystem]);
コード例 #4
0
def reduce_model(cobra_model, cobra_model_outFileName=None):
    '''reduce model'''
    # Input: cobra_model
    # Output: cobra_model
    #         the lower and upper bounds have been set to 0.0
    #         for all reactions that cannot carry a flux
    cobra_model.optimize()
    sol_f = cobra_model.solution.f

    fva_data = flux_variability_analysis(cobra_model,
                                         fraction_of_optimum=0.9,
                                         objective_sense='maximize',
                                         the_reactions=None,
                                         allow_loops=True,
                                         solver='gurobi',
                                         the_problem='return',
                                         tolerance_optimality=1e-6,
                                         tolerance_feasibility=1e-6,
                                         tolerance_barrier=1e-8,
                                         lp_method=1,
                                         lp_parallel=0,
                                         new_objective=None,
                                         relax_b=None,
                                         error_reporting=None,
                                         number_of_processes=1,
                                         copy_model=False)
    #with open("data\\ijo1366_irrev_fva.json", 'w') as outfile:
    #    json.dump(data, outfile, indent=4);

    #fva_data = json.load(open("data\\ijo1366_irrev_fva.json"));

    # Reduce model
    rxns_noflux = []
    for k, v in fva_data.items():
        if v['minimum'] == 0.0 and v['maximum'] == 0.0:
            cobra_model.reactions.get_by_id(k).lower_bound = 0.0
            cobra_model.reactions.get_by_id(k).upper_bound = 0.0
            rxns_noflux.append(k)

    if cobra_model_outFileName:
        write_cobra_model_to_sbml_file(cobra_model, cobra_model_outFileName)

    cobra_model.optimize()
    sol_reduced_f = cobra_model.solution.f

    # Check that the reduced model is consistent with the original model
    if not sol_f == sol_reduced_f:
        print('reduced model is inconsistent with the original model')
        print('original model solution: ' + str(sol_f))
        print('reduced model solution: ' + str(sol_reduced_f))
コード例 #5
0
def export_modelWithFlux(cobra_model_xml_I, ci_list_I, cobra_model_xml_O):
    '''update model lower_bound/upper_bound with calculated flux confidence intervals'''

    cobra_model = create_cobra_model_from_sbml_file(cobra_model_xml_I)

    rxns_add = []
    rxns_omitted = []
    rxns_break = []

    system_boundaries = [
        x.id for x in cobra_model.reactions if x.boundary == 'system_boundary'
    ]
    objectives = [
        x.id for x in cobra_model.reactions if x.objective_coefficient == 1
    ]

    for i, ci_I in enumerate(ci_list_I):
        print('add flux from ci ' + str(i))
        for rxn in cobra_model.reactions:
            if rxn.id in list(ci_I.keys()) and not(rxn.id in system_boundaries)\
                and not(rxn.id in objectives):
                cobra_model_copy = cobra_model.copy()
                # check for reactions that break the model:
                if ci_I[rxn.id]['minv'] > 0:
                    cobra_model_copy.reactions.get_by_id(
                        rxn.id).lower_bound = ci_I[rxn.id]['minv']
                if ci_I[rxn.id]['maxv'] > 0 and ci_I[rxn.id]['maxv'] > ci_I[
                        rxn.id]['minv']:
                    cobra_model_copy.reactions.get_by_id(
                        rxn.id).upper_bound = ci_I[rxn.id]['maxv']
                cobra_model_copy.optimize(solver='gurobi')
                if not cobra_model_copy.solution.f:
                    print(rxn.id + ' broke the model!')
                    rxns_break.append(rxn.id)
                else:
                    if ci_I[rxn.id]['minv'] > 0:
                        cobra_model.reactions.get_by_id(
                            rxn.id).lower_bound = ci_I[rxn.id]['minv']
                    if ci_I[rxn.id]['maxv'] > 0 and ci_I[
                            rxn.id]['maxv'] > ci_I[rxn.id]['minv']:
                        cobra_model.reactions.get_by_id(
                            rxn.id).upper_bound = ci_I[rxn.id]['maxv']
                    rxns_add.append(rxn.id)
            else:
                rxns_omitted.append(rxn.id)

    write_cobra_model_to_sbml_file(cobra_model, cobra_model_xml_O)
コード例 #6
0
def reduce_model_pfba(cobra_model,
                      cobra_model_outFileName=None,
                      fba_outFileName=None,
                      subs=[]):
    '''reduce model using pfba'''
    # Input: cobra_model
    #        cobra_model_outFileName
    #        subs = string of specific subsystems to reduce
    # Output: cobra_model
    #         the lower and upper bounds have been set to 0.0
    #         for all reactions that cannot carry a flux
    cobra_model.optimize()
    sol_f = cobra_model.solution.f

    # Find minimal flux solution:
    pfba = optimize_minimal_flux(cobra_model, True, solver='gurobi')

    # Reduce model
    rxns_noflux = []
    # set lb and ub for all reactions with 0 flux to 0;
    for k, v in cobra_model.solution.x_dict.items():
        if (v < 0.0 or v == 0.0
            ) and cobra_model.reactions.get_by_id(k).subsystem in subs:
            cobra_model.reactions.get_by_id(k).lower_bound = 0.0
            cobra_model.reactions.get_by_id(k).upper_bound = 0.0
            rxns_noflux.append(k)

    if cobra_model_outFileName:
        write_cobra_model_to_sbml_file(cobra_model, cobra_model_outFileName)

    if pfba_outFileName:
        # Write pfba solution to file
        with open(pfba_outFileName, mode='wb') as outfile:
            writer = csv.writer(outfile)
            writer.writerow(['Reaction', 'Flux'])
            for k, v in cobra_model.solution.x_dict.items():
                writer.writerow([k, v])

    cobra_model.optimize()
    sol_reduced_f = cobra_model.solution.f

    # Check that the reduced model is consistent with the original model
    if not sol_f == sol_reduced_f:
        print('reduced model is inconsistent with the original model')
        print('original model solution: ' + str(sol_f))
        print('reduced model solution: ' + str(sol_reduced_f))
コード例 #7
0
ファイル: cobra_methods.py プロジェクト: SBRG/sbaas
    def reduce_model_pfba(self,cobra_model,cobra_model_outFileName=None,fba_outFileName=None,subs=[]):
        '''reduce model using pfba'''
        # Input: cobra_model
        #        cobra_model_outFileName
        #        subs = string of specific subsystems to reduce
        # Output: cobra_model 
        #         the lower and upper bounds have been set to 0.0
        #         for all reactions that cannot carry a flux
        cobra_model.optimize()
        sol_f = cobra_model.solution.f

        # Find minimal flux solution:
        pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi');

        # Reduce model
        rxns_noflux = [];
        # set lb and ub for all reactions with 0 flux to 0;
        for k,v in cobra_model.solution.x_dict.items():
            if (v < 0.0 or v == 0.0) and cobra_model.reactions.get_by_id(k).subsystem in subs:
                cobra_model.reactions.get_by_id(k).lower_bound = 0.0;
                cobra_model.reactions.get_by_id(k).upper_bound = 0.0;
                rxns_noflux.append(k);

        if cobra_model_outFileName:
            write_cobra_model_to_sbml_file(cobra_model,cobra_model_outFileName)

        if pfba_outFileName:
            # Write pfba solution to file
            with open(pfba_outFileName,mode='wb') as outfile:
                writer = csv.writer(outfile)
                writer.writerow(['Reaction','Flux'])
                for k,v in cobra_model.solution.x_dict.items():
                    writer.writerow([k,v]);

        cobra_model.optimize()
        sol_reduced_f = cobra_model.solution.f

        # Check that the reduced model is consistent with the original model
        if not sol_f == sol_reduced_f:
            print('reduced model is inconsistent with the original model')
            print('original model solution: ' + str(sol_f))
            print('reduced model solution: ' + str(sol_reduced_f))
コード例 #8
0
ファイル: cobra_methods.py プロジェクト: SBRG/sbaas
    def reduce_model(self,cobra_model,cobra_model_outFileName=None):
        '''reduce model'''
        # Input: cobra_model
        # Output: cobra_model 
        #         the lower and upper bounds have been set to 0.0
        #         for all reactions that cannot carry a flux
        cobra_model.optimize()
        sol_f = cobra_model.solution.f

        fva_data = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9,
                                              objective_sense='maximize', the_reactions=None,
                                              allow_loops=True, solver='gurobi',
                                              the_problem='return', tolerance_optimality=1e-6,
                                              tolerance_feasibility=1e-6, tolerance_barrier=1e-8,
                                              lp_method=1, lp_parallel=0, new_objective=None,
                                              relax_b=None, error_reporting=None,
                                              number_of_processes=1, copy_model=False);
        #with open("data/ijo1366_irrev_fva.json", 'w') as outfile:
        #    json.dump(data, outfile, indent=4);

        #fva_data = json.load(open("data/ijo1366_irrev_fva.json"));

        # Reduce model
        rxns_noflux = [];
        for k,v in fva_data.items():
            if v['minimum'] == 0.0 and v['maximum'] == 0.0:
                cobra_model.reactions.get_by_id(k).lower_bound = 0.0;
                cobra_model.reactions.get_by_id(k).upper_bound = 0.0;
                rxns_noflux.append(k);

        if cobra_model_outFileName:
            write_cobra_model_to_sbml_file(cobra_model,cobra_model_outFileName)

        cobra_model.optimize()
        sol_reduced_f = cobra_model.solution.f

        # Check that the reduced model is consistent with the original model
        if not sol_f == sol_reduced_f:
            print('reduced model is inconsistent with the original model')
            print('original model solution: ' + str(sol_f))
            print('reduced model solution: ' + str(sol_reduced_f))
コード例 #9
0
ファイル: analyze13Cflux.py プロジェクト: SBRG/sbaas
def export_modelWithFlux(cobra_model_xml_I,ci_list_I,cobra_model_xml_O):
    '''update model lower_bound/upper_bound with calculated flux confidence intervals'''

    cobra_model = create_cobra_model_from_sbml_file(cobra_model_xml_I);

    rxns_add = [];
    rxns_omitted = [];
    rxns_break = [];

    system_boundaries = [x.id for x in cobra_model.reactions if x.boundary == 'system_boundary'];
    objectives = [x.id for x in cobra_model.reactions if x.objective_coefficient == 1];

    for i,ci_I in enumerate(ci_list_I):
        print('add flux from ci ' + str(i));
        for rxn in cobra_model.reactions:
            if rxn.id in list(ci_I.keys()) and not(rxn.id in system_boundaries)\
                and not(rxn.id in objectives):
                cobra_model_copy = cobra_model.copy();
                # check for reactions that break the model:
                if ci_I[rxn.id]['minv'] > 0:
                    cobra_model_copy.reactions.get_by_id(rxn.id).lower_bound = ci_I[rxn.id]['minv'];
                if ci_I[rxn.id]['maxv'] > 0 and ci_I[rxn.id]['maxv'] > ci_I[rxn.id]['minv']:
                    cobra_model_copy.reactions.get_by_id(rxn.id).upper_bound = ci_I[rxn.id]['maxv'];
                cobra_model_copy.optimize(solver='gurobi');
                if not cobra_model_copy.solution.f:
                    print(rxn.id + ' broke the model!')
                    rxns_break.append(rxn.id);
                else: 
                    if ci_I[rxn.id]['minv'] > 0:
                        cobra_model.reactions.get_by_id(rxn.id).lower_bound = ci_I[rxn.id]['minv'];
                    if ci_I[rxn.id]['maxv'] > 0 and ci_I[rxn.id]['maxv'] > ci_I[rxn.id]['minv']:
                        cobra_model.reactions.get_by_id(rxn.id).upper_bound = ci_I[rxn.id]['maxv'];
                    rxns_add.append(rxn.id);
            else:
                rxns_omitted.append(rxn.id);

    write_cobra_model_to_sbml_file(cobra_model,cobra_model_xml_O)
コード例 #10
0
            experimental_r_id = linkdict['exprxns'][0]['rxid']
            token_id = 't_{exprxnid}'.format(exprxnid = experimental_r_id)
            new_token_reaction = Reaction(token_id)
            new_token_reaction.name = 'Token exchange reaction for experimental reaction {exprxnid}'.format(exprxnid = experimental_r_id)
            new_token_reaction.lower_bound = -1000
            new_token_reaction.upper_bound = 1000
            new_token_metabolite = Metabolite(token_id,name = 'Token metabolite for experimental reaction {exprxnid}'.format(exprxnid = experimental_r_id),compartment='c')
            new_token_reaction.add_metabolites({new_token_metabolite: -1.0})
            model.add_reactions(new_token_reaction)
            for dictionary in linkdict['modrxns']:
                modelreaction = model.reactions.get_by_id(dictionary['rxid'])
                modelreaction.add_metabolites({new_token_metabolite: float(dictionary['coef'])})
    return model


if __name__ == "__main__":

    from cobra.io.sbml import create_cobra_model_from_sbml_file
    from cobra.io.sbml import write_cobra_model_to_sbml_file
    import loadData as load

    notokenmodel = create_cobra_model_from_sbml_file('../SBML/SCHUETZR_notokens.xml')
    notokenmap = load.ReactionMapfromXML('reactionmaps_notokens.xml','Perrenoud','SCHUETZR')
                                            
    tokenmodel = createTokens(notokenmodel,notokenmap)
    sbml_out_file = 'SCHUETZR_withtokens.xml'
    sbml_level = 2
    sbml_version = 1
    write_cobra_model_to_sbml_file(tokenmodel, sbml_out_file, sbml_level,sbml_version, print_time=False)
    
コード例 #11
0
# cobra/examples/02_read_simulate_write.py
#
# This example demonstrates reading in a COBRA SBML model xml file
# performing a simple optimization, and then saving the model as an SBML xml file.
#
# The model is from the Salmonella enterica Typhimurium LT2 publication in
# 2011 in BMC Sys Bio 5:8
#
# The simulated growth rate should be ~0.478.
#
from cobra.io.sbml import create_cobra_model_from_sbml_file
from cobra.io.sbml import write_cobra_model_to_sbml_file
from cobra.test import salmonella_sbml
sbml_out_file = 'salmonella.out.xml'
sbml_level = 2
sbml_version = 1  # Writing version 4 is not completely supported.
#Read in the sbml file.
cobra_model = create_cobra_model_from_sbml_file(salmonella_sbml, print_time=True)
# Run the optimization for the objective reaction and medium composition
# set in the file.
cobra_model.optimize(solver='glpk')  # 'gurobi' or 'cplex' are also supported
print '\nSimulated growth rate is %1.3f' % cobra_model.solution.f

#Save the model to an SBML file
print '\nConverting Model to SBML and saving as ' + sbml_out_file
write_cobra_model_to_sbml_file(cobra_model, sbml_out_file, sbml_level,
                               sbml_version, print_time=True)
コード例 #12
0
ファイル: iterations.py プロジェクト: SBRG/sbaas
def isotopomer_model_iteration2(pfba_filename,fva_reduced_model_filename,netrxn_irreversible_model_filename,reduced_lbub_filename):
    '''iteration 2:
    addition of finalized lumped reactions that are in pathways that are within the scope of the model
    and reduction by removing reactions with zero optimal minimal flux outside the scope of the model'''
    cobra_model = load_ALEWt();
    # Make the model irreversible for downstream manipulations:
    convert_to_irreversible(cobra_model);
    cobra_model.optimize();
    # Add lumped isotopomer reactions
    add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible,True);
    cobra_model.optimize();
    # Find minimal flux solution:
    pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi');
    # Write pfba solution to file
    with open(pfba_filename,mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Flux','Subsystem'])
        for k,v in cobra_model.solution.x_dict.items():
            writer.writerow([k,v,cobra_model.reactions.get_by_id(k).subsystem]);
    # Read in pfba solution 
    pfba_sol = {};
    with open(pfba_filename,mode='r') as infile:
        dictreader = csv.DictReader(infile)
        for r in dictreader:
            pfba_sol[r['Reaction']] = r['Flux'];
    # remove noflux reactions for pathways outside of the scope
    # of the isotopomer model
    subs = ['Cell Envelope Biosynthesis',
	    'Glycerophospholipid Metabolism',
	    'Lipopolysaccharide Biosynthesis / Recycling',
	    'Membrane Lipid Metabolism',
	    'Murein Biosynthesis'
        'Murein Recycling',
        'Cofactor and Prosthetic Group Biosynthesis',
        'Transport, Inner Membrane',
        'Transport, Outer Membrane',
        'Transport, Outer Membrane Porin',
        'tRNA Charging',
        'Unassigned',
        #'Exchange',
        'Inorganic Ion Transport and Metabolism',
        'Nitrogen Metabolism',
        'Alternate Carbon Metabolism'];
    remove_noflux_reactions(cobra_model,pfba_sol,subs)
    # Reduce model using FVA:
    reduce_model(cobra_model,fva_reduced_model_filename)
    # Reset secretion products that may have been turned off
    secrete = ['EX_meoh_LPAREN_e_RPAREN_',
                'EX_5mtr_LPAREN_e_RPAREN_',
                'EX_h_LPAREN_e_RPAREN_',
                'EX_co2_LPAREN_e_RPAREN_',
                'EX_co_LPAREN_e_RPAREN_',
                'EX_h2o_LPAREN_e_RPAREN_',
                'EX_ac_LPAREN_e_RPAREN_',
                'EX_fum_LPAREN_e_RPAREN_',
                'EX_for_LPAREN_e_RPAREN_',
                'EX_etoh_LPAREN_e_RPAREN_',
                'EX_lac_DASH_L_LPAREN_e_RPAREN_',
                'EX_pyr_LPAREN_e_RPAREN_',
                'EX_succ_LPAREN_e_RPAREN_'];
    for s in secrete:
        cobra_model.reactions.get_by_id(s).upper_bound = 1000.0;
    # Remove all reactions with 0 flux
    r1,r2 = get_reactionsInfo(cobra_model);
    while r2 !=0:
        remove_noflux_reactions(cobra_model);
        r1,r2 = get_reactionsInfo(cobra_model);
        print(r1,r2);
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model,netrxn_irreversible_model_filename)
    with open(reduced_lbub_filename,mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Formula','LB','UB','Subsystem'])
        for r in cobra_model.reactions:
            writer.writerow([r.id,
                             r.build_reaction_string(),
                            r.lower_bound,
                            r.upper_bound,
                            r.subsystem]);
コード例 #13
0
def gxFBA(cobramodel_1,cobramodel_2,gene_expressions,GPRlist,maxflux = 500, exprType = 2, verbose = True,FVAcondition = 2, wait = False,treshold = 0.5,objectiveweights = 'log',dumpmodel = False):
    if verbose:
        print 'Performing gxFBA. Verbose = True.'
        print 'Provided gene expression ratios:'
        print gene_expressions
        if exprType == 1:
            print 'Input gene expression ratios handled as absolute ratios.'
        else:
            print 'Input gene expression ratios handled as log ratios.'

    if exprType == 1:
        logvals = {gene:log(gene_expressions[gene],2) for gene in gene_expressions}
        ratios = gene_expressions
        if verbose:
            print 'Calculated log ratios:'
            print logvals
    else:
        logvals = gene_expressions
        ratios = {gene:2**gene_expressions[gene] for gene in gene_expressions}
    
    #Local variables:
    eps2 = 0.00001

    ##1) Generate the wild-type flux distribution v_i_wt for the starting condition:
    cobramodel_1.optimize(solver='gurobi')
    wildtype = cobramodel_1.solution.x_dict
    if verbose:
        print 'generated wild-type flux distribution.'
        #print cobramodel_1.solution.x_dict
        for key,value in sorted(cobramodel_1.solution.x_dict.items()):
            print key,value
    if wait:
        hold()
    ###2) Perform FVA with nutritional constraints for condition 1 or 2 (Default: condition 2) and minimum biomass flux = 0 to calculate the upper and lower fluxes each
    ###    reaction can carry.

    if FVAcondition == 1:
        FVA_result = cobra.flux_analysis.variability.flux_variability_analysis(cobramodel_1,fraction_of_optimum = 0)
    else:
        FVA_result = cobra.flux_analysis.variability.flux_variability_analysis(cobramodel_2,fraction_of_optimum = 0)
    if verbose:
        print 'Performed FVA for condition',FVAcondition
        for key,value in sorted(FVA_result.items()):
            print key,value
        #print FVA_result

    #Reset the objective function for condition 2:
    for reaction in cobramodel_2.reactions:
        reaction.objective_coefficient = 0

    ###    Calculate mean possible flux value for each reaction under condition 2, and the flux average for all active reactions under condition 1
    wt_avg = {key:np.mean([FVA_result[key]['minimum'],FVA_result[key]['maximum']])  for key in FVA_result}
    active_fluxes = [fluxvalue for fluxvalue in wildtype.values() if fluxvalue > eps2]
    wildtype_averageflux = np.mean(active_fluxes) #average wildtype flux

    if verbose:
        print 'FVA average fluxes:'
        #print wt_avg
        for key,value in wt_avg.items():
            print key,value
        print 'Total number of reactions in wildtype model:',len(wildtype.values())
        print 'Number of active reactions in wildtype FBA solution:',len(active_fluxes)
        print 'Average wildtype flux (Average of flux value for all fluxes in wildtype FBA solution):',wildtype_averageflux

    genemap = defaultdict(list)
    for gene in gene_expressions:
        if gene in GPRlist:
            for rx in GPRlist[gene]:
                genemap[rx].append(gene)

    if verbose:
        print 'Gene map:'
        print genemap


    if wait:
        hold()
    T = []
    ##3) Identify the set of reactions (called T) for which an mRNA expression value can be associated.
    if verbose:
        print 'Identifying reactions eligible for gx-regulation.'
    for reaction in cobramodel_2.reactions:
        #Skip reactions for which gene expression data is unavailable
        if reaction.id not in genemap:
            if verbose:
                print reaction.id,'not in genemap. Skipping reaction.'
            continue
        #Skip reactions for which the maximal up/down-regulation is below the set treshold:
        expressionratios = [ratios[gene] for gene in genemap[reaction.id] ]
        if max([abs(ratio-1) for ratio in expressionratios]) < treshold:
            if verbose:
                print reaction.id,': Level of regulation below treshold. Skipping reaction.'
            continue
        #Do not include the reaction if the average flux is too high:
        if wt_avg[reaction.id] >= maxflux:
            if verbose:
                print reaction.id,': FVA average flux too high. Skipping reaction.'
            continue
        #Do not include the reaction if it cannot carry any flux (as per FVA):
        if abs(wt_avg[reaction.id]) < eps2:
            if verbose:
                print reaction.id,': Reaction always inactive under specified conditions. Skipping reaction.'
            continue
        #Do not include the reaction if it is not irreversible under the given constraints:
        bounds = FVA_result[reaction.id].values()
        irreversible = not min(bounds) < 0 < max(bounds)
        if not irreversible:
            if verbose:
                print reaction.id,': Reaction may carry flux in both directions under specified conditions. Skipping reaction.'
            continue
        #Do not include the reaction if gene expression data is inconsistent (both up- and down-regulation):
        exprvalues = [logvals[gene] for gene in genemap[reaction.id] ]
        signs = [cmp(logvalue,0) for logvalue in exprvalues]
        if not (signs[1:] == signs[:-1]): #If all the signs are not the same value. Alternative: if not (signs.count(signs[0]) == signs(x))
            if verbose:
                print 'Gene expression information for reaction indicates mixed regulation (up/down). Skipping reaction.'
            continue
        #If none of the above checks failed, add the reaction to the list:
        if verbose:
            print 'Adding reaction',reaction.id,'to T.'
        T.append(reaction)


    ##4)  For each reaction in T; define a new upper bound UB = Ci_mRNA * v_i_wt if up-regulated or a new lower bound LB =
    ##    Ci_mRNA * v_i_wt if downregulated, where Ci_mRNA is the mRNA expression ratio.
    if verbose:
        print 'Calculating new bounds and objective function coefficients:'


    def reactionInfo(reaction_id):
        print 'Ci_mRNA:',Ci_mRNA
        print 'Wild-type flux:',wildtype[reaction.id]
        print 'Original reaction bounds:'
        print 'Lower:',cobramodel_1.reactions.get_by_id(reaction.id).lower_bound,'Upper:',cobramodel_1.reactions.get_by_id(reaction.id).upper_bound
        print 'New reaction bounds:'
        print 'Lower:',reaction.lower_bound,'Upper:',reaction.upper_bound
        print 'Objective coefficient:',reaction.objective_coefficient
    for reaction in T:
        if wait:
            hold()
        logvalues = [logvals[gene] for gene in genemap[reaction.id] ]
        expressionratios = [ratios[gene] for gene in genemap[reaction.id] ] 
        sign = cmp(logvalues[0],0)
        if verbose:
            print 'Processing reaction:',reaction.id
            print 'Logvalues:',logvalues
            print 'Ratios:',expressionratios
            
        if sign > 0:
            Ci_mRNA = 2**max(logvalues) ##    For reactions dependent on several genes (several mRNA values), use the maximal up/down-regulation value.
            if wildtype[reaction.id] == 0:
                reaction.upper_bound = Ci_mRNA * wildtype_averageflux
            else:
                reaction.upper_bound = Ci_mRNA * wildtype[reaction.id]
            #Set the objective function coefficient: Ci = log(Ci_mRNA) / (v_i average):
            if objectiveweights == 'log':
                reaction.objective_coefficient = max(logvalues) / wt_avg[reaction.id]
            elif objectiveweights =='logabs':
                reaction.objective_coefficient = max(logvalues) / wt_avg[reaction.id]
            elif objectiveweights == 'ratios':
                reaction.objective_coefficient = Ci_mRNA / wt_avg[reaction.id]
            elif objectiveweights == 'pureratios':
                reaction.objective_coefficient = Ci_mRNA
            
        elif sign < 0:
            Ci_mRNA = 2**min(logvalues) ##    For reactions dependent on several genes (several mRNA values), use the maximal up/down-regulation value.
            if wildtype[reaction.id] == 0:
                pass
            else:
                reaction.lower_bound = Ci_mRNA * wildtype[reaction.id]
            #Set the new objective function coefficient: Ci = log(Ci_mRNA) / (v_i average):
            if objectiveweights == 'log':
                reaction.objective_coefficient = min(logvalues) / wt_avg[reaction.id]
            elif objectiveweights =='logabs':
                reaction.objective_coefficient = abs(min(logvalues)) / wt_avg[reaction.id]
            elif objectiveweights =='ratios':
                reaction.objective_coefficient = Ci_mRNA / wt_avg[reaction.id]
            elif objectiveweights == 'pureratios':
                reaction.objective_coefficient = Ci_mRNA
        if verbose:
            reactionInfo(reaction.id)

    cobramodel_2.reactions.get_by_id('R5_akgdh').lower_bound = 0.65
    cobramodel_2.reactions.get_by_id('R5_akgdh').upper_bound = 1.3
    cobramodel_2.reactions.get_by_id('R2_lowergly').lower_bound = 0.8
    cobramodel_2.reactions.get_by_id('R2_lowergly').upper_bound = 3.42857

    cobramodel_2.reactions.get_by_id('R2_lowergly').objective_coefficient = 1.5
    cobramodel_2.reactions.get_by_id('R5_akgdh').objective_coefficient = 0.5
    cobramodel_2.reactions.get_by_id('R1_uppergly').objective_coefficient = 1.5
    cobramodel_2.reactions.get_by_id('R3_citsyn').objective_coefficient = 0.5
    if verbose:
        print 'New objective function:'
        #print {reaction.id:reaction.objective_coefficient for reaction in T}
        print {reaction.id:reaction.objective_coefficient for reaction in cobramodel_2.reactions}
        print 'New lower bounds:',[reaction.lower_bound for reaction in cobramodel_2.reactions]
        print 'New upper bounds:',[reaction.upper_bound for reaction in cobramodel_2.reactions]
        print 'Performing gx-FBA.'
        

    #Solve the gx-FBA problem:
    cobramodel_2.optimize(solver='gurobi')
    if verbose:
        print 'Flux solution:'
        print cobramodel_2.solution.x_dict
        print 'Objective value:',cobramodel_2.solution

    #Using Gurobi manually:
    gurobisolution = QPmindist.gurobiFBA(cobramodel_2)
    gurobisolutiondict = QPmindist.getgurobisolutiondict(gurobisolution)
    print 'gurobi solution:'
    print gurobisolutiondict
    print 'Objective value:',gurobisolution.Objval

    #Check that mass conservation is preserved:
    print 'Total metabolite fluxes:'
    for metabolite in cobramodel_2.metabolites:
        print metabolite.id,metabolitefluxsum(metabolite.id,cobramodel_2),metabolitefluxsum(metabolite.id,cobramodel_2, abs = True)

    #print 'ATP fluxes:',metabolitefluxes('atp_c',cobramodel_2)
    #print ''

    print 'Solution:'
    print cobramodel_2.solution.x
    vectorToText(cobramodel_2.solution.x,'flux.txt')
    print 'Flux solution dumped to flux.txt'
    #vectorToText([reaction.objective_coefficient for reaction in cobramodel_2.reactions],'objective.txt')
    vectorToText([reaction.objective_coefficient for reaction in cobramodel_2.reactions],'objective.txt', decimal = ',')
    vectorToText([reaction.lower_bound for reaction in cobramodel_1.reactions],'FBA-lb.txt')
    vectorToText([reaction.upper_bound for reaction in cobramodel_1.reactions],'FBA-ub.txt')
    vectorToText([reaction.lower_bound for reaction in cobramodel_2.reactions],'gxFBA-lb.txt')
    vectorToText([reaction.upper_bound for reaction in cobramodel_2.reactions],'gxFBA-ub.txt')

    vectorToText([reaction.objective_coefficient for reaction in cobramodel_2.reactions],'A.txt', decimal = ',', linestart = 'C:')
    #vectorToText([reaction.lower_bound for reaction in cobramodel_1.reactions],'A.txt',append = True, linestart = 'LB:')
    #vectorToText([reaction.upper_bound for reaction in cobramodel_1.reactions],'A.txt', append = True,linestart = 'UB:')
    vectorToText([reaction.lower_bound for reaction in cobramodel_2.reactions],'A.txt', append = True, linestart = 'LB:')
    vectorToText([reaction.upper_bound for reaction in cobramodel_2.reactions],'A.txt.', append = True, linestart = 'UB:')
    vectorToText(cobramodel_2.solution.x,'A.txt.', append = True, linestart = 'V:')

    if dumpmodel:
        write_cobra_model_to_sbml_file(cobramodel_2,'dumpedmodel.xml')
    
    return cobramodel_2
コード例 #14
0
ファイル: iterations.py プロジェクト: SBRG/sbaas
def isotopomer_model_iteration3(model_filename,xml_filename,mat_filename,csv_filename,isotopomer_mapping_filename,ko_list=[],flux_dict={},description=None):
    '''iteration 3:
    Remove reactions that are thermodynamically unfavorable and add isotopomer data'''
    # Read in the sbml file and define the model conditions
    cobra_model = create_cobra_model_from_sbml_file(model_filename, print_time=True)
    # Modify glucose uptake:
    if cobra_model.reactions.has_id('EX_glc_LPAREN_e_RPAREN__reverse'):
        lb,ub = cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN__reverse').lower_bound,cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN__reverse').upper_bound;
        EX_glc_mets = {};
        EX_glc_mets[cobra_model.metabolites.get_by_id('glc_DASH_D_e')] = -1;
        EX_glc = Reaction('EX_glc_LPAREN_e_RPAREN_');
        EX_glc.add_metabolites(EX_glc_mets);
        cobra_model.add_reaction(EX_glc)
        cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN_').lower_bound = -ub;
        cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN_').upper_bound = lb;
        cobra_model.remove_reactions(['EX_glc_LPAREN_e_RPAREN__reverse'])
    ## Remove thermodynamically infeasible reactions:
    #infeasible = [];
    #loops = [];
    #cobra_model.remove_reactions(infeasible + loops);
    # Apply KOs, if any:
    for ko in ko_list:
        cobra_model.reactions.get_by_id(ko).lower_bound = 0.0;
        cobra_model.reactions.get_by_id(ko).upper_bound = 0.0;
    # Apply flux constraints, if any:
    for rxn,flux in flux_dict.items():
        cobra_model.reactions.get_by_id(rxn).lower_bound = flux['lb'];
        cobra_model.reactions.get_by_id(rxn).upper_bound = flux['ub'];
    # Change description, if any:
    if description:
        cobra_model.description = description;
    # Read in isotopomer model
    isotopomer_mapping = read_isotopomer_mapping_csv(isotopomer_mapping_filename);
    isotopomer_str = build_isotopomer_str(isotopomer_mapping);
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model,xml_filename)
    # Add isotopomer field to model
    for r in cobra_model.reactions:
        if r.id in isotopomer_str:
            cobra_model.reactions.get_by_id(r.id).isotopomer = isotopomer_str[r.id];
        else:
            cobra_model.reactions.get_by_id(r.id).isotopomer = '';
    # Add null basis:
    cobra_model_array = cobra_model.to_array_based_model();
    N = null(cobra_model_array.S.todense()) #convert S from sparse to full and compute the nullspace
    cobra_model.N = N;
    # solve and save pFBA for later use:
    optimize_minimal_flux(cobra_model,True,solver='gurobi');
    # add match field:
    match = numpy.zeros(len(cobra_model.reactions));
    cobra_model.match = match;
    # write model to mat
    save_matlab_model_isotopomer(cobra_model,mat_filename);
    with open(csv_filename,mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction','Formula','LB','UB','Genes','Subsystem','Isotopomer'])
        for r in cobra_model.reactions:
            writer.writerow([r.id,
                             r.build_reaction_string(),
                            r.lower_bound,
                            r.upper_bound,
                            r.gene_reaction_rule,
                            r.subsystem,
                            r.isotopomer]);
コード例 #15
0
#cobra/examples/02_read_simulate_write.py
#
#This file provides a simple example of how to read a COBRA SBML model xml file,
#perform a simple optimization, and then save the model as an SBML xml file.
#
# The model is from the Salmonella enterica Typhimurium LT2 publication in
# 2011 in BMC Sys Bio 5:8
#
# The simulated growth rate should be ~0.478.
#
from cobra.io.sbml import create_cobra_model_from_sbml_file
from cobra.io.sbml import write_cobra_model_to_sbml_file
from cobra.test import salmonella_sbml
solver = 'glpk' #Change to 'gurobi' or 'cplex' if you have that solver installed instead.
sbml_out_file = 'salmonella.out.xml'
sbml_level = 2
sbml_version = 1 #Writing version 4 is not completely supported.
#Read in the sbml file.
cobra_model = create_cobra_model_from_sbml_file(salmonella_sbml, print_time=True)
#Run the optimization for the objective reaction and medium composition
#set in the file.
cobra_model.optimize(solver=solver)
print '\nSimulated growth rate is %1.3f'%cobra_model.solution.f

#Save the model to an SBML file
print '\nConverting Model to SBML and saving as ' + sbml_out_file
write_cobra_model_to_sbml_file(cobra_model, sbml_out_file, sbml_level,
                               sbml_version, print_time=True)
コード例 #16
0
# This example demonstrates reading in a COBRA SBML model xml file
# performing a simple optimization, and then saving the model as an SBML xml file.
#
# The model is from the Salmonella enterica Typhimurium LT2 publication in
# 2011 in BMC Sys Bio 5:8
#
# The simulated growth rate should be ~0.478.
#
from cobra.io.sbml import create_cobra_model_from_sbml_file
from cobra.io.sbml import write_cobra_model_to_sbml_file
from cobra.test import salmonella_sbml
sbml_out_file = 'salmonella.out.xml'
sbml_level = 2
sbml_version = 1  # Writing version 4 is not completely supported.
#Read in the sbml file.
cobra_model = create_cobra_model_from_sbml_file(salmonella_sbml)
# Run the optimization for the objective reaction and medium composition
# set in the file.
cobra_model.optimize(solver='glpk')  # 'gurobi' or 'cplex' are also supported
print('\nSimulated growth rate is %1.3f' % cobra_model.solution.f)

#Save the model to an SBML file
print('\nConverting Model to SBML and saving as ' + sbml_out_file)
write_cobra_model_to_sbml_file(cobra_model, sbml_out_file, sbml_level,
                               sbml_version)
コード例 #17
0
    def execute_makeModel(self,
            model_id_I=None,
            model_file_name_I=None,
            model_id_O=None,date_O=None,
            ko_list=[],flux_dict={},rxn_include_list=[],
            model_id_template_I='iJO1366',
            description=None,convert2irreversible_I=False,revert2reversible_I=False):
        '''make the model
        INPUT:
        model_id_I = existing model_id (if specified, an existing model in the database will be retrieved and modified)
        model_file_name_I = new model from file (if specified, a new model from file will be retrieved and modified)
        model_id_O = new model_id
        date_O = date the model was made
        description = description for the model
        INPUT (constraints in order):
        ko_list = list of reactions to constrain to zero flux
        flux_dict = dictionary of fluxes to constrain the model
        INPUT (model manipulation in order):
        rxn_include_list = list of reactions to include in the new model
        convert2irreversible_I = boolean, if True, the model will be converted to irreversible from reversible
        revert2reversible_I = boolean, if True, the model will be revert to reversible from irreversible

        Not yet implemented
        #----
        rxn_add_list = list of reactions to add from a different model
        model_add = model to add reactions from
        #----

        '''
        # retreive the model
        if model_id_I and model_id_O and date_O: #modify an existing model in the database
            cobra_model_sbml = None;
            cobra_model_sbml = self.get_row_modelID_dataStage02PhysiologyModels(model_id_I);
            cobra_model = self.writeAndLoad_modelTable(cobra_model_sbml);
        elif model_file_name_I and model_id_O and date_O: #modify an existing model not in the database
            # check for the file type
            cobra_model = self.load_model(model_file_name_I);
        else:
            print('need to specify either an existing model_id or model_file_name!')
            return;
        # Constrain the model
        self.constrain_modelModelVariables(cobra_model,
                          ko_list=ko_list,flux_dict=flux_dict);
        # Use only a subset of reactions, if specified
        if rxn_include_list:
            remove_reactions=[];
            for rxn in cobra_model.reactions:
                if not rxn.id in rxn_include_list:
                    remove_reactions.append(rxn);
            cobra_model.remove_reactions(remove_reactions,delete=True,remove_orphans=True);
        if convert2irreversible_I: convert_to_irreversible(cobra_model);
        if revert2reversible_I: 
            self.repair_irreversibleModel(cobra_model);
            self.revert2reversible(cobra_model);
            #revert_to_reversible(cobra_model,update_solution = False)
        # Change description, if any:
        if description:
            cobra_model.description = description;
        # test the model
        if self.test_model(cobra_model):
            # write the model to a temporary file
            write_cobra_model_to_sbml_file(cobra_model, 'cobra_model_tmp.xml');
            # upload the model to the database
            self.import_dataStage02PhysiologyModel_sbml(model_id_O, date_O, 'cobra_model_tmp.xml');
コード例 #18
0
ファイル: iterations.py プロジェクト: yseif/sbaas
def isotopomer_model_iteration2(pfba_filename, fva_reduced_model_filename,
                                netrxn_irreversible_model_filename,
                                reduced_lbub_filename):
    '''iteration 2:
    addition of finalized lumped reactions that are in pathways that are within the scope of the model
    and reduction by removing reactions with zero optimal minimal flux outside the scope of the model'''
    cobra_model = load_ALEWt()
    # Make the model irreversible for downstream manipulations:
    convert_to_irreversible(cobra_model)
    cobra_model.optimize()
    # Add lumped isotopomer reactions
    add_net_reaction(cobra_model, isotopomer_rxns_net_irreversible, True)
    cobra_model.optimize()
    # Find minimal flux solution:
    pfba = optimize_minimal_flux(cobra_model, True, solver='gurobi')
    # Write pfba solution to file
    with open(pfba_filename, mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction', 'Flux', 'Subsystem'])
        for k, v in cobra_model.solution.x_dict.items():
            writer.writerow(
                [k, v, cobra_model.reactions.get_by_id(k).subsystem])
    # Read in pfba solution
    pfba_sol = {}
    with open(pfba_filename, mode='r') as infile:
        dictreader = csv.DictReader(infile)
        for r in dictreader:
            pfba_sol[r['Reaction']] = r['Flux']
    # remove noflux reactions for pathways outside of the scope
    # of the isotopomer model
    subs = [
        'Cell Envelope Biosynthesis',
        'Glycerophospholipid Metabolism',
        'Lipopolysaccharide Biosynthesis / Recycling',
        'Membrane Lipid Metabolism',
        'Murein Biosynthesis'
        'Murein Recycling',
        'Cofactor and Prosthetic Group Biosynthesis',
        'Transport, Inner Membrane',
        'Transport, Outer Membrane',
        'Transport, Outer Membrane Porin',
        'tRNA Charging',
        'Unassigned',
        #'Exchange',
        'Inorganic Ion Transport and Metabolism',
        'Nitrogen Metabolism',
        'Alternate Carbon Metabolism'
    ]
    remove_noflux_reactions(cobra_model, pfba_sol, subs)
    # Reduce model using FVA:
    reduce_model(cobra_model, fva_reduced_model_filename)
    # Reset secretion products that may have been turned off
    secrete = [
        'EX_meoh_LPAREN_e_RPAREN_', 'EX_5mtr_LPAREN_e_RPAREN_',
        'EX_h_LPAREN_e_RPAREN_', 'EX_co2_LPAREN_e_RPAREN_',
        'EX_co_LPAREN_e_RPAREN_', 'EX_h2o_LPAREN_e_RPAREN_',
        'EX_ac_LPAREN_e_RPAREN_', 'EX_fum_LPAREN_e_RPAREN_',
        'EX_for_LPAREN_e_RPAREN_', 'EX_etoh_LPAREN_e_RPAREN_',
        'EX_lac_DASH_L_LPAREN_e_RPAREN_', 'EX_pyr_LPAREN_e_RPAREN_',
        'EX_succ_LPAREN_e_RPAREN_'
    ]
    for s in secrete:
        cobra_model.reactions.get_by_id(s).upper_bound = 1000.0
    # Remove all reactions with 0 flux
    r1, r2 = get_reactionsInfo(cobra_model)
    while r2 != 0:
        remove_noflux_reactions(cobra_model)
        r1, r2 = get_reactionsInfo(cobra_model)
        print(r1, r2)
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model,
                                   netrxn_irreversible_model_filename)
    with open(reduced_lbub_filename, mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['Reaction', 'Formula', 'LB', 'UB', 'Subsystem'])
        for r in cobra_model.reactions:
            writer.writerow([
                r.id,
                r.build_reaction_string(), r.lower_bound, r.upper_bound,
                r.subsystem
            ])
コード例 #19
0
        #Rename external metabolites
        for metabolite in cobramodel.metabolites:
            if metabolite.id.endswith('xt'):
                if verbose:
                    print 'renaming metabolite ',metabolite.id
                new_metabolite_id = metabolite.id.split('xt')[0] + '_e'
                metabolite.id = new_metabolite_id
                if verbose:
                    print 'new metabolite id:',metabolite.id
        #Combine in/out exchange reactions:
        for reaction in cobramodel.reactions:
            if reaction.id.endswith('xtO'): #If the reaction is an "out" exchange reaction
                metabolite_id = reaction.id.split('xtO')[0]
                in_reaction_id = metabolite_id + 'xtI' #Construct the ID of the corresponding "in" reaction
                if in_reaction_id in cobramodel.reactions: #If a corresponding "in" reaction exists:
                    bound_in = cobramodel.reactions.get_by_id(in_reaction_id).upper_bound #Find the maximal uptake rate defined by the "in" reaction upper bounds
                    reaction.lower_bound = -bound_in #Make the reaction a combined in/out exchange reaction by allowing negative flow (if allowed by the "in" reaction)
                    cobramodel.reactions.get_by_id(in_reaction_id).remove_from_model() #Remove redundant "in" reactions
                reaction.id = 'EX_' + metabolite_id #Rename the now combined exchange reaction

    if objective is not None and (objective in cobramodel.reactions):
            cobramodel.reactions.get_by_id(objective).objective_coefficient = 1

    return cobramodel

if __name__ == "__main__":
    filename = sys.argv[1]
    target = sys.argv[2]
    model = convertMPStoCobraModel(filename)
    write_cobra_model_to_sbml_file(model,target)
コード例 #20
0
ファイル: augPhase.py プロジェクト: stogqy/plantismash
def add_nonBBH_rxn(modelPrunedGPR, rxnid_info_dict, rxnid_mnxm_coeff_dict,
                   rxnid_locusTag_dict, bigg_mnxm_compound_dict,
                   kegg_mnxm_compound_dict, mnxm_compoundInfo_dict,
                   targetGenome_locusTag_prod_dict,
                   tempModel_exrxnid_flux_dict, options):

    for rxnid in rxnid_mnxm_coeff_dict.keys():
        logging.debug("%s being examined for a new nonBBH reaction..", rxnid)
        if rxnid_info_dict[rxnid] != None:
            #ID
            rxn = Reaction(rxnid)

            #Name
            #Some reaction IDs do not have NAME despite the presence of PATHWAY
            rxn.name = rxnid_info_dict[rxnid]['NAME']

            #Reversibility / Lower and upper bounds
            rxn.lower_bound = -1000
            rxn.uppwer_bound = 1000

            #Metabolites and their stoichiometric coeff's
            for metab in rxnid_mnxm_coeff_dict[rxnid]:
                metab_compt = '_'.join([metab, 'c'])

                #Add metabolites already in the model
                if metab_compt in modelPrunedGPR.metabolites:
                    rxn.add_metabolites({
                        modelPrunedGPR.metabolites.get_by_id(metab_compt):
                        rxnid_mnxm_coeff_dict[rxnid][metab]
                    })

                #Add metabolites with bigg compoundID, but not in the model
                elif metab in bigg_mnxm_compound_dict.keys():
                    mnxm = bigg_mnxm_compound_dict[metab]
                    metab_compt = Metabolite(
                        metab,
                        formula=mnxm_compoundInfo_dict[mnxm][1],
                        name=mnxm_compoundInfo_dict[mnxm][0],
                        compartment='c')
                    rxn.add_metabolites(
                        {metab_compt: rxnid_mnxm_coeff_dict[rxnid][metab]})

                #Add metabolites with MNXM and not in the model
                else:
                    mnxm = kegg_mnxm_compound_dict[metab]
                    metab_compt = Metabolite(
                        mnxm,
                        formula=mnxm_compoundInfo_dict[mnxm][1],
                        name=mnxm_compoundInfo_dict[mnxm][0],
                        compartment='c')
                    rxn.add_metabolites(
                        {metab_compt: rxnid_mnxm_coeff_dict[rxnid][metab]})

        #GPR association
            if rxnid not in rxnid_locusTag_dict:
                logging.warning(
                    "rxnid_locusTag_dict error: has no key %s; content: %s",
                    rxnid, str(rxnid_locusTag_dict))
            if len(rxnid_locusTag_dict[rxnid]) == 1:
                gpr = '( %s )' % (rxnid_locusTag_dict[rxnid][0])
            else:
                count = 1
                for locusTag in rxnid_locusTag_dict[rxnid]:

                    #Check the submitted gbk file contains "/product" for CDS
                    if locusTag in targetGenome_locusTag_prod_dict:

                        #Consider "and" relationship in the GPR association
                        if 'subunit' in targetGenome_locusTag_prod_dict[
                                locusTag]:
                            count += 1
                if count == len(rxnid_locusTag_dict[rxnid]):
                    gpr = ' and '.join(rxnid_locusTag_dict[rxnid])
                else:
                    gpr = ' or '.join(rxnid_locusTag_dict[rxnid])
                gpr = '( %s )' % (gpr)
            rxn.add_gene_reaction_rule(gpr)

            #Subsystem
            rxn.subsystem = rxnid_info_dict[rxnid]['PATHWAY']

            #E.C. number: not available feature in COBRApy
            #Objective coeff: default
            rxn.objective_coefficient = 0

            #Add a reaction to the model if it does not affect Exchange reaction flux direction
            modelPrunedGPR.add_reaction(rxn)

            write_cobra_model_to_sbml_file(
                modelPrunedGPR,
                options.metabolicmodeldir + os.sep + "modelPrunedGPR.xml")
            modelPrunedGPR = create_cobra_model_from_sbml_file(
                options.metabolicmodeldir + os.sep + "modelPrunedGPR.xml")

            target_exrxnid_flux_dict = get_exrxnid_flux(
                modelPrunedGPR, tempModel_exrxnid_flux_dict)
            exrxn_flux_change_list = check_exrxn_flux_direction(
                tempModel_exrxnid_flux_dict, target_exrxnid_flux_dict)

            if 'F' in exrxn_flux_change_list:
                modelPrunedGPR.remove_reactions(rxn)

                write_cobra_model_to_sbml_file(
                    modelPrunedGPR,
                    options.metabolicmodeldir + os.sep + "modelPrunedGPR.xml")
                modelPrunedGPR = create_cobra_model_from_sbml_file(
                    options.metabolicmodeldir + os.sep + "modelPrunedGPR.xml")

    prune_unused_metabolites(modelPrunedGPR)
    target_model = copy.deepcopy(modelPrunedGPR)
    return target_model
コード例 #21
0
ファイル: iterations.py プロジェクト: yseif/sbaas
def isotopomer_model_iteration3(model_filename,
                                xml_filename,
                                mat_filename,
                                csv_filename,
                                isotopomer_mapping_filename,
                                ko_list=[],
                                flux_dict={},
                                description=None):
    '''iteration 3:
    Remove reactions that are thermodynamically unfavorable and add isotopomer data'''
    # Read in the sbml file and define the model conditions
    cobra_model = create_cobra_model_from_sbml_file(model_filename,
                                                    print_time=True)
    # Modify glucose uptake:
    if cobra_model.reactions.has_id('EX_glc_LPAREN_e_RPAREN__reverse'):
        lb, ub = cobra_model.reactions.get_by_id(
            'EX_glc_LPAREN_e_RPAREN__reverse'
        ).lower_bound, cobra_model.reactions.get_by_id(
            'EX_glc_LPAREN_e_RPAREN__reverse').upper_bound
        EX_glc_mets = {}
        EX_glc_mets[cobra_model.metabolites.get_by_id('glc_DASH_D_e')] = -1
        EX_glc = Reaction('EX_glc_LPAREN_e_RPAREN_')
        EX_glc.add_metabolites(EX_glc_mets)
        cobra_model.add_reaction(EX_glc)
        cobra_model.reactions.get_by_id(
            'EX_glc_LPAREN_e_RPAREN_').lower_bound = -ub
        cobra_model.reactions.get_by_id(
            'EX_glc_LPAREN_e_RPAREN_').upper_bound = lb
        cobra_model.remove_reactions(['EX_glc_LPAREN_e_RPAREN__reverse'])
    ## Remove thermodynamically infeasible reactions:
    #infeasible = [];
    #loops = [];
    #cobra_model.remove_reactions(infeasible + loops);
    # Apply KOs, if any:
    for ko in ko_list:
        cobra_model.reactions.get_by_id(ko).lower_bound = 0.0
        cobra_model.reactions.get_by_id(ko).upper_bound = 0.0
    # Apply flux constraints, if any:
    for rxn, flux in flux_dict.items():
        cobra_model.reactions.get_by_id(rxn).lower_bound = flux['lb']
        cobra_model.reactions.get_by_id(rxn).upper_bound = flux['ub']
    # Change description, if any:
    if description:
        cobra_model.description = description
    # Read in isotopomer model
    isotopomer_mapping = read_isotopomer_mapping_csv(
        isotopomer_mapping_filename)
    isotopomer_str = build_isotopomer_str(isotopomer_mapping)
    # write model to sbml
    write_cobra_model_to_sbml_file(cobra_model, xml_filename)
    # Add isotopomer field to model
    for r in cobra_model.reactions:
        if r.id in isotopomer_str:
            cobra_model.reactions.get_by_id(
                r.id).isotopomer = isotopomer_str[r.id]
        else:
            cobra_model.reactions.get_by_id(r.id).isotopomer = ''
    # Add null basis:
    cobra_model_array = cobra_model.to_array_based_model()
    N = null(cobra_model_array.S.todense()
             )  #convert S from sparse to full and compute the nullspace
    cobra_model.N = N
    # solve and save pFBA for later use:
    optimize_minimal_flux(cobra_model, True, solver='gurobi')
    # add match field:
    match = numpy.zeros(len(cobra_model.reactions))
    cobra_model.match = match
    # write model to mat
    save_matlab_model_isotopomer(cobra_model, mat_filename)
    with open(csv_filename, mode='wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerow([
            'Reaction', 'Formula', 'LB', 'UB', 'Genes', 'Subsystem',
            'Isotopomer'
        ])
        for r in cobra_model.reactions:
            writer.writerow([
                r.id,
                r.build_reaction_string(), r.lower_bound, r.upper_bound,
                r.gene_reaction_rule, r.subsystem, r.isotopomer
            ])
コード例 #22
0
def keep_only_reactions(model, r_ids, file_path):
    to_delete = [r for r in model.reactions if r.id not in r_ids]
    for r in to_delete:
        model.reactions.remove(r.id)
    write_cobra_model_to_sbml_file(model, file_path, 2, 4)