def init_wt_model(model_name, carbon_sources, BM_lower_bound=0.1): if model_name == 'ecoli_core': model = create_cobra_model_from_sbml_file('data/ecoli_core.xml', old_sbml=True) # the core model has these annoying '_b' metabolites that are used as # 'ghost' metabolites that balance the exchange reactions. they should # be ignored in the mass-balance equation and therefore the best way to # deal with them is to remove them from all the reactions for m in model.metabolites: if m.endswith('_b'): for r in m.get_reaction(): coeff = r.get_coefficient(m) r.add_metabolites({m : -coeff}) rxns = dict([(r.id, r) for r in model.reactions]) rxns['ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns['EX_glc_e'].lower_bound = 0 # remove the default carbon source elif model_name == 'iJO1366': model = create_cobra_model_from_sbml_file('data/iJO1366.xml', old_sbml=True) rxns = dict([(r.id, r) for r in model.reactions]) rxns['ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns['EX_glc_e'].lower_bound = 0 # remove the default carbon source else: model = create_cobra_model_from_sbml_file('data/%s.xml' % model_name) for key, val in carbon_sources.iteritems(): set_exchange_bounds(model, key, val, upper_bound=0) # set BM lower bound for r in model.reactions: if r.objective_coefficient != 0: r.lower_bound = BM_lower_bound return model
def compare_sbml(sbml1_path, sbml2_path): """ Compare 2 sbml, print nb of metabolites and reactions. If reaction missing print reaction id, and reaction formula. Parameters ---------- sbml1_path: str path to the first sbml file to compare sbml2_path: str path to the second sbml file to compare """ sbml_1 = create_cobra_model_from_sbml_file(sbml1_path) sbml_2 = create_cobra_model_from_sbml_file(sbml2_path) print("sbml1:") print("metabolites: %s" %(len(sbml_1.metabolites))) print("reactions: %s" %(len(sbml_1.reactions))) print("sbml2:") print("metabolites: %s" %(len(sbml_2.metabolites))) print("reactions: %s" %(len(sbml_2.reactions))) not_in1 = [i for i in sbml_2.reactions if i not in sbml_1.reactions] print("reactions not in sbml1: %s" %len(not_in1)) for i in not_in1: print("\t%s" %i) not_in2 = [i for i in sbml_1.reactions if i not in sbml_2.reactions] print("reactions not in sbml2: %s" %len(not_in2)) for j in not_in2: print("\t%s" %j) all_diff = set() for rxn1 in sbml_1.reactions: rxn_id = rxn1.id try: rxn2 = sbml_2.reactions.get_by_id(rxn_id) same_cpd, same_rev = compare_rxn(rxn1, rxn2) if rxn_id not in all_diff: if not same_cpd: print("%s use different species" %rxn_id) if not same_rev: print("%s use different reversibility" %rxn_id) all_diff.add(rxn_id) except KeyError: pass for rxn2 in sbml_2.reactions: rxn_id = rxn2.id try: rxn1 = sbml_1.reactions.get_by_id(rxn_id) same_cpd, same_rev = compare_rxn(rxn1, rxn2) if rxn_id not in all_diff: if not same_cpd: print("%s use different species" %rxn_id) if not same_rev: print("%s use different reversibility" %rxn_id) all_diff.add(rxn_id) except KeyError: pass
def initialize(model_name='core', carbon_sources={}, irreversible=False, ATP_maintenance=False, BM_lower_bound=0.1): if model_name == 'core': model = create_cobra_model_from_sbml_file('data/ecoli_core.xml', old_sbml=True) if irreversible: convert_to_irreversible(model) # the core model has these annoying '_b' metabolites that are used as # 'ghost' metabolites that balance the exchange reactions. they should # be ignored in the mass-balance equation and therefore the best way to # deal with them is to remove them from all the reactions for m in model.metabolites: if str(m).endswith('_b'): for r in m.get_reaction(): coeff = r.get_coefficient(m) r.add_metabolites({m: -coeff}) rxns = dict([(r.id, r) for r in model.reactions]) if not ATP_maintenance: rxns[ 'ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns[ 'EX_glc_e'].lower_bound = 0 # remove the default carbon source elif model_name == 'full': model = create_cobra_model_from_sbml_file('data/iJO1366.xml') rxns = dict([(r.id, r) for r in model.reactions]) if not ATP_maintenance: rxns[ 'ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns[ 'EX_glc_e'].lower_bound = 0 # remove the default carbon source elif model_name == 'toy': model = create_cobra_model_from_sbml_file('data/toymodel.xml') for key, val in carbon_sources.items(): rxns['EX_' + key + '_e'].lower_bound = val # set BM lower bound for r in model.reactions: if r.objective_coefficient != 0: r.lower_bound = BM_lower_bound m = Model() m.cobra_model = model if model_name == 'core': # the ED pathway and exchange reactions are missing from the # core model. Add them now. m.knockin_reactions('EDD,EDA', 0, 1000) m.knockin_reactions( 'EX_g6p,EX_f6p,EX_xu5p_D,EX_r5p,EX_dhap,' 'EX_2pg,EX_e4p,EX_6pgc', 0, 0) return m
def simulate_loops_sbml(self,ijo1366_sbml,data_fva): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) # Change all uptake reactions to 0 for rxn in cobra_model.reactions: if 'EX_' in rxn.id and '_LPAREN_e_RPAREN_' in rxn.id: rxn.lower_bound = 0.0; # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0 # calculate the reaction bounds using FVA reaction_bounds = 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); # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4);
def get_points_numpy(self,numpy_data,model_sbml=None): '''load sampling points from numpy file''' # extract information about the file import os, time from datetime import datetime from stat import ST_SIZE, ST_MTIME try: st = os.stat(self.data_dir + '/' + numpy_data) except IOError: print("failed to get information about", self.data_dir + '/' + numpy_data) return; else: file_size = st[ST_SIZE] simulation_dateAndTime_struct = time.localtime(st[ST_MTIME]) simulation_dateAndTime = datetime.fromtimestamp(time.mktime(simulation_dateAndTime_struct)) # load points from numpy file points = loadtxt(numpy_data); # Read in the sbml file and define the model conditions if model_sbml: self.model = create_cobra_model_from_sbml_file(model_sbml, print_time=True) points_dict = {}; for i,r in enumerate(cobra_model.reactions): # extract points points_dict[r_id_conv]=points[i,:]; self.points = points_dict; #self.mixed_fraction = mixed_fraction; self.simulation_dateAndTime = simulation_dateAndTime;
def get_points_numpy(self, numpy_data, model_sbml=None): '''load sampling points from numpy file''' # extract information about the file import os, time from datetime import datetime from stat import ST_SIZE, ST_MTIME try: st = os.stat(self.data_dir + '/' + numpy_data) except IOError: print("failed to get information about", self.data_dir + '/' + numpy_data) return else: file_size = st[ST_SIZE] simulation_dateAndTime_struct = time.localtime(st[ST_MTIME]) simulation_dateAndTime = datetime.fromtimestamp( time.mktime(simulation_dateAndTime_struct)) # load points from numpy file points = loadtxt(numpy_data) # Read in the sbml file and define the model conditions if model_sbml: self.model = create_cobra_model_from_sbml_file(model_sbml, print_time=True) points_dict = {} for i, r in enumerate(cobra_model.reactions): # extract points points_dict[r_id_conv] = points[i, :] self.points = points_dict #self.mixed_fraction = mixed_fraction; self.simulation_dateAndTime = simulation_dateAndTime
def load_models(self,experiment_id_I,model_ids_I=[]): '''pre-load all models for the experiment_id''' # get the model ids: if model_ids_I: model_ids = model_ids_I; else: model_ids = []; model_ids = self.stage02_physiology_query.get_modelID_experimentID_dataStage02PhysiologySimulation(experiment_id_I); for model_id in model_ids: # get the cobra model cobra_model_sbml = None; cobra_model_sbml = self.stage02_physiology_query.get_row_modelID_dataStage02PhysiologyModels(model_id); # write the model to a temporary file if cobra_model_sbml['file_type'] == 'sbml': with open(settings.workspace_data + '/cobra_model_tmp.xml','wb') as file: file.write(cobra_model_sbml['model_file']); cobra_model = None; cobra_model = create_cobra_model_from_sbml_file(settings.workspace_data + '/cobra_model_tmp.xml', print_time=True); elif cobra_model_sbml['file_type'] == 'json': with open(settings.workspace_data + '/cobra_model_tmp.json','wb') as file: file.write(cobra_model_sbml['model_file']); cobra_model = None; cobra_model = load_json_model(settings.workspace_data + '/cobra_model_tmp.json'); else: print('file_type not supported') self.models[model_id]=cobra_model;
def get_reactions_from_model(self): """ Read all the reaction descriptions in the SBML file, and map them to KEGG reaction (using another file of all E. coli metabolites and their BiGG and KEGG IDs) """ cobra_model = create_cobra_model_from_sbml_file( settings.ECOLI_SBML_FNAME) for m in cobra_model.metabolites: m.CID = self.bigg2kegg.get(m.id[:-2], None) for r in cobra_model.reactions: CIDS = dict( zip(r.metabolites.keys(), map(lambda x: x.CID, r.metabolites.keys()))) if None in CIDS.values(): r.kegg_reaction = None else: sparse = { CIDS[m]: v for m, v in r.metabolites.iteritems() if CIDS[m] != 'C00080' } r.kegg_reaction = KeggReaction(sparse) return cobra_model.reactions
def simulate_loops(ijo1366_sbml,data_fva): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) # Change all uptake reactions to 0 for rxn in cobra_model.reactions: if 'EX_' in rxn.id and '_LPAREN_e_RPAREN_' in rxn.id: rxn.lower_bound = 0.0; # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0 # calculate the reaction bounds using FVA reaction_bounds = 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); # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4);
def categorize_reactions(model, db, category): fva_result_dict = {} # Wide range of ATP Synthase flux values can be positive or negative category_1_dict = {} # ATP Synthase flux can only be negative category_2_dict = {} # ATP Synthase flux can only be positive category_3_dict = {} model = create_cobra_model_from_sbml_file(model) rxn_list = pickle.load(open(db, 'rb')) for run in rxn_list.keys(): model_test = model.copy() fva_list = [model_test.reactions.ATPS] for rxn in rxn_list[run]: addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0) formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0) rxn = Reaction(addID) model_test.add_reaction(rxn) rxn.reaction = formula fva_list.append(rxn) fva_result = flux_analysis.flux_variability_analysis(model_test, fva_list) fva_result_dict[run] = fva_result for run in fva_result_dict: if fva_result_dict[run]['ATPS']['maximum'] > 0 and fva_result_dict[run]['ATPS']['minimum'] < 0: category_1_dict[run] = fva_result_dict[run] elif fva_result_dict[run]['ATPS']['maximum'] > 0: category_2_dict[run] = fva_result_dict[run] else: category_3_dict[run] = fva_result_dict[run] if category == 1: return category_1_dict.keys() elif category == 2: return category_2_dict.keys() else: return category_3_dict.keys()
def parsimonious_fba(model, db): ''' :param model: Takes in a model in SBML format and converts it into a cobrapy model :param db: Takes in a database of reactions to be added to the model that will make it feasible to solve :return: Will run a parsimonious FBA on the model which reduces the sum of total fluxes through the model. Then the sources and sinks of ATP in the reaction will be printed so that we can analyze where ATP comes from and where it goes in this model as that will give us insight into the mechanism by which the GrowMatch algorithm has added a reaction that allows the model to produce methanol. ''' model = create_cobra_model_from_sbml_file(model) rxn_list = pickle.load(open(db, 'rb')) # For loop that adds the reactions in a given run present in the dictionary to the model using regular expressions for run in rxn_list.keys(): model_test = model.copy() fva_list = [model_test.reactions.ATPS] for rxn in rxn_list[run]: addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0) formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0) rxn = Reaction(addID) model_test.add_reaction(rxn) rxn.reaction = formula # Creates a test model to run ParsFBA on and then prints out the run as well as the sources/sinks of ATP in the # reactions model_fba_test = model_test.copy() flux_analysis.optimize_minimal_flux(model_fba_test) # fluxes = findInsAndOuts(model_fba_test) # sorted_outs = fluxes[0] # sorted_ins = fluxes[1] print run model_fba_test.metabolites.get_by_id('cpd00002_c0').summary()
def load_models(self, experiment_id_I, model_ids_I=[]): '''pre-load all models for the experiment_id''' # get the model ids: if model_ids_I: model_ids = model_ids_I else: model_ids = [] model_ids = self.stage02_physiology_query.get_modelID_experimentID_dataStage02PhysiologySimulation( experiment_id_I) for model_id in model_ids: # get the cobra model cobra_model_sbml = None cobra_model_sbml = self.stage02_physiology_query.get_row_modelID_dataStage02PhysiologyModels( model_id) # write the model to a temporary file if cobra_model_sbml['file_type'] == 'sbml': with open(settings.workspace_data + '/cobra_model_tmp.xml', 'wb') as file: file.write(cobra_model_sbml['model_file']) cobra_model = None cobra_model = create_cobra_model_from_sbml_file( settings.workspace_data + '/cobra_model_tmp.xml', print_time=True) elif cobra_model_sbml['file_type'] == 'json': with open(settings.workspace_data + '/cobra_model_tmp.json', 'wb') as file: file.write(cobra_model_sbml['model_file']) cobra_model = None cobra_model = load_json_model(settings.workspace_data + '/cobra_model_tmp.json') else: print('file_type not supported') self.models[model_id] = cobra_model
def gapfillfunc(model, database, runs): """ This function gapfills the model using the growMatch algorithm that is built into cobrapy Returns a dictionary which contains the pertinent information about the gapfilled model such as the reactions added, the major ins and outs of the system and the objective value of the gapfilled model. This function calls on two other functions sort_and_deduplicate to assure the uniqueness of the solutions and findInsAndOuts to find major ins and outs of the model when gapfilled when certain reactions Args: model: a model in SBML format database: an external database database of reactions to be used for gapfilling runs: integer number of iterations the gapfilling algorithm will run through """ # Read model from SBML file and create Universal model to add reactions to func_model = create_cobra_model_from_sbml_file(model) Universal = Model("Universal Reactions") f = open(database, 'r') next(f) rxn_dict = {} # Creates a dictionary of the reactions from the tab delimited database, storing their ID and the reaction string for line in f: rxn_items = line.split('\t') rxn_dict[rxn_items[0]] = rxn_items[6], rxn_items[1] # Adds the reactions from the above dictionary to the Universal model for rxnName in rxn_dict.keys(): rxn = Reaction(rxnName) Universal.add_reaction(rxn) rxn.reaction = rxn_dict[rxnName][0] rxn.name = rxn_dict[rxnName][1] # Runs the growMatch algorithm filling gaps from the Universal model result = flux_analysis.growMatch(func_model, Universal, iterations=runs) resultShortened = sort_and_deduplicate(uniq(result)) rxns_added = {} rxn_met_list = [] print resultShortened for x in range(len(resultShortened)): func_model_test = deepcopy(func_model) # print func_model_test.optimize().f for i in range(len(resultShortened[x])): addID = resultShortened[x][i].id rxn = Reaction(addID) func_model_test.add_reaction(rxn) rxn.reaction = resultShortened[x][i].reaction rxn.reaction = re.sub('\+ dummy\S+', '', rxn.reaction) rxn.name = resultShortened[x][i].name mets = re.findall('cpd\d{5}_c0|cpd\d{5}_e0', rxn.reaction) for met in mets: y = func_model_test.metabolites.get_by_id(met) rxn_met_list.append(y.name) obj_value = func_model_test.optimize().f fluxes = findInsAndOuts(func_model_test) sorted_outs = fluxes[0] sorted_ins = fluxes[1] rxns_added[x] = resultShortened[x], obj_value, sorted_ins, sorted_outs, rxn_met_list rxn_met_list = [] return rxns_added
def make_Model(self,model_id_I=None,model_id_O=None,date_O=None,model_file_name_I=None,ko_list=[],flux_dict={},description=None): '''make a new model''' if model_id_I and model_id_O and date_O: #make a new model based off of a modification of an existing model in the database cobra_model_sbml = None; cobra_model_sbml = self.get_row_modelID_dataStage02IsotopomerModels(model_id_I); # write the model to a temporary file 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); # 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 with open('cobra_model_tmp.xml','w') as file: file.write(cobra_model); # upload the model to the database self.import_dataStage02Model_sbml(model_id_O, date_O, 'cobra_model_tmp.xml'); elif model_file_name_I and model_id_O and date_O: #modify an existing model in not in the database # check for the file type if '.json' in model_file_name_I: # Read in the sbml file and define the model conditions cobra_model = load_json_model(model_file_name_I, print_time=True); elif '.xml' in model_file_name_I: # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(model_file_name_I, print_time=True); else: print('file type not supported') # Constrain the model self.constrain_modelModelVariables(cobra_model=cobra_model,ko_list=ko_list,flux_dict=flux_dict); # 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 filename = ''; if '.xml' in model_file_name_I: filename = 'cobra_model_tmp.xml' with open(filename,'w') as file: file.write(cobra_model); file.close() elif '.json' in model_file_name_I: filename = 'cobra_model_tmp.json'; with open(filename,'w') as file: file.write(cobra_model); file.close() else: print('file type not supported') # upload the model to the database self.import_dataStage02Model_sbml(model_id_O, date_O, filename); else: print('need to specify either an existing model_id or model_file_name!')
def test_model(self, cobra_model_I=None, model_id_I=None, ko_list=[], flux_dict={}, description=None): '''simulate a cobra model''' if model_id_I: # get the xml model cobra_model_sbml = '' cobra_model_sbml = self.stage02_physiology_query.get_row_modelID_dataStage02PhysiologyModels( model_id_I) # load the model if cobra_model_sbml['file_type'] == 'sbml': with open(settings.workspace_data + '/cobra_model_tmp.xml', 'wb') as file: file.write(cobra_model_sbml['model_file']) file.close() cobra_model = None cobra_model = create_cobra_model_from_sbml_file( settings.workspace_data + '/cobra_model_tmp.xml', print_time=True) elif cobra_model_sbml['file_type'] == 'json': with open(settings.workspace_data + '/cobra_model_tmp.json', 'wb') as file: file.write(cobra_model_sbml['model_file']) file.close() cobra_model = None cobra_model = load_json_model(settings.workspace_data + '/cobra_model_tmp.json') else: print('file_type not supported') elif cobra_model_I: cobra_model = cobra_model_I # implement optimal KOs and flux constraints: 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 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 # test for a solution: cobra_model.optimize(solver='gurobi') if not cobra_model.solution.f: return False else: print(cobra_model.solution.f) return True
def init_wt_model(model_name, carbon_sources, reversible=False, ATP_maintenance=False, BM_lower_bound=0.1): if model_name == 'core': model = create_cobra_model_from_sbml_file('../shared_data/ecoli_core_model.xml', old_sbml=True) if reversible: convert_to_irreversible(model) # the core model has these annoying '_b' metabolites that are used as # 'ghost' metabolites that balance the exchange reactions. they should # be ignored in the mass-balance equation and therefore the best way to # deal with them is to remove them from all the reactions ## for m in model.metabolites: ## didn't work for m in [r.id for r in model.metabolites]: ## Yinon if m.endswith('_b'): for r in m.get_reaction(): coeff = r.get_coefficient(m) r.add_metabolites({m : -coeff}) rxns = dict([(r.id, r) for r in model.reactions]) if not ATP_maintenance: rxns['ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns['EX_glc_e'].lower_bound = 0 # remove the default carbon source elif model_name == 'full': model = create_cobra_model_from_sbml_file('../shared_data/iJO1366.xml', old_sbml=True) rxns = dict([(r.id, r) for r in model.reactions]) if not ATP_maintenance: rxns['ATPM'].lower_bound = 0 # remove the ATP maintenance requirement rxns['EX_glc_e'].lower_bound = 0 # remove the default carbon source elif model_name == 'toy': model = create_cobra_model_from_sbml_file('data/toymodel.xml') for key, val in carbon_sources.iteritems(): rxns['EX_' + key + '_e'].lower_bound = val # set BM lower bound for r in model.reactions: if r.objective_coefficient != 0: r.lower_bound = BM_lower_bound return model
def export_points(ijo1366_sbml, points_loopless_mean, data_srd, data_pfba, data_points): '''export sampling analysis''' srd = json.load(open(data_srd)); pfba = json.load(open(data_pfba)); # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) points = {}; assay = ['glx_c', 'glyclt_c', 'pyr_c', 'ala_DASH_L_c', 'lac_DASH_L_c', 'oxa_c', 'acac_c', 'ser_DASH_L_c', 'ura_c', 'fum_c', 'mmal_c', 'succ_c', 'thr_DASH_L_c', 'thym_c', '5oxpro_c', 'glutacon_c', 'orn_c', 'asn_DASH_L_c', 'oaa_c', 'asp_DASH_L_c', 'mal_DASH_L_c', 'ade_c', 'hxan_c', 'actp_c', 'gln_DASH_L_c', 'akg_c', 'glu_DASH_L_c', 'met_DASH_L_c', 'gua_c', 'xan_c', 'his_DASH_L_c', 'phpyr_c', 'phe_DASH_L_c', 'urate_c', 'pep_c', 'dhap_c', 'g3p_c', 'glyc3p_c', 'arg_DASH_L_c', 'acon_DASH_C_c', 'citr_DASH_L_c', 'tyr_DASH_L_c', '2pg_c', '3pg_c', 'cit_c', 'icit_c', 'trp_DASH_L_c', 'r5p_c', 'ru5p_DASH_D_c', 'Lcystin_c', 'cytd_c', 'btn_c', 'uri_c', 'gam6p_c', 'g6p_c', 'f6p_c', 'g1p_c', 'f1p_c', '23dpg_c', 'adn_c', 'ins_c', '6pgc_c', 'gsn_c', 's7p_c', 'gthrd_c', 'dcmp_c', 'dump_c', 'dtmp_c', 'cmp_c', 'ump_c', 'camp_c', 'damp_c', 'dimp_c', 'fdp_c', '35cgmp_c', 'amp_c', 'dgmp_c', 'imp_c', 'gmp_c', 'ribflv_c', 'dcdp_c', 'prpp_c', 'udp_c', 'dadp_c', 'adp_c', 'dgdp_c', 'fol_c', 'gdp_c', 'dctp_c', 'dutp_c', 'dttp_c', 'ctp_c', 'utp_c', 'datp_c', 'ditp_c', 'atp_c', 'itp_c', 'gtp_c', 'dtdpglu_c', 'adpglc_c', 'gthox_c', 'nad_c', 'nadh_c', 'nadp_c', 'nadph_c', 'coa_c', 'fad_c', 'accoa_c', 'succoa_c']; # combine analyses into a final data structure for k,v in points_loopless_mean.items(): ngenes = len(cobra_model.reactions.get_by_id(k).genes) genes = ', '.join(i.id for i in cobra_model.reactions.get_by_id(k).genes); nmets_down = len([i.id for i in cobra_model.reactions.get_by_id(k).products if i.compartment == 'c' and i.id in assay]); mets_down = ', '.join(i.id for i in cobra_model.reactions.get_by_id(k).products if i.compartment == 'c' and i.id in assay); nmets_up = len([i.id for i in cobra_model.reactions.get_by_id(k).reactants if i.compartment == 'c' and i.id in assay]); mets_up = ', '.join(i.id for i in cobra_model.reactions.get_by_id(k).reactants if i.compartment == 'c' and i.id in assay); #points[k] = {'mean':v['mean'],'std':v['std'],'gr_ratio':srd[k]['gr_ratio'],'pfba':pfba[k]}; points[k] = {'mean':v['mean'],'std':v['std'],'gr_ratio':srd[k]['gr_ratio'], 'ngenes':ngenes,'genes':genes,'nmets_up':nmets_up,'mets_up':mets_up, 'nmets_down':nmets_down,'mets_down':mets_down}; # Update the data file with open(data_points, 'wb') as outfile: csvwriter = csv.writer(outfile); #csvwriter.writerow(['rxn_id','mean','mean_abs','std','gr_ratio','pfba']); csvwriter.writerow(['rxn_id','mean','mean_abs','std','gr_ratio','ngenes','genes','nmets_up','mets_up','nmets_down','mets_down']); for k,v in points.items(): csvwriter.writerow([k,v['mean'],abs(v['mean']),v['std'],v['gr_ratio'], v['ngenes'],v['genes'],v['nmets_up'],v['mets_up'], v['nmets_down'],v['mets_down']]);
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)
def get_points_numpy(numpy_data,ijo1366_sbml): '''load sampling points from numpy file''' # load points from numpy file points = loadtxt(numpy_data); # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) points_dict = {}; for i,r in enumerate(cobra_model.reactions): # extract points points_dict[r.id] = {'points':points[i,:], 'mean':mean(points[i,:]), 'std':std(points[i,:])} return points_dict;
def load_model(self,model_file_name_I): '''load a cobra model from json or sbml INPUT: model_file_name_I = name of file OUTPUT: cobra_model ''' cobra_model=None; # check for the file type if '.json' in model_file_name_I: # Read in the sbml file and define the model conditions cobra_model = load_json_model(model_file_name_I, print_time=True); elif '.xml' in model_file_name_I: # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(model_file_name_I, print_time=True); else: print('file type not supported'); return cobra_model;
def writeAndLoad_modelTable(self,cobra_model_table_I): '''Load a cobra model from models table''' # write the model to a temporary file if cobra_model_table_I['file_type'] == 'sbml': with open('cobra_model_tmp.xml','w') as file: file.write(cobra_model_table_I['model_file']); file.close() cobra_model = None; cobra_model = create_cobra_model_from_sbml_file('cobra_model_tmp.xml', print_time=True); elif cobra_model_table_I['file_type'] == 'json': with open('cobra_model_tmp.json','w') as file: file.write(cobra_model_table_I['model_file']); file.close() cobra_model = None; cobra_model = load_json_model('cobra_model_tmp.json'); else: print('file_type not supported') return None; return cobra_model;
def test_model(self,cobra_model_I=None,model_id_I=None,ko_list=[],flux_dict={},description=None): '''simulate a cobra model''' if model_id_I: # get the xml model cobra_model_sbml = '' cobra_model_sbml = self.stage02_physiology_query.get_row_modelID_dataStage02PhysiologyModels(model_id_I); # load the model if cobra_model_sbml['file_type'] == 'sbml': with open(settings.workspace_data + '/cobra_model_tmp.xml','wb') as file: file.write(cobra_model_sbml['model_file']); file.close() cobra_model = None; cobra_model = create_cobra_model_from_sbml_file(settings.workspace_data + '/cobra_model_tmp.xml', print_time=True); elif cobra_model_sbml['file_type'] == 'json': with open(settings.workspace_data + '/cobra_model_tmp.json','wb') as file: file.write(cobra_model_sbml['model_file']); file.close() cobra_model = None; cobra_model = load_json_model(settings.workspace_data + '/cobra_model_tmp.json'); else: print('file_type not supported') elif cobra_model_I: cobra_model = cobra_model_I; # implement optimal KOs and flux constraints: 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; 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; # test for a solution: cobra_model.optimize(solver='gurobi'); if not cobra_model.solution.f: return False; else: print(cobra_model.solution.f); return True;
def __init__(self): self.cobra_model = create_cobra_model_from_sbml_file(S.ECOLI_SBML_FNAME) convert_to_irreversible(self.cobra_model) self.met_conc_df = self.get_metabolite_data() self.km_df = self.get_km_data() self.enz_conc_df, self.enz_mw_df = self.get_enzyme_data() self.flux_df = self.get_flux_data() self.data_df = pd.merge(self.km_df, self.met_conc_df, on='bigg.metabolite') self.data_df = pd.merge(self.data_df, self.enz_conc_df, on=['bigg.reaction', 'condition']) self.data_df = pd.merge(self.data_df, self.enz_mw_df, on=['bigg.reaction']) self.data_df = pd.merge(self.data_df, self.flux_df, on=['bigg.reaction', 'condition']) # keep only rows with non-zero flux, non-zero enzyme, and stoichiometry coeff = 1 ind = (self.data_df['flux [mmol/gCDW/h]'] > 0) & \ (self.data_df['enzyme conc [M]'] > 0) & \ (self.data_df['stoichiometry'] == -1) self.data_df = self.data_df[ind]
def perform_pFBA(condition): cs = gc['media_key'].loc[condition] gr = gc['growth rate [h-1]'].loc[condition] m = create_cobra_model_from_sbml_file('../data/iJO1366.xml') m.reactions.get_by_id('EX_glc_e').lower_bound = 0 convert_to_irreversible(m) reac = dict([(r.id, r) for r in m.reactions]) try: reac['EX_' + cs + '_e'].lower_bound = -1000 # redefine sole carbon source uptake reaction in mmol/gr/h except KeyError: raise 'media key not in model' reac['Ec_biomass_iJO1366_core_53p95M'].objective_coefficient = 0 reac['Ec_biomass_iJO1366_WT_53p95M'].objective_coefficient = 1 reac['Ec_biomass_iJO1366_WT_53p95M'].upper_bound = gr print "solving pFBA for %s" %condition optimize_minimal_flux(m, already_irreversible=True) return pd.Series(m.solution.x_dict)
def __init__(self): self.model = create_cobra_model_from_sbml_file("../data/iJO1366.xml") # Modify model convert_to_irreversible(self.model) self.rxns = dict([(r.id, r) for r in self.model.reactions]) self.genes = dict([(g.id, g) for g in self.model.genes]) add_to_model(self.model) self.include_specific_isozmyes() self.gc = pd.DataFrame.from_csv("../data/growth_conditions.csv") flux = pd.DataFrame.from_csv('../data/flux[mmol_gCDW_h].csv') self.v = self._convert_mmol_gCDW_h_to_mmol_gCDW_s(flux) # PPKr_reverse reaction is used for ATP generation from ADP # in the FBA model. Nevertheless, acording to EcoCyc, it is used to # to generate polyP (inorganic phosphate) chains from ATP and it is not # part of the oxidative phosphorilation, thus removed from rate calculations if 'PPKr_reverse' in self.v.index: self.v.drop('PPKr_reverse', axis=0, inplace=True) self.enzymatic_reactions = self._enzymatic_reactions() self.homomeric_reactions = self.reactions_by_homomeric_enzymes() proteins_copies_fL = pd.DataFrame.from_csv( '../data/meta_abundance[copies_fL].csv') self.proteins_mmol_gCDW = self._convert_copies_fL_to_mmol_gCDW( proteins_copies_fL) self.E = self.map_expression_by_reaction() self.kapp = self.get_kapp() # per subunit self.SA = self.get_specific_activity() self.kcat = pd.DataFrame.from_csv("../data/kcat_data.csv") self.p_per_as = (self.kcat['polypeptides per complex'] / self.kcat['catalytic sites per complex']) self.kmax = self.get_kmax(self.kapp) self.SAmax = self.get_maximum_specific_activity(self.SA)
def get_reactions_from_model(self): """ Read all the reaction descriptions in the SBML file, and map them to KEGG reaction (using another file of all E. coli metabolites and their BiGG and KEGG IDs) """ cobra_model = create_cobra_model_from_sbml_file( settings.ECOLI_SBML_FNAME) for m in cobra_model.metabolites: m.CID = self.bigg2kegg.get(m.id[:-2], None) for r in cobra_model.reactions: CIDS = dict(zip(r.metabolites.keys(), map(lambda x: x.CID, r.metabolites.keys()))) if None in CIDS.values(): r.kegg_reaction = None else: sparse = {CIDS[m]: v for m, v in r.metabolites.iteritems() if CIDS[m] != 'C00080'} r.kegg_reaction = KeggReaction(sparse) return cobra_model.reactions
def __init__(self, flux, abundance): self.model = create_cobra_model_from_sbml_file("../data/iJO1366.xml") convert_to_irreversible(self.model) self.rxns = {r.id:r for r in self.model.reactions} self._update_subsystems_for_reverse_direction() g_gCDW = abundance mmol_gCDW_h = flux mmol_gCDW_h = mmol_gCDW_h[mmol_gCDW_h>1e-10] self.conditions = pd.DataFrame.from_csv("../data/conditions.csv") self.conditions.sort_values('growth rate Gerosa [h-1]', inplace=True) self.conditions = self.conditions.loc[mmol_gCDW_h.columns & g_gCDW.columns] self.cs = self.conditions.index self.gr = self.conditions["growth rate Gerosa [h-1]"] self.cmap = plt.cm.viridis colors = list(self.cmap(np.linspace(0,0.9,6))) + ['#ffd11a'] self.colors = dict(zip(list(self.cs), colors)) self.umol_gCDW_min = mmol_gCDW_h[self.cs] * 1e3 / 60 self.umol_gCDW_min.replace(np.nan, 0, inplace=True) self.mg_gCDW = g_gCDW.loc[map(str, self.model.genes), self.cs] * 1e3 self.mg_gCDW.replace(np.nan, 0, inplace=True) self.flux_carrying_rxns = self.flux_carrying_reactions() self.E = self.map_enzyme_mass_to_reactions() self.SA = self.specific_activity() self.kmax = self.get_kmax() self.vmax = self.get_vmax() self.Emin = self.get_Emin() self.CU = self.capacity_usage() self.MCU = self.metabolic_capacity_usage() self.kcat = self.load_kcats()
def __init__(self): self.model = create_cobra_model_from_sbml_file("../data/iJO1366.xml") # Modify model convert_to_irreversible(self.model) self.rxns = dict([(r.id, r) for r in self.model.reactions]) self.genes = dict([(g.id, g) for g in self.model.genes]) add_to_model(self.model) self.include_specific_isozmyes() self.gc = pd.DataFrame.from_csv("../data/growth_conditions.csv") flux = pd.DataFrame.from_csv('../data/flux[mmol_gCDW_h].csv') self.v = self._convert_mmol_gCDW_h_to_mmol_gCDW_s(flux) # PPKr_reverse reaction is used for ATP generation from ADP # in the FBA model. Nevertheless, acording to EcoCyc, it is used to # to generate polyP (inorganic phosphate) chains from ATP and it is not # part of the oxidative phosphorilation, thus removed from rate calculations if 'PPKr_reverse' in self.v.index: self.v.drop('PPKr_reverse', axis=0, inplace=True) self.enzymatic_reactions = self._enzymatic_reactions() self.homomeric_reactions = self.reactions_by_homomeric_enzymes() proteins_copies_fL = pd.DataFrame.from_csv('../data/meta_abundance[copies_fL].csv') self.proteins_mmol_gCDW = self._convert_copies_fL_to_mmol_gCDW(proteins_copies_fL) self.E = self.map_expression_by_reaction() self.kapp = self.get_kapp() # per subunit self.SA = self.get_specific_activity() self.kcat = pd.DataFrame.from_csv("../data/kcat_data.csv") self.p_per_as = (self.kcat['polypeptides per complex'] / self.kcat['catalytic sites per complex']) self.kmax = self.get_kmax(self.kapp) self.SAmax = self.get_maximum_specific_activity(self.SA)
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)
def get_species_id_list(model_file = '/Users/wbryant/work/BTH/data/iAH991/BTH_with_gprs.xml'): """ Return a list of species IDs from an SBML model. Use COBRA. Also, return whether each metabolite is an orphan """ cobra_model = create_cobra_model_from_sbml_file(model_file) reader = SBMLReader() document = reader.readSBMLFromFile(model_file) model = document.getModel() species_id_list = [] print("Model orphans:\n") for metabolite in cobra_model.metabolites: ## Is metabolite an orphan (and internal)? reactions_list = metabolite.get_reaction() if len(reactions_list) == 1: orphan = True print metabolite.id else: orphan = False met_id = re.sub("__","-",metabolite.id) met_name = re.sub("__","-",metabolite.name) species_id_list.append((met_id, met_name, orphan)) # species_id_list = [] # for metabolite in model.getListOfSpecies(): # species_id_list.append((metabolite.getId(), metabolite.getName(), False)) return species_id_list
cobramodel.reactions.get_by_id(randomreaction).lower_bound = randomflux cobramodel.optimize(solver='gurobi') gxFBAsolution = gxFBA(cobramodel) #Does this ,make sense? Z_gxFBA.append(gxFBAsolution.solution.f) if biomassreaction is not None: bmFVA = cobra.flux_analysis.variability.flux_variability_analysis(cobramodel,the_reactions = [biomassreaction]) BMmax.append(bmFVA[biomassreaction]['maximum']) BMmin.append(bmFVA[biomassreaction]['minimum']) return R,FVAres if __name__ == "__main__": model = create_cobra_model_from_sbml_file('../SBML/SCHUETZR.xml') model.optimize(solver='gurobi') #fva = gxFBA(model,[],[]) example_a = create_cobra_model_from_sbml_file('../SBML/gx-fba.xml') ## gx-FBA example model 1: ## Parameters: ## Objective: Biomass ## ATP maintenance: 12 ## Max glucose import (glc_e -> glc_c): 10 ## Max puruvate export (pyr_c -> pyr_e): 5 example_a.optimize(solver='gurobi') #print 'Example A FBA result:' #print example_a.solution #print example_a.solution.x_dict
""" import pandas as pd import numpy as np from cobra.io.sbml import create_cobra_model_from_sbml_file from cobra.flux_analysis.parsimonious import optimize_minimal_flux from cobra.manipulation.modify import convert_to_irreversible conditions = pd.DataFrame.from_csv("../data/conditions.csv") conditions = conditions[conditions.media_key>0] conditions.sort_values('growth rate Gerosa [h-1]', inplace=True) cs = conditions.index projections = pd.DataFrame.from_csv('../data/flux projections[mmol_gCDW_h].csv') model = create_cobra_model_from_sbml_file('../source/iJO1366.xml') convert_to_irreversible(model) mmol_gCDW = pd.DataFrame(index = map(str, model.reactions), columns = cs) for c in projections.columns: cobra_c = conditions.loc[c, 'media_key'] gr = conditions.loc[c, 'growth rate Gerosa [h-1]'] model = create_cobra_model_from_sbml_file('../source/iJO1366.xml') convert_to_irreversible(model) # redefine sole carbon source uptake reaction in mmol/gr/h model.reactions.get_by_id('EX_glc_e').lower_bound = 0 model.reactions.get_by_id('EX_' + cobra_c + '_e').lower_bound = -1000 # set growth rate according to measurements
import pickle from types import * from cobra.io.sbml import create_cobra_model_from_sbml_file selected_tolerance = 1E-8 selected_growth = 0 selected_penalty = 0 gim3e_dir = gim3e.__file__ n_remove_chars = len('/core/gim3e.py') gim3e_dir = gim3e_dir[:(-1 * (n_remove_chars))] data_dir = gim3e_dir + "data/" # develop the sampling algorithm with E coli core as a first approach sbml_file = 'E_coli_core_M9.xml' cobra_model = create_cobra_model_from_sbml_file(data_dir + 'E_coli_core_M9.xml', print_time=True) cobra_model.reactions.get_by_id('ATPM').objective_coefficient = 1 cobra_model.optimize() cobra_model.solution.f gim3e.gim3e_optimize(cobra_model, objective_sense = 'maximize', the_problem = None, solver = 'cplex', error_reporting = None, tolerance_optimality = selected_tolerance, tolerance_feasibility = selected_tolerance, tolerance_barrier = 0.0001 * selected_tolerance, tolerance_integer = 0) cobra_model.solution.f # Make this into a GIM3E model gim3e_model, gim3e_FVA, penalty_score = gim3e.gim3e(cobra_model, expression_dict = {},
import pandas as pd from cobra.core import Metabolite, Reaction from cobra.io.sbml import create_cobra_model_from_sbml_file from cobra.manipulation.modify import convert_to_irreversible, revert_to_reversible from cobra.flux_analysis.variability import flux_variability_analysis gc = pd.DataFrame.from_csv('../data/growth_conditions.csv') gc = gc[gc.media_key>0] m = create_cobra_model_from_sbml_file('../data/iJO1366.xml') convert_to_irreversible(m) fake = Metabolite(id='fake') m.add_metabolites(fake) for r in m.reactions: r.add_metabolites({fake:1}) flux_counter = Reaction(name='flux_counter') flux_counter.add_metabolites(metabolites={fake:-1}) m.add_reaction(flux_counter) m.change_objective(flux_counter) m.reactions.get_by_id('EX_glc_e_reverse').upper_bound = 0 rxns = {r.id:r for r in m.reactions} index = pd.MultiIndex.from_product([gc.index, ['maximum', 'minimum']]) fluxes = pd.DataFrame(index=index, columns=rxns.keys()) for i,c in enumerate(gc.index): rxns['EX_'+gc['media_key'][c]+'_e'].lower_bound = -1000
def stoichio_crossroad(file_draft, file_metabo, file_seed, file_target, limit, repository, file_delete='y'): parser = etree.XMLParser(remove_blank_text=True) #################################################################### seed seed = etree.parse(file_seed, parser) root = "}".join(seed.getroot().tag.split("}")[:-1]) + "}" seed_tree = seed.getroot().find(root + 'model/' + root + 'listOfSpecies') listOfSeed = [] for element in seed_tree: listOfSeed.append(element.attrib['id']) #################################################################### target target = etree.parse(file_target, parser) root = "}".join(target.getroot().tag.split("}")[:-1]) + "}" target_tree = target.getroot().find(root + 'model/' + root + 'listOfSpecies') listOfTarget = [] for element in target_tree: listOfTarget.append(element.attrib['id']) #################################################################### metabolite name_metabolite = {} metabo_sbml = etree.parse(file_metabo, parser) root = "}".join(metabo_sbml.getroot().tag.split("}")[:-1]) + "}" listS = metabo_sbml.getroot().find(root + 'model/' + root + 'listOfSpecies') test = set() for specie in listS: id_specie = specie.attrib["id"] if id_specie not in listOfSeed and id_specie not in listOfTarget: test.add(specie.attrib["id"]) try: name_metabolite.update({id_specie: [specie.attrib["name"]]}) except KeyError: name_metabolite.update({id_specie: [id_specie]}) try: name_metabolite[id_specie].append(specie.attrib["compartment"]) except KeyError: pass ######################################################################## with open(file_draft, "r") as file: line0 = file.readlines()[0] file = open(repository + "stoichiometrical_crossroads.csv", "w") writer = csv.writer(file, delimiter="\t") if len(list(name_metabolite)[0]) == 2: writer.writerow(['identifiant', 'name', 'compartment']) else: writer.writerow(['identifiant', 'name']) file.close() for removed_metabo in test: outFile = draft_without_metabolite.without_metabo( file_draft, removed_metabo, "new_draft.sbml") model = create_cobra_model_from_sbml_file(outFile) model.optimize() growth = model.solution.f try: if abs(growth) <= limit: file = open(repository + "stoichiometrical_crossroads.csv", "a") writer = csv.writer(file, delimiter="\t") writer.writerow([removed_metabo] + name_metabolite[removed_metabo]) file.close() except TypeError: print(removed_metabo, "\t", growth) if file_delete == "y": os.remove(outFile)
# 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)
# -*- coding: utf-8 -*- """ Created on Mon Mar 28 12:54:03 2016 @author: dan """ import pandas as pd from capacity_usage import CAPACITY_USAGE from cobra.io.sbml import create_cobra_model_from_sbml_file cu = CAPACITY_USAGE() x = pd.read_pickle("../data/reaction_to_genes_per_condition.pkl") y = x.sum() y = y[y>1].dropna(how='all') mass = cu.enzymes_mg_gCDW.loc[y.index] model = create_cobra_model_from_sbml_file("../data/iJO1366.xml") genes = map(cu.model.genes.get_by_id, mass.index) s = set() for g in genes: s.update(set(map(str,g.reactions))) print mass.sum() / cu.enzymes_mg_gCDW.sum()
def load_thermoModel(anoxic=False): ijo1366_sbml = "/home/user/code/thermodynamics/thermodynamics_data/iJO1366.xml" # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) ## Update AMPMS2 #coc = Metabolite('co_c','CO','carbon monoxide','c'); #coc.charge = 0; #cop = Metabolite('co_p','CO','carbon monoxide','p'); #cop.charge = 0; #coe = Metabolite('co_e','CO','carbon monoxide','e'); #coe.charge = 0; #cobra_model.add_metabolites([coc,cop,coe]) #ampms2_mets = {}; #ampms2_mets[cobra_model.metabolites.get_by_id('air_c')] = -1; #ampms2_mets[cobra_model.metabolites.get_by_id('amet_c')] = -1; #ampms2_mets[cobra_model.metabolites.get_by_id('dad_DASH_5_c')] = 1; #ampms2_mets[cobra_model.metabolites.get_by_id('met_DASH_L_c')] = 1; #ampms2_mets[cobra_model.metabolites.get_by_id('4ampm_c')] = 1; #ampms2_mets[cobra_model.metabolites.get_by_id('h_c')] = 3; #ampms2_mets[cobra_model.metabolites.get_by_id('for_c')] = 1; #ampms2_mets[cobra_model.metabolites.get_by_id('co_c')] = 1; #ampms2 = Reaction('AMPMS3'); #ampms2.add_metabolites(ampms2_mets); #copp_mets = {}; #copp_mets[cobra_model.metabolites.get_by_id('co_c')] = -1; #copp_mets[cobra_model.metabolites.get_by_id('co_p')] = 1; #copp = Reaction('COtpp'); #copp.add_metabolites(copp_mets); #coex_mets = {}; #coex_mets[cobra_model.metabolites.get_by_id('co_p')] = -1; #coex_mets[cobra_model.metabolites.get_by_id('co_e')] = 1; #coex = Reaction('COtex'); #coex.add_metabolites(coex_mets); #cotrans_mets = {}; #cotrans_mets[cobra_model.metabolites.get_by_id('co_e')] = -1; #cotrans = Reaction('EX_co_LPAREN_e_RPAREN_'); #cotrans.add_metabolites(cotrans_mets); #cobra_model.add_reactions([ampms2,copp,coex,cotrans]); #cobra_model.remove_reactions(['AMPMS2']); # Define the model conditions: system_boundaries = [ x.id for x in cobra_model.reactions if x.boundary == 'system_boundary' ] for b in system_boundaries: cobra_model.reactions.get_by_id(b).lower_bound = 0.0 cobra_model.reactions.get_by_id(b).upper_bound = 0.0 # Reset demand reactions demand = [ 'DM_4CRSOL', 'DM_5DRIB', 'DM_AACALD', 'DM_AMOB', 'DM_MTHTHF', 'DM_OXAM' ] for d in demand: cobra_model.reactions.get_by_id(d).lower_bound = 0.0 cobra_model.reactions.get_by_id(d).upper_bound = 1000.0 # Change the objective cobra_model.objective = { cobra_model.reactions.Ec_biomass_iJO1366_WT_53p95M: 1.0 } cobra_model.remove_reactions(['Ec_biomass_iJO1366_core_53p95M']) # Assign KOs # Specify media composition (M9 glucose): if anoxic: cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN_').lower_bound = -18.0 cobra_model.reactions.get_by_id( 'EX_o2_LPAREN_e_RPAREN_').lower_bound = 0.0 else: cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN_').lower_bound = -10.0 cobra_model.reactions.get_by_id( 'EX_o2_LPAREN_e_RPAREN_').lower_bound = -18.0 #uptake = ['EX_cl_LPAREN_e_RPAREN_', # 'EX_h_LPAREN_e_RPAREN_', # 'EX_so4_LPAREN_e_RPAREN_', # 'EX_ca2_LPAREN_e_RPAREN_', # 'EX_pi_LPAREN_e_RPAREN_', # 'EX_fe2_LPAREN_e_RPAREN_', # 'EX_cu2_LPAREN_e_RPAREN_', # 'EX_zn2_LPAREN_e_RPAREN_', # 'EX_cbl1_LPAREN_e_RPAREN_', # 'EX_mobd_LPAREN_e_RPAREN_', # 'EX_ni2_LPAREN_e_RPAREN_', # 'EX_mn2_LPAREN_e_RPAREN_', # 'EX_k_LPAREN_e_RPAREN_', # 'EX_nh4_LPAREN_e_RPAREN_', # 'EX_cobalt2_LPAREN_e_RPAREN_', # 'EX_mg2_LPAREN_e_RPAREN_']; uptake = [ 'EX_ca2_LPAREN_e_RPAREN_', 'EX_cbl1_LPAREN_e_RPAREN_', 'EX_cl_LPAREN_e_RPAREN_', 'EX_co2_LPAREN_e_RPAREN_', 'EX_cobalt2_LPAREN_e_RPAREN_', 'EX_cu2_LPAREN_e_RPAREN_', 'EX_fe2_LPAREN_e_RPAREN_', 'EX_fe3_LPAREN_e_RPAREN_', 'EX_h_LPAREN_e_RPAREN_', 'EX_h2o_LPAREN_e_RPAREN_', 'EX_k_LPAREN_e_RPAREN_', 'EX_mg2_LPAREN_e_RPAREN_', 'EX_mn2_LPAREN_e_RPAREN_', 'EX_mobd_LPAREN_e_RPAREN_', 'EX_na1_LPAREN_e_RPAREN_', 'EX_nh4_LPAREN_e_RPAREN_', 'EX_ni2_LPAREN_e_RPAREN_', 'EX_pi_LPAREN_e_RPAREN_', 'EX_sel_LPAREN_e_RPAREN_', 'EX_slnt_LPAREN_e_RPAREN_', 'EX_so4_LPAREN_e_RPAREN_', 'EX_tungs_LPAREN_e_RPAREN_', 'EX_zn2_LPAREN_e_RPAREN_' ] for u in uptake: cobra_model.reactions.get_by_id(u).lower_bound = -1000.0 # Specify allowed secretion products 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_glyclt_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_' ] #secrete = ['EX_12ppd_DASH_R_LPAREN_e_RPAREN_', # 'EX_12ppd_DASH_S_LPAREN_e_RPAREN_', # 'EX_14glucan_LPAREN_e_RPAREN_', # 'EX_15dap_LPAREN_e_RPAREN_', # 'EX_23camp_LPAREN_e_RPAREN_', # 'EX_23ccmp_LPAREN_e_RPAREN_', # 'EX_23cgmp_LPAREN_e_RPAREN_', # 'EX_23cump_LPAREN_e_RPAREN_', # 'EX_23dappa_LPAREN_e_RPAREN_', # 'EX_26dap_DASH_M_LPAREN_e_RPAREN_', # 'EX_2ddglcn_LPAREN_e_RPAREN_', # 'EX_34dhpac_LPAREN_e_RPAREN_', # 'EX_3amp_LPAREN_e_RPAREN_', # 'EX_3cmp_LPAREN_e_RPAREN_', # 'EX_3gmp_LPAREN_e_RPAREN_', # 'EX_3hcinnm_LPAREN_e_RPAREN_', # 'EX_3hpp_LPAREN_e_RPAREN_', # 'EX_3hpppn_LPAREN_e_RPAREN_', # 'EX_3ump_LPAREN_e_RPAREN_', # 'EX_4abut_LPAREN_e_RPAREN_', # 'EX_4hoxpacd_LPAREN_e_RPAREN_', # 'EX_5dglcn_LPAREN_e_RPAREN_', # 'EX_5mtr_LPAREN_e_RPAREN_', # 'EX_LalaDglu_LPAREN_e_RPAREN_', # 'EX_LalaDgluMdap_LPAREN_e_RPAREN_', # 'EX_LalaDgluMdapDala_LPAREN_e_RPAREN_', # 'EX_LalaLglu_LPAREN_e_RPAREN_', # 'EX_ac_LPAREN_e_RPAREN_', # 'EX_acac_LPAREN_e_RPAREN_', # 'EX_acald_LPAREN_e_RPAREN_', # 'EX_acgal_LPAREN_e_RPAREN_', # 'EX_acgal1p_LPAREN_e_RPAREN_', # 'EX_acgam_LPAREN_e_RPAREN_', # 'EX_acgam1p_LPAREN_e_RPAREN_', # 'EX_acmana_LPAREN_e_RPAREN_', # 'EX_acmum_LPAREN_e_RPAREN_', # 'EX_acnam_LPAREN_e_RPAREN_', # 'EX_acolipa_LPAREN_e_RPAREN_', # 'EX_acser_LPAREN_e_RPAREN_', # 'EX_ade_LPAREN_e_RPAREN_', # 'EX_adn_LPAREN_e_RPAREN_', # 'EX_adocbl_LPAREN_e_RPAREN_', # 'EX_ag_LPAREN_e_RPAREN_', # 'EX_agm_LPAREN_e_RPAREN_', # 'EX_akg_LPAREN_e_RPAREN_', # 'EX_ala_DASH_B_LPAREN_e_RPAREN_', # 'EX_ala_DASH_D_LPAREN_e_RPAREN_', # 'EX_ala_DASH_L_LPAREN_e_RPAREN_', # 'EX_alaala_LPAREN_e_RPAREN_', # 'EX_all_DASH_D_LPAREN_e_RPAREN_', # 'EX_alltn_LPAREN_e_RPAREN_', # 'EX_amp_LPAREN_e_RPAREN_', # 'EX_anhgm_LPAREN_e_RPAREN_', # 'EX_arab_DASH_L_LPAREN_e_RPAREN_', # 'EX_arbt_LPAREN_e_RPAREN_', # 'EX_arbtn_LPAREN_e_RPAREN_', # 'EX_arbtn_DASH_fe3_LPAREN_e_RPAREN_', # 'EX_arg_DASH_L_LPAREN_e_RPAREN_', # 'EX_ascb_DASH_L_LPAREN_e_RPAREN_', # 'EX_asn_DASH_L_LPAREN_e_RPAREN_', # 'EX_aso3_LPAREN_e_RPAREN_', # 'EX_asp_DASH_L_LPAREN_e_RPAREN_', # 'EX_btn_LPAREN_e_RPAREN_', # 'EX_but_LPAREN_e_RPAREN_', # 'EX_butso3_LPAREN_e_RPAREN_', # 'EX_ca2_LPAREN_e_RPAREN_', # 'EX_cbi_LPAREN_e_RPAREN_', # 'EX_cbl1_LPAREN_e_RPAREN_', # 'EX_cd2_LPAREN_e_RPAREN_', # 'EX_cgly_LPAREN_e_RPAREN_', # 'EX_chol_LPAREN_e_RPAREN_', # 'EX_chtbs_LPAREN_e_RPAREN_', # 'EX_cit_LPAREN_e_RPAREN_', # 'EX_cl_LPAREN_e_RPAREN_', # 'EX_cm_LPAREN_e_RPAREN_', # 'EX_cmp_LPAREN_e_RPAREN_', # 'EX_co2_LPAREN_e_RPAREN_', # 'EX_cobalt2_LPAREN_e_RPAREN_', # 'EX_colipa_LPAREN_e_RPAREN_', # 'EX_colipap_LPAREN_e_RPAREN_', # 'EX_cpgn_LPAREN_e_RPAREN_', # 'EX_cpgn_DASH_un_LPAREN_e_RPAREN_', # 'EX_crn_LPAREN_e_RPAREN_', # 'EX_crn_DASH_D_LPAREN_e_RPAREN_', # 'EX_csn_LPAREN_e_RPAREN_', # 'EX_cu_LPAREN_e_RPAREN_', # 'EX_cu2_LPAREN_e_RPAREN_', # 'EX_cyan_LPAREN_e_RPAREN_', # 'EX_cynt_LPAREN_e_RPAREN_', # 'EX_cys_DASH_D_LPAREN_e_RPAREN_', # 'EX_cys_DASH_L_LPAREN_e_RPAREN_', # 'EX_cytd_LPAREN_e_RPAREN_', # 'EX_dad_DASH_2_LPAREN_e_RPAREN_', # 'EX_damp_LPAREN_e_RPAREN_', # 'EX_dca_LPAREN_e_RPAREN_', # 'EX_dcmp_LPAREN_e_RPAREN_', # 'EX_dcyt_LPAREN_e_RPAREN_', # 'EX_ddca_LPAREN_e_RPAREN_', # 'EX_dgmp_LPAREN_e_RPAREN_', # 'EX_dgsn_LPAREN_e_RPAREN_', # 'EX_dha_LPAREN_e_RPAREN_', # 'EX_dimp_LPAREN_e_RPAREN_', # 'EX_din_LPAREN_e_RPAREN_', # 'EX_dms_LPAREN_e_RPAREN_', # 'EX_dmso_LPAREN_e_RPAREN_', # 'EX_dopa_LPAREN_e_RPAREN_', # 'EX_doxrbcn_LPAREN_e_RPAREN_', # 'EX_dtmp_LPAREN_e_RPAREN_', # 'EX_dump_LPAREN_e_RPAREN_', # 'EX_duri_LPAREN_e_RPAREN_', # 'EX_eca4colipa_LPAREN_e_RPAREN_', # 'EX_enlipa_LPAREN_e_RPAREN_', # 'EX_enter_LPAREN_e_RPAREN_', # 'EX_etha_LPAREN_e_RPAREN_', # 'EX_ethso3_LPAREN_e_RPAREN_', # 'EX_etoh_LPAREN_e_RPAREN_', # 'EX_f6p_LPAREN_e_RPAREN_', # 'EX_fald_LPAREN_e_RPAREN_', # 'EX_fe2_LPAREN_e_RPAREN_', # 'EX_fe3_LPAREN_e_RPAREN_', # 'EX_fe3dcit_LPAREN_e_RPAREN_', # 'EX_fe3dhbzs_LPAREN_e_RPAREN_', # 'EX_fe3hox_LPAREN_e_RPAREN_', # 'EX_fe3hox_DASH_un_LPAREN_e_RPAREN_', # 'EX_fecrm_LPAREN_e_RPAREN_', # 'EX_fecrm_DASH_un_LPAREN_e_RPAREN_', # 'EX_feenter_LPAREN_e_RPAREN_', # 'EX_feoxam_LPAREN_e_RPAREN_', # 'EX_feoxam_DASH_un_LPAREN_e_RPAREN_', # 'EX_for_LPAREN_e_RPAREN_', # 'EX_fru_LPAREN_e_RPAREN_', # 'EX_frulys_LPAREN_e_RPAREN_', # 'EX_fruur_LPAREN_e_RPAREN_', # 'EX_fuc_DASH_L_LPAREN_e_RPAREN_', # 'EX_fum_LPAREN_e_RPAREN_', # 'EX_fusa_LPAREN_e_RPAREN_', # 'EX_g1p_LPAREN_e_RPAREN_', # 'EX_g3pc_LPAREN_e_RPAREN_', # 'EX_g3pe_LPAREN_e_RPAREN_', # 'EX_g3pg_LPAREN_e_RPAREN_', # 'EX_g3pi_LPAREN_e_RPAREN_', # 'EX_g3ps_LPAREN_e_RPAREN_', # 'EX_g6p_LPAREN_e_RPAREN_', # 'EX_gal_LPAREN_e_RPAREN_', # 'EX_gal_DASH_bD_LPAREN_e_RPAREN_', # 'EX_gal1p_LPAREN_e_RPAREN_', # 'EX_galct_DASH_D_LPAREN_e_RPAREN_', # 'EX_galctn_DASH_D_LPAREN_e_RPAREN_', # 'EX_galctn_DASH_L_LPAREN_e_RPAREN_', # 'EX_galt_LPAREN_e_RPAREN_', # 'EX_galur_LPAREN_e_RPAREN_', # 'EX_gam_LPAREN_e_RPAREN_', # 'EX_gam6p_LPAREN_e_RPAREN_', # 'EX_gbbtn_LPAREN_e_RPAREN_', # 'EX_gdp_LPAREN_e_RPAREN_', # 'EX_glc_LPAREN_e_RPAREN_', # 'EX_glcn_LPAREN_e_RPAREN_', # 'EX_glcr_LPAREN_e_RPAREN_', # 'EX_glcur_LPAREN_e_RPAREN_', # 'EX_glcur1p_LPAREN_e_RPAREN_', # 'EX_gln_DASH_L_LPAREN_e_RPAREN_', # 'EX_glu_DASH_L_LPAREN_e_RPAREN_', # 'EX_gly_LPAREN_e_RPAREN_', # 'EX_glyald_LPAREN_e_RPAREN_', # 'EX_glyb_LPAREN_e_RPAREN_', # 'EX_glyc_LPAREN_e_RPAREN_', # 'EX_glyc_DASH_R_LPAREN_e_RPAREN_', # 'EX_glyc2p_LPAREN_e_RPAREN_', # 'EX_glyc3p_LPAREN_e_RPAREN_', # 'EX_glyclt_LPAREN_e_RPAREN_', # 'EX_gmp_LPAREN_e_RPAREN_', # 'EX_gsn_LPAREN_e_RPAREN_', # 'EX_gthox_LPAREN_e_RPAREN_', # 'EX_gthrd_LPAREN_e_RPAREN_', # 'EX_gtp_LPAREN_e_RPAREN_', # 'EX_gua_LPAREN_e_RPAREN_', # 'EX_h_LPAREN_e_RPAREN_', # 'EX_h2_LPAREN_e_RPAREN_', # 'EX_h2o_LPAREN_e_RPAREN_', # 'EX_h2o2_LPAREN_e_RPAREN_', # 'EX_h2s_LPAREN_e_RPAREN_', # 'EX_hacolipa_LPAREN_e_RPAREN_', # 'EX_halipa_LPAREN_e_RPAREN_', # 'EX_hdca_LPAREN_e_RPAREN_', # 'EX_hdcea_LPAREN_e_RPAREN_', # 'EX_hg2_LPAREN_e_RPAREN_', # 'EX_his_DASH_L_LPAREN_e_RPAREN_', # 'EX_hom_DASH_L_LPAREN_e_RPAREN_', # 'EX_hxa_LPAREN_e_RPAREN_', # 'EX_hxan_LPAREN_e_RPAREN_', # 'EX_idon_DASH_L_LPAREN_e_RPAREN_', # 'EX_ile_DASH_L_LPAREN_e_RPAREN_', # 'EX_imp_LPAREN_e_RPAREN_', # 'EX_indole_LPAREN_e_RPAREN_', # 'EX_inost_LPAREN_e_RPAREN_', # 'EX_ins_LPAREN_e_RPAREN_', # 'EX_isetac_LPAREN_e_RPAREN_', # 'EX_k_LPAREN_e_RPAREN_', # 'EX_kdo2lipid4_LPAREN_e_RPAREN_', # 'EX_lac_DASH_D_LPAREN_e_RPAREN_', # 'EX_lac_DASH_L_LPAREN_e_RPAREN_', # 'EX_lcts_LPAREN_e_RPAREN_', # 'EX_leu_DASH_L_LPAREN_e_RPAREN_', # 'EX_lipa_LPAREN_e_RPAREN_', # 'EX_lipa_cold_LPAREN_e_RPAREN_', # 'EX_lipoate_LPAREN_e_RPAREN_', # 'EX_lys_DASH_L_LPAREN_e_RPAREN_', # 'EX_lyx_DASH_L_LPAREN_e_RPAREN_', # 'EX_mal_DASH_D_LPAREN_e_RPAREN_', # 'EX_mal_DASH_L_LPAREN_e_RPAREN_', # 'EX_malt_LPAREN_e_RPAREN_', # 'EX_malthx_LPAREN_e_RPAREN_', # 'EX_maltpt_LPAREN_e_RPAREN_', # 'EX_malttr_LPAREN_e_RPAREN_', # 'EX_maltttr_LPAREN_e_RPAREN_', # 'EX_man_LPAREN_e_RPAREN_', # 'EX_man6p_LPAREN_e_RPAREN_', # 'EX_manglyc_LPAREN_e_RPAREN_', # 'EX_melib_LPAREN_e_RPAREN_', # 'EX_meoh_LPAREN_e_RPAREN_', # 'EX_met_DASH_D_LPAREN_e_RPAREN_', # 'EX_met_DASH_L_LPAREN_e_RPAREN_', # 'EX_metsox_DASH_R_DASH_L_LPAREN_e_RPAREN_', # 'EX_metsox_DASH_S_DASH_L_LPAREN_e_RPAREN_', # 'EX_mg2_LPAREN_e_RPAREN_', # 'EX_mincyc_LPAREN_e_RPAREN_', # 'EX_minohp_LPAREN_e_RPAREN_', # 'EX_mmet_LPAREN_e_RPAREN_', # 'EX_mn2_LPAREN_e_RPAREN_', # 'EX_mnl_LPAREN_e_RPAREN_', # 'EX_mobd_LPAREN_e_RPAREN_', # 'EX_mso3_LPAREN_e_RPAREN_', # 'EX_n2o_LPAREN_e_RPAREN_', # 'EX_na1_LPAREN_e_RPAREN_', # 'EX_nac_LPAREN_e_RPAREN_', # 'EX_nh4_LPAREN_e_RPAREN_', # 'EX_ni2_LPAREN_e_RPAREN_', # 'EX_nmn_LPAREN_e_RPAREN_', # 'EX_no_LPAREN_e_RPAREN_', # 'EX_no2_LPAREN_e_RPAREN_', # 'EX_no3_LPAREN_e_RPAREN_', # 'EX_novbcn_LPAREN_e_RPAREN_', # 'EX_o16a4colipa_LPAREN_e_RPAREN_', # 'EX_o2_LPAREN_e_RPAREN_', # 'EX_o2s_LPAREN_e_RPAREN_', # 'EX_ocdca_LPAREN_e_RPAREN_', # 'EX_ocdcea_LPAREN_e_RPAREN_', # 'EX_octa_LPAREN_e_RPAREN_', # 'EX_orn_LPAREN_e_RPAREN_', # 'EX_orot_LPAREN_e_RPAREN_', # 'EX_pacald_LPAREN_e_RPAREN_', # 'EX_peamn_LPAREN_e_RPAREN_', # 'EX_phe_DASH_L_LPAREN_e_RPAREN_', # 'EX_pheme_LPAREN_e_RPAREN_', # 'EX_pi_LPAREN_e_RPAREN_', # 'EX_pnto_DASH_R_LPAREN_e_RPAREN_', # 'EX_ppa_LPAREN_e_RPAREN_', # 'EX_ppal_LPAREN_e_RPAREN_', # 'EX_pppn_LPAREN_e_RPAREN_', # 'EX_ppt_LPAREN_e_RPAREN_', # 'EX_pro_DASH_L_LPAREN_e_RPAREN_', # 'EX_progly_LPAREN_e_RPAREN_', # 'EX_psclys_LPAREN_e_RPAREN_', # 'EX_pser_DASH_L_LPAREN_e_RPAREN_', # 'EX_ptrc_LPAREN_e_RPAREN_', # 'EX_pydam_LPAREN_e_RPAREN_', # 'EX_pydx_LPAREN_e_RPAREN_', # 'EX_pydxn_LPAREN_e_RPAREN_', # 'EX_pyr_LPAREN_e_RPAREN_', # 'EX_quin_LPAREN_e_RPAREN_', # 'EX_r5p_LPAREN_e_RPAREN_', # 'EX_rfamp_LPAREN_e_RPAREN_', # 'EX_rib_DASH_D_LPAREN_e_RPAREN_', # 'EX_rmn_LPAREN_e_RPAREN_', # 'EX_sbt_DASH_D_LPAREN_e_RPAREN_', # 'EX_sel_LPAREN_e_RPAREN_', # 'EX_ser_DASH_D_LPAREN_e_RPAREN_', # 'EX_ser_DASH_L_LPAREN_e_RPAREN_', # 'EX_skm_LPAREN_e_RPAREN_', # 'EX_slnt_LPAREN_e_RPAREN_', # 'EX_so2_LPAREN_e_RPAREN_', # 'EX_so3_LPAREN_e_RPAREN_', # 'EX_so4_LPAREN_e_RPAREN_', # 'EX_spmd_LPAREN_e_RPAREN_', # 'EX_succ_LPAREN_e_RPAREN_', # 'EX_sucr_LPAREN_e_RPAREN_', # 'EX_sulfac_LPAREN_e_RPAREN_', # 'EX_tartr_DASH_D_LPAREN_e_RPAREN_', # 'EX_tartr_DASH_L_LPAREN_e_RPAREN_', # 'EX_taur_LPAREN_e_RPAREN_', # 'EX_tcynt_LPAREN_e_RPAREN_', # 'EX_thm_LPAREN_e_RPAREN_', # 'EX_thr_DASH_L_LPAREN_e_RPAREN_', # 'EX_thrp_LPAREN_e_RPAREN_', # 'EX_thym_LPAREN_e_RPAREN_', # 'EX_thymd_LPAREN_e_RPAREN_', # 'EX_tma_LPAREN_e_RPAREN_', # 'EX_tmao_LPAREN_e_RPAREN_', # 'EX_tre_LPAREN_e_RPAREN_', # 'EX_trp_DASH_L_LPAREN_e_RPAREN_', # 'EX_tsul_LPAREN_e_RPAREN_', # 'EX_ttdca_LPAREN_e_RPAREN_', # 'EX_ttdcea_LPAREN_e_RPAREN_', # 'EX_ttrcyc_LPAREN_e_RPAREN_', # 'EX_tungs_LPAREN_e_RPAREN_', # 'EX_tym_LPAREN_e_RPAREN_', # 'EX_tyr_DASH_L_LPAREN_e_RPAREN_', # 'EX_tyrp_LPAREN_e_RPAREN_', # 'EX_uacgam_LPAREN_e_RPAREN_', # 'EX_udpacgal_LPAREN_e_RPAREN_', # 'EX_udpg_LPAREN_e_RPAREN_', # 'EX_udpgal_LPAREN_e_RPAREN_', # 'EX_udpglcur_LPAREN_e_RPAREN_', # 'EX_ump_LPAREN_e_RPAREN_', # 'EX_ura_LPAREN_e_RPAREN_', # 'EX_urea_LPAREN_e_RPAREN_', # 'EX_uri_LPAREN_e_RPAREN_', # 'EX_val_DASH_L_LPAREN_e_RPAREN_', # 'EX_xan_LPAREN_e_RPAREN_', # 'EX_xmp_LPAREN_e_RPAREN_', # 'EX_xtsn_LPAREN_e_RPAREN_', # 'EX_xyl_DASH_D_LPAREN_e_RPAREN_', # 'EX_xylu_DASH_L_LPAREN_e_RPAREN_', # 'EX_zn2_LPAREN_e_RPAREN_']; for s in secrete: cobra_model.reactions.get_by_id(s).upper_bound = 1000.0 # Constrain specific reactions noFlux = ['F6PA', 'DHAPT'] ammoniaExcess = ['GLUDy'] aerobic = [ 'RNDR1', 'RNDR2', 'RNDR3', 'RNDR4', 'RNDR1b', 'RNDR2b', 'RNDR3b', 'RNDR4b', 'DHORD2', 'ASPO6', 'LCARR' ] anaerobic = [ 'RNTR1c2', 'RNTR2c2', 'RNTR3c2', 'RNTR4c2', 'RNDR1b', 'RNDR2b', 'RNDR3b', 'RNDR4b', 'DHORD5', 'ASPO5' ] if anoxic: rxnList = noFlux + ammoniaExcess + aerobic for rxn in rxnList: cobra_model.reactions.get_by_id(rxn).lower_bound = 0.0 cobra_model.reactions.get_by_id(rxn).upper_bound = 0.0 else: rxnList = noFlux + ammoniaExcess + anaerobic for rxn in rxnList: cobra_model.reactions.get_by_id(rxn).lower_bound = 0.0 cobra_model.reactions.get_by_id(rxn).upper_bound = 0.0 ## Set the direction for specific reactions #fattyAcidSynthesis = ['ACCOAC', 'ACOATA', 'HACD1', 'HACD2', 'HACD3', 'HACD4', 'HACD5', 'HACD6', 'HACD7', 'HACD8', 'KAS14', 'KAS15', 'MACPD', 'MCOATA', '3OAR100', '3OAR120', '3OAR121', '3OAR140', '3OAR141', '3OAR160', '3OAR161', '3OAR180', '3OAR181', '3OAR40', '3OAR60', '3OAR80'] #fattyAcidOxidation = ['ACACT1r', 'ACACT2r', 'ACACT3r', 'ACACT4r', 'ACACT5r', 'ACACT6r', 'ACACT7r', 'ACACT8r', 'ACOAD1f', 'ACOAD2f', 'ACOAD3f', 'ACOAD4f', 'ACOAD5f', 'ACOAD6f', 'ACOAD7f', 'ACOAD8f', 'CTECOAI6', 'CTECOAI7', 'CTECOAI8', 'ECOAH1', 'ECOAH2', 'ECOAH3', 'ECOAH4', 'ECOAH5', 'ECOAH6', 'ECOAH7', 'ECOAH8'] #ndpk = ['NDPK1','NDPK2','NDPK3','NDPK4','NDPK5','NDPK7','NDPK8']; #rxnList = fattyAcidSynthesis + fattyAcidOxidation; #for rxn in rxnList: # cobra_model.reactions.get_by_id(rxn).lower_bound = 0.0; # cobra_model.reactions.get_by_id(rxn).upper_bound = 1000.0; return cobra_model
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)
from cobra.io.sbml import create_cobra_model_from_sbml_file import pandas as pd import numpy as np from scipy.integrate import quad rho = 1100 # average cell density gr/liter DW_fraction = 0.3 # fraction of DW of cells Avogadro = 6.022 * 1e23 # Avogadro's number "exponent-less" ATPM = 3.14 # mmol_gCDW_h ATP_pool = 0.030 # mmol_gCDW from Bennett glycogen_pool = (2.5 / 100) / 0.18 # mmol_gCDW from Bennett proteome_T = 10 # h proteome turnover model = create_cobra_model_from_sbml_file('data/iJO1366.xml') rxns = dict([(r.id, r) for r in model.reactions]) rxns[ 'EX_glc_e'].lower_bound = 0 # uptake of carbon source reaction is initialized rxns['ATPM'].lower_bound = 0 rxns['Ec_biomass_iJO1366_core_53p95M'].objective_coefficient = 0 rxns['ATPS4rpp'].objective_coefficient = 1 AA = 'gly,ala_L,arg_L,asn_L,asp_L,cys_L,glu_L,gln_L,his_L,ile_L,leu_L,lys_L,met_L,\ phe_L,pro_L,ser_L,thr_L,trp_L,tyr_L,val_L'.split(',') AA_to_symbol = { 'gly': 'G', 'ala_L': 'A', 'arg_L': 'R', 'asn_L': 'N', 'asp_L': 'D', 'cys_L': 'C',
''' ids = [] values = [] for entry in fluxdict: ids.append(entry) values.append(fluxdict[entry]) normalizedvalues = values / np.linalg.norm(values) return dict(zip(ids, normalizedvalues)) if __name__ == "__main__": from cobra.io.sbml import create_cobra_model_from_sbml_file from cobra import flux_analysis iJE660a = create_cobra_model_from_sbml_file('iJE660a_fromMPS.sbml') iJE660a.reactions.get_by_id('EX_NH3').lower_bound = -100 iJE660a.reactions.get_by_id('EX_O2').lower_bound = -20 iJE660a.reactions.get_by_id('EX_O2').upper_bound = 0 iJE660a.reactions.get_by_id('ATPM').lower_bound = 7.6 iJE660a.reactions.get_by_id('ATPM').upper_bound = 7.6 iJE660a.reactions.get_by_id('EX_CO2').lower_bound = -1000 iJE660a.reactions.get_by_id('EX_K').lower_bound = -1000 #Potassium iJE660a.reactions.get_by_id('EX_PI').lower_bound = -1000 iJE660a.reactions.get_by_id('EX_SLF').lower_bound = -1000 #Set maximal carbon source uptake: iJE660a.reactions.get_by_id('EX_GLU').lower_bound = -20 #iJE660a.reactions.get_by_id('EX_SUCC').lower_bound = -20
def optimal_crossroad(networkFile, file_seed, file_target, limit, repository): model = create_cobra_model_from_sbml_file(networkFile) model.optimize() if (model.solution.f > limit) and file_seed != "": FVA_result = flux_analysis.variability.flux_variability_analysis( model, fraction_of_optimum=1.0) essential = {} cross_FVA = set() BDD_species = {} for id_reaction in FVA_result.keys(): inf = FVA_result[id_reaction]['minimum'] sup = FVA_result[id_reaction]['maximum'] if inf > limit and sup > limit: essential.update({id_reaction: "->"}) elif inf < -limit and sup < -limit: essential.update({id_reaction: "<-"}) parser = etree.XMLParser(remove_blank_text=True) #################################################################################### seed seed = etree.parse(file_seed, parser) root = "}".join(seed.getroot().tag.split("}")[:-1]) + "}" seed_tree = seed.getroot().find(root + 'model/' + root + 'listOfSpecies') listOfSeed = [] for element in seed_tree: listOfSeed.append(element.attrib['id']) #################################################################################### target target = etree.parse(file_target, parser) root = "}".join(target.getroot().tag.split("}")[:-1]) + "}" target_tree = target.getroot().find(root + 'model/' + root + 'listOfSpecies') listOfTarget = [] for element in target_tree: listOfTarget.append(element.attrib['id']) #################################################################################### draft = etree.parse(networkFile) sbml = draft.find('sbml') root = "}".join(draft.getroot().tag.split("}")[:-1]) + "}" listOfSpecies = draft.find(root + 'model/' + root + 'listOfSpecies') for specie in listOfSpecies: BDD_species.update({specie.attrib["id"]: [specie.attrib["name"]]}) try: BDD_species[specie.attrib["id"]].append( specie.attrib["compartment"]) except KeyError: pass listOfReactions = draft.find(root + 'model/' + root + 'listOfReactions') for reaction in listOfReactions: id_reac = reaction.attrib["id"] id_name_reac = "_".join(id_reac.split("_")[1:]) try: name_reac = reaction.attrib["name"] except KeyError: name_reac = "_".join(id_reac.split("_")[1:]) if id_reac in essential.keys() or name_reac in essential.keys( ) or id_name_reac in essential.keys(): try: direction = essential[id_reac] except KeyError: try: direction = essential[name_reac] except KeyError: direction = essential[id_name_reac] listOfReactants = reaction.find(root + "listOfReactants") if direction == "->": try: for specie in listOfReactants: if specie.attrib[ "species"] not in listOfSeed and specie.attrib[ "species"] not in listOfTarget: cross_FVA.add(specie.attrib["species"]) except: pass elif direction == "<-": listOfProducts = reaction.find(root + "listOfProducts") try: for specie in listOfProducts: if specie.attrib[ "species"] not in listOfSeed and specie.attrib[ "species"] not in listOfTarget: cross_FVA.add(specie.attrib["species"]) except: pass file = open(repository + "optimal_biomass_crossroads.sbml", "wt") writer = csv.writer(file, delimiter="\t") if len(list(BDD_species)[0]) == 2: writer.writerow(['identifiant', 'name', 'compartment']) else: writer.writerow(['identifiant', 'name']) for cross in cross_FVA: writer.writerow([cross] + BDD_species[cross]) file.close()
import cobra.test import os from cobra.io.sbml import create_cobra_model_from_sbml_file import pandas f = open('modelPractice.txt','w') mouseModel = create_cobra_model_from_sbml_file('iMM1415.xml') # for x in cobra_model.metabolites: # f.write("%s : %s" %(x.id, x.name)) # f.write('\n') # mouseModel.optimize() # print(mouseModel.solution.status) # print(mouseModel.solution.f) # # fva_output = cobra.flux_analysis.flux_variability_analysis(mouseModel, mouseModel.reactions[3700:]) # f.write(str(pandas.DataFrame.from_dict(fva_output).T.round(5))) checkvar = mouseModel.optimize() gr, s = cobra.flux_analysis.single_gene_deletion(mouseModel, mouseModel.genes) # f.write(str(pandas.DataFrame.from_dict({"growth_rates" : gr, "status" : s}))) for key in gr: if gr[key] != checkvar: print gr[key]
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]);
import mpld3 from cobra.io.sbml import create_cobra_model_from_sbml_file from cobra import Reaction, flux_analysis, Model import pickle import re import matplotlib.pyplot as plt import numpy as np import operator # mpld3.enable_notebook() model = create_cobra_model_from_sbml_file( 'Models' + '/2016_06_23_gapped_meoh_producing.xml') Universal = Model('Universal Reactions') # f = open('ModelSEED-reactions-db.xlsEdited - Reactions.tsv', 'r') # next(f) # rxn_dict = {} # Creates a dictionary of the reactions from the tab delimited database, storing their ID and the reaction string # for line in f: # rxn_items = line.split('\t') # rxn_dict[rxn_items[0]] = rxn_items[6], rxn_items[1] # # Adds the reactions from the above dictionary to the Universal model # for rxnName in rxn_dict.keys(): # rxn = Reaction(rxnName) # Universal.add_reaction(rxn) # rxn.reaction = rxn_dict[rxnName][0] # rxn.name = rxn_dict[rxnName][1] rxn_list = pickle.load(open('Text Files' + '/rxn_dict.p', 'rb')) fva_result_dict = {} fva_result_dict_testing = {}
def _parse_model_sbml(self,model_id_I,date_I,filename_I): # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(filename_I, print_time=True) model_data = []; model_data_tmp = {}; # parse out model metadata model_data_tmp['model_id'] = model_id_I; model_data_tmp['model_name'] = None; model_data_tmp['date'] = date_I; model_data_tmp['model_description'] = cobra_model.description; with open(filename_I, 'r') as f: model_data_tmp['model_file'] = f.read(); model_data_tmp['file_type'] = 'sbml' model_data.append(model_data_tmp) reaction_data = []; # parse out reaction data for r in cobra_model.reactions: reaction_data_dict = {}; reaction_data_dict['model_id'] = model_id_I reaction_data_dict['rxn_id'] = r.id reaction_data_dict['rxn_name'] = r.name reaction_data_dict['equation'] = r.build_reaction_string() reaction_data_dict['subsystem'] = r.subsystem reaction_data_dict['gpr'] = r.gene_reaction_rule reaction_data_dict['genes'] = [] genes = r.genes; for g in genes: reaction_data_dict['genes'].append(g.id); reaction_data_dict['reactants_stoichiometry'] = []; reaction_data_dict['reactants_ids'] = []; reactants = r.reactants; for react in reactants: reaction_data_dict['reactants_stoichiometry'].append(r.get_coefficient(react.id)); reaction_data_dict['reactants_ids'].append(react.id); reaction_data_dict['products_stoichiometry'] = []; reaction_data_dict['products_ids'] = []; products = r.products; for prod in products: reaction_data_dict['products_stoichiometry'].append(r.get_coefficient(prod.id)); reaction_data_dict['products_ids'].append(prod.id); reaction_data_dict['lower_bound'] = r.lower_bound reaction_data_dict['upper_bound'] = r.upper_bound reaction_data_dict['objective_coefficient'] = r.objective_coefficient reaction_data_dict['flux_units'] = 'mmol*gDW-1*hr-1' reaction_data_dict['reversibility'] = r.reversibility #reaction_data_dict['reactants_stoichiometry_tracked'] = None; #reaction_data_dict['products_stoichiometry_tracked'] = None; #reaction_data_dict['reactants_ids_tracked'] = None; #reaction_data_dict['products_ids_tracked'] = None; #reaction_data_dict['reactants_mapping'] = None; #reaction_data_dict['products_mapping'] = None; #reaction_data_dict['rxn_equation'] = None; reaction_data_dict['fixed'] = None; reaction_data_dict['free'] = None; reaction_data_dict['weight'] = None; reaction_data_dict['used_'] = True reaction_data_dict['comment_'] = None; reaction_data.append(reaction_data_dict); metabolite_data = []; # parse out metabolite data for met in cobra_model.metabolites: metabolite_data_tmp = {}; metabolite_data_tmp['model_id'] = model_id_I metabolite_data_tmp['met_name'] = met.name; metabolite_data_tmp['met_id'] = met.id; formula = {}; for k,v in met.formula.elements.items(): formula[k] = {0:v}; tmp = Formula() tmp._elements=formula metabolite_data_tmp['formula'] = tmp.formula; metabolite_data_tmp['charge'] = met.charge metabolite_data_tmp['compartment'] = met.compartment metabolite_data_tmp['bound'] = met._bound metabolite_data_tmp['constraint_sense'] = met._constraint_sense #metabolite_data_tmp['met_elements'] = None; #metabolite_data_tmp['met_atompositions'] = None; #metabolite_data_tmp['balanced'] = None; #metabolite_data_tmp['met_symmetry'] = None; #metabolite_data_tmp['met_symmetry_atompositions'] = None; metabolite_data_tmp['used_'] = True metabolite_data_tmp['comment_'] = None; metabolite_data.append(metabolite_data_tmp); return model_data,reaction_data,metabolite_data
def printsplits(splits): keys = splits.keys() keys.sort(key=int) for key in keys: print key,'%.2f' %splits[key] if __name__ == "__main__": import loadData as load from cobra.io.sbml import create_cobra_model_from_sbml_file import extractflux as extract expfluxes = load.ExpFluxesfromXML('expdata.xml','Perrenoud','Batch','aerobe') splitmap = load.SplitMapfromXML('reactionmaps.xml','SCHUETZR','EXPDATA') splits = computesplits(expfluxes,splitmap) print 'Experimental splits:' printsplits(splits) splitmap = load.SplitMapfromXML('reactionmaps.xml','SCHUETZR','SCHUETZR') cobramodel = create_cobra_model_from_sbml_file('../SBML/SCHUETZR.xml') cobramodel.optimize(solver='gurobi') compfluxes = extract.vectorToDict(cobramodel.solution.x,cobramodel) compsplits = computesplits(compfluxes,splitmap) print 'SCHUETZR FBA result splits:' printsplits(compsplits)
# reversibility index N_P = sum([v for v in r.metabolites.itervalues() if v > 0]) N_S = sum([-v for v in r.metabolites.itervalues() if v < 0]) N = N_P + N_S fixed_conc = 0.1 r.logRI = (2 / N) * (r.logKeq + (N_P - N_S) * np.log(fixed_conc)) for r in set(reactions) - set(self.reactions): r.dG0_prime = np.NaN r.dGm_prime = np.NaN r.logKeq = np.NaN r.logRI = np.NaN return dG0_prime if __name__ == "__main__": from model_addons import add_to_model model_fname = "../shared_data/iJO1366.xml" model = create_cobra_model_from_sbml_file(model_fname) add_to_model(model) reactions = [ 'MDH', 'FBA', 'TPI', 'FBP', 'PGM', 'SERAT', 'TMDS', 'DBTS', 'DM_4CRSOL' ] reactions = ['PPS'] reactions = map(model.reactions.get_by_id, reactions) # reactions = model.reactions Th = reaction_thermodynamics(reactions)
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 ])
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