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


Python LpProblem.writeLP方法代码示例

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


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

示例1: make_into_lp_problem

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
def make_into_lp_problem(good_for, N):
    """
    Helper function for solve_with_lp_and_reduce()

    N --- number of isoform sequences
    good_for --- dict of <isoform_index> --> list of matched paths index
    """
    prob = LpProblem("The Whiskas Problem",LpMinimize)

    # each good_for is (isoform_index, [list of matched paths index])
    # ex: (0, [1,2,4])
    # ex: (3, [2,5])
    variables = [LpVariable(str(i),0,1,LpInteger) for i in xrange(N)]

    # objective is to minimize sum_{Xi}
    prob += sum(v for v in variables)

    # constraints are for each isoform, expressed as c_i * x_i >= 1
    # where c_i = 1 if x_i is matched for the isoform
    # ex: (0, [1,2,4]) becomes t_0 = x_1 + x_2 + x_4 >= 1
    for t_i, p_i_s in good_for:
        #c_i_s = [1 if i in p_i_s else 0 for i in xrange(N)]
        prob += sum(variables[i]*(1 if i in p_i_s else 0) for i in xrange(N)) >= 1
    prob.writeLP('cogent.lp')
    return prob
开发者ID:Magdoll,项目名称:Cogent,代码行数:27,代码来源:process_path.py

示例2: pe185

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
def pe185():
    """
    Modelling as an integer programming problem.
    Then using PuLP to solve it. It's really fast, just 0.24 seconds. 
    For details, see https://pythonhosted.org/PuLP/index.html
    """
    
    from pulp import LpProblem, LpVariable, LpMinimize, LpInteger, lpSum, value

    constraints = [
        ('2321386104303845', 0),
        ('3847439647293047', 1),
        ('3174248439465858', 1),
        ('8157356344118483', 1),
        ('6375711915077050', 1),
        ('6913859173121360', 1),
        ('4895722652190306', 1),
        ('5616185650518293', 2),
        ('4513559094146117', 2),
        ('2615250744386899', 2),
        ('6442889055042768', 2),
        ('2326509471271448', 2),
        ('5251583379644322', 2),
        ('2659862637316867', 2),
        ('5855462940810587', 3),
        ('9742855507068353', 3),
        ('4296849643607543', 3),
        ('7890971548908067', 3),
        ('8690095851526254', 3),
        ('1748270476758276', 3),
        ('3041631117224635', 3),
        ('1841236454324589', 3)
    ]

    VALs = map(str, range(10))
    LOCs = map(str, range(16))
    choices = LpVariable.dicts("Choice", (LOCs, VALs), 0, 1, LpInteger)

    prob = LpProblem("pe185", LpMinimize)
    prob += 0, "Arbitrary Objective Function"

    for s in LOCs:
        prob += lpSum([choices[s][v] for v in VALs]) == 1, ""

    for c, n in constraints:
        prob += lpSum([choices[str(i)][v] for i,v in enumerate(c)]) == n, ""

    prob.writeLP("pe185.lp")
    prob.solve()
    res = int(''.join(v for s in LOCs for v in VALs if value(choices[s][v])))

    # answer: 4640261571849533
    return res
开发者ID:ColdHumour,项目名称:ProjectEulerSolutions,代码行数:55,代码来源:solutions(181-190).py

示例3: TransProblem

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
class TransProblem(object):
    def __init__(self, home_list, work_list, util_matrix):
        """ Input a list of utils
            utils = [   #Works
                    #1 2 3 4 5
                    [2,4,5,2,1],#A   Homes
                    [3,1,3,2,3] #B
                    ]
        """
        self.util_matrix = util_matrix
        self.homes = dict((home, home.houses) for home in home_list)
        self.works = dict((work, work.jobs) for work in work_list)
        self.utils = makeDict([home_list, work_list], util_matrix, 0)

        # Creates the 'prob' variable to contain the problem data
        self.prob = LpProblem("Residential Location Choice Problem", LpMinimize)

        # Creates a list of tuples containing all the possible location choices
        self.choices = [(h, w) for h in self.homes for w in self.works.keys()]

        # A dictionary called 'volumes' is created to contain the referenced variables(the choices)
        self.volumes = LpVariable.dicts("choice", (self.homes, self.works), 0, None, LpContinuous)

        # The objective function is added to 'prob' first
        self.prob += (
            lpSum([self.volumes[h][w] * self.utils[h][w] for (h, w) in self.choices]),
            "Sum_of_Transporting_Costs",
        )

        # The supply maximum constraints are added to prob for each supply node (home)
        for h in self.homes:
            self.prob += (
                lpSum([self.volumes[h][w] for w in self.works]) <= self.homes[h],
                "Sum_of_Products_out_of_Home_%s" % h,
            )

        # The demand minimum constraints are added to prob for each demand node (work)
        for w in self.works:
            self.prob += (
                lpSum([self.volumes[h][w] for h in self.homes]) >= self.works[w],
                "Sum_of_Products_into_Work%s" % w,
            )

    def solve(self):
        # The problem data is written to an .lp file
        self.prob.writeLP("ResidentialLocationChoiceProblem.lp")

        # The problem is solved using PuLP's choice of Solver
        self.prob.solve(solvers.GLPK())

        # print the utility matrix
        print "Utility Matrix", self.util_matrix

        # The status of the solution is printed to the screen
        print "Status:", LpStatus[self.prob.status]

        # The optimised objective function value is printed to the screen
        print "Total Utility = ", value(self.prob.objective)

    def get_solution(self):
        # put the solution variables into a dict
        sol_var = {}
        for vol in self.prob.variables():
            sol_var[vol.name] = vol.varValue
        # construct the solution dict
        opt_sol = {}
        for home in self.homes:
            for work in self.works:
                key = "choice" + "_" + str(home) + "_" + str(work)
                opt_sol[(work, home)] = sol_var[key]
                print (work, home), opt_sol[(work, home)]
        return opt_sol
开发者ID:wlxiong,项目名称:PyMarkovActv,代码行数:74,代码来源:hitchcock.py

示例4: __init__

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
class LPSolver:
    '''
    LP solver class
    Used for solving LP and MILP problems
    '''
    
    def __init__(self,name='analysis',verbose=False):
        self.lpProblem = LpProblem()
        self.lpVariables = {}
        self.lpObjective = {}
        self.predictionMap = {}
        self.objectiveValue = None
        
        self.rowNames= []
        self.columnNames= []
        self.configFile = ''
        self.statusCode = None
        
        self.verbose = verbose
        self.useLimitTag = False
        self.mpsLogFile = False
        self.ignoreBadReferences = False
        self.Mip = True
        self.scip_path = ":" + os.environ["HOME"] + "/bin"
            
    def _parseSCIPLog(self, fileName):
        '''
        Parse result of SCIP analysis.
        This section needs a much more solid testing as it key interface with the solver 
        but often solver errors are dropped when they occur with no / minimal warnings.
        
        @var fileName: name and directory information of file being parsed, usually a temp file 
        @type fileName: string
        @return: (values of fluxes, value of objective function, status of optimization)
        @rtype: (dict,float,string) 
        '''
        fileHandle = open(fileName, 'r')
        location = 0
        line = fileHandle.readline()
        
        while not line.startswith('SCIP Status        :'):
            if line.startswith('Syntax error'):
                print "SCIP parsing syntax error: %s" % line
                line = fileHandle.readline()
                print line
            ilocation = fileHandle.tell() 
            if  location == ilocation:
                print "failed to read file %s" %(fileName)
                return ({},0.0,"failed to read file")
            location = ilocation

            line = fileHandle.readline()
        
        m = re.match('[\w\s:]*\[([\w\s]*)\]', line)
        statusString = m.group(1)

        objectiveValue = None
        result = dict()
        
        if statusString == 'optimal solution found':
            line = fileHandle.readline()
            while not line.startswith('objective value:'):
                #Good place to check all the features of the solution.
                if line.startswith('solution violates'):
                    print "Error solving optimization [%s]" % line
                ilocation = fileHandle.tell() 
                if  location == ilocation:
                    print "failed to read file %s" %(fileName)
                    return ({},0.0,"failed to read file")
                line = fileHandle.readline()
                
            m = re.match('objective value:\s+([\S]+)', line)
            objectiveValue = float(m.group(1))
            
            line = fileHandle.readline()
            while not line.strip() == '':
                m = re.match('([\S]+)\s+([\S]+)', line)
                name = m.group(1)
                result[name] = float(m.group(2))
                line = fileHandle.readline()
        
        fileHandle.close()
        
        return (result, objectiveValue, statusString)
        
        
    def writeMPS(self,fileName):
        """
        @param fileName: name of file
        @type fileName: String
        """
        self.lpProblem.writeMPS(fileName)
        return True
        
    def writeLP(self,fileName):
        """
        @param fileName: name of file
        @type fileName: String
        """
        self.lpProblem.writeLP(fileName,writeSOS=0)
#.........这里部分代码省略.........
开发者ID:bionomicron,项目名称:Redirector,代码行数:103,代码来源:LPSolver.py

示例5: set

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
# labels. For each such set, if every underlying label has a non-zero
# allocation, then the allocations to all the labels must be added to
# the scenario loss

scenario2labels = {i : set() for i in labels}
for label_set in allcombinations(nonzeros, npoisoned):
    scenario = 0
    for label in label_set:
        scenario |= label
    for label in label_set:
        scenario2labels[scenario].add(label)

for scenario in labels:
    prob += scenario_loss[scenario] == lpSum(allocs[label0] for label0 in scenario2labels[scenario])

prob.writeLP("drunk_mice.lp")
prob.solve()

alloc = [0] * len(labels)
for l in nonzeros:
    alloc[l] = int(allocs[l].value())
print "".join([chr(i) for i in alloc]).encode("base64")

"""
Kw0NBQ0EBQUMBQUFBQUGAAwFBQUFBQUABQUFAAUAAAAMBgUFBQYFAAUEBQAFAAAABQUFAAUAAAAF
AAAAAAAAAA0FBQUFBQUABQYFAAUAAAAFBQUABQAAAAUAAAAAAAAABQUFAAUAAAAFAAAAAAAAAAUA
AAAAAAAAAAAAAAAAAAAMBQUFBQUFAAUFBAAFAAAABAUGAAUAAAAFAAAAAAAAAAUFBQAFAAAABgAA
AAAAAAAFAAAAAAAAAAAAAAAAAAAABQUGAAUAAAAFAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAFAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0FBQUFBQUABQUFAAUAAAAGBQUABQAAAAUAAAAA
AAAABQUFAAUAAAAGAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAFBQUABQAAAAUAAAAAAAAABQAAAAAA
AAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQUFAAUAAAAFAAAAAAAA
开发者ID:chiaolun,项目名称:winepuzzle,代码行数:33,代码来源:pulp_solution.py

示例6: run

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import writeLP [as 别名]
def run(scenario_id):
    # read data from scenario_id
    coll = get_collection('scenario').find_one(
        {'_id': ObjectId(scenario_id)})
    fund = coll['fund']
    products = []
    for prod_dict in coll['products']:
        product = Product(prod_dict['name'], prod_dict['lowerLimit'],
                          prod_dict['salePrice'])
        product.discounts.append({'threshold': 0, 'discount': 1})
        for discount in prod_dict['discounts']:
            product.discounts.append(discount)

        products.append(product)

    for prod in products:
        prod.x = [LpVariable('x_{0}{1}'.format(prod.name, i + 1), 0)
                  for i in range(len(prod.discounts))]
        prod.y = [LpVariable('y_{0}{1}'.format(prod.name, i + 1), cat=LpBinary)
                  for i in range(len(prod.discounts))]

    problem = LpProblem('MVP_{0}'.format(scenario_id), sense=LpMaximize)

    mv_obj_var = LpVariable('MV_Obj')
    y_obj_var = LpVariable('y_Obj')
    problem += mv_obj_var - y_obj_var

    # Objective functions
    problem += lpSum([prod.sale_price * prod.x[i] for prod in products
                      for i in range(len(prod.x))]) == mv_obj_var
    problem += lpSum([prod.y[i] for prod in products
                      for i in range(len(prod.y))]) == y_obj_var
    # End of Obj

    # Constraints
    # sum(b_ij * X_ij) == fund
    problem += lpSum(
        [prod.sale_price * prod.discounts[i]['discount'] * prod.x[i]
         for prod in products for i in range(len(prod.discounts))]) == fund

    for prod in products:
        expr = LpAffineExpression()
        n = len(prod.discounts)
        for i in range(n):
            expr += prod.x[i]

            # M * y_ij >= x_ij
            problem += BIG_M * prod.y[i] >= prod.x[i]

            if i + 1 < n:
                rhs = prod.discounts[i + 1]['threshold'] \
                      - prod.discounts[i]['threshold'] - SLACK
                # x_ij <= C_ij+1 - C_ij - 1
                problem += prod.x[i] <= rhs

            if i > 0:
                rhs = prod.discounts[i]['threshold'] \
                      - prod.discounts[i - 1]['threshold'] - SLACK
                # M * (1 - y_ij) >= C_ij - C_ij-1 - X_ij-1 - 1
                problem += BIG_M * (1 - prod.y[i]) >= rhs - prod.x[i - 1]

        if len(expr) > 0:
            # sum(X_i) >= lower_limit
            problem += expr >= prod.lower_limit

        problem.writeLP('C:\\Projects\Python\{0}.lp'.format(problem.name))
        problem.solve()
        if problem.status == LpStatusOptimal:
            with open('C:\\Projects\Python\{0}.sol'.format(problem.name),
                      'w') as sol:
                sol.write('Solution of {0}\n'.format(problem.name))
                sol.write('Obj value: {0}\n'.format(problem.objective.value()))
                sol.writelines(['{0} = {1}\n'.format(v.name, v.value())
                                for v in problem.variables()])

    return LpStatus[problem.status]
开发者ID:fatwin,项目名称:flask-rest-solver,代码行数:78,代码来源:solver.py

示例7: opAss_LP

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

#.........这里部分代码省略.........

        # calculation of Delta_Ass
        for d in Delta_Assignment:
            if OldAss[(d[0],d[1])] == 1:
                prob += lpSum(OldAss[(d[0],d[1])] - PB_ass[(d[0],d[1])]) <= Delta_Ass[(d[0],d[1])]
            else:
                prob += lpSum(PB_ass[(d[0],d[1])] - OldAss[(d[0],d[1])]) <= Delta_Ass[(d[0],d[1])]  
            
            
    # 4th obj = fill a subline
    if weightFactors[3]>0:
        # verify whether there are machines active in the sublines
        subline={0:{'noMach':0, 'WIP':0}, 1:{'noMach':0, 'WIP':0}}
        for mach in machineList:
            if machineList[mach]['stationID'] in [0,1,2]:
                subline[machineList[mach]['machineID']]['noMach'] += 1
                subline[machineList[mach]['machineID']]['WIP'] += machineList[mach]['WIP']
    
        chosenSubLine = False      
    
        # choose subline to be filled first
        if subline[0]['noMach'] == 3:        
            # case when both sublines are fully active
            if subline[1]['noMach'] == 3:
                if subline[0]['WIP'] >= subline [1]['WIP']:
                    chosenSubLine = 1
                else:
                    chosenSubLine = 2        
            else:
                chosenSubLine = 1
    
        elif subline[1]['noMach'] == 3:
            chosenSubLine = 2
    
        #create variable for the chosen subline
        if chosenSubLine:
            chosenSubLine -= 1
            subLine = LpVariable('SubL', lowBound=0)
            sub = []
            for station in range(3):
                mach = Tool[station][chosenSubLine].name        #'St'+str(station)+'_M'+str(chosenSubLine)
                for oper in PBlist:
                    if station in PBskills[oper]:
                        sub.append(PB_ass[(oper,mach)])
            
            
            prob += lpSum(sub) >= subLine
            chosenSubLine+=1
            obj.append(subLine*weightFactors[3]/3.0)  
            
            
    # 5th objective: prioritise machines with furthest in time last assignment 
    LastAssignmentSum = float(sum([machineList[mach]['lastAssignment'] for mach in machines ]))
    if LastAssignmentSum > 0 and weightFactors[4]>0:
        obj += [machineList[mach]['lastAssignment']*PB_ass[(oper,mach)]*weightFactors[4]/float(LastAssignmentSum) for oper in PBlist for mach in machines if machineList[mach]['stationID'] in PBskills[oper]]
       
    # 6th objective: max the number of pb assigned
    if weightFactors[5]>0:
        obj += [PB_ass[(oper,mach)]*weightFactors[5]/float(len(PBlist)) for oper in PBlist for mach in machines if machineList[mach]['stationID'] in PBskills[oper]]
       
    prob += lpSum(obj)
        
    # constraint 1: # operators assigned to a station <= 1
    for machine in machines:
        prob += lpSum([PB_ass[(oper,machine)] for oper in PBlist if machineList[machine]['stationID'] in PBskills[oper]]) <= 1
        
    # constraint 2: # machines assigned to an operator <= 1
    for operator in PBlist:
        prob += lpSum([PB_ass[(operator,machine)] for machine in machines if machineList[machine]['stationID'] in PBskills[operator]]) <= 1
            
            
    # write the problem data to an .lp file.
    prob.writeLP("PBassignment.lp") 
    
    prob.solve()
    
    if LpStatus[prob.status] != 'Optimal':
        print 'WARNING: LP solution ', LpStatus[prob.status]
    
    PBallocation = {}
    
    for mach in machines:
        for oper in PBlist:
            if machineList[mach]['stationID'] in PBskills[oper]:
                if PB_ass[(oper,mach)].varValue > 0.00001:
                    PBallocation[oper]=mach
            
    files = glob.glob('*.mps')
    for f in files:
        os.remove(f)
        
    files = glob.glob('*.lp')
    for f in files:
        os.remove(f)
    
    G.totalPulpTime+=time.time()-startPulp
    return PBallocation
    
        
        
开发者ID:PanosBarlas,项目名称:dream,代码行数:101,代码来源:opAss_LPmethod.py

示例8: OptKnock

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

#.........这里部分代码省略.........

        self.create_prob(sense=LpMaximize, use_glpk=use_glpk)
        self.add_primal_variables_and_constraints()
        self.add_dual_variables_and_constraints()
        self.add_optknock_variables_and_constraints()

        # add the objective of maximizing the flux in the target reaction
        self.prob.setObjective(self.var_v[self.r_target])

        self.add_knockout_bounds(ko_candidates, num_deletions)

    def prepare_optslope(self, target_reaction_id, ko_candidates=None,
                         num_deletions=5, use_glpk=False):
        # add the objective of maximizing the flux in the target reaction
        self.r_target = self.get_reaction_by_id(target_reaction_id)

        # set biomass maximum to 0
        self.r_biomass.lower_bound = 0
        self.r_biomass.upper_bound = 0
        self.r_target.lower_bound = 0
        self.r_target.upper_bound = 0

        self.create_prob(sense=LpMaximize, use_glpk=use_glpk)
        self.add_primal_variables_and_constraints()
        self.add_dual_variables_and_constraints()
        self.add_optknock_variables_and_constraints()

        # set the objective as maximizing the shadow price of v_target upper bound
        self.prob.setObjective(self.var_w_U[self.r_target] - self.var_w_L[self.r_target])

        self.add_knockout_bounds(ko_candidates, num_deletions)

    def write_linear_problem(self, fname):
        self.prob.writeLP(fname)

    def solve(self):
        self.prob.solve()

        if self.prob.status != LpStatusOptimal:
            if self.verbose:
                print "LP was not solved because: ", LpStatus[self.prob.status]
            self.solution = Solution(None)
        else:        
            self.solution = Solution(self.prob.objective.value())
            if self.has_flux_as_variables:
                self.solution.x = [self.var_v[r].varValue for r in self.model.reactions]
        self.solution.status = self.prob.status
        
        return self.solution
    
    def get_objective_value(self):
        if self.solution.status != LpStatusOptimal:
            return None
        else:
            return self.prob.objective.value()

    def print_primal_results(self, short=True):
        obj = self.get_objective_value()
        if obj is None:
            return
        print "Objective : %6.3f" % obj
        if not short:
            print "List of reactions : "
            for r in self.model.reactions:
                print "%30s (%4g <= v <= %4g) : v = %6.3f" % \
                    (r.name, r.lower_bound, r.upper_bound, self.var_v[r].varValue)
开发者ID:eladnoor,项目名称:optslope,代码行数:70,代码来源:optknock.py


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