Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions modelseedpy/fbapkg/objconstpkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@ def build_constraint(self, lower_bound, upper_bound):
coef = self.model.solver.objective.get_linear_coefficients(
self.model.solver.objective.variables
)
#Check if the constraint already exists and if so, just updating bounds in place
# Check if the constraint already exists and if so, just updating bounds in place
for name in self.constraints["objc"]:
constraint = self.constraints["objc"][name]
existing_coef = constraint.get_linear_coefficients(
constraint.variables
)
existing_coef = constraint.get_linear_coefficients(constraint.variables)
if coef == existing_coef:
constraint.lb = lower_bound
constraint.ub = upper_bound
Expand Down
64 changes: 38 additions & 26 deletions modelseedpy/fbapkg/objectivepkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@

logger = logging.getLogger(__name__)
logger.setLevel(
logging.WARNING#INFO
logging.WARNING # INFO
) # When debugging - set this to INFO then change needed messages below from DEBUG to INFO


class ObjectiveTerm:
def __init__(self, variable, coefficient,direction=""):
def __init__(self, variable, coefficient, direction=""):
self.coefficient = coefficient
self.variable = variable
self.direction = direction
Expand All @@ -22,28 +23,28 @@ def from_string(term_string):
coefficient = 1
variable = None
direction = ""
#Checking for coefficient
# Checking for coefficient
if term_string[0:1] == "(":
array = term_string.split(")")
coefficient = float(array[0][1:])
term_string = array[1]
#Checking for a +/- on term
# Checking for a +/- on term
if term_string[0:1] == "+" or term_string[0:1] == "-":
variable = term_string[1:]
direction = term_string[0:1]
else:
variable = term_string
direction = ""
return ObjectiveTerm(variable, coefficient, direction)

def to_string(self):
coefficient = self.coefficient
if float(coefficient).is_integer():
coefficient = int(coefficient)
return "("+str(coefficient)+")"+self.direction+self.variable
return "(" + str(coefficient) + ")" + self.direction + self.variable


#Class for defining an objective function in a modelseedpy model.
# Class for defining an objective function in a modelseedpy model.
class ObjectiveData:
def __init__(self, terms, sense="max"):
self.sense = sense
Expand All @@ -54,31 +55,35 @@ def from_string(objective_string):
sense = "max"
terms = []
if objective_string[0:3] == "MAX":
objective_string = objective_string[4:-1]#Clearing out the directionality MAX{}
objective_string = objective_string[
4:-1
] # Clearing out the directionality MAX{}
elif objective_string[0:3] == "MIN":
objective_string = objective_string[4:-1]#Clearing out the directionality MIN{}
objective_string = objective_string[
4:-1
] # Clearing out the directionality MIN{}
sense = "min"
term_strings = objective_string.split("|")
for term_string in term_strings:
term = ObjectiveTerm.from_string(term_string)
terms.append(term)
return ObjectiveData(terms, sense)

def to_string(self):
objective_string = ""
if self.sense == "max":
objective_string += "MAX{"
else:
objective_string += "MIN{"
for term in self.terms:
objective_string += term.to_string()+"|"
objective_string += term.to_string() + "|"
objective_string = objective_string[:-1] + "}"
return objective_string

def to_cobrapy_objective(self, model):
#Creating empty objective
# Creating empty objective
objective = model.problem.Objective(Zero, direction=self.sense)
#Parsing the terms
# Parsing the terms
coefficients = {}
for term in self.terms:
if term.variable in model.reactions:
Expand All @@ -90,13 +95,14 @@ def to_cobrapy_objective(self, model):
coefficients[rxnobj.reverse_variable] = coef
else:
coefficients[rxnobj.forward_variable] = coef
coefficients[rxnobj.reverse_variable] = -1*coef
coefficients[rxnobj.reverse_variable] = -1 * coef
else:
logger.warning("Reaction "+term.variable+" not found in model")
logger.warning("Reaction " + term.variable + " not found in model")
model.objective = objective
objective.set_linear_coefficients(coefficients)
return objective


# Base class for FBA packages
class ObjectivePkg(BaseFBAPkg):
def __init__(self, model):
Expand All @@ -106,29 +112,35 @@ def __init__(self, model):
self.objective_data = None
self.objective_data_cache = {}

def build_package(self,objective_or_string,objective_name=None,set_objective=True):
#Caching the current objective
def build_package(
self, objective_or_string, objective_name=None, set_objective=True
):
# Caching the current objective
self.original_model_objective = self.model.objective
#check if input is a string or an ObjectiveData object
# check if input is a string or an ObjectiveData object
if isinstance(objective_or_string, str):
self.objective_data = ObjectiveData.from_string(objective_or_string)
elif isinstance(objective_or_string, ObjectiveData):
self.objective_data = objective_or_string
else:
raise TypeError("Input must be a string or an ObjectiveData object")
#Setting default objective name if not provided
# Setting default objective name if not provided
self.objective_name = objective_name
if objective_name == None:
self.objective_name = self.objective_data.to_string()
#Caching objective with name
# Caching objective with name
self.objective_data_cache[self.objective_name] = self.objective_data
#Creating the objective in the model
# Creating the objective in the model
if set_objective:
self.objective_data_cache[self.objective_name].to_cobrapy_objective(self.model)
self.objective_data_cache[self.objective_name].to_cobrapy_objective(
self.model
)
return self.objective_name

def restore_objective(self,name):
def restore_objective(self, name):
if name in self.objective_data_cache:
self.model.objective = self.objective_data_cache[name].to_cobrapy_objective(self.model)
self.model.objective = self.objective_data_cache[name].to_cobrapy_objective(
self.model
)
else:
logger.warning("Objective "+name+" not found in cache")
logger.warning("Objective " + name + " not found in cache")
4 changes: 3 additions & 1 deletion tests/fbapkg/test_objectivepkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ def test_build_package_without_setting_objective(model):
"""set_objective=False caches the objective without applying it to the model."""
pkg = ObjectivePkg(model)
before = model.objective.direction
pkg.build_package("MIN{(1)+rxn00001_c0}", objective_name="dry_run", set_objective=False)
pkg.build_package(
"MIN{(1)+rxn00001_c0}", objective_name="dry_run", set_objective=False
)

assert "dry_run" in pkg.objective_data_cache
assert model.objective.direction == before
Expand Down
Loading