INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
kcenter -- minimize the maximum travel cost from customers to k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, ready to be solved. | def kcenter(I,J,c,k):
"""kcenter -- minimize the maximum travel cost from customers to k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model,... |
prints results | def printFunc(name,m):
"""prints results"""
print("* %s *" % name)
objSet = bool(m.getObjective().terms.keys())
print("* Is objective set? %s" % objSet)
if objSet:
print("* Sense: %s" % m.getObjectiveSense())
for v in m.getVars():
if v.name != "n":
print("%s: %d" % (v... |
diet -- model for the modern diet problem
Parameters:
F - set of foods
N - set of nutrients
a[i] - minimum intake of nutrient i
b[i] - maximum intake of nutrient i
c[j] - cost of food j
d[j][i] - amount of nutrient i in food j
Returns a model, ready to be solved. | def diet(F,N,a,b,c,d):
"""diet -- model for the modern diet problem
Parameters:
F - set of foods
N - set of nutrients
a[i] - minimum intake of nutrient i
b[i] - maximum intake of nutrient i
c[j] - cost of food j
d[j][i] - amount of nutrient i in food j
Returns... |
mkp -- model for solving the multi-constrained knapsack
Parameters:
- I: set of dimensions
- J: set of items
- v[j]: value of item j
- a[i,j]: weight of item j on dimension i
- b[i]: capacity of knapsack on dimension i
Returns a model, ready to be solved. | def mkp(I,J,v,a,b):
"""mkp -- model for solving the multi-constrained knapsack
Parameters:
- I: set of dimensions
- J: set of items
- v[j]: value of item j
- a[i,j]: weight of item j on dimension i
- b[i]: capacity of knapsack on dimension i
Returns a model, ready to ... |
creates example data set | def example():
"""creates example data set"""
J,v = multidict({1:16, 2:19, 3:23, 4:28})
a = {(1,1):2, (1,2):3, (1,3):4, (1,4):5,
(2,1):3000, (2,2):3500, (2,3):5100, (2,4):7200,
}
I,b = multidict({1:7, 2:10000})
return I,J,v,a,b |
eoq -- multi-item capacitated economic ordering quantity model
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- W: capacity (limit on order quantity)
- a0... | def eoq(I,F,h,d,w,W,a0,aK,K):
"""eoq -- multi-item capacitated economic ordering quantity model
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- W: capacity (... |
scheduling_linear_ordering: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the linear ordering formulation
Parameters:
- J: set of jobs
- p[j]: processing time of job j
- d[j]: latest non-tardy time for jo... | def scheduling_linear_ordering(J,p,d,w):
"""
scheduling_linear_ordering: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the linear ordering formulation
Parameters:
- J: set of jobs
- p[j]: processing time ... |
scheduling_time_index: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the time index formulation
Parameters:
- J: set of jobs
- p[j]: processing time of job j
- r[j]: earliest start time of job j
-... | def scheduling_time_index(J,p,r,w):
"""
scheduling_time_index: model for the one machine total weighted tardiness problem
Model for the one machine total weighted tardiness problem
using the time index formulation
Parameters:
- J: set of jobs
- p[j]: processing time of job j
... |
scheduling_disjunctive: model for the one machine total weighted completion time problem
Disjunctive optimization model for the one machine total weighted
completion time problem with release times.
Parameters:
- J: set of jobs
- p[j]: processing time of job j
- r[j]: earliest star... | def scheduling_disjunctive(J,p,r,w):
"""
scheduling_disjunctive: model for the one machine total weighted completion time problem
Disjunctive optimization model for the one machine total weighted
completion time problem with release times.
Parameters:
- J: set of jobs
- p[j]: proce... |
scheduling_cutting_plane: heuristic to one machine weighted completion time based on cutting planes
Use a cutting-plane method as a heuristics for solving the
one-machine total weighted completion time problem with release
times.
Parameters:
- J: set of jobs
- p[j]: processing time of ... | def scheduling_cutting_plane(J,p,r,w):
"""
scheduling_cutting_plane: heuristic to one machine weighted completion time based on cutting planes
Use a cutting-plane method as a heuristics for solving the
one-machine total weighted completion time problem with release
times.
Parameters:
-... |
Data generator for the one machine scheduling problem. | def make_data(n):
"""
Data generator for the one machine scheduling problem.
"""
p,r,d,w = {},{},{},{}
J = range(1,n+1)
for j in J:
p[j] = random.randint(1,4)
w[j] = random.randint(1,3)
T = sum(p)
for j in J:
r[j] = random.randint(0,5)
d[j] = r[j] + ran... |
Data generator for the one machine scheduling problem. | def example(n):
"""
Data generator for the one machine scheduling problem.
"""
J,p,r,d,w = multidict({
1:[1,4,0,3],
2:[4,0,0,1],
3:[2,2,0,2],
4:[3,4,0,3],
5:[1,1,0,1],
6:[4,5,0,2],
})
return J,p,r,d,w |
solve_vrp -- solve the vehicle routing problem.
- start with assignment model (depot has a special status)
- add cuts until all components of the graph are connected
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
- m: number of vehicles... | def vrp(V, c, m, q, Q):
"""solve_vrp -- solve the vehicle routing problem.
- start with assignment model (depot has a special status)
- add cuts until all components of the graph are connected
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
... |
make_data: compute matrix distance based on euclidean distance | def make_data(n):
"""make_data: compute matrix distance based on euclidean distance"""
V = range(1,n+1)
x = dict([(i, random.random()) for i in V])
y = dict([(i, random.random()) for i in V])
c, q = {}, {}
Q = 100
for i in V:
q[i] = random.randint(10, 20)
for j in V:
... |
add cuts if necessary and return whether model is feasible | def addCuts(self, checkonly):
"""add cuts if necessary and return whether model is feasible"""
cutsadded = False
edges = []
x = self.model.data
for (i, j) in x:
if self.model.getVal(x[i, j]) > .5:
if i != V[0] and j != V[0]:
edges.a... |
weber: model for solving the single source weber problem using soco.
Parameters:
- I: set of customers
- x[i]: x position of customer i
- y[i]: y position of customer i
- w[i]: weight of customer i
Returns a model, ready to be solved. | def weber(I,x,y,w):
"""weber: model for solving the single source weber problem using soco.
Parameters:
- I: set of customers
- x[i]: x position of customer i
- y[i]: y position of customer i
- w[i]: weight of customer i
Returns a model, ready to be solved.
"""
model... |
creates example data set | def make_data(n,m):
"""creates example data set"""
I = range(1,n+1)
J = range(1,m+1)
x,y,w = {},{},{}
for i in I:
x[i] = random.randint(0,100)
y[i] = random.randint(0,100)
w[i] = random.randint(1,5)
return I,J,x,y,w |
weber -- model for solving the weber problem using soco (multiple source version).
Parameters:
- I: set of customers
- J: set of potential facilities
- x[i]: x position of customer i
- y[i]: y position of customer i
- w[i]: weight of customer i
Returns a model, ready to b... | def weber_MS(I,J,x,y,w):
"""weber -- model for solving the weber problem using soco (multiple source version).
Parameters:
- I: set of customers
- J: set of potential facilities
- x[i]: x position of customer i
- y[i]: y position of customer i
- w[i]: weight of customer i... |
markowitz -- simple markowitz model for portfolio optimization.
Parameters:
- I: set of items
- sigma[i]: standard deviation of item i
- r[i]: revenue of item i
- alpha: acceptance threshold
Returns a model, ready to be solved. | def markowitz(I,sigma,r,alpha):
"""markowitz -- simple markowitz model for portfolio optimization.
Parameters:
- I: set of items
- sigma[i]: standard deviation of item i
- r[i]: revenue of item i
- alpha: acceptance threshold
Returns a model, ready to be solved.
"""
m... |
tsp -- model for solving the traveling salesman problem with callbacks
- start with assignment model
- add cuts until there are no sub-cycles
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
Returns the optimum objective value and the list of... | def tsp(V,c):
"""tsp -- model for solving the traveling salesman problem with callbacks
- start with assignment model
- add cuts until there are no sub-cycles
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
Returns the optimum objective ... |
phi_inv: inverse of gaussian (normal) CDF
Source:
Handbook of Mathematical Functions
Dover Books on Mathematics
Milton Abramowitz and Irene A. Stegun (Editors)
Formula 26.2.23. | def phi_inv(p):
"""phi_inv: inverse of gaussian (normal) CDF
Source:
Handbook of Mathematical Functions
Dover Books on Mathematics
Milton Abramowitz and Irene A. Stegun (Editors)
Formula 26.2.23.
"""
if p < 0.5:
t = math.sqrt(-2.0*math.log(p))
return (... |
p_portfolio -- modified markowitz model for portfolio optimization.
Parameters:
- I: set of items
- sigma[i]: standard deviation of item i
- r[i]: revenue of item i
- alpha: acceptance threshold
- beta: desired confidence level
Returns a model, ready to be solved. | def p_portfolio(I,sigma,r,alpha,beta):
"""p_portfolio -- modified markowitz model for portfolio optimization.
Parameters:
- I: set of items
- sigma[i]: standard deviation of item i
- r[i]: revenue of item i
- alpha: acceptance threshold
- beta: desired confidence level
... |
optimize: function for solving the model, updating candidate solutions' list
Will add to cand all the intermediate solutions found, as well as the optimum
Parameters:
- model: Gurobi model object
- cand: list of pairs of objective functions (for appending more solutions)
Returns the solver's... | def optimize(model,cand):
"""optimize: function for solving the model, updating candidate solutions' list
Will add to cand all the intermediate solutions found, as well as the optimum
Parameters:
- model: Gurobi model object
- cand: list of pairs of objective functions (for appending more so... |
base_model: mtz model for the atsp, prepared for two objectives
Loads two additional variables/constraints to the mtz model:
- C: sum of travel costs
- T: sum of travel times
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
... | def base_model(n,c,t):
"""base_model: mtz model for the atsp, prepared for two objectives
Loads two additional variables/constraints to the mtz model:
- C: sum of travel costs
- T: sum of travel times
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compu... |
solve_segment: segmentation for finding set of solutions for two-objective TSP
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
- segments: number of segments for finding various non-dominated solutions
Returns list of candidate soluti... | def solve_segment_time(n,c,t,segments):
"""solve_segment: segmentation for finding set of solutions for two-objective TSP
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
- segments: number of segments for finding various non-dominated... |
solve_ideal: use ideal point for finding set of solutions for two-objective TSP
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
- segments: number of segments for finding various non-dominated solutions
Returns list of candidate solut... | def solve_ideal(n,c,t,segments):
"""solve_ideal: use ideal point for finding set of solutions for two-objective TSP
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
- segments: number of segments for finding various non-dominated solut... |
solve_scalarization: scale objective function to find new point
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
Returns list of candidate solutions | def solve_scalarization(n,c,t):
"""solve_scalarization: scale objective function to find new point
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
Returns list of candidate solutions
"""
model = base_model(n,c,t) # base model f... |
staff: staff scheduling
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set of shifts in each period (shift 0 == rest)
- S: subset of shifts that must be kept at least ... | def staff_mo(I,T,N,J,S,c,b):
"""
staff: staff scheduling
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set of shifts in each period (shift 0 == rest)
- S: sub... |
optimize: function for solving the model, updating candidate solutions' list
Parameters:
- model: Gurobi model object
- cand: list of pairs of objective functions (for appending more solutions)
- obj: name of a model's variable to setup as objective
Returns the solver's exit status | def optimize(model,cand,obj):
"""optimize: function for solving the model, updating candidate solutions' list
Parameters:
- model: Gurobi model object
- cand: list of pairs of objective functions (for appending more solutions)
- obj: name of a model's variable to setup as objective
R... |
solve_segment: segmentation for finding set of solutions for two-objective TSP
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set of shifts in each period (shift 0 == rest)
... | def solve_segment(I,T,N,J,S,c,b):
"""
solve_segment: segmentation for finding set of solutions for two-objective TSP
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set... |
flp -- model for the capacitated facility location problem
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for customer i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: unit cost of servicing demand ... | def flp(I,J,d,M,f,c):
"""flp -- model for the capacitated facility location problem
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for customer i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: u... |
solve_vrp -- solve the vehicle routing problem.
- start with assignment model (depot has a special status)
- add cuts until all components of the graph are connected
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
- m: number of vehicles... | def solve_vrp(V,c,m,q,Q):
"""solve_vrp -- solve the vehicle routing problem.
- start with assignment model (depot has a special status)
- add cuts until all components of the graph are connected
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j... |
creates example data set | def make_data():
"""creates example data set"""
I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180}) # demand
J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed costs
c = {(1,1):4, (1,2):6, (1,3):9, # transportation costs
(2,1):5, (2,2):4, (2,3):7,
... |
kcover -- minimize the number of uncovered customers from k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, ready to be solved. | def kcover(I,J,c,k):
"""kcover -- minimize the number of uncovered customers from k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, read... |
solve_kcenter -- locate k facilities minimizing distance of most distant customer.
Parameters:
I - set of customers
J - set of potential facilities
c[i,j] - cost of servicing customer i from facility j
k - number of facilities to be used
delta - tolerance for terminating bise... | def solve_kcenter(I,J,c,k,delta):
"""solve_kcenter -- locate k facilities minimizing distance of most distant customer.
Parameters:
I - set of customers
J - set of potential facilities
c[i,j] - cost of servicing customer i from facility j
k - number of facilities to be used
... |
eoq_soco -- multi-item capacitated economic ordering quantity model using soco
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- W: capacity (limit on order quanti... | def eoq_soco(I,F,h,d,w,W):
"""eoq_soco -- multi-item capacitated economic ordering quantity model using soco
Parameters:
- I: set of items
- F[i]: ordering cost for item i
- h[i]: holding cost for item i
- d[i]: demand for item i
- w[i]: unit weight for item i
- ... |
mtzts: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]: latest date for visiting ... | def mtztw(n,c,e,l):
"""mtzts: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]... |
tsptw2: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's formulation, two-index potential)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]: latest date for visitin... | def tsptw2(n,c,e,l):
"""tsptw2: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's formulation, two-index potential)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l... |
mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]: lates... | def mtz2tw(n,c,e,l):
"""mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting ... |
make_data: compute matrix distance and time windows. | def make_data(n,width):
"""make_data: compute matrix distance and time windows."""
x = dict([(i,100*random.random()) for i in range(1,n+1)])
y = dict([(i,100*random.random()) for i in range(1,n+1)])
c = {}
for i in range(1,n+1):
for j in range(1,n+1):
if j != i:
c... |
Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters | def distL2(x1,y1,x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 - x1
ydiff ... |
Compute the L1-norm (Manhattan) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters | def distL1(x1,y1,x2,y2):
"""Compute the L1-norm (Manhattan) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
return int(abs(x2-x1) + ab... |
Compute the Linfty distance between two points (see TSPLIB documentation) | def distLinf(x1,y1,x2,y2):
"""Compute the Linfty distance between two points (see TSPLIB documentation)"""
return int(max(abs(x2-x1),abs(y2-y1))) |
Compute the ATT distance between two points (see TSPLIB documentation) | def distATT(x1,y1,x2,y2):
"""Compute the ATT distance between two points (see TSPLIB documentation)"""
xd = x2 - x1
yd = y2 - y1
rij = math.sqrt((xd*xd + yd*yd) /10.)
tij = int(rij + .5)
if tij < rij:
return tij + 1
else:
return tij |
returns smallest integer not less than the distance of two points | def distCEIL2D(x1,y1,x2,y2):
"""returns smallest integer not less than the distance of two points"""
xdiff = x2 - x1
ydiff = y2 - y1
return int(math.ceil(math.sqrt(xdiff*xdiff + ydiff*ydiff))) |
basic function for reading a symmetric problem in the TSPLIB format | def read_tsplib(filename):
"basic function for reading a symmetric problem in the TSPLIB format"
"data is stored in an upper triangular matrix"
"NOTE: some distance types are not handled yet"
if filename[-3:] == ".gz":
f = gzip.open(filename, "rt")
else:
f = open(filename)
line ... |
basic function for reading a ATSP problem on the TSPLIB format | def read_atsplib(filename):
"basic function for reading a ATSP problem on the TSPLIB format"
"NOTE: only works for explicit matrices"
if filename[-3:] == ".gz":
f = gzip.open(filename, 'r')
data = f.readlines()
else:
f = open(filename, 'r')
data = f.readlines()
for ... |
First Fit Decreasing heuristics for the Bin Packing Problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a list of lists with bin compositions. | def FFD(s,B):
"""First Fit Decreasing heuristics for the Bin Packing Problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a list of lists with bin compositions.
"""
remain = [B] # keep list of empty space per bin
sol = [[]] # a list ot items (... |
bpp: Martello and Toth's model to solve the bin packing problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a model, ready to be solved. | def bpp(s,B):
"""bpp: Martello and Toth's model to solve the bin packing problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a model, ready to be solved.
"""
n = len(s)
U = len(FFD(s,B)) # upper bound of the number of bins
model = Model("bpp")
# setP... |
DiscreteUniform: create random, uniform instance for the bin packing problem. | def DiscreteUniform(n=10,LB=1,UB=99,B=100):
"""DiscreteUniform: create random, uniform instance for the bin packing problem."""
B = 100
s = [0]*n
for i in range(n):
s[i] = random.randint(LB,UB)
return s,B |
solveBinPacking: use an IP model to solve the in Packing Problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a solution: list of lists, each of which with the items in a roll. | def solveBinPacking(s,B):
"""solveBinPacking: use an IP model to solve the in Packing Problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a solution: list of lists, each of which with the items in a roll.
"""
n = len(s)
U = len(FFD(s,B)) # upper bound of t... |
solve_tsp -- solve the traveling salesman problem
- start with assignment model
- add cuts until there are no sub-cycles
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
Returns the optimum objective value and the list of edges used. | def solve_tsp(V,c):
"""solve_tsp -- solve the traveling salesman problem
- start with assignment model
- add cuts until there are no sub-cycles
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
Returns the optimum objective value and the l... |
solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- add cuts until there are no fractional setup variables
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
- c[t]: variable costs
... | def sils_cut(T,f,c,d,h):
"""solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- add cuts until there are no fractional setup variables
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
... |
ssa -- multi-stage (serial) safety stock allocation model
Parameters:
- n: number of stages
- h[i]: inventory cost on stage i
- K: number of linear segments
- f: (non-linear) cost function
- T[i]: production lead time on stage i
Returns the model with the piecewise linear... | def ssa(n,h,K,f,T):
"""ssa -- multi-stage (serial) safety stock allocation model
Parameters:
- n: number of stages
- h[i]: inventory cost on stage i
- K: number of linear segments
- f: (non-linear) cost function
- T[i]: production lead time on stage i
Returns the mode... |
creates example data set | def make_data():
"""creates example data set"""
n = 30 # number of stages
z = 1.65 # for 95% service level
sigma = 100 # demand's standard deviation
h = {} # inventory cost
T = {} # production lead time
h[n] = 1
for i in range(n-1,0,-1):
h[i] = h[i+1] + random.r... |
mils: standard formulation for the multi-item lot-sizing problem
Parameters:
- T: number of periods
- P: set of products
- f[t,p]: set-up costs (on period t, for product p)
- g[t,p]: set-up times
- c[t,p]: variable costs
- d[t,p]: demand values
- h[t,p]: holdi... | def mils(T,P,f,g,c,d,h,M):
"""
mils: standard formulation for the multi-item lot-sizing problem
Parameters:
- T: number of periods
- P: set of products
- f[t,p]: set-up costs (on period t, for product p)
- g[t,p]: set-up times
- c[t,p]: variable costs
- d[t,p]... |
mils_fl: facility location formulation for the multi-item lot-sizing problem
Requires more variables, but gives a better solution because LB is
better than the standard formulation. It can be used as a
heuristic method that is sometimes better than relax-and-fix.
Parameters:
- T: number of pe... | def mils_fl(T,P,f,g,c,d,h,M):
"""
mils_fl: facility location formulation for the multi-item lot-sizing problem
Requires more variables, but gives a better solution because LB is
better than the standard formulation. It can be used as a
heuristic method that is sometimes better than relax-and-fix.
... |
Data generator for the multi-item lot-sizing problem
it uses a simular algorithm for generating the standard benchmarks in:
"Capacitated Lot Sizing with Setup Times" by
William W. Trigeiro, L. Joseph Thomas, John O. McClain
MANAGEMENT SCIENCE
Vol. 35, No. 3, March 1989, pp. 353-366
Parameters:
... | def trigeiro(T,N,factor):
"""
Data generator for the multi-item lot-sizing problem
it uses a simular algorithm for generating the standard benchmarks in:
"Capacitated Lot Sizing with Setup Times" by
William W. Trigeiro, L. Joseph Thomas, John O. McClain
MANAGEMENT SCIENCE
Vol. 35, No. 3, Mar... |
gcp -- model for minimizing the number of colors in a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: upper bound on the number of colors
Returns a model, ready to be solved. | def gcp(V,E,K):
"""gcp -- model for minimizing the number of colors in a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: upper bound on the number of colors
Returns a model, ready to be solved.
"""
model = Model("gcp")
x,y = ... |
rcs -- model for the resource constrained scheduling problem
Parameters:
- J: set of jobs
- P: set of precedence constraints between jobs
- R: set of resources
- T: number of periods
- p[j]: processing time of job j
- c[j,t]: cost incurred when job j starts processing... | def rcs(J,P,R,T,p,c,a,RUB):
"""rcs -- model for the resource constrained scheduling problem
Parameters:
- J: set of jobs
- P: set of precedence constraints between jobs
- R: set of resources
- T: number of periods
- p[j]: processing time of job j
- c[j,t]: cost in... |
creates example data set 1 | def make_1r():
"""creates example data set 1"""
J, p = multidict({ # jobs, processing times
1 : 1,
2 : 3,
3 : 2,
4 : 2,
})
P = [(1,2), (1,3), (2,4)]
R = [1]
T = 6
c = {}
for j in J:
for t in range(1,T-p[j]+2):
c[j,t] = 1*(t-1+... |
prodmix: robust production planning using soco
Parameters:
I - set of materials
K - set of components
a[i][k] - coef. matrix
p[i] - price of material i
LB[k] - amount needed for k
Returns a model, ready to be solved. | def prodmix(I,K,a,p,epsilon,LB):
"""prodmix: robust production planning using soco
Parameters:
I - set of materials
K - set of components
a[i][k] - coef. matrix
p[i] - price of material i
LB[k] - amount needed for k
Returns a model, ready to be solved.
"""
... |
creates example data set | def make_data():
"""creates example data set"""
a = { (1,1):.25, (1,2):.15, (1,3):.2,
(2,1):.3, (2,2):.3, (2,3):.1,
(3,1):.15, (3,2):.65, (3,3):.05,
(4,1):.1, (4,2):.05, (4,3):.8
}
epsilon = 0.01
I,p = multidict({1:5, 2:6, 3:8, 4:20})
K,LB = multidict({1:.... |
ssp -- model for the stable set problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved. | def ssp(V,E):
"""ssp -- model for the stable set problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model("ssp")
x = {}
for i in V:
x[i] = model.addVar(vtype="B", name="x(%s)"%i... |
mult_selection -- add piecewise relation with multiple selection formulation
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th point in the piecewise linear rela... | def mult_selection(model,a,b):
"""mult_selection -- add piecewise relation with multiple selection formulation
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k... |
convex_comb_sos -- add piecewise relation with gurobi's SOS constraints
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th point in the piecewise linear relation
... | def convex_comb_sos(model,a,b):
"""convex_comb_sos -- add piecewise relation with gurobi's SOS constraints
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th ... |
convex_comb_dis -- add piecewise relation with convex combination formulation
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th point in the piecewise linear rel... | def convex_comb_dis(model,a,b):
"""convex_comb_dis -- add piecewise relation with convex combination formulation
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the... |
convex_comb_dis_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]... | def convex_comb_dis_log(model,a,b):
"""convex_comb_dis_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in t... |
convex_comb_agg -- add piecewise relation convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th point in the pie... | def convex_comb_agg(model,a,b):
"""convex_comb_agg -- add piecewise relation convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-... |
convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear re... | def convex_comb_agg_log(model,a,b):
"""convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate o... |
creates a multidictionary | def multidict(D):
'''creates a multidictionary'''
keys = list(D.keys())
if len(keys) == 0:
return [[]]
try:
N = len(D[keys[0]])
islist = True
except:
N = 1
islist = False
dlist = [dict() for d in range(N)]
for k in keys:
if islist:
... |
mils_standard: standard formulation for the multi-item, multi-stage lot-sizing problem
Parameters:
- T: number of periods
- K: set of resources
- P: set of items
- f[t,p]: set-up costs (on period t, for product p)
- g[t,p]: set-up times
- c[t,p]: variable costs
... | def mils_standard(T,K,P,f,g,c,d,h,a,M,UB,phi):
"""
mils_standard: standard formulation for the multi-item, multi-stage lot-sizing problem
Parameters:
- T: number of periods
- K: set of resources
- P: set of items
- f[t,p]: set-up costs (on period t, for product p)
- ... |
mils_echelon: echelon formulation for the multi-item, multi-stage lot-sizing problem
Parameters:
- T: number of periods
- K: set of resources
- P: set of items
- f[t,p]: set-up costs (on period t, for product p)
- g[t,p]: set-up times
- c[t,p]: variable costs
... | def mils_echelon(T,K,P,f,g,c,d,h,a,M,UB,phi):
"""
mils_echelon: echelon formulation for the multi-item, multi-stage lot-sizing problem
Parameters:
- T: number of periods
- K: set of resources
- P: set of items
- f[t,p]: set-up costs (on period t, for product p)
- g[t... |
1..T: set of periods
K: set of resources
P: set of items
f[t,p]: set-up costs
g[t,p]: set-up times
c[t,p]: variable costs
d[t,p]: demand values
h[t,p]: holding costs
a[t,k,p]: amount of resource k for producing product p in period. t
M[t,k]: resource upper bounds
UB[t,p]: upper b... | def make_data():
"""
1..T: set of periods
K: set of resources
P: set of items
f[t,p]: set-up costs
g[t,p]: set-up times
c[t,p]: variable costs
d[t,p]: demand values
h[t,p]: holding costs
a[t,k,p]: amount of resource k for producing product p in period. t
M[t,k]: resource uppe... |
gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: number of colors to be used
Returns a model, ready to be solved. | def gcp_fixed_k(V,E,K):
"""gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: number of colors to be used
Returns a model, ready to be solved.
"""
model = Model("... |
solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to vertices | def solve_gcp(V,E):
"""solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to vertices
"""
LB = 0
... |
Find plugins in given module | def register_plugin_module(mod):
"""Find plugins in given module"""
for k, v in load_plugins_from_module(mod).items():
if k:
if isinstance(k, (list, tuple)):
k = k[0]
global_registry[k] = v |
Find plugins in given directory | def register_plugin_dir(path):
"""Find plugins in given directory"""
import glob
for f in glob.glob(path + '/*.py'):
for k, v in load_plugins_from_module(f).items():
if k:
global_registry[k] = v |
Information about this parameter | def describe(self):
"""Information about this parameter"""
desc = {
'name': self.name,
'description': self.description,
# the Parameter might not have a type at all
'type': self.type or 'unknown',
}
for attr in ['min', 'max', 'allowed', 'de... |
Compile env, client_env, shell and client_shell commands | def expand_defaults(self, client=False, getenv=True, getshell=True):
"""Compile env, client_env, shell and client_shell commands
"""
if not isinstance(self._default, six.string_types):
self.expanded_default = self._default
else:
self.expanded_default = coerce(self... |
Does value meet parameter requirements? | def validate(self, value):
"""Does value meet parameter requirements?"""
if self.type is not None:
value = coerce(self.type, value)
if self.min is not None and value < self.min:
raise ValueError('%s=%s is less than %s' % (self.name, value,
... |
Basic information about this entry | def describe(self):
"""Basic information about this entry"""
if isinstance(self._plugin, list):
pl = [p.name for p in self._plugin]
elif isinstance(self._plugin, dict):
pl = {k: classname(v) for k, v in self._plugin.items()}
else:
pl = self._plugin if ... |
Instantiate the DataSource for the given parameters | def get(self, **user_parameters):
"""Instantiate the DataSource for the given parameters"""
plugin, open_args = self._create_open_args(user_parameters)
data_source = plugin(**open_args)
data_source.catalog_object = self._catalog
data_source.name = self.name
data_source.de... |
Load text of fcatalog file and pass to parse
Will do nothing if autoreload is off and reload is not explicitly
requested | def _load(self, reload=False):
"""Load text of fcatalog file and pass to parse
Will do nothing if autoreload is off and reload is not explicitly
requested
"""
if self.autoreload or reload:
# First, we load from YAML, failing if syntax errors are found
opt... |
Create entries from catalog text
Normally the text comes from the file at self.path via the ``_load()``
method, but could be explicitly set instead. A copy of the text is
kept in attribute ``.text`` .
Parameters
----------
text : str
YAML formatted catalog s... | def parse(self, text):
"""Create entries from catalog text
Normally the text comes from the file at self.path via the ``_load()``
method, but could be explicitly set instead. A copy of the text is
kept in attribute ``.text`` .
Parameters
----------
text : str
... |
If catalog is named 'catalog' take name from parent directory | def name_from_path(self):
"""If catalog is named 'catalog' take name from parent directory"""
name = os.path.splitext(os.path.basename(self.path))[0]
if name == 'catalog':
name = os.path.basename(os.path.dirname(self.path))
return name.replace('.', '_') |
Access one source's info.
This is for direct access to an entry by name for random access, which
is useful to the client when the whole catalog has not first been
listed and pulled locally (e.g., in the case of pagination). | def get(self):
"""
Access one source's info.
This is for direct access to an entry by name for random access, which
is useful to the client when the whole catalog has not first been
listed and pulled locally (e.g., in the case of pagination).
"""
head = self.requ... |
Function to run on each cat input | def preprocess(cls, cat):
"""Function to run on each cat input"""
if isinstance(cat, str):
cat = intake.open_catalog(cat)
return cat |
Populate widget with nested catalogs | def expand_nested(self, cats):
"""Populate widget with nested catalogs"""
down = '│'
right = '└──'
def get_children(parent):
return [e() for e in parent._entries.values() if e._container == 'catalog']
if len(cats) == 0:
return
cat = cats[0]
... |
Collapse any items that are nested under cats.
`max_nestedness` acts as a fail-safe to prevent infinite looping. | def collapse_nested(self, cats, max_nestedness=10):
"""
Collapse any items that are nested under cats.
`max_nestedness` acts as a fail-safe to prevent infinite looping.
"""
children = []
removed = set()
nestedness = max_nestedness
old = list(self.widget.o... |
Remove the selected catalog - allow the passing of arbitrary
args so that buttons work. Also remove any nested catalogs. | def remove_selected(self, *args):
"""Remove the selected catalog - allow the passing of arbitrary
args so that buttons work. Also remove any nested catalogs."""
self.collapse_nested(self.selected)
self.remove(self.selected) |
Clear/create a directory to store a persisted dataset into | def getdir(self, source):
"""Clear/create a directory to store a persisted dataset into"""
subdir = posixpath.join(self.pdir, source._tok)
try:
self.fs.rm(subdir, True)
except Exception as e:
logger.debug("Directory clear failed: %s" % e)
self.fs.mkdirs(su... |
Add the persisted source to the store under the given key
key : str
The unique token of the un-persisted, original source
source : DataSource instance
The thing to add to the persisted catalogue, referring to persisted
data | def add(self, key, source):
"""Add the persisted source to the store under the given key
key : str
The unique token of the un-persisted, original source
source : DataSource instance
The thing to add to the persisted catalogue, referring to persisted
data
... |
Get string token from object
Strings are assumed to already be a token; if source or entry, see
if it is a persisted thing ("original_tok" is in its metadata), else
generate its own token. | def get_tok(self, source):
"""Get string token from object
Strings are assumed to already be a token; if source or entry, see
if it is a persisted thing ("original_tok" is in its metadata), else
generate its own token.
"""
if isinstance(source, str):
return s... |
Remove a dataset from the persist store
source : str or DataSource or Lo
If a str, this is the unique ID of the original source, which is
the key of the persisted dataset within the store. If a source,
can be either the original or the persisted source.
delfiles : bo... | def remove(self, source, delfiles=True):
"""Remove a dataset from the persist store
source : str or DataSource or Lo
If a str, this is the unique ID of the original source, which is
the key of the persisted dataset within the store. If a source,
can be either the ori... |
Given a unique key in the store, recreate original source | def backtrack(self, source):
"""Given a unique key in the store, recreate original source"""
key = self.get_tok(source)
s = self[key]()
meta = s.metadata['original_source']
cls = meta['cls']
args = meta['args']
kwargs = meta['kwargs']
cls = import_name(cls... |
Recreate and re-persist the source for the given unique ID | def refresh(self, key):
"""Recreate and re-persist the source for the given unique ID"""
s0 = self[key]
s = self.backtrack(key)
s.persist(**s0.metadata['persist_kwargs']) |
Has the (persisted) source expired in the store
Will return True if the source is not in the store at all, if it's
TTL is set to None, or if more seconds have passed than the TTL. | def needs_refresh(self, source):
"""Has the (persisted) source expired in the store
Will return True if the source is not in the store at all, if it's
TTL is set to None, or if more seconds have passed than the TTL.
"""
now = time.time()
if source._tok in self:
... |
Set sources from a list of cats | def cats(self, cats):
"""Set sources from a list of cats"""
sources = []
for cat in coerce_to_list(cats):
sources.extend([entry for entry in cat._entries.values() if entry._container != 'catalog'])
self.items = sources |
Execute the "intake" command line program. | def main(argv=None):
''' Execute the "intake" command line program.
'''
from intake.cli.bootstrap import main as _main
return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.