当前位置: 首页>>代码示例>>Python>>正文


Python LpProblem.setObjective方法代码示例

本文整理汇总了Python中pulp.LpProblem.setObjective方法的典型用法代码示例。如果您正苦于以下问题:Python LpProblem.setObjective方法的具体用法?Python LpProblem.setObjective怎么用?Python LpProblem.setObjective使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pulp.LpProblem的用法示例。


在下文中一共展示了LpProblem.setObjective方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: OptKnock

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import setObjective [as 别名]
class OptKnock(object):

    def __init__(self, model, verbose=False):
        self.model = deepcopy(model)
        self.verbose = verbose

        # locate the biomass reaction
        biomass_reactions = [r for r in self.model.reactions
                             if r.objective_coefficient != 0]
        if len(biomass_reactions) != 1:
            raise Exception('There should be only one single biomass reaction')
        self.r_biomass = biomass_reactions[0]
        
        self.has_flux_as_variables = False
    
    def create_prob(self, sense=LpMaximize, use_glpk=False):
        # create the LP
        self.prob = LpProblem('OptKnock', sense=sense)
        if use_glpk:
            self.prob.solver = solvers.GLPK()
        else:
            self.prob.solver = solvers.CPLEX(msg=self.verbose)
        if not self.prob.solver.available():
            raise Exception("CPLEX not available")    

    def add_primal_variables_and_constraints(self):
        # create the continuous flux variables (can be positive or negative)
        self.var_v = {}
        for r in self.model.reactions:
            self.var_v[r] = LpVariable("v_%s" % r.id,
                                       lowBound=r.lower_bound,
                                       upBound=r.upper_bound,
                                       cat=LpContinuous)

        # this flag will be used later to know if to expect the flux
        # variables to exist
        self.has_flux_as_variables = True
        
        # add the mass-balance constraints to each of the metabolites (S*v = 0)
        for m in self.model.metabolites:
            S_times_v = LpAffineExpression([(self.var_v[r], r.get_coefficient(m))
                                            for r in m.reactions])
            self.prob.addConstraint(S_times_v == 0, 'mass_balance_%s' % m.id)
    
    def add_dual_variables_and_constraints(self):
        # create dual variables associated with stoichiometric constraints
        self.var_lambda = dict([(m, LpVariable("lambda_%s" % m.id, 
                                               lowBound=-M,
                                               upBound=M,
                                               cat=LpContinuous))
                                for m in self.model.metabolites])

        # create dual variables associated with the constraints on the primal fluxes
        self.var_w_U = dict([(r, LpVariable("w_U_%s" % r.id, lowBound=0, upBound=M, cat=LpContinuous))
                             for r in self.model.reactions])
        self.var_w_L = dict([(r, LpVariable("w_L_%s" % r.id, lowBound=0, upBound=M, cat=LpContinuous))
                             for r in self.model.reactions])

        # add the dual constraints:
        #   S'*lambda + w_U - w_L = c_biomass
        for r in self.model.reactions:
            S_times_lambda = LpAffineExpression([(self.var_lambda[m], coeff)
                                                 for m, coeff in r._metabolites.iteritems()
                                                 if coeff != 0])
            row_sum = S_times_lambda + self.var_w_U[r] - self.var_w_L[r]
            self.prob.addConstraint(row_sum == r.objective_coefficient, 'dual_%s' % r.id)
                                   
    def prepare_FBA_primal(self, use_glpk=False):
        """
            Run standard FBA (primal)
        """
        self.create_prob(sense=LpMaximize, use_glpk=use_glpk)
        self.add_primal_variables_and_constraints()
        self.prob.setObjective(self.var_v[self.r_biomass])

    def prepare_FBA_dual(self, use_glpk=False):
        """
            Run shadow FBA (dual)
        """
        self.create_prob(sense=LpMinimize, use_glpk=use_glpk)
        self.add_dual_variables_and_constraints()
        
        w_sum = LpAffineExpression([(self.var_w_U[r], r.upper_bound)
                                    for r in self.model.reactions if r.upper_bound != 0] +
                                   [(self.var_w_L[r], -r.lower_bound)
                                    for r in self.model.reactions if r.lower_bound != 0])
        self.prob.setObjective(w_sum)
    
    def get_reaction_by_id(self, reaction_id):
        if reaction_id not in self.model.reactions:
            return None
        reaction_ind = self.model.reactions.index(reaction_id)
        reaction = self.model.reactions[reaction_ind]
        return reaction
        
    def add_optknock_variables_and_constraints(self):
        # create the binary variables indicating which reactions knocked out
        self.var_y = dict([(r, LpVariable("y_%s" % r.id, cat=LpBinary))
                           for r in self.model.reactions])

#.........这里部分代码省略.........
开发者ID:eladnoor,项目名称:optslope,代码行数:103,代码来源:optknock.py

示例2: solve

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import setObjective [as 别名]

#.........这里部分代码省略.........
        if col.together is not None:
            if col.together:
                # For {n}: cells that are at least n appart cannot be both blue.
                # Example: For {3}, the configurations X??X, X???X, X????X, ... are impossible.
                for span in range(col.value, len(col.members)):
                    for start in range(len(col.members)-span):
                        problem += lpSum([get_var(col.members[start]), get_var(col.members[start+span])]) <= 1
            else:
                # For -n-, the sum of any range of n cells may contain at most n-1 blues
                for offset in range(len(col.members)-col.value+1):
                    problem += lpSum(get_var(col.members[offset+i]) for i in range(col.value)) <= col.value-1
    
    # Constraints from cell number information
    for cell in known:
        # If the displays a number, the sum of its neighbourhood (radius 1 or 2) is known
        if cell.value is not None:
            problem += lpSum(get_var(neighbour) for neighbour in cell.members) == cell.value
        
        # Additional togetherness information available?
        # Note: Only relevant if value between 2 and 4.
        # In fact: The following code would do nonsense for 0,1,5,6!
        if cell.together is not None and cell.value >= 2 and cell.value <= 4:
            # Note: Cells are ordered clockwise.
            # Convenience: Have it wrap around.
            m = cell.members+cell.members
            
            if cell.together:
                # note how togetherness is equivalent to the following
                # two patterns not occuring: "-X-" and the "X-X"
                # in other words: No lonely blue cell and no lonely gap
                for i in range(len(cell.members)):
                    # No lonely cell condition:
                    # Say m[i] is a blue.
                    # Then m[i-1] or m[i+1] must be blue.
                    # That means: -m[i-1] +m[i] -m[i+1] <= 0
                    # Note that m[i+1] and m[i-1] only count
                    # if they are real neighbours.
                    cond = get_var(m[i])
                    if m[i].is_neighbor(m[i-1]):
                        cond -= get_var(m[i-1])
                    if m[i].is_neighbor(m[i+1]):
                        cond -= get_var(m[i+1])
                        
                    # no isolated cell
                    problem += cond <= 0
                    # no isolated gap (works by a similar argument)
                    problem += cond >= -1
            else:
                # -n-: any circular range of n cells contains at most n-1 blues.
                for i in range(len(cell.members)):
                    # the range m[i], ..., m[i+n-1] may not all be blue if they are consecutive
                    if all(m[i+j].is_neighbor(m[i+j+1]) for j in range(cell.value-1)):
                        problem += lpSum(get_var(m[i+j]) for j in range(cell.value)) <= cell.value-1

    # First, get any solution.
    # Default solver can't handle no objective, so invent one:
    spam = LpVariable('spam', 0, 1, 'binary')
    problem += (spam == 1)
    problem.setObjective(spam) # no optimisation function yet
    problem.solve(solver)
    
    def get_true_false_classes():
        true_set  = set()
        false_set = set()
        
        for rep, size in classes.items():
            if value(get_var(rep)) == 0:
                false_set.add(rep)
            elif value(get_var(rep)) == size:
                true_set.add(rep)
        return true_set, false_set
    
    # get classes that are fully true or false
    # they are candidates for solvable classes
    true, false = get_true_false_classes()
    
    while true or false:
        # Now try to vary as much away from the
        # initial solution as possible:
        # We try to make the variables True, that were False before
        # and vice versa. If no change could be achieved, then
        # the remaining variables have their unique possible value.
        problem.setObjective(lpSum(get_var(t) for t in true)-lpSum(get_var(f) for f in false))
        problem.solve(solver)
        
        # all true variables stayed true and false stayed false?
        # Then they have their unique value and we are done!
        if value(problem.objective) == sum(classes[rep] for rep in true):
            for tf_set, kind in [(true, Cell.full), (false, Cell.empty)]:
                for rep in tf_set:
                    for cell in unknown:
                        if rep_of[cell] is rep:
                            yield cell, kind
            return
        
        true_new, false_new = get_true_false_classes()
        
        # remember only those classes that subbornly kept their pure trueness/falseness
        true &= true_new
        false &= false_new
开发者ID:BlaXpirit,项目名称:sixcells,代码行数:104,代码来源:solver.py


注:本文中的pulp.LpProblem.setObjective方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。