-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfba.py
380 lines (262 loc) · 14.4 KB
/
fba.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/python
#try to specify that we will use python version 3.9
__author__ = "Wheaton Schroeder"
#latest version: 12/08/2021
#written to implement Flux Balance Analysis (FBA)
#These are the imports I have used in past for cobrapy, so will use them here as well, not sure the the necessity of any of these
#from __future__ import absolute_import
from optlang.interface import OPTIMAL, FEASIBLE, INFEASIBLE, ITERATION_LIMIT, NUMERIC, SUBOPTIMAL, TIME_LIMIT
from optlang.symbolics import Zero, add
import os
import sys
import warnings
import re
import cobra
from datetime import datetime
import copy
from cobra import Model, Reaction, Metabolite, Solution
#now that we have defined the import library, let us create a class for the mintransfers algorithm
class FBA(object):
#initialization of class:
#self - needs to be passed itself
#model - model which FVA will be applied to
def __init__(self,model,bigM=1000):
#add the models to the self object
self.model = model.copy()
self.bigM = bigM
#update model pointers to make sure copied model works
self.model.solver.update()
self.model.repair()
#pass a string to set the solver to that string
def set_solver(self,solver):
#set the solver to the passed string
try:
self.model.solver = solver
#if an exception occurs, store as "e"
except Exception as e:
print("solver assignement unsuccessful, exception: "+str(e))
#this will perform FBA
#note that directions, reversibility, objective, and bounds should be defined in the SBML
#we will allow playing aroudn with various settings later
# objective - the reaction id of the reaction that is to be the objective
# obj_dir - direction for optimization, must be "min" or "max"
# fixed_rates - dictionary of fluxes which should be fixed during FBA and keys of the values
# tolerance - numerical tolerance for FBA
#note that this only works for setting a single reaction as the objective
def run(self,objective,obj_dir="max",fixed_rates=dict()):
#repair the self model before copying
self.model.solver.update()
self.model.repair()
#make a copy of the model for fba
FBA_model = self.model.copy()
#try to make sure the model is good to go for solving
FBA_model.solver.update()
FBA_model.repair()
#give the problem a name
FBA_model.problem.name = "flux balance analysis (FBA)"
#try to make sure the model is good to go for solving
FBA_model.solver.update()
FBA_model.repair()
#initialize an empty dictionary for returning with results
fba_results = { }
#change the objective if needed
obj_eqn = FBA_model.problem.Objective(Zero, direction=obj_dir)
#save a reaction index
rxn_index = 0
#go through each reaction, see which matches the identifier
for rxn in FBA_model.reactions:
#check if the reaction matches the objective id passed
if bool(re.fullmatch(str(rxn.id),objective)):
#set the linear coefficient
obj_eqn = FBA_model.problem.Objective(rxn.flux_expression,direction=obj_dir)
#if the reaction is in the fixed rates dictionary, fix its rate
if rxn.id in fixed_rates.keys():
#set dummy bounds
FBA_model.reactions[FBA_model.reactions.index(rxn.id)].upper_bound = 10000
FBA_model.reactions[FBA_model.reactions.index(rxn.id)].lower_bound = -10000
#enforce bounds we want to enforce
FBA_model.reactions[FBA_model.reactions.index(rxn.id)].lower_bound = fixed_rates[rxn.id]
FBA_model.reactions[FBA_model.reactions.index(rxn.id)].upper_bound = fixed_rates[rxn.id]
#fix the model
FBA_model.solver.update()
FBA_model.repair()
FBA_model.objective = obj_eqn
#solve, but put in a try/except framework in case there is an error
try:
start_time_fba = datetime.now()
#last fix of the model
FBA_model.solver.update()
FBA_model.repair()
#try to solve, here is where the error may get thrown
fba_soln = FBA_model.optimize()
end_time_fba = datetime.now()
#get the total solve time
total_time_fba = end_time_fba - start_time_fba
#write and store the lower bound, flux, and upper bound for each reaction
for rxn in FBA_model.reactions:
#write the results to the output dictionary
#I believe this would be most useful set up as a nested dictionary
#initialize element to nest
fba_results[rxn.id] = { }
#add nestings
fba_results[rxn.id]['lb'] = rxn.lower_bound
fba_results[rxn.id]['flux'] = fba_soln.fluxes[rxn.id]
fba_results[rxn.id]['ub'] = rxn.upper_bound
#state that no exception occured
fba_results['exception']=False
fba_results['status'] = fba_soln.status
#return the solution time in the dictionary
fba_results['total_time'] = str(total_time_fba)
#return the objective
fba_results['objective'] = fba_soln.objective_value
#if an exception occurs, store as "e"
except Exception as e:
#get the timein information
end_time_fba = datetime.now()
#print the total solve time
total_time_fba = end_time_fba - start_time_fba
#state that an exception occured
fba_results['exception']=True
fba_results['status'] = "exception occurred"
#save the exception string to return
fba_results['exception_str']=str(e)
#return the solution time in the dictionary
fba_results['total_time'] = str(total_time_fba)
#return objective value of NaN since the problem was not solved
fba_results['objective'] = "NaN"
#return our dictionary
return fba_results
#this will perform parsimonious FBA
#note that directions, reversibility, objective, and bounds should be defined in the SBML
#we will allow playing aroudn with various settings later
# objective - the reaction id of the reaction that is to be the objective
# obj_dir - direction for optimization, must be "min" or "max"
# fixed_rates - dictionary of fluxes which should be fixed during FBA and keys of the flux values
# tolerance - numerical tolerance for FBA
#note that this only works for setting a single reaction as the objective
def run_pFBA(self,objective,obj_dir="max",fixed_rates=dict()):
#repair the self model before copying
self.model.solver.update()
self.model.repair()
pFBA_model = self.model.copy()
#try to make sure the model is good to go for solving
pFBA_model.solver.update()
pFBA_model.repair()
#give the problem a name
pFBA_model.problem.name = "parsimonious flux balance analysis (FBA)"
#change the objective if needed
pFBA_model.objective = pFBA_model.problem.Objective(Zero, direction=obj_dir)
#save a reaction index
rxn_index = 0
#try to make sure the model is good to go for solving
pFBA_model.solver.update()
pFBA_model.repair()
#go through each reaction, see which matches the identifier
for rxn in pFBA_model.reactions:
#check if the reaction matches the objective id passed
if bool(re.fullmatch(str(rxn.id),objective)):
#set the linear coefficient
pFBA_model.objective.set_linear_coefficients({rxn.forward_variable: 1})
pFBA_model.objective.set_linear_coefficients({rxn.reverse_variable: -1})
#if the reaction is in the fixed rates dictionary, fix its rate
if rxn.id in fixed_rates.keys():
#set dummy bounds
pFBA_model.reactions[pFBA_model.reactions.index(rxn.id)].upper_bound = 10 * self.bigM
pFBA_model.reactions[pFBA_model.reactions.index(rxn.id)].lower_bound = -10 * self.bigM
#enforce the bounds we want
pFBA_model.reactions[pFBA_model.reactions.index(rxn.id)].lower_bound = fixed_rates[rxn.id]
pFBA_model.reactions[pFBA_model.reactions.index(rxn.id)].upper_bound = fixed_rates[rxn.id]
#fix the model
pFBA_model.solver.update()
pFBA_model.repair()
#try to make sure the model is good to go for solving
pFBA_model.solver.update()
pFBA_model.repair()
#initialize an empty dictionary for returning with results
pfba_results = { }
#solve, but put in a try/except framework in case there is an error
try:
start_time_pfba = datetime.now()
#try to make sure the model is good to go for solving
pFBA_model.solver.update()
pFBA_model.repair()
#try to solve, here is where the error may get thrown
#do a manual pFBA so that we can capture both shadow prices
#this is the built-in pFBA command
#fba_soln = cobra.flux_analysis.pfba(pFBA_model)
print("solving first problem")
#this does the "maximize objective" step
fba_soln = pFBA_model.optimize()
print("first problem solved")
#return shadow prices
for met in pFBA_model.metabolites:
#initialize element to nest
pfba_results[met.id] = { }
pfba_results[met.id]['shadow_bio'] = pFBA_model.solver.shadow_prices[met.id]
#next we fix the objective value, most of the time this will be fixing the biomas rate
pFBA_model.reactions[pFBA_model.reactions.index(objective)].lower_bound = fba_soln.objective_value
pFBA_model.reactions[pFBA_model.reactions.index(objective)].upper_bound = fba_soln.objective_value
#go through each reaction, see which matches the identifier
#create a new objective equation minimizing the sum of flux rates
pFBA_model.objective = pFBA_model.problem.Objective(Zero, direction='min')
#go through each reaction, see which matches the identifier
for rxn in pFBA_model.reactions:
#make a variable to store the absolute value of each reaction rate
v_plus_rxn = pFBA_model.problem.Variable(name='v_+_{}'.format(rxn.id),lb=0,ub=2*self.bigM)
#create two constraints to get back the absolute value
v_plus_const_1 = pFBA_model.problem.Constraint(v_plus_rxn - rxn.flux_expression,lb=0,ub=2*self.bigM,name='v_+_1_{}'.format(rxn.id),sloppy=True)
v_plus_const_2 = pFBA_model.problem.Constraint(v_plus_rxn + rxn.flux_expression,lb=0,ub=2*self.bigM,name='v_+_2_{}'.format(rxn.id),sloppy=True)
#add these constraints to the model
pFBA_model.add_cons_vars([v_plus_const_1, v_plus_const_2], sloppy=False)
#set the objective so that we are minimizing the sum of absolute values
pFBA_model.objective.set_linear_coefficients({v_plus_rxn: 1})
#try to make sure the model is good to go for solving
pFBA_model.solver.update()
pFBA_model.repair()
#minimize sum of fluxes for the objective being fixed
print("solving second problem")
pfba_soln = pFBA_model.optimize()
print("second problem solved")
end_time_pfba = datetime.now()
#get the total solve time
total_time_fba = end_time_pfba - start_time_pfba
#write and store the lower bound, flux, and upper bound for each reaction
for rxn in pFBA_model.reactions:
#write the results to the output dictionary
#I believe this would be most useful set up as a nested dictionary
#initialize element to nest
pfba_results[rxn.id] = { }
#add nestings
pfba_results[rxn.id]['lb'] = rxn.lower_bound
pfba_results[rxn.id]['flux'] = pfba_soln.fluxes[rxn.id]
pfba_results[rxn.id]['ub'] = rxn.upper_bound
#state that no exception occured
pfba_results['exception']=False
pfba_results['status1'] = fba_soln.status
pfba_results['status2'] = pfba_soln.status
#return the solution time in the dictionary
pfba_results['total_time'] = str(total_time_fba)
#return the objective
pfba_results['objective'] = pfba_soln.objective_value
#return shadow prices
for met in self.model.metabolites:
#now assign the shadow price based on the flux rates
pfba_results[met.id]['shadow_flux'] = pFBA_model.solver.shadow_prices[met.id]
#if an exception occurs, store as "e"
except Exception as e:
print("error: "+str(e))
#get the timein information
end_time_pfba = datetime.now()
#print the total solve time
total_time_fba = end_time_pfba - start_time_pfba
#state that an exception occured
pfba_results['exception']=True
pfba_results['status'] = "exception occurred"
#save the exception string to return
pfba_results['exception_str']=str(e)
#return the solution time in the dictionary
pfba_results['total_time'] = str(total_time_fba)
#return objective value of NaN since the problem was not solved
pfba_results['objective'] = "NaN"
#return our dictionary
return pfba_results