コード例 #1
0
ファイル: primal.py プロジェクト: oefirouz/network-art
    def add_constraints(self, count, S_s):
        for i in range(self.N):
            temp = pulp.LpAffineExpression()
            for j in range(self.N):
                if i != j:
                    if i < j:
                        temp += pulp.lpSum(self.X_[count][str(i) + "_" +
                                                          str(j)])
                    else:
                        temp += pulp.lpSum(self.X_[count][str(j) + "_" +
                                                          str(i)])
            self.primal_[count] += temp == 2

        for S_x in self.S_s:
            for idx, S_i in enumerate(S_x):
                temp = pulp.LpAffineExpression()
                for i in S_i:
                    for S_not_including_i in S_x:
                        if S_x[idx] != S_not_including_i:
                            for j in S_not_including_i:
                                if i != j:
                                    if i < j:
                                        temp += pulp.lpSum(
                                            self.X_[count][str(i) + "_" +
                                                           str(j)])
                                    else:
                                        temp += pulp.lpSum(
                                            self.X_[count][str(j) + "_" +
                                                           str(i)])
                # print("lol, ", temp)
                self.primal_[count] += temp >= 2
コード例 #2
0
    def solve_problem(obj, tolerance=0.01, threads=1, timeLimit=120):
        material_model = pulp.LpProblem("MaterialProductionModel",
                                        pulp.LpMinimize)

        # Create Equality Constraints that produce the Price and Volume as independent variables.
        price_coefficients = [(mineral, obj.price_per_ore[mineral])
                              for mineral in obj.variable_ore_dict.values()]
        price_coefficients.append((obj.price, -1))
        price_constraint = pulp.LpConstraint(
            pulp.LpAffineExpression(price_coefficients),
            sense=pulp.LpConstraintEQ,
            name='PriceConstraint',
            rhs=0)

        volume_coefficients = [(mineral, obj.volume_per_ore[mineral])
                               for mineral in obj.variable_ore_dict.values()]
        volume_coefficients.append((obj.volume, -1))
        volume_constraint = pulp.LpConstraint(
            pulp.LpAffineExpression(volume_coefficients),
            sense=pulp.LpConstraintEQ,
            name='VolumeConstraint',
            rhs=0)

        material_model += price_constraint
        material_model += volume_constraint

        # Create Cost Function in terms of variables
        # I'll be lazy for now and just minimize price in ISK.
        material_model += (obj.weight_of_price * obj.price +
                           obj.weight_of_volume * obj.volume)

        # Now go through the required materials and impose constraints that ensure we produce the right amount of stuff
        for material, amount in obj.required_materials.items():

            production_expr = pulp.LpAffineExpression(
                obj.yield_per_mineral[material].items())
            production_constraint = pulp.LpConstraint(
                production_expr,
                sense=pulp.LpConstraintGE,
                name='Produce{}'.format(material),
                rhs=amount)

            # Add Constraint to Model
            material_model += production_constraint

        solver = pulp.PULP_CBC_CMD(timeLimit=timeLimit,
                                   gapRel=tolerance,
                                   threads=threads)

        print(material_model)

        material_model.solve(solver)

        # The status of the solution is printed to the screen
        print("Status:", pulp.LpStatus[material_model.status])

        result = dict()
        for v in material_model.variables():
            result[v.name] = v.varValue
        return result
コード例 #3
0
ファイル: gr_core.py プロジェクト: iJasonne/pslplay
    def pulp_solve(self):
        problem = pulp.LpProblem(pulp.LpMinimize)

        vs = self.get_vars()
        our_vars = dict()
        v = []
        for i in range(len(vs)):
            v.append(pulp.LpVariable('%d' %vs[i][0], vs[i][1], vs[i][2]))
            our_vars[vs[i][0]] = v[i]

        ob = self.get_objective()
        problem.objective = pulp.LpAffineExpression([(our_vars[ob[i][0]], ob[i][1]) for i in range(len(ob))])

        css = self.get_linear_cons()
        for i in range(len(css)):
            ids, coefs, cnst = css[i]
            c = pulp.LpConstraint(
                pulp.LpAffineExpression([(our_vars[ids[j]], coefs[j]) for j in range(len(coefs))], 
                                        constant=cnst)
                , sense=-1)
            problem.constraints[i] = c
            
        problem.solve()
        self.solutions.clear()
        for variable in problem.variables():
            self.solutions[int(variable.name)] = variable.varValue
        self.obj_val = pulp.value(problem.objective)
コード例 #4
0
ファイル: dea.py プロジェクト: Daddeee/VR_DEA
	def solve(self):
		status = {}
		efficiency = {}

		for i in self._n:
			prob = pulp.LpProblem("DMU_" + str(i), pulp.LpMaximize)

			u = pulp.LpVariable.dicts("u", self._s, lowBound=0)
			v = pulp.LpVariable.dicts("v", self._m, lowBound=0)
			
			# objective
			prob += pulp.LpAffineExpression([(u[s], self.outputs[i][s]) for s in self._s])
			
			# Set up constraints
			prob += pulp.LpAffineExpression([(v[m], self.inputs[i][m]) for m in self._m]) == 1,  "fix_denom_constraint"

			for j in self._n:
				prob += pulp.LpAffineExpression([(u[s], self.outputs[j][s]) for s in self._s]) - pulp.LpAffineExpression([(v[m], self.inputs[j][m]) for m in self._m]) <= 0, "DMU_constr_" + str(j)

			prob.solve()

			status[i] = pulp.LpStatus[prob.status]
			
			efficiency[i] = pulp.value(prob.objective)


		return status, efficiency
コード例 #5
0
def build_linear_program(temp_ajd,temp_prob,lmbda,subset_size):
    ILP = pulp.LpProblem("clustering", pulp.LpMinimize)
    x = {}
    xi = {}
    for i in range(0, subset_size - 1):
        for j in range(i + 1, subset_size - 1):
            x[str(i) + ',' + str(j)] = pulp.LpVariable('x' + str(i) + str(j), cat='Continuous', lowBound=0.0,
                                                       upBound=1.0)
            xi[str(i) + ',' + str(j)] = pulp.LpVariable('xi' + str(i) + str(j), cat='Continuous', lowBound=0.0,
                                                        upBound=1.0)

    ILP += pulp.LpAffineExpression([(x[str(i) + ',' + str(j)], temp_ajd[i, j] * temp_prob[i, j])
                                    for i in range(0, subset_size - 1) for j in range(i + 1, subset_size - 1)])
    ILP += pulp.LpAffineExpression([(xi[str(i) + ',' + str(j)], lmbda * (1 - temp_ajd[i, j]) * (temp_prob[i, j]))
                                    for i in range(0, subset_size - 1) for j in range(i + 1, subset_size - 1)])


    for i in range(0, subset_size - 1):
        for j in range(i + 1, subset_size - 1):
            for w in range(0, subset_size - 1):
                if w != j and w != i:
                    ILP += x[str(i) + ',' + str(j)] <= x[str(min(i, w)) + ',' + str(max(i, w))] + x[
                        str(min(j, w)) + ',' + str(max(w, j))]
            ILP += xi[str(i) + ',' + str(j)] == 1 - x[str(i) + ',' + str(j)]

    return x, ILP
コード例 #6
0
    def find_angle_assignments(self):
        """Sets up and solves a linear solver"""
        prob = pl.LpProblem(self.word.word, pl.LpMinimize)
        equation = ["one", "two"]
        lp_variables = {}

        for link in self.links:
            for label in link.get_labels():
                if label != "none":
                    lp_variables[label] = pl.LpVariable(
                        label, 0, None, pl.LpContinuous)

        lp_disc = [lp_variables[x] for x in self.attaching_disc]
        objective = pl.LpAffineExpression([(x, 1) for x in lp_disc])
        link_equations = []
        region_equations = []
        num_of_edges = 0

        for link in self.links:
            for equation in link.get_equations():
                link_equations.append([
                    pl.LpAffineExpression([(lp_variables[x], 1)
                                           for x in equation["labels"]
                                           if x != "none"]),
                    equation["constant"],
                ])

        for region in self.regions:
            num_of_edges += len(region.get_equation()) / 2

            # skips adding removed face to linear model
            if region.get_equation()[0] in self.removed_region.get_equation():
                continue

            region_equations.append([
                pl.LpAffineExpression([(lp_variables[str(x)], 1)
                                       for x in region.get_equation()]),
                len(region.get_equation()) - 2,
            ])

        prob += objective, "minimize attaching disc"

        for equation in link_equations:
            prob += equation[0] >= equation[1]

        for equation in region_equations:
            prob += equation[0] <= equation[1]

        solver = pl.CPLEX_PY(msg=0)
        prob.solve(solver)

        self.curvature = pl.value(
            prob.objective) - (len(self.attaching_disc) - 2)

        angle_labels = [x.name for x in prob.variables()]
        angles = [x.varValue for x in prob.variables()]
        self.angle_assignments = dict(zip(angle_labels, angles))
コード例 #7
0
    def estimate_energy(self):
        "Estimate minimum energy by constructing and solving a majorization problem."
        # Do nothing if the pulp module isn't available.
        if not have_pulp:
            return None

        # Convert from Ising to QUBO.
        if self.qubo:
            qubo = self
        else:
            qubo = self.convert_to_qubo()

        # Allocate all of the variables we'll need, one x per linear term and
        # one y per quadratic term.
        all_vars = set(qubo.weights.keys())
        for (q0, q1) in qubo.strengths.keys():
            all_vars.add(q0)
            all_vars.add(q1)
        x = {
            q: pulp.LpVariable("x_%d" % q,
                               cat="Continuous",
                               lowBound=0.0,
                               upBound=1.0)
            for q in all_vars
        }
        y = {(q0, q1): pulp.LpVariable("y_%d_%d" % (q0, q1),
                                       cat="Continuous",
                                       lowBound=0.0,
                                       upBound=1.0)
             for q0 in all_vars for q1 in all_vars if q0 < q1}

        # Specify the objective function.
        prob = pulp.LpProblem("major", pulp.LpMinimize)
        lterms = pulp.LpAffineExpression([(xi, qubo.weights[i])
                                          for i, xi in x.items()
                                          if qubo.weights[i] != 0.0])
        qterms = pulp.LpAffineExpression([(yij, qubo.strengths[(i, j)])
                                          for (i, j), yij in y.items()
                                          if qubo.strengths[(i, j)] != 0.0])
        prob += qubo.offset + lterms + qterms

        # Specify constraints on the (linearized) quadratic terms.
        for (i, j), cij in qubo.strengths.items():
            yij = y[(i, j)]
            if cij > 0.0:
                prob += yij >= x[i] + x[j] - 1.0
                prob += yij >= 0.0
            elif cij < 0.0:
                prob += yij <= x[i]
                prob += yij <= x[j]

        # Solve the linear program.
        if prob.solve() != pulp.LpStatusOptimal:
            return None
        return pulp.value(prob.objective)
コード例 #8
0
    def _dmu_constraint(self, j0, j1):
        """
        Calculate and return the DMU constraint for a single DMU's LP problem.

        """

        eOut = pulp.LpAffineExpression([(self.outputWeights[j0][r1],
                                         self.outputs.values[j1][r1])
                                        for r1 in self._r])
        eIn = pulp.LpAffineExpression([(self.inputWeights[j0][i1],
                                        self.inputs.values[j1][i1])
                                       for i1 in self._i])
        return eOut - eIn
コード例 #9
0
ファイル: optimize.py プロジェクト: yufei77/optimizer
def solve(AA, bb, ff, lb, ub, nn):
    vs1 = pulp.LpVariable.dicts('v', range(nn))
    vs2 = pulp.LpVariable.dicts('v', range(nn, 2 * nn))
    vs3 = pulp.LpVariable.dicts('v', range(2 * nn, 3 * nn), None, None,
                                pulp.LpInteger)
    vs4 = pulp.LpVariable.dicts('v', range(3 * nn, 4 * nn), None, None,
                                pulp.LpInteger)
    vs = {}
    vs.update(vs1)
    vs.update(vs2)
    vs.update(vs3)
    vs.update(vs4)
    for i in vs:
        vs[i].bounds(lb[i], ub[i])
    prob = pulp.LpProblem("New Problem", pulp.LpMinimize)
    obj = pulp.LpAffineExpression([(vs[i], v) for i, v in enumerate(ff) if v])
    prob += obj
    for i, rr in enumerate(AA):
        constraint = pulp.LpConstraint([(vs[i], v)
                                        for i, v in enumerate(rr) if v],
                                       pulp.LpConstraintLE, None, bb[i])
        prob += constraint
    solver = pulp.solvers.PULP_CBC_CMD()
    solver.maxSeconds = 120
    prob.setSolver(solver)
    prob.solve()
    xx = [0] * 4 * nn
    for v in prob.variables():
        s, n = v.name.split('_')
        xx[int(n)] = v.varValue
    xx = numpy.array(xx)
    solution = xx[:nn] - xx[nn:2 * nn]
    solution = numpy.round(solution * 1e9) / 1e9
    return pulp.LpStatus[prob.status], solution
コード例 #10
0
ファイル: views.py プロジェクト: ds501/Troptimal
def travel_constraint_1(prob, choices, period, attract_start, attract_end,
                        duration_matrix):
    for a1 in attract_start:
        for a2 in attract_end:
            for p in period:
                adj = get_adjacent_periods(
                    duration_matrix[int(p)][int(a1)][int(a2)],
                    p,
                    len(period),
                    add_one=True)
                if int(p) < (len(period) -
                             duration_matrix[int(p)][int(a1)][int(a2)]):
                    adj_high = [x for x in adj if int(x) > int(p)]
                    constr_dict_1 = {}
                    for time in adj_high:
                        for dest in attract_end:
                            if dest != a1 and a1 == a2:
                                constr_dict_1[choices[time][a1][dest]] = 1
                            elif dest == a2 and a1 != a2:
                                constr_dict_1[choices[time][a2][a2]] = 1
                    if len(constr_dict_1) > 0:
                        constr_dict_1[choices[p][a1][a2]] = -1
                        travel_constraint_1 = pulp.LpAffineExpression(
                            constr_dict_1)
                        prob += travel_constraint_1 >= 0
コード例 #11
0
ファイル: mip_pulp.py プロジェクト: tropicalmentat/pyschedule
 def con(self, affine, sense=0, rhs=0):
     affine = self._compress_affine(affine)
     con = pl.LpConstraint(pl.LpAffineExpression(affine),
                           sense=sense,
                           rhs=rhs)
     self.mip += con
     return con
コード例 #12
0
ファイル: core.py プロジェクト: acninetyfive/predictit
def create_problem(market):
    lp_vars = {}

    problem = pulp.LpProblem(market.name, pulp.LpMaximize)

    profit = pulp.LpVariable('profit', lowBound=0, cat='Continuous')

    problem += profit

    for c in market.contracts:
        lp_vars[market.contracts[c].name] = pulp.LpVariable(
            market.contracts[c].name, lowBound=0, cat='Integer')

    #print(lp_vars)
    for v in lp_vars:
        if v is not "profit":
            expr = pulp.LpAffineExpression(
                [(lp_vars[x], market.contracts[x].profit) if x != v else
                 (lp_vars[x], -1 * market.contracts[x].cost)
                 for x in lp_vars] + [(profit, -1)])
            c = pulp.LpConstraint(
                expr, 1)  #1 indicates the expression should be >= 0
            problem += c
            problem += lp_vars[v] * market.contracts[v].cost <= 850

    #max_profit = pulp.LpAffineExpression([(lp_vars[x], market.contracts[x].profit) for x in lp_vars])
    #max_profit += -850
    #c = pulp.LpConstraint(max_profit, -1)
    #problem += c

    return problem
コード例 #13
0
def create_formulation(f_input_data):
    input_vars = f_input_data[0]
    sites = f_input_data[1]
    budget = f_input_data[2]

    solver = pulp.solvers.COIN()

    mdl_vars = {}

    for k, v in input_vars.items():
        mdl_vars[k] = pulp.LpVariable(f"x{k}", 0, 1, cat='Integer')

    prob = pulp.LpProblem("problem", pulp.LpMinimize)

    ## Create objective to minimize total cost by adding all the things

    objective = []
    obj_list = [
        cost * mdl_vars[k] for k, w_cost in input_vars.items()
        for t_cost, cost in w_cost.items() if t_cost != "coord"
    ]
    prob += pulp.lpSum(obj_list)

    ## Create constraints to choose the constrained number of sites

    lhs = pulp.LpAffineExpression((mdl_vars[k], 1) for k in mdl_vars.keys())
    rhs = sites
    prob += (lhs >= rhs)

    ## Create budget constraints
    if budget:
        lhs = pulp.LpAffineExpression(
            (mdl_vars[k], input_vars[k]["cost"]) for k in mdl_vars.keys())
        rhs = budget
        prob += (lhs <= rhs)

    prob.writeLP("test.lp")
    status = prob.solve()

    solution = []
    for k in mdl_vars:
        value = pulp.value(mdl_vars[k])
        if value:
            solution.append(k)

    return solution
コード例 #14
0
ファイル: problema2.py プロジェクト: romanAVJ/Ido_proyectos
def TSP(T, k, names):
    # initialize ILP as a min problem
    model = pl.LpProblem(name='Optimizacion_Labiales', sense=pl.LpMinimize)

    # number of lipsticks
    n = len(T)
    N = {x for x in range(1, n + 1)}

    print('\nNúmero de productos a optimizar sus tiempos de producción: ',
          (n - 1))

    # variables
    x = pl.LpVariable.dicts('cambio_labial', ((i, j) for i in N for j in N),
                            cat='Binary')

    # objective function
    z = pl.LpAffineExpression(e=[(x[i, j], T[i - 1, j - 1]) for i, j in x],
                              constant=k,
                              name='Funcion_Objetivo')
    model += z

    # constraints
    # constraint 1: all are visited but only once
    for i in N:
        N_update = N - {i}
        model += pl.LpConstraint(
            [(x[i, j], 1) for j in N_update],
            sense=pl.LpConstraintEQ,
            rhs=1  # right side of the equality
        )

    # constraint 2: all are leaved and only once
    for j in N:
        N_update = N - {j}
        model += pl.LpConstraint(
            [(x[i, j], 1) for i in N_update],
            sense=pl.LpConstraintEQ,
            rhs=1  # right side of the equality
        )

    # subtour elimination
    # aux vars definied by Miller, Tucker and Zemlin
    u = pl.LpVariable.dict('aux_var', (i for i in N), cat='Continuous')

    N0 = N - {1}
    for (i, j) in product(N0, N0):
        if i != j:
            model += pl.LpConstraint(u[i] - u[j] + n * x[i, j],
                                     sense=pl.LpConstraintLE,
                                     rhs=n - 1)
    # solve model
    # solve
    model.solve()

    # print answer
    print_TSP(model, names, k, n)

    return ()
コード例 #15
0
ファイル: problem3.py プロジェクト: ademarazn/Agroplex
    def __init__(self):
        try:
            self.modelo = pulp.LpProblem("Maximizar o valor presente",
                                         pulp.LpMaximize)

            self.x = []  # variáveis/plantas
            self.obj = []  # função objetivo
            self.b = []  # valores base
            self.c = []  # restrições
            self.xor = []  # exclusividade
            self.c2 = [
            ]  # plantas que só podem ser cultivadas em conjunto com outra
            self.ler()  # ler os dados

            print(" Resolvendo...", end="")

            self.modelo.setObjective(pulp.LpAffineExpression(self.obj))

            self.modelo += pulp.LpAffineExpression(self.c[0]) <= self.b[0]
            self.modelo += pulp.LpAffineExpression(self.c[1]) <= self.b[1]
            self.modelo += pulp.LpAffineExpression(self.c[2]) >= self.b[2]
            self.modelo += pulp.LpAffineExpression(self.c[3]) >= self.b[3]
            for i in range(len(self.xor)):
                self.modelo += pulp.LpAffineExpression(self.xor[i]) <= 1
            for i in range(len(self.c2)):
                self.modelo += pulp.LpAffineExpression(self.c2[i]) >= 0
            self.modelo.solve()
            # print(self.modelo)
            if self.modelo.status.__eq__(
                    pulp.LpStatusOptimal):  # Modelo resolvido com sucesso
                print("\n\n Deve cultivar", end=" ")
                for i in range(len(self.x)):
                    if self.x[i].varValue == 1:
                        print(self.x[i].name, end=", ")
                print("e terá um valor presente de ${}.".format(
                    pulp.value(self.modelo.objective)),
                      end="")
            elif self.modelo.status.__eq__(
                    pulp.LpStatusNotSolved):  # Falha ao solucionar
                print("\n\n Modelo não solucionado.", end=" ")
            elif self.modelo.status.__eq__(
                    pulp.LpStatusInfeasible):  # Falha ao solucionar
                print(
                    "\n\n Falha ao solucionar. O problema parece ser inviável.",
                    end=" ")
            elif self.modelo.status.__eq__(
                    pulp.LpStatusUnbounded):  # Falha ao solucionar
                print(
                    "\n\n Falha ao solucionar. O problema parece ser ilimitado.",
                    end=" ")
            elif self.modelo.status.__eq__(
                    pulp.LpStatusUndefined):  # Falha ao solucionar
                print(
                    "\n\n Falha ao solucionar. O problema parece ser indefinido.",
                    end=" ")
        except ValueError:
            print(end='')
        except KeyboardInterrupt:
            print('\n\n Finalizando...', end='\n')
            sys.exit(0)
コード例 #16
0
ファイル: dea.py プロジェクト: Daddeee/VR_DEA
    def solve(self):
        status = {}
        efficiency = {}

        for i in self._n:
            dp0 = pulp.LpProblem("dp0_DMU_" + str(i), pulp.LpMinimize)
            
            theta = pulp.LpVariable("theta")
            lambdas = pulp.LpVariable.dicts("lambda", self._n, lowBound=0)
            sminus = pulp.LpVariable.dicts("sminus", self._m, lowBound=0)
            splus = pulp.LpVariable.dicts("splus", self._s, lowBound=0)
            
            dp0 += theta

            for m in self._m:
                dp0 += theta*self.inputs[i][m] - pulp.LpAffineExpression([(lambdas[j], self.inputs[j][m]) for j in self._n]) - sminus[m] == 0
                
            for s in self._s:
                dp0 += pulp.LpAffineExpression([(lambdas[j], self.outputs[j][s]) for j in self._n]) - self.outputs[i][s] - splus[s] == 0

            dp0.solve()

            thetaopt = pulp.value(dp0.objective)

            dp1 = pulp.LpProblem("dp1_DMU_" + str(i), pulp.LpMaximize)
            
            lambdas = pulp.LpVariable.dicts("lambda", self._n, lowBound=0)
            sminus = pulp.LpVariable.dicts("sminus", self._m, lowBound=0)
            splus = pulp.LpVariable.dicts("splus", self._s, lowBound=0)
            
            dp1 += pulp.LpAffineExpression([(sminus[m], 1) for m in self._m] + [(splus[s], 1) for s in self._s])
            for m in self._m:
                dp1 += thetaopt*self.inputs[i][m] - pulp.LpAffineExpression([(lambdas[j], self.inputs[j][m]) for j in self._n] + [(sminus[m], -1)])  == 0
            for s in self._s:
                dp1 += pulp.LpAffineExpression([(lambdas[j], self.outputs[j][s]) for j in self._n]) + [(splus[s], -1)] - self.outputs[i][s] == 0
            
            dp1.solve()

            status[i] = pulp.LpStatus[dp1.status]
            
            efficiency[i] = thetaopt


        return status, efficiency
コード例 #17
0
ファイル: util.py プロジェクト: hanqiu92/dual_simplex_solve
def solve_pulp(A_dict,
               b_dict,
               sense_dict,
               c_dict,
               l_dict,
               u_dict,
               m,
               n,
               msg=0):
    solver = PULP_CBC_CMD(msg=msg)
    model = pulp.LpProblem("test", pulp.LpMinimize)
    model.solver = solver

    A_by_row = dict([(j, dict()) for j in range(n)])
    for key, value in A_dict.items():
        A_by_row[key[0]][key[1]] = value

    x_pulp = dict([(i,
                    pulp.LpVariable(str(i),
                                    lowBound=l_dict.get(i, 0),
                                    upBound=u_dict.get(i, INF)))
                   for i in range(m)])
    cons_pulp = dict()
    for j in range(n):
        cons_pulp[j] = pulp.LpConstraint(pulp.LpAffineExpression(
            [(x_pulp[i], value) for i, value in A_by_row[j].items()],
            constant=-b_dict.get(j, 0)),
                                         sense=sense_dict.get(j, 0))
        model += cons_pulp[j]
    model.objective = pulp.LpAffineExpression([
        (x_pulp[key], value) for key, value in c_dict.items()
    ])
    model.solve()

    x = np.zeros((m, ))
    for i in range(m):
        x[i] = x_pulp[i].value()
    x[np.isnan(x)] = 0
    lam = np.zeros((n, ))
    for j in range(n):
        lam[j] = cons_pulp[j].pi
    lam[np.isnan(lam)] = 0
    return x, lam, model.status
コード例 #18
0
ファイル: matching.py プロジェクト: Skxu3/SEC-Webscraping
def getOptMatches(probDist):
    fourAIDs = list(probDist.keys())
    fourIDs = list(probDist[fourAIDs[0]].keys())
    n, m = len(fourAIDs), len(fourIDs)
    allVars, variables = [], []
    for i in range(n):
        x = [str(i) + '|' + str(j) for j in range(m)]
        variables.append(x)

    lp = pulp.LpProblem("max weighted matching", pulp.LpMaximize)
    lstVars = []
    for j in range(len(variables)):
        a = [pulp.LpVariable(variables[j][i], lowBound = 0, upBound = 1, cat='Integer') for i in range(len(variables[j]))]
        lstVars.append(a)
        allVars += a
        
    objFunc, varWeightMap = [], {}
    for var in allVars:
        varName = var.name.split('|')
        fourAID, fourID = fourAIDs[int(varName[0])], fourIDs[int(varName[1])]
        objFunc += [(var, probDist[fourAID][fourID])] 
        varWeightMap[var.name] = probDist[fourAID][fourID]
    objFunc = pulp.LpAffineExpression(objFunc)
    lp += objFunc

    for j in range(len(lstVars)):
        cons = [(var, 1) for var in lstVars[j]]
        lp += pulp.LpAffineExpression(cons) <= 1 #constraints
    lp.solve()
    # for variable in lp.variables(): # if want to see weights
    #     print("{} = {}".format(variable.name, variable.varValue))
    
    chosenVars = [(var.name, varWeightMap[var.name]) for var in lp.variables() if var.varValue == 1]
    chosenVars = sorted(chosenVars, key=lambda tup: tup[1], reverse=True) #sort by prob of matching
    
    allMatches, unmatched = [], []
    for i in range(n): #only top m matches
        chosenName = chosenVars[i][0].split('|')
        if i < m:
            allMatches.append((fourAIDs[int(chosenName[0])], fourIDs[int(chosenName[1])]))
        else:
            unmatched.append(fourAIDs[int(chosenName[0])])
    return allMatches, unmatched
コード例 #19
0
def _add_constraints_for_captain_must_be_on_team(
    problem: pulp.LpProblem,
    players: List[structures.Player],
    positions: List[structures.Position],
    squads: List[structures.Squad],
    player_vars: PlayerVarMap,
    captain_vars: CaptainVarMap,
) -> None:
    for p in players:
        problem.addConstraint(
            pulp.LpConstraint(
                pulp.lpSum([
                    pulp.LpAffineExpression({
                        player_vars[squad][pos][p]: 1
                        for squad in squads for pos in positions
                    }),
                    pulp.LpAffineExpression({captain_vars[p]: -1})
                ]), pulp.LpConstraintGE,
                '{} can only be captain if also in the team'.format(p.name)))
コード例 #20
0
def _get_problem_with_objective(
    positions: List[structures.Position],
    squads: List[structures.Squad],
    player_vars: PlayerVarMap,
    captain_vars: CaptainVarMap,
) -> pulp.LpProblem:
    problem = pulp.LpProblem('afl_dream_team', pulp.LpMaximize)
    objective = pulp.lpSum([
        pulp.LpAffineExpression({
            var: var.objective_coef
            for squad in squads for pos in positions
            for var in player_vars[squad][pos].values()
        }),
        pulp.LpAffineExpression(
            {var: var.objective_coef
             for var in captain_vars.values()})
    ])
    problem.setObjective(objective)
    return problem
コード例 #21
0
ファイル: views.py プロジェクト: ds501/Troptimal
def add_objective(prob, choices, period, attract_start, attract_end,
                  desirability_matrix):
    obj_dict = dict()
    for p in period:
        for a1 in attract_start:
            for a2 in attract_end:
                obj_dict[choices[p][a1][a2]] = desirability_matrix[int(p)][int(
                    a1)][int(a2)]
    obj = pulp.LpAffineExpression(obj_dict)
    prob += obj
コード例 #22
0
ファイル: model.py プロジェクト: summer-yue/nycTaxiAnalysis
def solveModel(capacity, timeVect, revenueVect):
    """Linear Optimization Model for NYC taxi rides selection.
    Params: @capacity: number of taxis the company owns
    		@timeVect: binary 2D matrix with row representing each ride and column being time
    		@revenueVect: Vector on revenue on each ride, ordering same as timeVect
    """
    print("Solving model for " + str(capacity))

    timeSectionNum = timeVect.shape[1]
    model = pulp.LpProblem("Profit maximizing problem", pulp.LpMaximize)

    tripNum = numpy.size(revenueVect)
    RANGE = range(tripNum)
    assignment = pulp.LpVariable.dicts('assignment', RANGE, cat='Binary')

    #Maximize revenue, set objective
    totalRev = 0
    for j in range(tripNum):
        totalRev += assignment[j] * revenueVect[j][0]
    model += totalRev

    time = []
    #print "Time Vect: ", timeVect
    for i in xrange(timeSectionNum):
        time.append(
            pulp.LpAffineExpression([(assignment[j], timeVect[j][i])
                                     for j in range(tripNum)]))

    print('time')
    print(time)
    #Setting time constraint
    for temp in xrange(timeSectionNum):
        timeVal = time[temp]
        # print('timeVal')
        # print(timeVal)
        # print('capacity')
        # print(capacity)

        print(timeVal <= capacity)
        model += pulp.LpConstraint(e=timeVal,
                                   sense=-1,
                                   name=str(temp) + "time_constraint",
                                   rhs=capacity)
    print "Objective was: ", model
    optimization_result = model.solve()
    # print('Objective becomes')
    # print pulp.value(model.objective)
    # print('optimization_result')
    # print(optimization_result)
    # print(time)
    with open("result.csv", "wb") as out:
        writer = csv.writer(out)
        for i in xrange(tripNum):
            print(assignment[i].value())
            writer.writerow(assignment[i].value())
コード例 #23
0
ファイル: mip_pulp.py プロジェクト: samuelchen2015/pyschedule
 def con(self, affine, sense=0, rhs=0):
     # sum up (pulp doesnt do this)
     affine_ = {a: 0 for a, b in affine}
     for a, b in affine:
         affine_[a] += b
     affine = [(a, affine_[a]) for a in affine_]
     con = pl.LpConstraint(pl.LpAffineExpression(affine),
                           sense=sense,
                           rhs=rhs)
     self.mip += con
     return con
コード例 #24
0
    def _make_problem(self, j0):
        """
        Create a pulp.LpProblem for a DMU.

        """

        # Set up pulp
        prob = pulp.LpProblem("".join(["DMU_", str(j0)]), pulp.LpMaximize)
        self.inputWeights = pulp.LpVariable.dicts("inputWeight",
                                                  (self._j, self._i),
                                                  lowBound=self._in_weights[0],
                                                  upBound=self._in_weights[1])
        self.outputWeights = pulp.LpVariable.dicts(
            "outputWeight", (self._j, self._r),
            lowBound=self._out_weights[0],
            upBound=self._out_weights[1])

        # Set returns to scale
        if self.returns == "CRS":
            w = 0
        elif self.returns == "VRS":
            w = pulp.LpVariable.dicts("w", (self._j, self._r))
        else:
            raise Exception(ValueError)

        # Set up objective function
        prob += pulp.LpAffineExpression(
            [(self.outputWeights[j0][r1], self.outputs.values[j0][r1])
             for r1 in self._r]) - w

        # Set up constraints
        prob += pulp.LpAffineExpression([
            (self.inputWeights[j0][i1], self.inputs.values[j0][i1])
            for i1 in self._i
        ]) == 1, "Norm_constraint"
        for j1 in self._j:
            prob += self._dmu_constraint(j0, j1) - \
                w <= 0, "".join(["DMU_constraint_", str(j1)])
        return prob
コード例 #25
0
def _add_constraint_for_only_one_captain(
    problem: pulp.LpProblem,
    players: List[structures.Player],
    captain_vars: CaptainVarMap,
) -> None:
    problem.addConstraint(
        pulp.LpConstraint(
            pulp.LpAffineExpression({captain_vars[p]: 1
                                     for p in players}),
            pulp.LpConstraintLE,
            'There can only be one captain selected',
            1,
        ))
コード例 #26
0
def get_solve(data):
    x = []
    for i in range(data.get('num_caches')):
        x.append([])
        for j in range(data.get('num_videos')):
            x[i].append(pulp.LpVariable('x{}{}'.format(i, j), 0, 1))

    prob = pulp.LpProblem('problem', pulp.LpMaximize)
    video_sizes = data.get('video_sizes')
    cache_sizes = data.get('cache_size')
    dc_latency = data.get('data_center_latency')
    latency = data.get('endpoint_cache_latency')
    reqs = data.get('endpoint_video_requests')
    n_caches = data.get('num_caches')
    n_endpoints = data.get('num_endpoints')
    n_videos = data.get('num_videos')

    for i in range(data.get('num_caches')):
        condition = pulp.lpSum(
            [x[i][j] * video_sizes[j] for j in range(data.get('num_videos'))])
        prob += condition <= cache_sizes, 'Sizes for {} cache'.format(i)

    aim = []
    from math import pow
    for e in range(data.get('num_endpoints')):
        for v in range(data.get('num_videos')):
            # cache_lat = latency[e][c] or dc_latency[e]
            # for c in range(data.get('num_caches')):
            # print(reqs[e][v])
            dob = reqs[e][v]
            # print(pow(dob, 1 / n_caches))
            # print(dob)

            d = pulp.LpAffineExpression([
                (x[c][v],
                 dob * (dc_latency[e] - (latency[e][c] or dc_latency[e])))
                for c in range(n_caches)
            ])
            aim.append(d)
    prob += pulp.lpSum(aim)
    print(12312312312, prob)

    status = prob.solve(pulp.GLPK(msg=0))
    print(pulp.LpStatus[status])
    res = []
    for i in range(data.get('num_caches')):
        res.append([])
        for j in range(data.get('num_videos')):
            res[i].append(pulp.value(x[i][j]))
    results = np.array(res)
    return results
コード例 #27
0
ファイル: automatch.py プロジェクト: incnone/condor_ratings
def get_matchups(
        elos: Dict[str, float],
        banned_matches: Set[Matchup],
        num_matches: int = NUM_AUTOGENS
) -> Set[Matchup]:
    ilp_prob = pulp.LpProblem('matchup_problem', pulp.LpMaximize)

    # Make variables
    all_players = list(elos.keys())
    matchups = dict()   # type: Dict[str, Dict[str, pulp.LpVariable]]
    for p_idx in range(len(all_players)):
        p1_name = all_players[p_idx]
        matchups[p1_name] = dict()
        for q_idx in range(p_idx + 1, len(all_players)):
            p2_name = all_players[q_idx]
            if Matchup(p1_name, p2_name) not in banned_matches:
                matchups[p1_name][p2_name] = pulp.LpVariable(
                    "matchup_{0}_{1}".format(p1_name, p2_name), 0, 1, pulp.LpInteger
                )

    # Add entropy value of each matchup
    matchup_utility = dict()
    for player in matchups:
        for opp in matchups[player]:
            matchup_utility[matchups[player][opp]] = get_utility(elos[player], elos[opp])

    # Set optimization objective
    ilp_prob.setObjective(pulp.LpAffineExpression(matchup_utility, name="matchup_utility"))

    # Make constraints
    for player in matchups:
        edges_from_player = [matchups[player][opp] for opp in matchups[player]]
        for otherplayer in matchups:
            if player in matchups[otherplayer]:
                edges_from_player.append(matchups[otherplayer][player])

        if player in SPECIAL_NUM_AUTOGENS:
            ilp_prob += pulp.lpSum(edges_from_player) == SPECIAL_NUM_AUTOGENS[player], ""
        else:
            ilp_prob += pulp.lpSum(edges_from_player) == num_matches, ""

    # Solve problem
    ilp_prob.solve(pulp.PULP_CBC_CMD(maxSeconds=20, msg=0, fracGap=0.001))
    print("Status:", pulp.LpStatus[ilp_prob.status])
    created_matches = set()
    for player in matchups:
        for opp in matchups[player]:
            if pulp.value(matchups[player][opp]) == 1:
                created_matches.add(Matchup(player, opp,))
    return created_matches
コード例 #28
0
ファイル: views.py プロジェクト: ds501/Troptimal
def contiguity_constraint(prob, choices, period, attract_start, attract_end,
                          duration_matrix):
    for a1 in attract_start:
        for a2 in attract_end:
            for p in period:
                adj = get_adjacent_periods(
                    duration_matrix[int(p)][int(a1)][int(a2)], p, len(period))
                constr_dict = {}
                for item in adj:
                    constr_dict[choices[item][a1][a2]] = 1
                constr_dict[choices[p][a1][a2]] = constr_dict[choices[p][a1][
                    a2]] - duration_matrix[int(p)][int(a1)][int(a2)]
                duration_constraint = pulp.LpAffineExpression(constr_dict)
                prob += duration_constraint >= 0
コード例 #29
0
ファイル: lp_picker.py プロジェクト: mnalpert/nfl_survivor
    def _max_probability_objective(self):
        """ LP objective for maximizing probability of winning all weeks in season

        Returns
        -------
        pulp.LpAffineExpression

        """
        logger.info('Adding objective to maximize win probability')
        wt_to_lp_var = self._week_team_to_lp_variable

        return pulp.LpAffineExpression(e=((wt_to_lp_var[week.week_number, team],
                                           np.log(game.win_probability(team)))
                                          for week in self.season
                                          for game in week
                                          for team in game))
コード例 #30
0
def _add_constraint_for_salary_cap(
    problem: pulp.LpProblem,
    players: List[structures.Player],
    positions: List[structures.Position],
    squads: List[structures.Squad],
    player_vars: PlayerVarMap,
    salary_cap: float,
) -> None:
    problem.addConstraint(
        pulp.LpConstraint(
            pulp.LpAffineExpression({
                player_vars[squad][pos][p]: p.price
                for squad in squads for pos in positions for p in players
            }), pulp.LpConstraintLE,
            'Total cost of all players in team must not exceed the salary cap',
            salary_cap))