本文整理汇总了Python中cobra.Model.add_reaction方法的典型用法代码示例。如果您正苦于以下问题:Python Model.add_reaction方法的具体用法?Python Model.add_reaction怎么用?Python Model.add_reaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cobra.Model
的用法示例。
在下文中一共展示了Model.add_reaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gapfillfunc
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
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
示例2: test_quadratic
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def test_quadratic(self):
solver = self.solver
if not hasattr(solver, "set_quadratic_objective"):
self.skipTest("no qp support")
c = Metabolite("c")
c._bound = 2
x = Reaction("x")
x.objective_coefficient = -0.5
x.lower_bound = 0.
y = Reaction("y")
y.objective_coefficient = -0.5
y.lower_bound = 0.
x.add_metabolites({c: 1})
y.add_metabolites({c: 1})
m = Model()
m.add_reactions([x, y])
lp = self.solver.create_problem(m)
quadratic_obj = scipy.sparse.eye(2) * 2
solver.set_quadratic_objective(lp, quadratic_obj)
solver.solve_problem(lp, objective_sense="minimize")
solution = solver.format_solution(lp, m)
self.assertEqual(solution.status, "optimal")
# Respecting linear objectives also makes the objective value 1.
self.assertAlmostEqual(solution.f, 1.)
self.assertAlmostEqual(solution.x_dict["y"], 1.)
self.assertAlmostEqual(solution.x_dict["y"], 1.)
# When the linear objectives are removed the objective value is 2.
solver.change_variable_objective(lp, 0, 0.)
solver.change_variable_objective(lp, 1, 0.)
solver.solve_problem(lp, objective_sense="minimize")
solution = solver.format_solution(lp, m)
self.assertEqual(solution.status, "optimal")
self.assertAlmostEqual(solution.f, 2.)
# test quadratic from solve function
solution = solver.solve(m, quadratic_component=quadratic_obj,
objective_sense="minimize")
self.assertEqual(solution.status, "optimal")
self.assertAlmostEqual(solution.f, 1.)
c._bound = 6
z = Reaction("z")
x.objective_coefficient = 0.
y.objective_coefficient = 0.
z.lower_bound = 0.
z.add_metabolites({c: 1})
m.add_reaction(z)
solution = solver.solve(m, quadratic_component=scipy.sparse.eye(3),
objective_sense="minimize")
# should be 12 not 24 because 1/2 (V^T Q V)
self.assertEqual(solution.status, "optimal")
self.assertAlmostEqual(solution.f, 6)
self.assertAlmostEqual(solution.x_dict["x"], 2, places=6)
self.assertAlmostEqual(solution.x_dict["y"], 2, places=6)
self.assertAlmostEqual(solution.x_dict["z"], 2, places=6)
示例3: test_remove_breaks
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def test_remove_breaks(self):
model = Model("test model")
A = Metabolite("A")
r = Reaction("r")
r.add_metabolites({A: -1})
r.lower_bound = -1000
r.upper_bound = 1000
model.add_reaction(r)
convert_to_irreversible(model)
model.remove_reactions(["r"])
with pytest.raises(KeyError):
revert_to_reversible(model)
示例4: test_gene_knockout_computation
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def test_gene_knockout_computation(self):
cobra_model = self.model
delete_model_genes = delete.delete_model_genes
get_removed = lambda m: {x.id for x in m._trimmed_reactions}
gene_list = ['STM1067', 'STM0227']
dependent_reactions = {'3HAD121', '3HAD160', '3HAD80', '3HAD140',
'3HAD180', '3HAD100', '3HAD181','3HAD120',
'3HAD60', '3HAD141', '3HAD161', 'T2DECAI',
'3HAD40'}
delete_model_genes(cobra_model, gene_list)
self.assertEqual(get_removed(cobra_model), dependent_reactions)
# cumulative
delete_model_genes(cobra_model, ["STM4221"],
cumulative_deletions=True)
dependent_reactions.add('PGI')
self.assertEqual(get_removed(cobra_model), dependent_reactions)
# non-cumulative
delete_model_genes(cobra_model, ["STM4221"],
cumulative_deletions=False)
self.assertEqual(get_removed(cobra_model), {'PGI'})
# make sure on reset that the bounds are correct
reset_bound = cobra_model.reactions.get_by_id("T2DECAI").upper_bound
self.assertEqual(reset_bound, 1000.)
# test computation when gene name is a subset of another
test_model = Model()
test_reaction_1 = Reaction("test1")
test_reaction_1.gene_reaction_rule = "eggs or (spam and eggspam)"
test_model.add_reaction(test_reaction_1)
delete.delete_model_genes(test_model, ["eggs"])
self.assertEqual(get_removed(test_model), set())
delete_model_genes(test_model, ["spam"], cumulative_deletions=True)
self.assertEqual(get_removed(test_model), {'test1'})
# test computation with nested boolean expression
delete.undelete_model_genes(test_model)
test_reaction_1.gene_reaction_rule = \
"g1 and g2 and (g3 or g4 or (g5 and g6))"
delete_model_genes(test_model, ["g3"], cumulative_deletions=False)
self.assertEqual(get_removed(test_model), set())
delete_model_genes(test_model, ["g1"], cumulative_deletions=False)
self.assertEqual(get_removed(test_model), {'test1'})
delete_model_genes(test_model, ["g5"], cumulative_deletions=False)
self.assertEqual(get_removed(test_model), set())
delete_model_genes(test_model, ["g3", "g4", "g5"],
cumulative_deletions=False)
self.assertEqual(get_removed(test_model), {'test1'})
示例5: test_gapfilling
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def test_gapfilling(self):
try:
solver = get_solver_name(mip=True)
except:
self.skipTest("no MILP solver found")
m = Model()
m.add_metabolites(map(Metabolite, ["a", "b", "c"]))
r = Reaction("EX_A")
m.add_reaction(r)
r.add_metabolites({m.metabolites.a: 1})
r = Reaction("r1")
m.add_reaction(r)
r.add_metabolites({m.metabolites.b: -1, m.metabolites.c: 1})
r = Reaction("DM_C")
m.add_reaction(r)
r.add_metabolites({m.metabolites.c: -1})
r.objective_coefficient = 1
U = Model()
r = Reaction("a2b")
U.add_reaction(r)
r.build_reaction_from_string("a --> b", verbose=False)
r = Reaction("a2d")
U.add_reaction(r)
r.build_reaction_from_string("a --> d", verbose=False)
# GrowMatch
result = gapfilling.growMatch(m, U)[0]
self.assertEqual(len(result), 1)
self.assertEqual(result[0].id, "a2b")
# SMILEY
result = gapfilling.SMILEY(m, "b", U)[0]
self.assertEqual(len(result), 1)
self.assertEqual(result[0].id, "a2b")
# 2 rounds of GrowMatch with exchange reactions
result = gapfilling.growMatch(m, None, ex_rxns=True, iterations=2)
self.assertEqual(len(result), 2)
self.assertEqual(len(result[0]), 1)
self.assertEqual(len(result[1]), 1)
self.assertEqual({i[0].id for i in result},
{"SMILEY_EX_b", "SMILEY_EX_c"})
示例6: print
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
omrsACP_c: 1.0})
print (reaction.reaction)
reaction.gene_reaction_rule = ('STM2378 or STM1197')
# print(reaction.genes)
# print ('%i reaction' %len(cobra_model.reactions))
# print ('%i metabolites' %len(cobra_model.metabolites))
# print ('%i genes' %len(cobra_model.genes))
# print (reaction.name)
# print (reaction.subsystem)
cobra_model.add_reaction(reaction)
print('%i reaction' %len(cobra_model.reactions))
print('%i metabolites' %len(cobra_model.metabolites))
print ('%i genes' %len(cobra_model.genes))
print
print("Reactions" '\n' "--------")
for x in cobra_model.reactions:
print ("%s : %s" %(x.id,x.reaction))
print ("")
print("Metabolites" '\n' "-----------")
for x in cobra_model.metabolites:
print ("%s : %s" %(x.id, x.formula))
示例7: Metabolite
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
#
# This problem can be written as a COBRA model as well.
total_cost = Metabolite("constraint")
total_cost._bound = 15.05
costs = {"mixed_fruit": 2.15, "french_fries": 2.75, "side_salad": 3.35,
"hot_wings": 3.55, "mozarella_sticks": 4.20, "sampler_plate": 5.80}
m = Model("appetizers")
for item, cost in costs.items():
r = Reaction(item)
r.add_metabolites({total_cost: cost})
r.variable_kind = "integer"
m.add_reaction(r)
# To add to the problem, suppose we don't want to eat all mixed fruit.
m.reactions.mixed_fruit.objective_coefficient = 1
m.optimize(objective_sense="minimize").x_dict
# Output:
# {'french_fries': 0.0,
# 'hot_wings': 2.0,
# 'mixed_fruit': 1.0,
# 'mozarella_sticks': 0.0,
# 'sampler_plate': 1.0,
# 'side_salad': 0.0}
# There is another solution to this problem, which would have been obtained if
# we had maximized for mixed fruit instead of minimizing.
示例8: sort_and_deduplicate
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
for item in lst:
if item == last:
continue
yield item
last = item
def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))
rxn_dict = {}
for line in f:
rxn_items = line.split('\t')
rxn_dict[rxn_items[0]] = rxn_items[2]
for rxnName in rxn_dict.keys():
rxn = Reaction(rxnName)
Universal.add_reaction(rxn)
rxn.reaction = rxn_dict[rxnName]
growthValue = []
its = 4
result = flux_analysis.growMatch(mattModel, Universal, iterations=4)
resultShortened = sort_and_deduplicate(uniq(result))
print resultShortened
for x in range(len(resultShortened)):
mattModelTest = deepcopy(mattModel)
for i in range(len(resultShortened[x])):
addID = resultShortened[x][i].id
rxn = Reaction(addID)
rxn = Universal.reactions.get_by_id(addID)
mattModelTest.add_reaction(rxn)
示例9: test_gene_knockout_computation
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def test_gene_knockout_computation(self):
cobra_model = create_test_model()
# helper functions for running tests
delete_model_genes = delete.delete_model_genes
find_gene_knockout_reactions = delete.find_gene_knockout_reactions
def find_gene_knockout_reactions_fast(cobra_model, gene_list):
compiled_rules = delete.get_compiled_gene_reaction_rules(
cobra_model)
return find_gene_knockout_reactions(
cobra_model, gene_list,
compiled_gene_reaction_rules=compiled_rules)
def get_removed(m):
return {x.id for x in m._trimmed_reactions}
def test_computation(m, gene_ids, expected_reaction_ids):
genes = [m.genes.get_by_id(i) for i in gene_ids]
expected_reactions = {m.reactions.get_by_id(i)
for i in expected_reaction_ids}
removed1 = set(find_gene_knockout_reactions(m, genes))
removed2 = set(find_gene_knockout_reactions_fast(m, genes))
self.assertEqual(removed1, expected_reactions)
self.assertEqual(removed2, expected_reactions)
delete.delete_model_genes(m, gene_ids, cumulative_deletions=False)
self.assertEqual(get_removed(m), expected_reaction_ids)
delete.undelete_model_genes(m)
gene_list = ['STM1067', 'STM0227']
dependent_reactions = {'3HAD121', '3HAD160', '3HAD80', '3HAD140',
'3HAD180', '3HAD100', '3HAD181', '3HAD120',
'3HAD60', '3HAD141', '3HAD161', 'T2DECAI',
'3HAD40'}
test_computation(cobra_model, gene_list, dependent_reactions)
test_computation(cobra_model, ['STM4221'], {'PGI'})
test_computation(cobra_model, ['STM1746.S'], {'4PEPTabcpp'})
# test cumulative behavior
delete_model_genes(cobra_model, gene_list[:1])
delete_model_genes(cobra_model, gene_list[1:],
cumulative_deletions=True)
delete_model_genes(cobra_model, ["STM4221"],
cumulative_deletions=True)
dependent_reactions.add('PGI')
self.assertEqual(get_removed(cobra_model), dependent_reactions)
# non-cumulative following cumulative
delete_model_genes(cobra_model, ["STM4221"],
cumulative_deletions=False)
self.assertEqual(get_removed(cobra_model), {'PGI'})
# make sure on reset that the bounds are correct
reset_bound = cobra_model.reactions.get_by_id("T2DECAI").upper_bound
self.assertEqual(reset_bound, 1000.)
# test computation when gene name is a subset of another
test_model = Model()
test_reaction_1 = Reaction("test1")
test_reaction_1.gene_reaction_rule = "eggs or (spam and eggspam)"
test_model.add_reaction(test_reaction_1)
test_computation(test_model, ["eggs"], set())
test_computation(test_model, ["eggs", "spam"], {'test1'})
# test computation with nested boolean expression
test_reaction_1.gene_reaction_rule = \
"g1 and g2 and (g3 or g4 or (g5 and g6))"
test_computation(test_model, ["g3"], set())
test_computation(test_model, ["g1"], {'test1'})
test_computation(test_model, ["g5"], set())
test_computation(test_model, ["g3", "g4", "g5"], {'test1'})
# test computation when gene names are python expressions
test_reaction_1.gene_reaction_rule = "g1 and (for or in)"
test_computation(test_model, ["for", "in"], {'test1'})
test_computation(test_model, ["for"], set())
test_reaction_1.gene_reaction_rule = "g1 and g2 and g2.conjugate"
test_computation(test_model, ["g2"], {"test1"})
test_computation(test_model, ["g2.conjugate"], {"test1"})
test_reaction_1.gene_reaction_rule = "g1 and (try:' or 'except:1)"
test_computation(test_model, ["try:'"], set())
test_computation(test_model, ["try:'", "'except:1"], {"test1"})
示例10: print
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
break
if dup == False:
met = copy.deepcopy(x)
met.id = met.id[:-2]+'_a'
met.compartment = 'a'
new_model.add_metabolites({met})
#Adding all reactions excluding transport, exchange, flippase, sink
print("Adding all reactions excluding transport, exchange, flippase, sink...")
for react in eco.reactions:
if (react.name.find('transport') == -1 and react.subsystem.find('Transport') == -1 and react.name.find('exchange') == -1 and react.name.find('flippase') == -1 and react.name.find('Sink') == -1):
for x in react.reactants:
x.id = x.id[:-2]+'_a'
for x in react.products:
x.id = x.id[:-2]+'_a'
new_model.add_reaction(react)
print("Number of reactions in new_model",len(new_model.reactions))
#removing all reactions that are dupliates
print("Removing all duplicate reactions...")
for react in new_model.reactions:
for y in new_model.reactions:
if react.reaction == y.reaction and react.name != y.name:
y.delete()
print("Number of reactions after deleting duplicates: ",len(new_model.reactions))
# adding necessary metabolites and reactions for biosensor project
print("Adding necessary metabolites and reactions for biosensor project...")
Au_plus = Metabolite('Au_plus', formula='Au', name='Gold(1)',compartment='a')
示例11: read_excel
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
#.........这里部分代码省略.........
fail=False)
if met_formula_key is None:
met_formula_key = guess_name(met_frame.keys(), MET_FORMULA_KEYS,
fail=False)
for i in met_frame.index:
met_row = met_frame.ix[i]
met_attributes = {}
if met_formula_key is not None:
formula = extract(met_row, met_formula_key)
if formula is not None and formula.lower() != "None":
met_attributes["formula"] = formula
met = Metabolite(met_row[met_id_key],
name=extract(met_row, met_id_key),
**met_attributes)
try:
m.add_metabolites(met)
except ValueError:
if verbose:
print("duplicate metabolite '%s' not added" % met.id)
elif verbose:
print("metabolite sheet not found")
# Reactions
rxn_frame = pandas.read_excel(filename, rxn_sheet_name,
header=rxn_sheet_header)
# strip spaces from header
rxn_frame.columns = [i.strip() for i in rxn_frame.keys()]
if rxn_id_key is None:
rxn_id_key = guess_name(rxn_frame.keys(), RXN_ID_KEYS)
if rxn_str_key is None:
rxn_str_key = guess_name(rxn_frame.keys(), RXN_STR_KEYS)
if rxn_name_key is None:
rxn_name_key = guess_name(rxn_frame.keys(), RXN_NAME_KEYS, fail=False)
if verbose and rxn_name_key is None:
print("reaction name column not identified")
if rxn_gpr_key is None:
rxn_gpr_key = guess_name(rxn_frame.keys(), RXN_GPR_KEYS, fail=False)
if verbose and rxn_gpr_key is None:
print("gene reaction rule column not identified")
if rxn_lb_key is None:
rxn_lb_key = guess_name(rxn_frame.keys(), RXN_LB_KEYS, fail=False)
if verbose and rxn_lb_key is None:
print("reaction lower bound column not identified")
if rxn_ub_key is None:
rxn_ub_key = guess_name(rxn_frame.keys(), RXN_UB_KEYS, fail=False)
if verbose and rxn_ub_key is None:
print("reaction upper bound column not identified")
for i in range(len(rxn_frame)):
row = rxn_frame.ix[i]
rxn_id = row[rxn_id_key]
rxn_str = row[rxn_str_key]
if not isinstance(rxn_id, string_types) or \
not isinstance(rxn_str, string_types):
continue
rxn = Reaction()
rxn.id = escape_str(rxn_id)
rxn.name = extract(row, rxn_name_key)
if rxn.id in m.reactions:
if verbose:
print("duplicate reaction '%s' found" % rxn.id)
# add underscores to the end of duplicate reactions
while rxn.id in m.reactions:
rxn.id += "_"
m.add_reaction(rxn)
rxn.build_reaction_from_string(
rxn_str, verbose=verbose, fwd_arrow=rxn_fwd_arrow,
rev_arrow=rxn_rev_arrow, reversible_arrow=rxn_reversible_arrow)
gpr = extract(row, rxn_gpr_key)
if "," in gpr or "+" in gpr:
# break on ',' (which is or) then '+' (which is and)
ors = ["( %s )" % o.replace("+", " and ") if "+" in o else o
for o in gpr.split(",")]
gpr = " or ".join(ors)
rxn.gene_reaction_rule = gpr
if rxn_lb_key is not None:
rxn.lower_bound = float(row[rxn_lb_key])
if rxn_ub_key is not None:
rxn.upper_bound = float(row[rxn_ub_key])
# fix upper and lower bounds if they include infinity
inf = float("inf")
max_lower_bound = max(abs(i) for i in m.reactions.list_attr("lower_bound")
if abs(i) < inf)
max_upper_bound = max(abs(i) for i in m.reactions.list_attr("upper_bound")
if abs(i) < inf)
inf_replace = max(max_upper_bound, max_lower_bound, 1000.) * 100
def clip_inf(value):
if value == inf:
return inf_replace
elif value == -inf:
return -inf_replace
else:
return value
for reaction in m.reactions:
reaction.lower_bound = clip_inf(reaction.lower_bound)
reaction.upper_bound = clip_inf(reaction.upper_bound)
return m
示例12: create_cobra_model_from_file
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
def create_cobra_model_from_file(fn):
data_rows_dict=read_spreadsheets(file_names=fn,csv_delimiter=',',more_than_1=False)
model = Model('Constraint based model')
candidate_metabolites=[]
for data in data_rows_dict:
for row in data_rows_dict[data]:
#print row
if len(row)>1:
if row[1]==None:
continue
if "->" in row[1] or "=>" in row[1] or "<-" in row[1]: #Is a reaction:
rid=row[0]
new_reaction=Reaction(str(rid))
print row[1]
try:
model.add_reaction(new_reaction)
new_reaction.build_reaction_from_string(str(row[1]))
except:
print rid+": not added"
try:
new_reaction.name=str(row[2])
except:
print rid+": name not added"
try:
new_reaction.lower_bound=float(row[3])
except:
print rid+": lb not added"
try:
new_reaction.upper_bound=float(row[4])
except:
print rid+": ub not added"
try:
new_reaction.objective_coefficient=float(row[5])
except:
print rid+": Objective coefficient not added"
try:
new_reaction.gene_reaction_rule=str(row[6])
except:
print rid+" gene rules not added"
else: #Probably is a metabolite add them to the list of candidate metabolites
candidate_metabolites.append(row)
#Check if all candidate metabolites are efectivelly metabolites
for row in candidate_metabolites:
try:
str(row[0])
except:
continue
if str(row[0]) in model.metabolites:
metabolite=model.metabolites.get_by_id(str(row[0]))
try:
metabolite.name=str(row[1])
except:
print row[0]+": name not added"
try:
metabolite.compartment=str(row[3])
except:
print row[0]+": compartment not added"
try:
metabolite.formula=str(row[2])
except:
print row[0]+": formula not added"
return model
示例13: open
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
smatrix_write_file = open('Text Files'+'/nathans_file_s_matrix.txt', 'w')
met_list_file = open('Text Files'+'/nathans_file_met_list', 'w')
met_list_check = []
met_list_in = []
met_list_not_in = []
next(f)
rxn_dict = {}
model_test = Model('Test Model')
for line in temp:
met_list_check.append(line)
for line in f:
rxn_items = line.split('\t')
rxn_dict[rxn_items[0]] = rxn_items[6], rxn_items[1]
for rxnName in rxn_dict.keys():
rxn = Reaction(rxnName)
model_test.add_reaction(rxn)
rxn.reaction = rxn_dict[rxnName][0]
rxn.name = rxn_dict[rxnName][1]
for rxn in model_test.reactions:
list = rxn.get_coefficients(rxn.metabolites)
# list = rxn_test.get_coefficients(rxn_test.metabolites)
for item in rxn.metabolites.keys():
string = (str(item) + '.' + str(rxn.id) + ' ' + str(rxn.metabolites[item]))
print string
smatrix_write_file.write(string)
smatrix_write_file.write('\n')
for met in model_test.metabolites:
met_list_in.append(met.id)
示例14: read_excel
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
#.........这里部分代码省略.........
if verbose and rxn_name_key is None:
print("reaction name column not identified")
if rxn_gpr_key is None:
rxn_gpr_key = guess_name(rxn_frame.keys(), RXN_GPR_KEYS, fail=False)
if verbose and rxn_gpr_key is None:
print("gene reaction rule column not identified")
if rxn_lb_key is None:
rxn_lb_key = guess_name(rxn_frame.keys(), RXN_LB_KEYS, fail=False)
if verbose and rxn_lb_key is None:
print("reaction lower bound column not identified")
if rxn_ub_key is None:
rxn_ub_key = guess_name(rxn_frame.keys(), RXN_UB_KEYS, fail=False)
if verbose and rxn_ub_key is None:
print("reaction upper bound column not identified")
for i in range(len(rxn_frame)):
row = rxn_frame.ix[i]
if rxn_id_key == "auto":
rxn_id = "R%04d" % i
else:
rxn_id = extract(row, rxn_id_key)
rxn_str = extract(row, rxn_str_key)
# skip empty rows
if (
not isinstance(rxn_id, string_types)
or not isinstance(rxn_str, string_types)
or len(rxn_str) == 0
or len(rxn_id) == 0
):
continue
# skip duplicated header rows
if rxn_id == rxn_id_key and rxn_str == rxn_str_key:
continue
rxn = Reaction()
rxn.id = rxn_id
rxn.name = extract(row, rxn_name_key)
if rxn.id in m.reactions:
if verbose:
print("duplicate reaction '%s' found" % rxn.id)
# add underscores to the end of duplicate reactions
while rxn.id in m.reactions:
rxn.id += "_"
m.add_reaction(rxn)
# Now build the reaction from the string
# no need to print new metabolite created if no metaboltie sheet
verbose_build = verbose and met_frame is not None
build_kwargs = {
"verbose": verbose,
"fwd_arrow": rxn_fwd_arrow,
"rev_arrow": rxn_rev_arrow,
"reversible_arrow": rxn_reversible_arrow,
}
try:
rxn.build_reaction_from_string(rxn_str, **build_kwargs)
except Exception as e:
# replace metabolites which have spaces, and try again
fixed_rxn_str = rxn_str
for k, v in met_rename_list:
fixed_rxn_str = fixed_rxn_str.replace(k, v)
if verbose:
print("converted '%s' to '%s'" % (rxn_str, fixed_rxn_str))
try:
rxn.build_reaction_from_string(fixed_rxn_str, **build_kwargs)
except Exception as e:
print("Error parsing %s string '%s'" % (repr(rxn), rxn_str))
raise e
# parse gene reaction rule
gpr = extract(row, rxn_gpr_key)
if "," in gpr or "+" in gpr:
# break on ',' (which is or) then '+' (which is and)
ors = ["( %s )" % o.replace("+", " and ") if "+" in o else o for o in gpr.split(",")]
gpr = " or ".join(ors)
rxn.gene_reaction_rule = gpr
if rxn_lb_key is not None:
rxn.lower_bound = float(row[rxn_lb_key])
if rxn_ub_key is not None:
rxn.upper_bound = float(row[rxn_ub_key])
# fix upper and lower bounds if they include infinity
inf = float("inf")
max_lower_bound = max(abs(i) for i in m.reactions.list_attr("lower_bound") if abs(i) < inf)
max_upper_bound = max(abs(i) for i in m.reactions.list_attr("upper_bound") if abs(i) < inf)
inf_replace = max(max_upper_bound, max_lower_bound, 1000.0) * 100
def clip_inf(value):
if value == inf:
return inf_replace
elif value == -inf:
return -inf_replace
else:
return value
for reaction in m.reactions:
reaction.lower_bound = clip_inf(reaction.lower_bound)
reaction.upper_bound = clip_inf(reaction.upper_bound)
return m
示例15: str
# 需要导入模块: from cobra import Model [as 别名]
# 或者: from cobra.Model import add_reaction [as 别名]
# print >>r_ignored, str(r), reaction.reaction
generics = cyc.reaction_get_generic(org, r, generic_exceptions, substitutions)
if r.in_pathway != None: # remember missed pathways
plist = r.in_pathway if isinstance(r.in_pathway, list) else [r.in_pathway]
for path in plist:
# p_ignored_set |= set((map(str, plist)))
if p_ignored_set.has_key(str(path)):
p_ignored_set[str(path)] = p_ignored_set[str(path)] | generics
else:
p_ignored_set[str(path)] = generics
for g in generics: # remember missed reactions
m_generic_set[g] = (
m_generic_set.get(g, 0) + 1
) # count for each generic metabolite how often it causes a irgnored reaction
else:
model.add_reaction(reaction)
if diffusion_reactions:
model.add_reactions(diffusion_reactions_list) # adding automatically additional diffusion reactions
if bigg_names_metabolites:
model = cyc.change_metabolite_names(model, metabolites_dic)
#
# III. output
#
for i in model.metabolites:
print i
print "\n check reaction mass balance"
fixed_mass_balance = open("fixed_mass_balance.txt", "w")