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


Python LpProblem.variables方法代码示例

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


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

示例1: pi_solve

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [as 别名]
def pi_solve(pi, Q, s):
    # The 'prob' variable will contain the problem data.
    prob = LpProblem('FindPi', LpMinimize)

    a0 = LpVariable('a0', 0.0)  # the minimum is 0.0
    a1 = LpVariable('a1', 0.0)  # the minimum is 0.0
    a2 = LpVariable('a2', 0.0)  # the minimum is 0.0
    a3 = LpVariable('a3', 0.0)  # the minimum is 0.0
    a4 = LpVariable('a4', 0.0)  # the minimum is 0.0
    v = LpVariable('v', 0.0)

    # The objective function is added to 'prob' first
    prob += v, "to minimize"

    # constraints
    prob +=  a0 * Q[s,0,0] + a1 * Q[s,1,0] + a2 * Q[s,2,0] + a3 * Q[s,3,0] + a4 * Q[s,4,0] <= v, 'constraint 1'
    prob +=  a0 * Q[s,0,1] + a1 * Q[s,1,1] + a2 * Q[s,2,1] + a3 * Q[s,3,1] + a4 * Q[s,4,1] <= v, 'constraint 2'
    prob +=  a0 * Q[s,0,2] + a1 * Q[s,1,2] + a2 * Q[s,2,2] + a3 * Q[s,3,2] + a4 * Q[s,4,2] <= v, 'constraint 3'
    prob +=  a0 * Q[s,0,3] + a1 * Q[s,1,3] + a2 * Q[s,2,3] + a3 * Q[s,3,3] + a4 * Q[s,4,3] <= v, 'constraint 4'
    prob +=  a0 * Q[s,0,4] + a1 * Q[s,1,4] + a2 * Q[s,2,4] + a3 * Q[s,3,4] + a4 * Q[s,4,4] <= v, 'constraint 5'

    prob +=  1.0*a0 + 1.0*a1 + 1.0*a2 + 1.0*a3 + 1.0*a4 == 1, 'constraint 6'

    prob.solve()

    pi_prime = [a.varValue for a in prob.variables()[:5]]

    return np.array(pi_prime)
开发者ID:mwalton,项目名称:reinforcement-learning,代码行数:30,代码来源:soccer.py

示例2: solve_under_coverage

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [as 别名]
def solve_under_coverage(graph, min_coverage=80):

    prob = LpProblem("granularity selection", LpMinimize)
    codelet_vars = LpVariable.dicts("codelet",
            graph,
            lowBound=0,
            upBound=1,
            cat=LpInteger)

    # Objective function: minimize the total replay cost of selected codelets

    # Compute replay time
    for n,d in graph.nodes(data=True):
      d['_total_replay_cycles'] = 0
      for inv in d['_invocations']:
        d['_total_replay_cycles'] = d['_total_replay_cycles'] + float(inv["Invivo (cycles)"])

    prob += lpSum([codelet_vars[n]*d['_total_replay_cycles'] for n,d in graph.nodes(data=True)])

    # and with good coverage
    prob += (lpSum([codelet_vars[n]*d['_coverage'] for n,d in graph.nodes(data=True)]) >= min_coverage)

    # selected codelets should match
    for n,d in graph.nodes(data=True):
        if not d['_matching']:
            prob += codelet_vars[n] == 0

    # Finally we should never include both the children and the parents
    for dad in graph.nodes():
        for son in graph.nodes():
            if not dad in nx.ancestors(graph, son):
                continue
            # We cannot select dad and son at the same time
            prob += codelet_vars[dad] + codelet_vars[son] <= 1

    #prob.solve(GLPK())
    prob.solve()
    if (LpStatus[prob.status] != 'Optimal'):
        raise Unsolvable()

    for v in prob.variables():
        assert v.varValue == 1.0 or v.varValue == 0.0
        if v.varValue == 1.0:

            for n,d in graph.nodes(data=True):
                if ("codelet_"+str(n)) == v.name:
                    d["_selected"] = True
                    yield n
开发者ID:Chadi-akel,项目名称:cere,代码行数:50,代码来源:granularity.py

示例3: _recurse

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [as 别名]
    def _recurse(work_pairs, mae, grace=None):
        req = grace or 1.0

        demands = {
            'morning': mae[0],
            'afternoon': mae[1],
            'exam': mae[2],
        }
        total_avg = float(sum([demands[i] for i in SHIFTS])) / work_pairs
        total_low, total_high = floor(total_avg), ceil(total_avg)
        work_pair_count = work_pairs
        avgs = [float(demands[i]) / work_pair_count for i in SHIFTS]
        lows = [floor(a) for a in avgs]
        highs = [ceil(a) for a in avgs]

        target = req * total_avg * float(sum([COSTS[i] for i in SHIFTS])) / len(SHIFTS)

        prob = LpProblem("Work Distribution", LpMinimize)
        var_prefix = "shift"
        shift_vars = LpVariable.dicts(var_prefix, SHIFTS, 0, cat=LpInteger)
        prob += lpSum([COSTS[i] * shift_vars[i] for i in SHIFTS]), "cost of combination"
        prob += lpSum([COSTS[i] * shift_vars[i] for i in SHIFTS]) >= target, "not too good"
        prob += lpSum([shift_vars[i] for i in SHIFTS]) >= total_low, "low TOTAL"
        prob += lpSum([shift_vars[i] for i in SHIFTS]) <= total_high, "high TOTAL"

        for shift, low, high in zip(SHIFTS, lows, highs):
            prob += lpSum([shift_vars[shift]]) >= low, "low %s" % shift
            prob += lpSum([shift_vars[shift]]) <= high, "high %s" % shift

        prob.solve(GLPK_CMD(msg=0))

        if not LpStatus[prob.status] == 'Optimal':
            next_grace = req - 0.1
            assert 0.0 < next_grace
            return _recurse(work_pairs, mae, next_grace)

        new_mae = [0, 0, 0]
        solution = [0, 0, 0]
        for v in prob.variables():
            for pos, name in enumerate(SHIFTS):
                if v.name == "%s_%s" % (var_prefix, name):
                    solution[pos] = v.varValue
                    new_mae[pos] = mae[pos] - solution[pos]

        return (PairAlloc(solution), work_pairs - 1) + tuple(new_mae)
开发者ID:Baljan,项目名称:cafesys,代码行数:47,代码来源:workdist.py

示例4: TransProblem

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [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

示例5: get_optimal_routes

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [as 别名]
def get_optimal_routes(sources, destinations):
    sources = collections.OrderedDict([(x['id'], x) for x in sources])
    destinations = collections.OrderedDict([(x['id'], x) for x in destinations])

    sources_points = [{'lat': x['lat'], 'lng': x['lng']} for x in sources.values()]
    destinations_points = [{'lat': x['lat'], 'lng': x['lng']} for x in destinations.values()]

    source_ids = [str(x['id']) for x in sources.values()]
    dest_ids = [str(x['id']) for x in destinations.values()]

    demand = {str(x['id']): convert_int(x['num_students']) for x in sources.values()}
    supply = {str(x['id']): convert_int(x['num_students']) for x in destinations.values()}

    log.info("Calling gmaps api...")
    distances = gmaps.distance_matrix(origins=sources_points, destinations=destinations_points, mode='walking')

    costs = {}
    for i, origin in enumerate(distances['rows']):
        origin_costs = {}
        for j, entry in enumerate(origin['elements']):
            origin_costs[dest_ids[j]] = entry['duration']['value']
        costs[source_ids[i]] = origin_costs

    prob = LpProblem("Evaucation Routing for Schools",LpMinimize)
    routes = [(s,d) for s in source_ids for d in dest_ids]
    route_lookup = {'Route_{}_{}'.format(x.replace(' ','_'),y.replace(' ','_')):(x,y) for (x,y) in routes}
    route_vars = LpVariable.dicts("Route",(source_ids,dest_ids),0,None,LpInteger)
    prob += lpSum([route_vars[w][b]*(costs[w][b]**2) for (w,b) in routes])
    for dest in dest_ids:
        prob += lpSum([route_vars[source][dest] for source in source_ids]) <= supply[dest], "Students going to {} is <= {}".format(dest, supply[dest])
    for source in source_ids:
        prob += lpSum([route_vars[source][dest] for dest in dest_ids]) == demand[source], "Students leaving {} is {}".format(source, demand[source])

    log.info("Optimizing routes...")
    prob.solve()

    if prob.status != 1:
        raise Exception("Algorithm could not converge to a solution")

    result = []
    for v in prob.variables():
        src, dst = route_lookup[v.name]
        value = v.value()
        result.append({'src': sources[src], 'dst': destinations[dst], 'value': int(value)})
    return result
开发者ID:louisdang,项目名称:govhack2016,代码行数:47,代码来源:utils.py

示例6: pulp_solver

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [as 别名]
def pulp_solver(G, h, A, b, c, n):
    # First, create a variable for each of the columsn of G and A.
    #
    # pre-condition: G and A have the same number of columns.
    #
    # The second argument specifies a lower bound for the variable, so we can
    # safely ignore the inequality constraints given by G and h.
    variables = [LpVariable('s{}'.format(i), 0) for i in range(G.shape[1])]
    # LpVariable has a second argument that allows you to specify a lower bound
    # for the variable (for example, x1 >= 0). We don't specify nonnegativity
    # here, because it is already specified by the inequality constraints G and
    # h.
    #variables = [LpVariable('s{}'.format(i)) for i in range(G.shape[1])]
    # Next, create a problem context object and add the objective function c to
    # it. The first object added to LpProblem is implicitly interpreted as the
    # objective function.
    problem = LpProblem('fraciso', LpMinimize)
    # The np.dot() function doesn't like mixing numbers and LpVariable objects,
    # so we compute the dot product ourselves.
    #
    #problem += np.dot(variables, c), 'Dummy objective function'
    problem += _pulp_dot_product(c, variables), 'Dummy objective function'
    # Add each equality constraint to the problem context.
    for i, (row, b_value) in enumerate(zip(A, b)):
        #problem += np.dot(row, variables), 'Constraint {}'.format(i)
        # Convert the row to a list so pulp has an easier time dealing with it.
        row_as_list = np.asarray(row).flatten().tolist()
        dot_product = _pulp_dot_product(row_as_list, variables)
        problem += dot_product == b_value, 'Constraint {}'.format(i)
    solver_backend = GLPK()
    #solver_backend = COIN()
    problem.solve(solver_backend)
    if problem.status == LpStatusOptimal:
        # PuLP is silly and sorts the variables by name before returning them,
        # so we need to re-sort them in numerical order.
        solution = [s.varValue for s in sorted(problem.variables(),
                                               key=lambda s: int(s.name[1:]))]
        return True, solution
    # TODO status could be unknown here, but we're currently ignoring that
    return False, None
开发者ID:Arafatk,项目名称:fraciso,代码行数:42,代码来源:linprog.py

示例7: run

# 需要导入模块: from pulp import LpProblem [as 别名]
# 或者: from pulp.LpProblem import variables [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


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