當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。