我正试图用cobra进行优化,为两种生物体创建一种合作社培养基。为此,我设置了约束条件和目标,就像文档中所解释的那样。遗憾的是,我的代码产生了ContainerAlreadyContains错误,我不知道它是从哪里来的;在网上搜索也无济于事。我知道我新定义的约束会被添加到模型中已经存在的约束中,或者如果影响到同一个组件,它们可能会覆盖旧的约束,或者这是不正确的吗?
我使用了另外两个模型,但在下面发布的代码中,cobra测试模型也出现了同样的错误。使用python 3.7.0和cobra 0.19.0。希望有人能帮助我;无论如何,谢谢!
import cobra
import copy
import cobra.test
def optimize_model(inmodel, medium, biomass, verbose=False):
model = copy.deepcopy(inmodel)
metabolites = list(medium.keys())
reactions = [r.id for r in model.reactions]
#variables
thetas = {}
for m in metabolites:
var = model.problem.Variable(name="theta_{}".format(m), lb=0, type="binary")
thetas["theta_{}".format(m)] = var
#constraints
constraints = []
for m in metabolites:
try:
const = model.problem.Constraint(model.reactions.get_by_id(m).flux_expression +
model.reactions.get_by_id(m).lower_bound*thetas["theta_"+m],
lb=model.reactions.get_by_id(m).lower_bound,
name="V_COOPM_{}".format(m))
constraints.add_cons_vars(const)
except:
pass
VBM_COMPM = model.optimize().objective_value / 10
cost = model.problem.Constraint(biomass.flux_expression, lb=VBM_COMPM)
constraints.append(cost)
#objective
obj = model.problem.Objective(sum(thetas[t] for t in thetas.keys()),
direction="max")
model.add_cons_vars(constraints)
model.objective = obj
model.solver.update()
status = model.optimize()
medium = {
'EX_ala__L_e': 'Alanine', 'EX_arg__L_e': 'Arginine',
'EX_cys__L_e': 'Cysteine', 'EX_glu__L_e': 'Glutamic acid',
'EX_gly_e': 'Glycine', 'EX_his__L_e': 'Histidine',
'EX_leu__L_e': 'Leucine', 'EX_lys__L_e': 'Lysine', 'EX_orn_e': 'Ornithine',
'EX_phe__L_e': 'Phenylalanine', 'EX_pro__L_e': 'Proline',
'EX_ser__L_e': 'Serine', 'EX_thr__L_e': 'Threonine',
'EX_trp__L_e': 'Tryptophane', 'EX_val__L_e': 'Valine',
'EX_cit_e': 'citric acid', 'EX_fum_e': 'Fumaric acid',
'EX_male_e': 'maleic acid', 'EX_pyr_e': 'pyruvic acid',
'EX_succ_e': 'succinic acid', 'EX_glc__D_e': 'glucose',
'EX_urea_e': 'Urea', 'EX_na1_e': 'Sodium', 'EX_cl_e': 'Chloride',
'EX_k_e': 'Potassium', 'EX_pi_e': 'Phosphate', 'EX_mg2_e': 'Magnesium',
'EX_so4_e': 'Sulphate', 'EX_ca2_e': 'Calcium', 'EX_zn2_e': 'ZnCl2',
'EX_mn2_e': 'MnCl2', 'EX_cobalt2_e': 'CoCl2', 'EX_cu2_e': 'CuCl2',
'EX_ni2_e': 'NiCl2', 'EX_mobd_e': 'MoNa2O4', 'EX_adocbl_e': 'Cyanocobalamine',
'EX_4abz_e': 'p-Aminobenzoic acid', 'EX_btn_e': 'Biotin', 'EX_nac_e': 'Nicotinic acid',
'EX_pnto__R_e': 'Ca-D-Pantothenic acid', 'EX_pydam_e': 'Pyridoxamine-2HCl',
'EX_thm_e': 'Thiamine-dichloride', 'EX_ribflv_e': 'Riboflavin', 'EX_o2_e': 'Oxygen',
'EX_fe2_e': 'Fe3+', 'EX_h2o_e': 'Water', 'EX_co2_e': 'Co2'
}
model = cobra.test.create_test_model("textbook")
for r in model.reactions:
if r.id == "Biomass_Ecoli_core":
biomass = r
break
optimize_model(model, medium, biomass, True)
请参阅此处了解有效的更改:
https://github.com/opencobra/cobrapy/issues/1026