Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create_mip(solver, J, dur, S, c, r, EST, relax=False, sense=MINIMIZE):
"""Creates a mip model to solve the RCPSP"""
NR = len(c)
mip = Model(solver_name=solver)
sd = sum(dur[j] for j in J)
vt = CONTINUOUS if relax else BINARY
x = [
{
t: mip.add_var("x(%d,%d)" % (j, t), var_type=vt)
for t in range(EST[j], sd + 1)
}
for j in J
]
TJ = [set(x[j].keys()) for j in J]
T = set()
for j in J:
T = T.union(TJ[j])
if sense == MINIMIZE:
mip.objective = minimize(xsum(t * x[J[-1]][t] for t in TJ[-1]))
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Simple column generation implementation for a Cutting Stock Problem
"""
from mip import Model, xsum, Column, CONTINUOUS, INTEGER
L = 250 # bar length
m = 4 # number of requests
w = [187, 119, 74, 90] # size of each item
b = [1, 2, 2, 1] # demand for each item
# creating master model
master = Model()
# creating an initial set of patterns which cut one item per bar
# to provide the restricted master problem with a feasible solution
lambdas = [master.add_var(obj=1, name='lambda_%d' % (j + 1))
for j in range(m)]
# creating constraints
constraints = []
for i in range(m):
constraints.append(master.add_constr(lambdas[i] >= b[i], name='i_%d' % (i + 1)))
# creating the pricing problem
pricing = Model()
# creating pricing variables
a = [pricing.add_var(obj=0, var_type=INTEGER, name='a_%d' % (i + 1)) for i in range(m)]
(40.37, 14.23),
(37.57, 22.56),
]
# latitude and longitude
coord = [(rad(x), rad(y)) for (x, y) in coord]
# distances in an upper triangular matrix
# number of nodes and list of vertices
n, V = len(coord), set(range(len(coord)))
# distances matrix
c = [[0 if i == j else dist(coord[i], coord[j]) for j in V] for i in V]
model = Model()
# binary variables indicating if arc (i,j) is used on the route or not
x = [[model.add_var(var_type=BINARY) for j in V] for i in V]
# continuous variable to prevent subtours: each city will have a
# different sequential id in the planned route except the first one
y = [model.add_var() for i in V]
# objective function: minimize the distance
model.objective = minimize(xsum(c[i][j] * x[i][j] for i in V for j in V))
# constraint : leave each city only once
for i in V:
model += xsum(x[i][j] for j in V - {i}) == 1
# constraint : enter each city only once
"""
from os.path import basename
from itertools import product
from sys import argv
from time import time
import bmcp_data
from mip import Model, xsum, minimize, MINIMIZE, BINARY
data = bmcp_data.read(argv[1])
ncol = int(argv[3])
N, r, d = data.N, data.r, data.d
U = list(range(ncol))
st = time()
m = Model(solver_name=argv[2])
x = [
[m.add_var("x({},{})".format(i, c), var_type=BINARY) for c in U] for i in N
]
z = m.add_var("z")
m.objective = minimize(z)
for i in N:
m += xsum(x[i][c] for c in U) == r[i]
for i, j, c1, c2 in product(N, N, U, U):
if i != j and c1 <= c2 < c1 + d[i][j]:
m += x[i][c1] + x[j][c2] <= 1
for i, c1, c2 in product(N, U, U):
from itertools import product
from networkx import minimum_cut, DiGraph
from mip import Model, xsum, BINARY, OptimizationStatus, CutType
N = ["a", "b", "c", "d", "e", "f", "g"]
A = { ("a", "d"): 56, ("d", "a"): 67, ("a", "b"): 49, ("b", "a"): 50,
("f", "c"): 35, ("g", "b"): 35, ("g", "b"): 35, ("b", "g"): 25,
("a", "c"): 80, ("c", "a"): 99, ("e", "f"): 20, ("f", "e"): 20,
("g", "e"): 38, ("e", "g"): 49, ("g", "f"): 37, ("f", "g"): 32,
("b", "e"): 21, ("e", "b"): 30, ("a", "g"): 47, ("g", "a"): 68,
("d", "c"): 37, ("c", "d"): 52, ("d", "e"): 15, ("e", "d"): 20,
("d", "b"): 39, ("b", "d"): 37, ("c", "f"): 35, }
Aout = {n: [a for a in A if a[0] == n] for n in N}
Ain = {n: [a for a in A if a[1] == n] for n in N}
m = Model()
x = {a: m.add_var(name="x({},{})".format(a[0], a[1]), var_type=BINARY) for a in A}
m.objective = xsum(c * x[a] for a, c in A.items())
for n in N:
m += xsum(x[a] for a in Aout[n]) == 1, "out({})".format(n)
m += xsum(x[a] for a in Ain[n]) == 1, "in({})".format(n)
newConstraints = True
while newConstraints:
m.optimize(relax=True)
print("status: {} objective value : {}".format(m.status, m.objective_value))
G = DiGraph()
for a in A:
[117, 65, 125, 43],
[54, 22, 84],
[60, 44],
[97],
[]]
# nr. de pontos e conjunto de pontos
n, V = len(dists), set(range(len(dists)))
# matriz com tempos
c = [[0 if i == j
else dists[i][j-i-1] if j > i
else dists[j][i-j-1]
for j in V] for i in V]
model = Model()
# variáveis 0/1 indicando se um arco (i,j) participa da rota ou não
x = [[model.add_var(var_type=BINARY, name='x(%d,%d)' % (i, j)) for j in V] for i in V]
# função objetivo: minimizar tempo
model.objective = minimize(xsum(c[i][j]*x[i][j] for i in V for j in V))
# restrição: selecionar arco de saÃda da cidade
for i in V:
model += xsum(x[i][j] for j in V - {i}) == 1
# restrição: selecionar arco de entrada na cidade
for i in V:
model += xsum(x[j][i] for j in V - {i}) == 1
# chamada da otimização com limite tempo de 30 segundos
plt.scatter((p[0]), (p[1]), marker="^", color="purple", s=50)
plt.text((p[0]), (p[1]), "$f_%d$" % i)
# plotting location of clients
for i, p in pc.items():
plt.scatter((p[0]), (p[1]), marker="o", color="black", s=15)
plt.text((p[0]), (p[1]), "$c_{%d}$" % i)
plt.text((20), (78), "Region 1")
plt.text((70), (78), "Region 2")
plt.plot((50, 50), (0, 80))
dist = {(f, c): round(sqrt((pf[f][0] - pc[c][0]) ** 2 + (pf[f][1] - pc[c][1]) ** 2), 1)
for (f, c) in product(F, C) }
m = Model()
z = {i: m.add_var(ub=c[i]) for i in F} # plant capacity
# Type 1 SOS: only one plant per region
for r in [0, 1]:
# set of plants in region r
Fr = [i for i in F if r * 50 <= pf[i][0] <= 50 + r * 50]
m.add_sos([(z[i], i - 1) for i in Fr], 1)
# amount that plant i will supply to client j
x = {(i, j): m.add_var() for (i, j) in product(F, C)}
# satisfy demand
for j in C:
m += xsum(x[(i, j)] for i in F) == d[j]
[117, 65, 125, 43],
[54, 22, 84],
[60, 44],
[97],
[]]
# number of nodes and list of vertices
n, V = len(dists), range(len(dists))
# distances matrix
c = [[0 if i == j
else dists[i][j-i-1] if j > i
else dists[j][i-j-1]
for j in V] for i in V]
model = Model()
# binary variables indicating if arc (i,j) is used on the route or not
x = [[model.add_var(var_type=BINARY) for j in V] for i in V]
# continuous variable to prevent subtours: each city will have a
# different sequential id in the planned route except the first one
y = [model.add_var() for i in V]
# objective function: minimize the distance
model.objective = minimize(xsum(c[i][j]*x[i][j] for i in V for j in V))
# constraint : leave each city only once
for i in V:
model += xsum(x[i][j] for j in set(V) - {i}) == 1
# constraint : enter each city only once
"""
from itertools import product
from sys import argv
from time import time
import bmcp_data
import bmcp_greedy
from mip import Model, xsum, minimize, MINIMIZE, BINARY
data = bmcp_data.read(argv[1])
N, r, d = data.N, data.r, data.d
S = bmcp_greedy.build(data)
C, U = S.C, [i for i in range(S.u_max+1)]
st = time()
m = Model()
x = [[m.add_var('x({},{})'.format(i, c), var_type=BINARY)
for c in U] for i in N]
z = m.add_var('z')
m.objective = minimize(z)
for i in N:
m += xsum(x[i][c] for c in U) == r[i]
for i, j, c1, c2 in product(N, N, U, U):
if i != j and c1 <= c2 < c1+d[i][j]:
m += x[i][c1] + x[j][c2] <= 1
for i, c1, c2 in product(N, U, U):
if c1 < c2 < c1+d[i][i]:
"""Example of a solver to the n-queens problem: n chess queens should be
placed in a n x n chess board so that no queen can attack another, i.e., just
one queen per line, column and diagonal. """
from sys import stdout
from mip import Model, xsum, BINARY
# number of queens
n = 40
queens = Model()
x = [[queens.add_var('x({},{})'.format(i, j), var_type=BINARY)
for j in range(n)] for i in range(n)]
# one per row
for i in range(n):
queens += xsum(x[i][j] for j in range(n)) == 1, 'row({})'.format(i)
# one per column
for j in range(n):
queens += xsum(x[i][j] for i in range(n)) == 1, 'col({})'.format(j)
# diagonal \
for p, k in enumerate(range(2 - n, n - 2 + 1)):
queens += xsum(x[i][i - k] for i in range(n)
if 0 <= i - k < n) <= 1, 'diag1({})'.format(p)