docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
solve_tsp -- solve the traveling salesman problem - start with assignment model - check flow from a source to every other node; - if no flow, a sub-cycle has been found --> add cut - otherwise, the solution is optimal 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): def addcut(X): for sink in V[1:]: mflow = maxflow(V,X,V[0],sink) mflow.optimize() f,cons = mflow.data if mflow.ObjVal < 2-EPS: # no flow to sink, can add cut break else: return False #add a cut/constraint CutA = set([V[0]]) for i in cons: if cons[i].Pi <= -1+EPS: CutA.add(i) CutB = set(V) - CutA main.addCons( quicksum(x[i,j] for i in CutA for j in CutB if j>i) + \ quicksum(x[j,i] for i in CutA for j in CutB if j<i) >= 2) print("mflow:",mflow.getObjVal(),"cut:",CutA,"+",CutB,">= 2") print("mflow:",mflow.getObjVal(),"cut:",[(i,j) for i in CutA for j in CutB if j>i],"+",[(j,i) for i in CutA for j in CutB if j<i],">= 2") return True def isMIP(x): for var in x: if var.vtype == "CONTINUOUS": return False return True # main part of the solution process: main = Model("tsp") x = {} for i in V: for j in V: if j > i: x[i,j] = main.addVar(ub=1, vtype="C", name="x(%s,%s)"%(i,j)) for i in V: main.addCons(quicksum(x[j,i] for j in V if j < i) + \ quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i) main.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j > i), "minimize") while True: main.optimize() z = main.getObjVal() X = {} for (i,j) in x: if main.getVal(x[i,j]) > EPS: X[i,j] = main.getVal(x[i,j]) if addcut(X) == False: # i.e., components are connected if isMIP(): # integer variables, components connected: solution found break for (i,j) in x: # all components connected, switch to integer model main.chgVarType(x[i,j], "BINARY") # process solution edges = [] for (i,j) in x: if main.getVal(x[i,j]) > EPS: edges.append((i,j)) return main.getObjVal(),edges
220,068
gpp -- model for the graph partitioning problem Parameters: - n: number of jobs - m: number of machines - p[i,j]: processing time of job i on machine j Returns a model, ready to be solved.
def permutation_flow_shop(n,m,p): model = Model("permutation flow shop") x,s,f = {},{},{} for j in range(1,n+1): for k in range(1,n+1): x[j,k] = model.addVar(vtype="B", name="x(%s,%s)"%(j,k)) for i in range(1,m+1): for k in range(1,n+1): s[i,k] = model.addVar(vtype="C", name="start(%s,%s)"%(i,k)) f[i,k] = model.addVar(vtype="C", name="finish(%s,%s)"%(i,k)) for j in range(1,n+1): model.addCons(quicksum(x[j,k] for k in range(1,n+1)) == 1, "Assign1(%s)"%(j)) model.addCons(quicksum(x[k,j] for k in range(1,n+1)) == 1, "Assign2(%s)"%(j)) for i in range(1,m+1): for k in range(1,n+1): if k != n: model.addCons(f[i,k] <= s[i,k+1], "FinishStart(%s,%s)"%(i,k)) if i != m: model.addCons(f[i,k] <= s[i+1,k], "Machine(%s,%s)"%(i,k)) model.addCons(s[i,k] + quicksum(p[i,j]*x[j,k] for j in range(1,n+1)) <= f[i,k], "StartFinish(%s,%s)"%(i,k)) model.setObjective(f[m,n], "minimize") model.data = x,s,f return model
220,075
flp_nonlinear_soco -- use Parameters: - I: set of customers - J: set of facilities - d[i]: demand for product 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 point i from facility j Returns a model, ready to be solved.
def flp_nonlinear_soco(I,J,d,M,f,c): model = Model("nonlinear flp -- soco formulation") x,X,u = {},{},{} for j in J: X[j] = model.addVar(ub=M[j], vtype="C", name="X(%s)"%j) # for sum_i x_ij u[j] = model.addVar(vtype="C", name="u(%s)"%j) # for replacing sqrt sum_i x_ij in soco for i in I: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) # i's demand satisfied from j # constraints for customer's demand satisfaction for i in I: model.addCons(quicksum(x[i,j] for j in J) == 1, "Demand(%s)"%i) for j in J: model.addCons(quicksum(d[i]*x[i,j] for i in I) == X[j], "Capacity(%s)"%j) model.addQConstr(quicksum(f[j]**2*d[i]*x[i,j]*x[i,j] for i in I) <= u[j]*u[j], "SOC(%s)"%j) model.setObjective(quicksum(u[j] for j in J) +\ quicksum(c[i,j]*d[i]*x[i,j] for j in J for i in I),\ "minimize") model.data = x,u return model
220,078
flp_nonlinear_mselect -- use multiple selection model 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 point i from facility j - K: number of linear pieces for approximation of non-linear cost function Returns a model, ready to be solved.
def flp_nonlinear_mselect(I,J,d,M,f,c,K): a,b = {},{} for j in J: U = M[j] L = 0 width = U/float(K) a[j] = [k*width for k in range(K+1)] b[j] = [f[j]*math.sqrt(value) for value in a[j]] model = Model("nonlinear flp -- piecewise linear version with multiple selection") x = {} for j in J: for i in I: x[i,j] = model.addVar(vtype="C", name="x(%s,%s)"%(i,j)) # i's demand satisfied from j # total volume transported from plant j, corresponding (linearized) cost, selection variable: X,F,z = {},{},{} for j in J: # add constraints for linking piecewise linear part: X[j],F[j],z[j] = mult_selection(model,a[j],b[j]) X[j].ub = M[j] # for i in I: # model.addCons( # x[i,j] <= \ # quicksum(min(d[i],a[j][k+1]) * z[j][k] for k in range(K)),\ # "Strong(%s,%s)"%(i,j)) # constraints for customer's demand satisfaction for i in I: model.addCons(quicksum(x[i,j] for j in J) == d[i], "Demand(%s)"%i) for j in J: model.addCons(quicksum(x[i,j] for i in I) == X[j], "Capacity(%s)"%j) model.setObjective(quicksum(F[j] for j in J) +\ quicksum(c[i,j]*x[i,j] for j in J for i in I),\ "minimize") model.data = x,X,F return model
220,079
lower_brkpts: lower approximation of the cost function Parameters: - a,...,p_max: cost parameters - n: number of breakpoints' intervals to insert between valve points Returns: list of breakpoints in the form [(x0,y0),...,(xK,yK)]
def lower_brkpts(a,b,c,e,f,p_min,p_max,n): EPS = 1.e-12 # for avoiding round-off errors if f == 0: f = math.pi/(p_max-p_min) brk = [] nvalve = int(math.ceil(f*(p_max-p_min)/math.pi)) for i in range(nvalve+1): p0 = p_min + i*math.pi/f if p0 >= p_max-EPS: brk.append((p_max,cost(a,b,c,e,f,p_min,p_max))) break for j in range(n): p = p0 + j*math.pi/f/n if p >= p_max: break brk.append((p,cost(a,b,c,e,f,p_min,p))) return brk
220,083
eld -- economic load dispatching in electricity generation Parameters: - U: set of generators (units) - p_min[u]: minimum operating power for unit u - p_max[u]: maximum operating power for unit u - d: demand - brk[k]: (x,y) coordinates of breakpoint k, k=0,...,K Returns a model, ready to be solved.
def eld_complete(U,p_min,p_max,d,brk): model = Model("Economic load dispatching") p,F = {},{} for u in U: p[u] = model.addVar(lb=p_min[u], ub=p_max[u], name="p(%s)"%u) # capacity F[u] = model.addVar(lb=0,name="fuel(%s)"%u) # set fuel costs based on piecewise linear approximation for u in U: abrk = [X for (X,Y) in brk[u]] bbrk = [Y for (X,Y) in brk[u]] # convex combination part: K = len(brk[u])-1 z = {} for k in range(K+1): z[k] = model.addVar(ub=1) # do not name variables for avoiding clash model.addCons(p[u] == quicksum(abrk[k]*z[k] for k in range(K+1))) model.addCons(F[u] == quicksum(bbrk[k]*z[k] for k in range(K+1))) model.addCons(quicksum(z[k] for k in range(K+1)) == 1) model.addConsSOS2([z[k] for k in range(K+1)]) # demand satisfaction model.addCons(quicksum(p[u] for u in U) == d, "demand") # objective model.setObjective(quicksum(F[u] for u in U), "minimize") model.data = p return model
220,084
eld -- economic load dispatching in electricity generation Parameters: - U: set of generators (units) - p_min[u]: minimum operating power for unit u - p_max[u]: maximum operating power for unit u - d: demand - brk[u][k]: (x,y) coordinates of breakpoint k, k=0,...,K for unit u Returns a model, ready to be solved.
def eld_another(U,p_min,p_max,d,brk): model = Model("Economic load dispatching") # set objective based on piecewise linear approximation p,F,z = {},{},{} for u in U: abrk = [X for (X,Y) in brk[u]] bbrk = [Y for (X,Y) in brk[u]] p[u],F[u],z[u] = convex_comb_sos(model,abrk,bbrk) p[u].lb = p_min[u] p[u].ub = p_max[u] # demand satisfaction model.addCons(quicksum(p[u] for u in U) == d, "demand") # objective model.setObjective(quicksum(F[u] for u in U), "minimize") model.data = p return model
220,085
mctransp -- model for solving the Multi-commodity Transportation Problem Parameters: - I: set of customers - J: set of facilities - K: set of commodities - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k - d[i][k]: demand for commodity k at node i - M[j]: capacity Returns a model, ready to be solved.
def mctransp(I,J,K,c,d,M): model = Model("multi-commodity transportation") # Create variables x = {} for (i,j,k) in c: x[i,j,k] = model.addVar(vtype="C", name="x(%s,%s,%s)" % (i,j,k)) # Demand constraints for i in I: for k in K: model.addCons(sum(x[i,j,k] for j in J if (i,j,k) in x) == d[i,k], "Demand(%s,%s)" % (i,k)) # Capacity constraints for j in J: model.addCons(sum(x[i,j,k] for (i,j2,k) in x if j2 == j) <= M[j], "Capacity(%s)" % j) # Objective model.setObjective(quicksum(c[i,j,k]*x[i,j,k] for (i,j,k) in x), "minimize") model.data = x return model
220,088
mtz: Miller-Tucker-Zemlin's model for the (asymmetric) traveling salesman problem (potential formulation) Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) Returns a model, ready to be solved.
def mtz(n,c): model = Model("atsp - mtz") x,u = {},{} for i in range(1,n+1): u[i] = model.addVar(lb=0, ub=n-1, vtype="C", name="u(%s)"%i) for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for i in range(1,n+1): model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i) model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i) for i in range(1,n+1): for j in range(2,n+1): if i != j: model.addCons(u[i] - u[j] + (n-1)*x[i,j] <= n-2, "MTZ(%s,%s)"%(i,j)) model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.data = x,u return model
220,089
mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) Returns a model, ready to be solved.
def mcf(n,c): model = Model("mcf") x,f = {},{} for i in range(1,n+1): for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) if i != j and j != 1: for k in range(2,n+1): if i != k: f[i,j,k] = model.addVar(ub=1, vtype="C", name="f(%s,%s,%s)"%(i,j,k)) for i in range(1,n+1): model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i) model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i) for k in range(2,n+1): model.addCons(quicksum(f[1,i,k] for i in range(2,n+1) if (1,i,k) in f) == 1, "FlowOut(%s)"%k) model.addCons(quicksum(f[i,k,k] for i in range(1,n+1) if (i,k,k) in f) == 1, "FlowIn(%s)"%k) for i in range(2,n+1): if i != k: model.addCons(quicksum(f[j,i,k] for j in range(1,n+1) if (j,i,k) in f) == \ quicksum(f[i,j,k] for j in range(1,n+1) if (i,j,k) in f), "FlowCons(%s,%s)"%(i,k)) for (i,j,k) in f: model.addCons(f[i,j,k] <= x[i,j], "FlowUB(%s,%s,%s)"%(i,j,k)) model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.data = x,f return model
220,090
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): model = Model("modern diet") # Create variables x,y,z = {},{},{} for j in F: x[j] = model.addVar(vtype="I", name="x(%s)"%j) y[j] = model.addVar(vtype="B", name="y(%s)"%j) for i in N: z[i] = model.addVar(lb=a[i], ub=b[i], name="z(%s)"%j) v = model.addVar(vtype="C", name="v") # Constraints: for i in N: model.addCons(quicksum(d[j][i]*x[j] for j in F) == z[i], name="Nutr(%s)"%i) model.addCons(quicksum(c[j]*x[j] for j in F) == v, name="Cost") for j in F: model.addCons(y[j] <= x[j], name="Eat(%s)"%j) # Objective: model.setObjective(quicksum(y[j] for j in F), "maximize") model.data = x,y,z,v return model
220,092
sils -- LP lotsizing for the single item lot sizing problem Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns a model, ready to be solved.
def sils(T,f,c,d,h): model = Model("single item lotsizing") Ts = range(1,T+1) M = sum(d[t] for t in Ts) y,x,I = {},{},{} for t in Ts: y[t] = model.addVar(vtype="I", ub=1, name="y(%s)"%t) x[t] = model.addVar(vtype="C", ub=M, name="x(%s)"%t) I[t] = model.addVar(vtype="C", name="I(%s)"%t) I[0] = 0 for t in Ts: model.addCons(x[t] <= M*y[t], "ConstrUB(%s)"%t) model.addCons(I[t-1] + x[t] == I[t] + d[t], "FlowCons(%s)"%t) model.setObjective(\ quicksum(f[t]*y[t] + c[t]*x[t] + h[t]*I[t] for t in Ts),\ "minimize") model.data = y,x,I return model
220,096
solve_sils -- solve the lot sizing problem with cutting planes - start with a relaxed model - used lazy constraints to elimitate fractional setup variables with cutting planes Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns the final model solved, with all necessary cuts added.
def sils_cut(T,f,c,d,h, conshdlr): Ts = range(1,T+1) model = sils(T,f,c,d,h) y,x,I = model.data # relax integer variables for t in Ts: model.chgVarType(y[t], "C") model.addVar(vtype="B", name="fake") # for making the problem MIP # compute D[i,j] = sum_{t=i}^j d[t] D = {} for t in Ts: s = 0 for j in range(t,T+1): s += d[j] D[t,j] = s #include the lot sizing constraint handler model.includeConshdlr(conshdlr, "SILS", "Constraint handler for single item lot sizing", sepapriority = 0, enfopriority = -1, chckpriority = -1, sepafreq = -1, propfreq = -1, eagerfreq = -1, maxprerounds = 0, delaysepa = False, delayprop = False, needscons = False, presoltiming = SCIP_PRESOLTIMING.FAST, proptiming = SCIP_PROPTIMING.BEFORELP) conshdlr.data = D,Ts model.data = y,x,I return model
220,097
mctransp -- model for solving the Multi-commodity Transportation Problem Parameters: - I: set of customers - J: set of facilities - K: set of commodities - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k - d[i][k]: demand for commodity k at node i - M[j]: capacity Returns a model, ready to be solved.
def mctransp(I,J,K,c,d,M): model = Model("multi-commodity transportation") # Create variables x = {} for (i,j,k) in c: x[i,j,k] = model.addVar(vtype="C", name="x(%s,%s,%s)" % (i,j,k), obj=c[i,j,k]) # tuplelist is a Gurobi data structure to manage lists of equal sized tuples - try itertools as alternative arcs = tuplelist([(i,j,k) for (i,j,k) in x]) # Demand constraints for i in I: for k in K: model.addCons(sum(x[i,j,k] for (i,j,k) in arcs.select(i,"*",k)) == d[i,k], "Demand(%s,%s)" % (i,k)) # Capacity constraints for j in J: model.addCons(sum(x[i,j,k] for (i,j,k) in arcs.select("*",j,"*")) <= M[j], "Capacity(%s)" % j) model.data = x return model
220,102
solveCuttingStock: use column generation (Gilmore-Gomory approach). Parameters: - w: list of item's widths - q: number of items of a width - B: bin/roll capacity Returns a solution: list of lists, each of which with the cuts of a roll.
def solveCuttingStock(w,q,B): t = [] # patterns m = len(w) # Generate initial patterns with one size for each item width for (i,width) in enumerate(w): pat = [0]*m # vector of number of orders to be packed into one roll (bin) pat[i] = int(B/width) t.append(pat) # if LOG: # print "sizes of orders=",w # print "quantities of orders=",q # print "roll size=",B # print "initial patterns",t K = len(t) master = Model("master LP") # master LP problem x = {} for k in range(K): x[k] = master.addVar(vtype="I", name="x(%s)"%k) orders = {} for i in range(m): orders[i] = master.addCons( quicksum(t[k][i]*x[k] for k in range(K) if t[k][i] > 0) >= q[i], "Order(%s)"%i) master.setObjective(quicksum(x[k] for k in range(K)), "minimize") # master.Params.OutputFlag = 0 # silent mode # iter = 0 while True: # print "current patterns:" # for ti in t: # print ti # print # iter += 1 relax = master.relax() relax.optimize() pi = [relax.getDualsolLinear(c) for c in relax.getConss()] # keep dual variables knapsack = Model("KP") # knapsack sub-problem knapsack.setMaximize # maximize y = {} for i in range(m): y[i] = knapsack.addVar(lb=0, ub=q[i], vtype="I", name="y(%s)"%i) knapsack.addCons(quicksum(w[i]*y[i] for i in range(m)) <= B, "Width") knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), "maximize") knapsack.hideOutput() # silent mode knapsack.optimize() # if LOG: # print "objective of knapsack problem:", knapsack.ObjVal if knapsack.getObjVal() < 1+EPS: # break if no more columns break pat = [int(y[i].X+0.5) for i in y] # new pattern t.append(pat) # if LOG: # print "shadow prices and new pattern:" # for (i,d) in enumerate(pi): # print "\t%5s%12s%7s" % (i,d,pat[i]) # print # add new column to the master problem col = Column() for i in range(m): if t[K][i] > 0: col.addTerms(t[K][i], orders[i]) x[K] = master.addVar(obj=1, vtype="I", name="x(%s)"%K, column=col) # master.write("MP" + str(iter) + ".lp") K += 1 # Finally, solve the IP # if LOG: # master.Params.OutputFlag = 1 # verbose mode master.optimize() # if LOG: # print # print "final solution (integer master problem): objective =", master.ObjVal # print "patterns:" # for k in x: # if x[k].X > EPS: # print "pattern",k, # print "\tsizes:", # print [w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i]) ], # print "--> %s rolls" % int(x[k].X+.5) rolls = [] for k in x: for j in range(int(x[k].X + .5)): rolls.append(sorted([w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i])])) rolls.sort() return rolls
220,104
transp -- model for solving the transportation problem Parameters: I - set of customers J - set of facilities c[i,j] - unit transportation cost on arc (i,j) d[i] - demand at node i M[j] - capacity Returns a model, ready to be solved.
def transp(I,J,c,d,M): model = Model("transportation") # Create variables x = {} for i in I: for j in J: x[i,j] = model.addVar(vtype="C", name="x(%s,%s)" % (i, j)) # Demand constraints for i in I: model.addCons(quicksum(x[i,j] for j in J if (i,j) in x) == d[i], name="Demand(%s)" % i) # Capacity constraints for j in J: model.addCons(quicksum(x[i,j] for i in I if (i,j) in x) <= M[j], name="Capacity(%s)" % j) # Objective model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.optimize() model.data = x return model
220,107
Prints if a value is even/odd/neither per each value in a example list This example is made for newcomers and motivated by: - modulus is unsupported for pyscipopt.scip.Variable and int - variables are non-integer by default Based on this: #172#issuecomment-394644046 Args: number: value which parity is checked Returns: sval: 1 if number is odd, 0 if number is even, -1 if neither
def parity(number): sval = -1 if verbose: print(80*"*") try: assert number == int(round(number)) m = Model() m.hideOutput() # x and n are integer, s is binary # Irrespective to their type, variables are non-negative by default # since 0 is the default lb. To allow for negative values, give None # as lower bound. # (None means -infinity as lower bound and +infinity as upper bound) x = m.addVar("x", vtype="I", lb=None, ub=None) #ub=None is default n = m.addVar("n", vtype="I", lb=None) s = m.addVar("s", vtype="B") # CAVEAT: if number is negative, x's lower bound must be None # if x is set by default as non-negative and number is negative: # there is no feasible solution (trivial) but the program # does not highlight which constraints conflict. m.addCons(x==number) # minimize the difference between the number and twice a natural number m.addCons(s == x-2*n) m.setObjective(s) m.optimize() assert m.getStatus() == "optimal" boolmod = m.getVal(s) == m.getVal(x)%2 if verbose: for v in m.getVars(): print("%*s: %d" % (fmtlen, v,m.getVal(v))) print("%*d%%2 == %d?" % (fmtlen, m.getVal(x), m.getVal(s))) print("%*s" % (fmtlen, boolmod)) xval = m.getVal(x) sval = m.getVal(s) sstr = sdic[sval] print("%*d is %s" % (fmtlen, xval, sstr)) except (AssertionError, TypeError): print("%*s is neither even nor odd!" % (fmtlen, number.__repr__())) finally: if verbose: print(80*"*") print("") return sval
220,110
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): model = Model("k-center") z = model.addVar(vtype="C", name="z") x,y = {},{} for j in J: y[j] = model.addVar(vtype="B", name="y(%s)"%j) for i in I: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for i in I: model.addCons(quicksum(x[i,j] for j in J) == 1, "Assign(%s)"%i) for j in J: model.addCons(x[i,j] <= y[j], "Strong(%s,%s)"%(i,j)) model.addCons(c[i,j]*x[i,j] <= z, "Max_x(%s,%s)"%(i,j)) model.addCons(quicksum(y[j] for j in J) == k, "Facilities") model.setObjective(z, "minimize") model.data = x,y return model
220,111
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): model = Model("modern diet") # Create variables x,y,z = {},{},{} for j in F: x[j] = model.addVar(vtype="I", name="x(%s)" % j) for i in N: z[i] = model.addVar(lb=a[i], ub=b[i], vtype="C", name="z(%s)" % i) # Constraints: for i in N: model.addCons(quicksum(d[j][i]*x[j] for j in F) == z[i], name="Nutr(%s)" % i) model.setObjective(quicksum(c[j]*x[j] for j in F), "minimize") model.data = x,y,z return model
220,114
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): model = Model("mkp") # Create Variables x = {} for j in J: x[j] = model.addVar(vtype="B", name="x(%s)"%j) # Create constraints for i in I: model.addCons(quicksum(a[i,j]*x[j] for j in J) <= b[i], "Capacity(%s)"%i) # Objective model.setObjective(quicksum(v[j]*x[j] for j in J), "maximize") model.data = x return model
220,115
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 job j - w[j]: weighted of job j; the objective is the sum of the weighted completion time Returns a model, ready to be solved.
def scheduling_linear_ordering(J,p,d,w): model = Model("scheduling: linear ordering") T,x = {},{} # tardiness variable; x[j,k] =1 if job j precedes job k, =0 otherwise for j in J: T[j] = model.addVar(vtype="C", name="T(%s)"%(j)) for k in J: if j != k: x[j,k] = model.addVar(vtype="B", name="x(%s,%s)"%(j,k)) for j in J: model.addCons(quicksum(p[k]*x[k,j] for k in J if k != j) - T[j] <= d[j]-p[j], "Tardiness(%r)"%(j)) for k in J: if k <= j: continue model.addCons(x[j,k] + x[k,j] == 1, "Disjunctive(%s,%s)"%(j,k)) for ell in J: if ell > k: model.addCons(x[j,k] + x[k,ell] + x[ell,j] <= 2, "Triangle(%s,%s,%s)"%(j,k,ell)) model.setObjective(quicksum(w[j]*T[j] for j in J), "minimize") model.data = x,T return model
220,118
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 - w[j]: weighted of job j; the objective is the sum of the weighted completion time Returns a model, ready to be solved.
def scheduling_time_index(J,p,r,w): model = Model("scheduling: time index") T = max(r.values()) + sum(p.values()) X = {} # X[j,t]=1 if job j starts processing at time t, 0 otherwise for j in J: for t in range(r[j], T-p[j]+2): X[j,t] = model.addVar(vtype="B", name="x(%s,%s)"%(j,t)) for j in J: model.addCons(quicksum(X[j,t] for t in range(1,T+1) if (j,t) in X) == 1, "JobExecution(%s)"%(j)) for t in range(1,T+1): ind = [(j,t2) for j in J for t2 in range(t-p[j]+1,t+1) if (j,t2) in X] if ind != []: model.addCons(quicksum(X[j,t2] for (j,t2) in ind) <= 1, "MachineUB(%s)"%t) model.setObjective(quicksum((w[j] * (t - 1 + p[j])) * X[j,t] for (j,t) in X), "minimize") model.data = X return model
220,119
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 start time of job j - w[j]: weighted of job j; the objective is the sum of the weighted completion time Returns a model, ready to be solved.
def scheduling_disjunctive(J,p,r,w): model = Model("scheduling: disjunctive") M = max(r.values()) + sum(p.values()) # big M s,x = {},{} # start time variable, x[j,k] = 1 if job j precedes job k, 0 otherwise for j in J: s[j] = model.addVar(lb=r[j], vtype="C", name="s(%s)"%j) for k in J: if j != k: x[j,k] = model.addVar(vtype="B", name="x(%s,%s)"%(j,k)) for j in J: for k in J: if j != k: model.addCons(s[j] - s[k] + M*x[j,k] <= (M-p[j]), "Bound(%s,%s)"%(j,k)) if j < k: model.addCons(x[j,k] + x[k,j] == 1, "Disjunctive(%s,%s)"%(j,k)) model.setObjective(quicksum(w[j]*s[j] for j in J), "minimize") model.data = s,x return model
220,120
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 available - q[i]: demand for customer i - Q: vehicle capacity Returns the optimum objective value and the list of edges used.
def vrp(V, c, m, q, Q): model = Model("vrp") vrp_conshdlr = VRPconshdlr() x = {} for i in V: for j in V: if j > i and i == V[0]: # depot x[i,j] = model.addVar(ub=2, vtype="I", name="x(%s,%s)"%(i,j)) elif j > i: x[i,j] = model.addVar(ub=1, vtype="I", name="x(%s,%s)"%(i,j)) model.addCons(quicksum(x[V[0],j] for j in V[1:]) == 2*m, "DegreeDepot") for i in V[1:]: model.addCons(quicksum(x[j,i] for j in V if j < i) + quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i) model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j>i), "minimize") model.data = x return model, vrp_conshdlr
220,126
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): model = Model("weber") X,Y,z,xaux,yaux = {},{},{},{},{} X = model.addVar(lb=-model.infinity(), vtype="C", name="X") Y = model.addVar(lb=-model.infinity(), vtype="C", name="Y") for i in I: z[i] = model.addVar(vtype="C", name="z(%s)"%(i)) xaux[i] = model.addVar(lb=-model.infinity(), vtype="C", name="xaux(%s)"%(i)) yaux[i] = model.addVar(lb=-model.infinity(), vtype="C", name="yaux(%s)"%(i)) for i in I: model.addCons(xaux[i]*xaux[i] + yaux[i]*yaux[i] <= z[i]*z[i], "MinDist(%s)"%(i)) model.addCons(xaux[i] == (x[i]-X), "xAux(%s)"%(i)) model.addCons(yaux[i] == (y[i]-Y), "yAux(%s)"%(i)) model.setObjective(quicksum(w[i]*z[i] for i in I), "minimize") model.data = X,Y,z return model
220,129
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 be solved.
def weber_MS(I,J,x,y,w): M = max([((x[i]-x[j])**2 + (y[i]-y[j])**2) for i in I for j in I]) model = Model("weber - multiple source") X,Y,v,u = {},{},{},{} xaux,yaux,uaux = {},{},{} for j in J: X[j] = model.addVar(lb=-model.infinity(), vtype="C", name="X(%s)"%j) Y[j] = model.addVar(lb=-model.infinity(), vtype="C", name="Y(%s)"%j) for i in I: v[i,j] = model.addVar(vtype="C", name="v(%s,%s)"%(i,j)) u[i,j] = model.addVar(vtype="B", name="u(%s,%s)"%(i,j)) xaux[i,j] = model.addVar(lb=-model.infinity(), vtype="C", name="xaux(%s,%s)"%(i,j)) yaux[i,j] = model.addVar(lb=-model.infinity(), vtype="C", name="yaux(%s,%s)"%(i,j)) uaux[i,j] = model.addVar(vtype="C", name="uaux(%s,%s)"%(i,j)) for i in I: model.addCons(quicksum(u[i,j] for j in J) == 1, "Assign(%s)"%i) for j in J: model.addCons(xaux[i,j]*xaux[i,j] + yaux[i,j]*yaux[i,j] <= v[i,j]*v[i,j], "MinDist(%s,%s)"%(i,j)) model.addCons(xaux[i,j] == (x[i]-X[j]), "xAux(%s,%s)"%(i,j)) model.addCons(yaux[i,j] == (y[i]-Y[j]), "yAux(%s,%s)"%(i,j)) model.addCons(uaux[i,j] >= v[i,j] - M*(1-u[i,j]), "uAux(%s,%s)"%(i,j)) model.setObjective(quicksum(w[i]*uaux[i,j] for i in I for j in J), "minimize") model.data = X,Y,v,u return model
220,131
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): model = Model("markowitz") x = {} for i in I: x[i] = model.addVar(vtype="C", name="x(%s)"%i) # quantity of i to buy model.addCons(quicksum(r[i]*x[i] for i in I) >= alpha) model.addCons(quicksum(x[i] for i in I) == 1) # set nonlinear objective: SCIP only allow for linear objectives hence the following obj = model.addVar(vtype="C", name="objective", lb = None, ub = None) # auxiliary variable to represent objective model.addCons(quicksum(sigma[i]**2 * x[i] * x[i] for i in I) <= obj) model.setObjective(obj, "minimize") model.data = x return model
220,132
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 edges used.
def tsp(V,c): model = Model("TSP_lazy") conshdlr = TSPconshdlr() x = {} for i in V: for j in V: if j > i: x[i,j] = model.addVar(vtype = "B",name = "x(%s,%s)" % (i,j)) for i in V: model.addCons(quicksum(x[j, i] for j in V if j < i) + quicksum(x[i, j] for j in V if j > i) == 2, "Degree(%s)" % i) model.setObjective(quicksum(c[i, j] * x[i, j] for i in V for j in V if j > i), "minimize") model.data = x return model, conshdlr
220,133
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): model = Model("p_portfolio") x = {} for i in I: x[i] = model.addVar(vtype="C", name="x(%s)"%i) # quantity of i to buy rho = model.addVar(vtype="C", name="rho") rhoaux = model.addVar(vtype="C", name="rhoaux") model.addCons(rho == quicksum(r[i]*x[i] for i in I)) model.addCons(quicksum(x[i] for i in I) == 1) model.addCons(rhoaux == (alpha - rho)*(1/phi_inv(beta))) #todo model.addCons(quicksum(sigma[i]**2 * x[i] * x[i] for i in I) <= rhoaux * rhoaux) model.setObjective(rho, "maximize") model.data = x return model
220,138
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 exit status
def optimize(model,cand): model.hideOutput() model.optimize() x,y,C,T = model.data status = model.getStatus() if status == "optimal": # collect suboptimal solutions solutions = model.getSols() for sol in solutions: cand.append((model.getSolVal(T, sol), model.getSolVal(C))) return status
220,139
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 Returns list of candidate solutions
def base_model(n,c,t): from atsp import mtz_strong model = mtz_strong(n,c) # model for minimizing cost x,u = model.data # some auxiliary information C = model.addVar(vtype="C", name="C") # for computing solution cost T = model.addVar(vtype="C", name="T") # for computing solution time model.addCons(T == quicksum(t[i,j]*x[i,j] for (i,j) in x), "Time") model.addCons(C == quicksum(c[i,j]*x[i,j] for (i,j) in x), "Cost") model.data = x,u,C,T return model
220,140
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 solutions
def solve_segment_time(n,c,t,segments): model = base_model(n,c,t) # base model for minimizing cost or time x,u,C,T = model.data # store the set of solutions for plotting cand = [] # print("optimizing time" model.setObjective(T, "minimize") stat1 = optimize(model,cand) # print("optimizing cost" model.setObjective(C, "minimize") stat2 = optimize(model,cand) if stat1 != "optimal" or stat2 != "optimal": return [] times = [ti for (ti,ci) in cand] max_time = max(times) min_time = min(times) delta = (max_time-min_time)/segments # print("making time range from",min_time,"to",max_time # add a time upper bound constraint, moving between min and max values TimeCons = model.addCons(T <= max_time, "TimeCons") for i in range(segments+1): time_ub = max_time - delta*i model.chgRhs(TimeCons, time_ub) # print("optimizing cost subject to time <=",time_ub optimize(model,cand) return cand
220,141
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 solutions
def solve_ideal(n,c,t,segments): model = base_model(n,c,t) # base model for minimizing cost or time x,u,C,T = model.data # store the set of solutions for plotting cand = [] # print("optimizing time" model.setObjective(T, "minimize") stat1 = optimize(model,cand) # print("optimizing cost" model.setObjective(C, "minimize") stat2 = optimize(model,cand) #find the minimum cost routes if stat1 != "optimal" or stat2 != "optimal": return [] times = [ti for (ti,ci) in cand] costs = [ci for (ti,ci) in cand] min_time = min(times) min_cost = min(costs) # print("ideal point:",min_time,",",min_cost #=============================================================== # Objective function is f1^2 + f2^2 where f=Sum tx-min_time and g=Sum cx-min_cost f1 = model.addVar(vtype="C", name="f1") f2 = model.addVar(vtype="C", name="f2") model.addCons(f1 == T - min_time, "obj1") model.addCons(f2 == C - min_cost, "obj2") # print("optimizing distance to ideal point:" for i in range(segments+1): lambda_ = float(i)/segments # print(lambda_ z = model.addVar(name="z") Obj = model.addCons(lambda_*f1*f1 + (1-lambda_)*f2*f2 == z) model.setObjective(z, "minimize") optimize(model, cand) # find the minimum cost routes return cand
220,142
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): model = base_model(n,c,t) # base model for minimizing cost or time x,u,C,T = model.data def explore(C1,T1,C2,T2,front): alpha = float(C1 - C2)/(T2 - T1) # print("%s,%s -- %s,%s (%s)..." % (C1,T1,C2,T2,alpha) init = list(front) model.setObjective(quicksum((c[i,j] + alpha*t[i,j])*x[i,j] for (i,j) in x), "minimize") optimize(model,front) front = pareto_front(front) # print("... added %s points" % (len(front)-len(init)) if front == init: # print("no points added, returning" return front CM = model.getVal(C) TM = model.getVal(T) # print("will explore %s,%s -- %s,%s and %s,%s -- %s,%s" % (C1,T1,CM,TM,CM,TM,C2,T2) if TM > T1: front = explore(C1,T1,CM,TM,front) if T2 > TM: front = explore(CM,TM,C2,T2,front) return front # store the set of solutions for plotting cand = [] # to store the set of solutions for plotting model.setObjective(T, "minimize") stat = optimize(model,cand) if stat != "optimal": return [] C1 = model.getVal(C) T1 = model.getVal(T) # change the objective function to minimize the travel cost model.setObjective(C, "minimize") stat = optimize(model,cand) if stat != "optimal": return [] C2 = model.getVal(C) T2 = model.getVal(T) front = pareto_front(cand) return explore(C1,T1,C2,T2,front)
220,143
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): # model.Params.OutputFlag = 0 # silent mode model.setObjective(obj,"minimize") model.optimize() x,y,C,U = model.data status = model.getStatus() if status == "optimal" or status == "bestsollimit": # todo GRB.Status.SUBOPTIMAL: sols = model.getSols() for sol in sols: cand.append((model.getVal(var=U,solution=sol),model.getVal(var=C,solution=sol))) # for k in range(model.SolCount): # model.Params.SolutionNumber = k # cand.append(model.getVal(U),model.getVal(C)) return status
220,146
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 point i from facility j Returns a model, ready to be solved.
def flp(I,J,d,M,f,c): model = Model("flp") x,y = {},{} for j in J: y[j] = model.addVar(vtype="B", name="y(%s)"%j) for i in I: x[i,j] = model.addVar(vtype="C", name="x(%s,%s)"%(i,j)) for i in I: model.addCons(quicksum(x[i,j] for j in J) == d[i], "Demand(%s)"%i) for j in M: model.addCons(quicksum(x[i,j] for i in I) <= M[j]*y[j], "Capacity(%s)"%i) for (i,j) in x: model.addCons(x[i,j] <= d[i]*y[j], "Strong(%s,%s)"%(i,j)) model.setObjective( quicksum(f[j]*y[j] for j in J) + quicksum(c[i,j]*x[i,j] for i in I for j in J), "minimize") model.data = x,y return model
220,151
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 available - q[i]: demand for customer i - Q: vehicle capacity Returns the optimum objective value and the list of edges used.
def solve_vrp(V,c,m,q,Q): def addcut(cut_edges): G = networkx.Graph() G.add_edges_from(cut_edges) Components = networkx.connected_components(G) cut = False for S in Components: S_card = len(S) q_sum = sum(q[i] for i in S) NS = int(math.ceil(float(q_sum)/Q)) S_edges = [(i,j) for i in S for j in S if i<j and (i,j) in cut_edges] if S_card >= 3 and (len(S_edges) >= S_card or NS > 1): add = model.addCons(quicksum(x[i,j] for i in S for j in S if j > i) <= S_card-NS) cut = True return cut model = Model("vrp") x = {} for i in V: for j in V: if j > i and i == V[0]: # depot x[i,j] = model.addVar(ub=2, vtype="I", name="x(%s,%s)"%(i,j)) elif j > i: x[i,j] = model.addVar(ub=1, vtype="I", name="x(%s,%s)"%(i,j)) model.addCons(quicksum(x[V[0],j] for j in V[1:]) == 2*m, "DegreeDepot") for i in V[1:]: model.addCons(quicksum(x[j,i] for j in V if j < i) + quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i) model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j>i), "minimize") model.hideOutput() EPS = 1.e-6 while True: model.optimize() edges = [] for (i,j) in x: if model.getVal(x[i,j]) > EPS: if i != V[0] and j != V[0]: edges.append((i,j)) if addcut(edges) == False: break return model.getObjVal(),edges
220,153
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): model = Model("k-center") z,y,x = {},{},{} for i in I: z[i] = model.addVar(vtype="B", name="z(%s)"%i, obj=1) for j in J: y[j] = model.addVar(vtype="B", name="y(%s)"%j) for i in I: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for i in I: model.addCons(quicksum(x[i,j] for j in J) + z[i] == 1, "Assign(%s)"%i) for j in J: model.addCons(x[i,j] <= y[j], "Strong(%s,%s)"%(i,j)) model.addCons(sum(y[j] for j in J) == k, "k_center") model.data = x,y,z return model
220,154
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 bisection Returns: - list of facilities to be used - edges linking them to customers
def solve_kcenter(I,J,c,k,delta): model = kcover(I,J,c,k) x,y,z = model.data facilities,edges = [],[] LB = 0 UB = max(c[i,j] for (i,j) in c) model.setObjlimit(0.1) while UB-LB > delta: theta = (UB+LB) / 2. # print "\n\ncurrent theta:", theta for j in J: for i in I: if c[i,j]>theta: model.chgVarUb(x[i,j], 0.0) else: model.chgVarUb(x[i,j], 1.0) # model.Params.OutputFlag = 0 # silent mode model.setObjlimit(.1) model.optimize() if model.getStatus == "optimal": # infeasibility = sum([z[i].X for i in I]) # print "infeasibility=",infeasibility UB = theta facilities = [j for j in y if model.getVal(y[j]) > .5] edges = [(i,j) for (i,j) in x if model.getVal(x[i,j]) > .5] # print "updated solution:" # print "facilities",facilities # print "edges",edges else: # infeasibility > 0: LB = theta return facilities,edges
220,155
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 quantity) Returns a model, ready to be solved.
def eoq_soco(I,F,h,d,w,W): model = Model("EOQ model using SOCO") T,c = {},{} for i in I: T[i] = model.addVar(vtype="C", name="T(%s)"%i) # cycle time for item i c[i] = model.addVar(vtype="C", name="c(%s)"%i) # total cost for item i for i in I: model.addCons(F[i] <= c[i]*T[i]) model.addCons(quicksum(w[i]*d[i]*T[i] for i in I) <= W) model.setObjective(quicksum(c[i] + h[i]*d[i]*T[i]*0.5 for i in I), "minimize") model.data = T,c return model
220,156
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 node i Returns a model, ready to be solved.
def mtztw(n,c,e,l): model = Model("tsptw - mtz") x,u = {},{} for i in range(1,n+1): u[i] = model.addVar(lb=e[i], ub=l[i], vtype="C", name="u(%s)"%i) for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for i in range(1,n+1): model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i) model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i) for i in range(1,n+1): for j in range(2,n+1): if i != j: M = max(l[i] + c[i,j] - e[j], 0) model.addCons(u[i] - u[j] + M*x[i,j] <= M-c[i,j], "MTZ(%s,%s)"%(i,j)) model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.data = x,u return model
220,157
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]: latest date for visiting node i Returns a model, ready to be solved.
def mtz2tw(n,c,e,l): model = Model("tsptw - mtz-strong") x,u = {},{} for i in range(1,n+1): u[i] = model.addVar(lb=e[i], ub=l[i], vtype="C", name="u(%s)"%i) for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for i in range(1,n+1): model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i) model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i) for j in range(2,n+1): if i != j: M1 = max(l[i] + c[i,j] - e[j], 0) M2 = max(l[i] + min(-c[j,i], e[j]-e[i]) - e[j], 0) model.addCons(u[i] + c[i,j] - M1*(1-x[i,j]) + M2*x[j,i] <= u[j], "LiftedMTZ(%s,%s)"%(i,j)) for i in range(2,n+1): model.addCons(e[i] + quicksum(max(e[j]+c[j,i]-e[i],0) * x[j,i] for j in range(1,n+1) if i != j) \ <= u[i], "LiftedLB(%s)"%i) model.addCons(u[i] <= l[i] - \ quicksum(max(l[i]-l[j]+c[i,j],0) * x[i,j] for j in range(2,n+1) if i != j), \ "LiftedUB(%s)"%i) model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.data = x,u return model
220,158
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 visiting node i Returns a model, ready to be solved.
def tsptw2(n,c,e,l): model = Model("tsptw2") x,u = {},{} for i in range(1,n+1): for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) u[i,j] = model.addVar(vtype="C", name="u(%s,%s)"%(i,j)) for i in range(1,n+1): model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i) model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i) for j in range(2,n+1): model.addCons(quicksum(u[i,j] + c[i,j]*x[i,j] for i in range(1,n+1) if i != j) - quicksum(u[j,k] for k in range(1,n+1) if k != j) <= 0, "Relate(%s)"%j) for i in range(1,n+1): for j in range(1,n+1): if i != j: model.addCons(e[i]*x[i,j] <= u[i,j], "LB(%s,%s)"%(i,j)) model.addCons(u[i,j] <= l[i]*x[i,j], "UB(%s,%s)"%(i,j)) model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize") model.data = x,u return model
220,159
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): remain = [B] # keep list of empty space per bin sol = [[]] # a list ot items (i.e., sizes) on each used bin for item in sorted(s,reverse=True): for (j,free) in enumerate(remain): if free >= item: remain[j] -= item sol[j].append(item) break else: #does not fit in any bin sol.append([item]) remain.append(B-item) return sol
220,170
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): n = len(s) U = len(FFD(s,B)) # upper bound of the number of bins model = Model("bpp") # setParam("MIPFocus",1) x,y = {},{} for i in range(n): for j in range(U): x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) for j in range(U): y[j] = model.addVar(vtype="B", name="y(%s)"%j) # assignment constraints for i in range(n): model.addCons(quicksum(x[i,j] for j in range(U)) == 1, "Assign(%s)"%i) # bin capacity constraints for j in range(U): model.addCons(quicksum(s[i]*x[i,j] for i in range(n)) <= B*y[j], "Capac(%s)"%j) # tighten assignment constraints for j in range(U): for i in range(n): model.addCons(x[i,j] <= y[j], "Strong(%s,%s)"%(i,j)) # tie breaking constraints for j in range(U-1): model.addCons(y[j] >= y[j+1],"TieBrk(%s)"%j) # SOS constraints for i in range(n): model.addConsSOS1([x[i,j] for j in range(U)]) model.setObjective(quicksum(y[j] for j in range(U)), "minimize") model.data = x,y return model
220,171
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): n = len(s) U = len(FFD(s,B)) # upper bound of the number of bins model = bpp(s,B) x,y = model.data model.optimize() bins = [[] for i in range(U)] for (i,j) in x: if model.getVal(x[i,j]) > .5: bins[j].append(s[i]) for i in range(bins.count([])): bins.remove([]) for b in bins: b.sort() bins.sort() return bins
220,172
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): def addcut(cut_edges): G = networkx.Graph() G.add_edges_from(cut_edges) Components = list(networkx.connected_components(G)) if len(Components) == 1: return False model.freeTransform() for S in Components: model.addCons(quicksum(x[i,j] for i in S for j in S if j>i) <= len(S)-1) print("cut: len(%s) <= %s" % (S,len(S)-1)) return True def addcut2(cut_edges): G = networkx.Graph() G.add_edges_from(cut_edges) Components = list(networkx.connected_components(G)) if len(Components) == 1: return False model.freeTransform() for S in Components: T = set(V) - set(S) print("S:",S) print("T:",T) model.addCons(quicksum(x[i,j] for i in S for j in T if j>i) + quicksum(x[i,j] for i in T for j in S if j>i) >= 2) print("cut: %s >= 2" % "+".join([("x[%s,%s]" % (i,j)) for i in S for j in T if j>i])) return True # main part of the solution process: model = Model("tsp") model.hideOutput() # silent/verbose mode x = {} for i in V: for j in V: if j > i: x[i,j] = model.addVar(ub=1, name="x(%s,%s)"%(i,j)) for i in V: model.addCons(quicksum(x[j,i] for j in V if j < i) + \ quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i) model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j > i), "minimize") EPS = 1.e-6 isMIP = False while True: model.optimize() edges = [] for (i,j) in x: if model.getVal(x[i,j]) > EPS: edges.append( (i,j) ) if addcut(edges) == False: if isMIP: # integer variables, components connected: solution found break model.freeTransform() for (i,j) in x: # all components connected, switch to integer model model.chgVarType(x[i,j], "B") isMIP = True return model.getObjVal(),edges
220,174
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 - d[t]: demand values - h[t]: holding costs Returns the final model solved, with all necessary cuts added.
def sils_cut(T,f,c,d,h): Ts = range(1,T+1) model = sils(T,f,c,d,h) y,x,I = model.data # relax integer variables for t in Ts: y[t].vtype = "C" # compute D[i,j] = sum_{t=i}^j d[t] D = {} for t in Ts: s = 0 for j in range(t,T+1): s += d[j] D[t,j] = s EPS = 1.e-6 cuts = True while cuts: model.optimize() cuts = False for ell in Ts: lhs = 0 S,L = [],[] for t in range(1,ell+1): yt = model.getVal(y[t]) xt = model.getVal(x[t]) if D[t,ell]*yt < xt: S.append(t) lhs += D[t,ell]*yt else: L.append(t) lhs += xt if lhs < D[1,ell]: # add cutting plane constraint model.addCons(quicksum([x[t] for t in L]) +\ quicksum(D[t,ell] * y[t] for t in S) >= D[1,ell]) cuts = True model.data = y,x,I return model
220,175
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 relation on added variables x, f, and z.
def ssa(n,h,K,f,T): model = Model("safety stock allocation") # calculate endpoints for linear segments a,b = {},{} for i in range(1,n+1): a[i] = [k for k in range(K)] b[i] = [f(i,k) for k in range(K)] # x: net replenishment time for stage i # y: corresponding cost # s: piecewise linear segment of variable x x,y,s = {},{},{} L = {} # service time of stage i for i in range(1,n+1): x[i],y[i],s[i] = convex_comb_sos(model,a[i],b[i]) if i == 1: L[i] = model.addVar(ub=0, vtype="C", name="L[%s]"%i) else: L[i] = model.addVar(vtype="C", name="L[%s]"%i) L[n+1] = model.addVar(ub=0, vtype="C", name="L[%s]"%(n+1)) for i in range(1,n+1): # net replenishment time for each stage i model.addCons(x[i] + L[i] == T[i] + L[i+1]) model.setObjective(quicksum(h[i]*y[i] for i in range(1,n+1)), "minimize") model.data = x,s,L return model
220,176
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]: holding costs - M[t]: resource upper bound on period t Returns a model, ready to be solved.
def mils(T,P,f,g,c,d,h,M): def mils_callback(model,where): # remember to set model.params.DualReductions = 0 before using! if where != GRB.Callback.MIPSOL and where != GRB.Callback.MIPNODE: return for p in P: for ell in Ts: lhs = 0 S,L = [],[] for t in range(1,ell+1): yt = model.cbGetSolution(y[t,p]) xt = model.cbGetSolution(x[t,p]) if D[t,ell,p]*yt < xt: S.append(t) lhs += D[t,ell,p]*yt else: L.append(t) lhs += xt if lhs < D[1,ell,p]: # add cutting plane constraint model.cbLazy(quicksum(x[t,p] for t in L) +\ quicksum(D[t,ell,p] * y[t,p] for t in S) >= D[1,ell,p]) return model = Model("standard multi-item lotsizing") y,x,I = {},{},{} Ts = range(1,T+1) for p in P: for t in Ts: y[t,p] = model.addVar(vtype="B", name="y(%s,%s)"%(t,p)) x[t,p] = model.addVar(vtype="C", name="x(%s,%s)"%(t,p)) I[t,p] = model.addVar(vtype="C", name="I(%s,%s)"%(t,p)) I[0,p] = 0 for t in Ts: # time capacity constraints model.addCons(quicksum(g[t,p]*y[t,p] + x[t,p] for p in P) <= M[t], "TimeUB(%s)"%(t)) for p in P: # flow conservation constraints model.addCons(I[t-1,p] + x[t,p] == I[t,p] + d[t,p], "FlowCons(%s,%s)"%(t,p)) # capacity connection constraints model.addCons(x[t,p] <= (M[t]-g[t,p])*y[t,p], "ConstrUB(%s,%s)"%(t,p)) # tighten constraints model.addCons(x[t,p] <= d[t,p]*y[t,p] + I[t,p], "Tighten(%s,%s)"%(t,p)) model.setObjective(\ quicksum(f[t,p]*y[t,p] + c[t,p]*x[t,p] + h[t,p]*I[t,p] for t in Ts for p in P),\ "minimize") # compute D[i,j,p] = sum_{t=i}^j d[t,p] D = {} for p in P: for t in Ts: s = 0 for j in range(t,T+1): s += d[j,p] D[t,j,p] = s model.data = y,x,I return model,mils_callback
220,178
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): model = Model("gcp") x,y = {},{} for k in range(K): y[k] = model.addVar(vtype="B", name="y(%s)"%k) for i in V: x[i,k] = model.addVar(vtype="B", name="x(%s,%s)"%(i,k)) for i in V: model.addCons(quicksum(x[i,k] for k in range(K)) == 1, "AssignColor(%s)"%i) for (i,j) in E: for k in range(K): model.addCons(x[i,k] + x[j,k] <= y[k], "NotSameColor(%s,%s,%s)"%(i,j,k)) model.setObjective(quicksum(y[k] for k in range(K)), "minimize") model.data = x return model
220,181
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): model = Model("robust product mix") x,rhs = {},{} for i in I: x[i] = model.addVar(vtype="C", name="x(%s)"%i) for k in K: rhs[k] = model.addVar(vtype="C", name="rhs(%s)"%k) model.addCons(quicksum(x[i] for i in I) == 1) for k in K: model.addCons(rhs[k] == -LB[k]+ quicksum(a[i,k]*x[i] for i in I) ) model.addCons(quicksum(epsilon*epsilon*x[i]*x[i] for i in I) <= rhs[k]*rhs[k]) model.setObjective(quicksum(p[i]*x[i] for i in I), "minimize") model.data = x,rhs return model
220,184
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): model = Model("ssp") x = {} for i in V: x[i] = model.addVar(vtype="B", name="x(%s)"%i) for (i,j) in E: model.addCons(x[i] + x[j] <= 1, "Edge(%s,%s)"%(i,j)) model.setObjective(quicksum(x[i] for i in V), "maximize") model.data = x return model
220,186
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 relation Returns the model with the piecewise linear relation on added variables X, Y, and z.
def mult_selection(model,a,b): K = len(a)-1 w,z = {},{} for k in range(K): w[k] = model.addVar(lb=-model.infinity()) # do not name variables for avoiding clash z[k] = model.addVar(vtype="B") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity()) for k in range(K): model.addCons(w[k] >= a[k]*z[k]) model.addCons(w[k] <= a[k+1]*z[k]) model.addCons(quicksum(z[k] for k in range(K)) == 1) model.addCons(X == quicksum(w[k] for k in range(K))) c = [float(b[k+1]-b[k])/(a[k+1]-a[k]) for k in range(K)] d = [b[k]-c[k]*a[k] for k in range(K)] model.addCons(Y == quicksum(d[k]*z[k] + c[k]*w[k] for k in range(K))) return X,Y,z
220,187
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 Returns the model with the piecewise linear relation on added variables X, Y, and z.
def convex_comb_sos(model,a,b): K = len(a)-1 z = {} for k in range(K+1): z[k] = model.addVar(lb=0, ub=1, vtype="C") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity(), vtype="C") model.addCons(X == quicksum(a[k]*z[k] for k in range(K+1))) model.addCons(Y == quicksum(b[k]*z[k] for k in range(K+1))) model.addCons(quicksum(z[k] for k in range(K+1)) == 1) model.addConsSOS2([z[k] for k in range(K+1)]) return X,Y,z
220,188
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 relation Returns the model with the piecewise linear relation on added variables X, Y, and z.
def convex_comb_dis(model,a,b): K = len(a)-1 wL,wR,z = {},{},{} for k in range(K): wL[k] = model.addVar(lb=0, ub=1, vtype="C") wR[k] = model.addVar(lb=0, ub=1, vtype="C") z[k] = model.addVar(vtype="B") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity(), vtype="C") model.addCons(X == quicksum(a[k]*wL[k] + a[k+1]*wR[k] for k in range(K))) model.addCons(Y == quicksum(b[k]*wL[k] + b[k+1]*wR[k] for k in range(K))) for k in range(K): model.addCons(wL[k] + wR[k] == z[k]) model.addCons(quicksum(z[k] for k in range(K)) == 1) return X,Y,z
220,189
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]: y-coordinate of the k-th point in the piecewise linear relation Returns the model with the piecewise linear relation on added variables X, Y, and z.
def convex_comb_dis_log(model,a,b): K = len(a)-1 G = int(math.ceil((math.log(K)/math.log(2)))) # number of required bits N = 1<<G # number of required variables # print("K,G,N:",K,G,N wL,wR,z = {},{},{} for k in range(N): wL[k] = model.addVar(lb=0, ub=1, vtype="C") wR[k] = model.addVar(lb=0, ub=1, vtype="C") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity(), vtype="C") g = {} for j in range(G): g[j] = model.addVar(vtype="B") model.addCons(X == quicksum(a[k]*wL[k] + a[k+1]*wR[k] for k in range(K))) model.addCons(Y == quicksum(b[k]*wL[k] + b[k+1]*wR[k] for k in range(K))) model.addCons(quicksum(wL[k] + wR[k] for k in range(K)) == 1) # binary variables setup for j in range(G): ones = [] zeros = [] for k in range(K): if k & (1<<j): ones.append(k) else: zeros.append(k) model.addCons(quicksum(wL[k] + wR[k] for k in ones) <= g[j]) model.addCons(quicksum(wL[k] + wR[k] for k in zeros) <= 1-g[j]) return X,Y,wL,wR
220,190
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 piecewise linear relation Returns the model with the piecewise linear relation on added variables X, Y, and z.
def convex_comb_agg(model,a,b): K = len(a)-1 w,z = {},{} for k in range(K+1): w[k] = model.addVar(lb=0, ub=1, vtype="C") for k in range(K): z[k] = model.addVar(vtype="B") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity(), vtype="C") model.addCons(X == quicksum(a[k]*w[k] for k in range(K+1))) model.addCons(Y == quicksum(b[k]*w[k] for k in range(K+1))) model.addCons(w[0] <= z[0]) model.addCons(w[K] <= z[K-1]) for k in range(1,K): model.addCons(w[k] <= z[k-1]+z[k]) model.addCons(quicksum(w[k] for k in range(K+1)) == 1) model.addCons(quicksum(z[k] for k in range(K)) == 1) return X,Y,z
220,191
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 relation - b[k]: y-coordinate of the k-th point in the piecewise linear relation Returns the model with the piecewise linear relation on added variables X, Y, and z.
def convex_comb_agg_log(model,a,b): K = len(a)-1 G = int(math.ceil((math.log(K)/math.log(2)))) # number of required bits w,g = {},{} for k in range(K+1): w[k] = model.addVar(lb=0, ub=1, vtype="C") for j in range(G): g[j] = model.addVar(vtype="B") X = model.addVar(lb=a[0], ub=a[K], vtype="C") Y = model.addVar(lb=-model.infinity(), vtype="C") model.addCons(X == quicksum(a[k]*w[k] for k in range(K+1))) model.addCons(Y == quicksum(b[k]*w[k] for k in range(K+1))) model.addCons(quicksum(w[k] for k in range(K+1)) == 1) # binary variables setup for j in range(G): zeros,ones = [0],[] # print(j,"\tinit zeros:",zeros,"ones:",ones for k in range(1,K+1): # print(j,k,"\t>zeros:",zeros,"ones:",ones if (1 & gray(k)>>j) == 1 and (1 & gray(k-1)>>j) == 1: ones.append(k) if (1 & gray(k)>>j) == 0 and (1 & gray(k-1)>>j) == 0: zeros.append(k) # print(j,k,"\tzeros>:",zeros,"ones:",ones # print(j,"\tzeros:",zeros,"ones:",ones model.addCons(quicksum(w[k] for k in ones) <= g[j]) model.addCons(quicksum(w[k] for k in zeros) <= 1-g[j]) return X,Y,w
220,192
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): model = Model("gcp - fixed k") x,z = {},{} for i in V: for k in range(K): x[i,k] = model.addVar(vtype="B", name="x(%s,%s)"%(i,k)) for (i,j) in E: z[i,j] = model.addVar(vtype="B", name="z(%s,%s)"%(i,j)) for i in V: model.addCons(quicksum(x[i,k] for k in range(K)) == 1, "AssignColor(%s)" % i) for (i,j) in E: for k in range(K): model.addCons(x[i,k] + x[j,k] <= 1 + z[i,j], "BadEdge(%s,%s,%s)"%(i,j,k)) model.setObjective(quicksum(z[i,j] for (i,j) in E), "minimize") model.data = x,z return model
220,199
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): LB = 0 UB = len(V) color = {} while UB-LB > 1: K = int((UB+LB) / 2) gcp = gcp_fixed_k(V,E,K) # gcp.Params.OutputFlag = 0 # silent mode #gcp.Params.Cutoff = .1 gcp.setObjlimit(0.1) gcp.optimize() status = gcp.getStatus() if status == "optimal": x,z = gcp.data for i in V: for k in range(K): if gcp.getVal(x[i,k]) > 0.5: color[i] = k break # else: # raise "undefined color for", i UB = K else: LB = K return UB,color
220,200
Load a Qt Designer .ui file and returns an instance of the user interface Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Returns: QWidget: the base instance
def setup_ui(uifile, base_instance=None): ui = QtCompat.loadUi(uifile) # Qt.py mapped function if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui
220,540
Return blocks of code as list of dicts Arguments: fname (str): Relative name of caveats file
def parse(fname): blocks = list() with io.open(fname, "r", encoding="utf-8") as f: in_block = False current_block = None current_header = "" for line in f: # Doctests are within a quadruple hashtag header. if line.startswith("#### "): current_header = line.rstrip() # The actuat test is within a fenced block. if line.startswith("```"): in_block = False if in_block: current_block.append(line) if line.startswith("```python"): in_block = True current_block = list() current_block.append(current_header) blocks.append(current_block) tests = list() for block in blocks: header = ( block[0].strip("# ") # Remove Markdown .rstrip() # Remove newline .lower() # PEP08 ) # Remove unsupported characters header = re.sub(r"\W", "_", header) # Adding "untested" anywhere in the first line of # the doctest excludes it from the test. if "untested" in block[1].lower(): continue data = re.sub(" ", "", block[1]) # Remove spaces data = ( data.strip("#") .rstrip() # Remove newline .split(",") ) binding, doctest_version = (data + [None])[:2] # Run tests on both Python 2 and 3, unless explicitly stated if doctest_version is not None: if doctest_version not in ("Python2", "Python3"): raise SyntaxError( "Invalid Python version:\n%s\n" "Python version must follow binding, e.g.\n" "# PyQt5, Python3" % doctest_version) active_version = "Python%i" % sys.version_info[0] if doctest_version != active_version: continue tests.append({ "header": header, "binding": binding, "body": block[2:] }) return tests
220,548
Produce Python module from blocks of tests Arguments: blocks (list): Blocks of tests from func:`parse()`
def format_(blocks): tests = list() function_count = 0 # For each test to have a unique name for block in blocks: # Validate docstring format of body if not any(line[:3] == ">>>" for line in block["body"]): # A doctest requires at least one `>>>` directive. block["body"].insert(0, ">>> assert False, " "'Body must be in docstring format'\n") # Validate binding on first line if not block["binding"] in ("PySide", "PySide2", "PyQt5", "PyQt4"): block["body"].insert(0, ">>> assert False, " "'Invalid binding'\n") if sys.version_info > (3, 4) and block["binding"] in ("PySide"): # Skip caveat test if it requires PySide on Python > 3.4 continue else: function_count += 1 block["header"] = block["header"] block["count"] = str(function_count) block["body"] = " ".join(block["body"]) tests.append(.format(**block)) return tests
220,549
Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None
def _qInstallMessageHandler(handler): def messageOutputHandler(*args): # In Qt4 bindings, message handlers are passed 2 arguments # In Qt5 bindings, message handlers are passed 3 arguments # The first argument is a QtMsgType # The last argument is the message to be printed # The Middle argument (if passed) is a QMessageLogContext if len(args) == 3: msgType, logContext, msg = args elif len(args) == 2: msgType, msg = args logContext = None else: raise TypeError( "handler expected 2 or 3 arguments, got {0}".format(len(args))) if isinstance(msg, bytes): # In python 3, some bindings pass a bytestring, which cannot be # used elsewhere. Decoding a python 2 or 3 bytestring object will # consistently return a unicode object. msg = msg.decode() handler(msgType, logContext, msg) passObject = messageOutputHandler if handler else handler if Qt.IsPySide or Qt.IsPyQt4: return Qt._QtCore.qInstallMsgHandler(passObject) elif Qt.IsPySide2 or Qt.IsPyQt5: return Qt._QtCore.qInstallMessageHandler(passObject)
220,550
Apply misplaced members from `binding` to Qt.py Arguments: binding (dict): Misplaced members
def _reassign_misplaced_members(binding): for src, dst in _misplaced_members[binding].items(): dst_value = None src_parts = src.split(".") src_module = src_parts[0] src_member = None if len(src_parts) > 1: src_member = src_parts[1:] if isinstance(dst, (list, tuple)): dst, dst_value = dst dst_parts = dst.split(".") dst_module = dst_parts[0] dst_member = None if len(dst_parts) > 1: dst_member = dst_parts[1] # Get the member we want to store in the namesapce. if not dst_value: try: _part = getattr(Qt, "_" + src_module) while src_member: member = src_member.pop(0) _part = getattr(_part, member) dst_value = _part except AttributeError: # If the member we want to store in the namespace does not # exist, there is no need to continue. This can happen if a # request was made to rename a member that didn't exist, for # example if QtWidgets isn't available on the target platform. _log("Misplaced member has no source: {0}".format(src)) continue try: src_object = getattr(Qt, dst_module) except AttributeError: if dst_module not in _common_members: # Only create the Qt parent module if its listed in # _common_members. Without this check, if you remove QtCore # from _common_members, the default _misplaced_members will add # Qt.QtCore so it can add Signal, Slot, etc. msg = 'Not creating missing member module "{m}" for "{c}"' _log(msg.format(m=dst_module, c=dst_member)) continue # If the dst is valid but the Qt parent module does not exist # then go ahead and create a new module to contain the member. setattr(Qt, dst_module, _new_module(dst_module)) src_object = getattr(Qt, dst_module) # Enable direct import of the new module sys.modules[__name__ + "." + dst_module] = src_object if not dst_value: dst_value = getattr(Qt, "_" + src_module) if src_member: dst_value = getattr(dst_value, src_member) setattr( src_object, dst_member or dst_module, dst_value )
220,558
Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions.
def _build_compatibility_members(binding, decorators=None): decorators = decorators or dict() # Allow optional site-level customization of the compatibility members. # This method does not need to be implemented in QtSiteConfig. try: import QtSiteConfig except ImportError: pass else: if hasattr(QtSiteConfig, 'update_compatibility_decorators'): QtSiteConfig.update_compatibility_decorators(binding, decorators) _QtCompat = type("QtCompat", (object,), {}) for classname, bindings in _compatibility_members[binding].items(): attrs = {} for target, binding in bindings.items(): namespaces = binding.split('.') try: src_object = getattr(Qt, "_" + namespaces[0]) except AttributeError as e: _log("QtCompat: AttributeError: %s" % e) # Skip reassignment of non-existing members. # This can happen if a request was made to # rename a member that didn't exist, for example # if QtWidgets isn't available on the target platform. continue # Walk down any remaining namespace getting the object assuming # that if the first namespace exists the rest will exist. for namespace in namespaces[1:]: src_object = getattr(src_object, namespace) # decorate the Qt method if a decorator was provided. if target in decorators.get(classname, []): # staticmethod must be called on the decorated method to # prevent a TypeError being raised when the decorated method # is called. src_object = staticmethod( decorators[classname][target](src_object)) attrs[target] = src_object # Create the QtCompat class and install it into the namespace compat_class = type(classname, (_QtCompat,), attrs) setattr(Qt.QtCompat, classname, compat_class)
220,559
Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines())
def _convert(lines): def parse(line): line = line.replace("from PySide2 import", "from Qt import QtCompat,") line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate") if "QtCore.SIGNAL" in line: raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 " "and so Qt.py does not support it: you " "should avoid defining signals inside " "your ui files.") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
220,563
This optional function is called by Qt.py to modify the decorators applied to QtCompat namespace objects. Arguments: binding (str): The Qt binding being wrapped by Qt.py decorators (dict): Maps specific decorator functions to QtCompat namespace methods. See Qt._build_compatibility_members for more info.
def update_compatibility_decorators(binding, decorators): def _widgetDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper # Assign a different decorator for the same method name on each class def _mainWindowDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "QMainWindow Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper decorators.setdefault("QWidget", {})["windowTitleDecorator"] = ( _widgetDecorator ) decorators.setdefault("QMainWindow", {})["windowTitleDecorator"] = ( _mainWindowDecorator )
220,566
Provide PyQt4.uic.loadUi functionality to PySide Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Note: pysideuic is required for this to work with PySide. This seems to work correctly in Maya as well as outside of it as opposed to other implementations which involve overriding QUiLoader. Returns: QWidget: the base instance
def pyside_load_ui(uifile, base_instance=None): form_class, base_class = load_ui_type(uifile) if not base_instance: typeName = form_class.__name__ finalType = type(typeName, (form_class, base_class), {}) base_instance = finalType() else: if not isinstance(base_instance, base_class): raise RuntimeError( 'The base_instance passed to loadUi does not inherit from' ' needed base type (%s)' % type(base_class)) typeName = type(base_instance).__name__ base_instance.__class__ = type(typeName, (form_class, type(base_instance)), {}) base_instance.setupUi(base_instance) return base_instance
220,568
Load a Qt Designer .ui file and returns an instance of the user interface Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Returns: function: pyside_load_ui or uic.loadUi
def load_ui_wrapper(uifile, base_instance=None): if 'PySide' in __binding__: return pyside_load_ui(uifile, base_instance) elif 'PyQt' in __binding__: uic = __import__(__binding__ + ".uic").uic return uic.loadUi(uifile, base_instance)
220,569
Like load, but returns None if the load fails due to a cache miss. Args: on_error (str): How to handle non-io errors errors. Either raise, which re-raises the exception, or clear which deletes the cache and returns None.
def tryload(self, cfgstr=None, on_error='raise'): cfgstr = self._rectify_cfgstr(cfgstr) if self.enabled: try: if self.verbose > 1: self.log('[cacher] tryload fname={}'.format(self.fname)) return self.load(cfgstr) except IOError: if self.verbose > 0: self.log('[cacher] ... {} cache miss'.format(self.fname)) except Exception: if self.verbose > 0: self.log('[cacher] ... failed to load') if on_error == 'raise': raise elif on_error == 'clear': self.clear(cfgstr) return None else: raise KeyError('Unknown method on_error={}'.format(on_error)) else: if self.verbose > 1: self.log('[cacher] ... cache disabled: fname={}'.format(self.fname)) return None
221,144
Check to see if a previously existing stamp is still valid and if the expected result of that computation still exists. Args: cfgstr (str, optional): override the default cfgstr if specified product (PathLike or Sequence[PathLike], optional): override the default product if specified
def expired(self, cfgstr=None, product=None): products = self._rectify_products(product) certificate = self._get_certificate(cfgstr=cfgstr) if certificate is None: # We dont have a certificate, so we are expired is_expired = True elif products is None: # We dont have a product to check, so assume not expired is_expired = False elif not all(map(os.path.exists, products)): # We are expired if the expected product does not exist is_expired = True else: # We are expired if the hash of the existing product data # does not match the expected hash in the certificate product_file_hash = self._product_file_hash(products) certificate_hash = certificate.get('product_file_hash', None) is_expired = product_file_hash != certificate_hash return is_expired
221,153
Calls `get_app_data_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_data_dir Example: >>> import ubelt as ub >>> dpath = ub.ensure_app_data_dir('ubelt') >>> assert exists(dpath)
def ensure_app_data_dir(appname, *args): from ubelt import util_path dpath = get_app_data_dir(appname, *args) util_path.ensuredir(dpath) return dpath
221,168
Calls `get_app_config_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_config_dir Example: >>> import ubelt as ub >>> dpath = ub.ensure_app_config_dir('ubelt') >>> assert exists(dpath)
def ensure_app_config_dir(appname, *args): from ubelt import util_path dpath = get_app_config_dir(appname, *args) util_path.ensuredir(dpath) return dpath
221,169
Calls `get_app_cache_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_cache_dir Example: >>> import ubelt as ub >>> dpath = ub.ensure_app_cache_dir('ubelt') >>> assert exists(dpath)
def ensure_app_cache_dir(appname, *args): from ubelt import util_path dpath = get_app_cache_dir(appname, *args) util_path.ensuredir(dpath) return dpath
221,170
Returns the user's home directory. If `username` is None, this is the directory for the current user. Args: username (str): name of a user on the system Returns: PathLike: userhome_dpath: path to the home directory Example: >>> import getpass >>> username = getpass.getuser() >>> assert userhome() == expanduser('~') >>> assert userhome(username) == expanduser('~')
def userhome(username=None): if username is None: # get home directory for the current user if 'HOME' in os.environ: userhome_dpath = os.environ['HOME'] else: # nocover if sys.platform.startswith('win32'): # win32 fallback when HOME is not defined if 'USERPROFILE' in os.environ: userhome_dpath = os.environ['USERPROFILE'] elif 'HOMEPATH' in os.environ: drive = os.environ.get('HOMEDRIVE', '') userhome_dpath = join(drive, os.environ['HOMEPATH']) else: raise OSError("Cannot determine the user's home directory") else: # posix fallback when HOME is not defined import pwd userhome_dpath = pwd.getpwuid(os.getuid()).pw_dir else: # A specific user directory was requested if sys.platform.startswith('win32'): # nocover # get the directory name for the current user c_users = dirname(userhome()) userhome_dpath = join(c_users, username) if not exists(userhome_dpath): raise KeyError('Unknown user: {}'.format(username)) else: import pwd try: pwent = pwd.getpwnam(username) except KeyError: # nocover raise KeyError('Unknown user: {}'.format(username)) userhome_dpath = pwent.pw_dir return userhome_dpath
221,176
Reads (utf8) text from a file. Args: fpath (PathLike): file path aslines (bool): if True returns list of lines verbose (bool): verbosity flag Returns: str: text from fpath (this is unicode)
def readfrom(fpath, aslines=False, errors='replace', verbose=None): if verbose: print('Reading text file: %r ' % (fpath,)) if not exists(fpath): raise IOError('File %r does not exist' % (fpath,)) with open(fpath, 'rb') as file: if aslines: text = [line.decode('utf8', errors=errors) for line in file.readlines()] if sys.platform.startswith('win32'): # nocover # fix line endings on windows text = [ line[:-2] + '\n' if line.endswith('\r\n') else line for line in text ] else: text = file.read().decode('utf8', errors=errors) return text
221,188
Converts `data` into a byte representation and calls update on the hasher `hashlib.HASH` algorithm. Args: hasher (HASH): instance of a hashlib algorithm data (object): ordered data with structure types (bool): include type prefixes in the hash Example: >>> hasher = hashlib.sha512() >>> data = [1, 2, ['a', 2, 'c']] >>> _update_hasher(hasher, data) >>> print(hasher.hexdigest()[0:8]) e2c67675 2ba8d82b
def _update_hasher(hasher, data, types=True): # Determine if the data should be hashed directly or iterated through if isinstance(data, (tuple, list, zip)): needs_iteration = True else: needs_iteration = any(check(data) for check in _HASHABLE_EXTENSIONS.iterable_checks) if needs_iteration: # Denote that we are hashing over an iterable # Multiple structure bytes makes it harder accidently make conflicts SEP = b'_,_' ITER_PREFIX = b'_[_' ITER_SUFFIX = b'_]_' iter_ = iter(data) hasher.update(ITER_PREFIX) # first, try to nest quickly without recursive calls # (this works if all data in the sequence is a non-iterable) try: for item in iter_: prefix, hashable = _convert_to_hashable(item, types) binary_data = prefix + hashable + SEP hasher.update(binary_data) except TypeError: # need to use recursive calls # Update based on current item _update_hasher(hasher, item, types) for item in iter_: # Ensure the items have a spacer between them _update_hasher(hasher, item, types) hasher.update(SEP) hasher.update(ITER_SUFFIX) else: prefix, hashable = _convert_to_hashable(data, types) binary_data = prefix + hashable hasher.update(binary_data)
221,208
make an iso8601 timestamp Args: method (str): type of timestamp Example: >>> stamp = timestamp() >>> print('stamp = {!r}'.format(stamp)) stamp = ...-...-...T...
def timestamp(method='iso8601'): if method == 'iso8601': # ISO 8601 # datetime.datetime.utcnow().isoformat() # datetime.datetime.now().isoformat() # utcnow tz_hour = time.timezone // 3600 utc_offset = str(tz_hour) if tz_hour < 0 else '+' + str(tz_hour) stamp = time.strftime('%Y-%m-%dT%H%M%S') + utc_offset return stamp else: raise ValueError('only iso8601 is accepted for now')
221,224
Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match.
def _SetValues(self, values): def _ToStr(value): if isinstance(value, (list, tuple)): result = [] for val in value: result.append(str(val)) return result else: return str(value) # Row with identical header can be copied directly. if isinstance(values, Row): if self._keys != values.header: raise TypeError('Attempt to append row with mismatched header.') self._values = copy.deepcopy(values.values) elif isinstance(values, dict): for key in self._keys: if key not in values: raise TypeError('Dictionary key mismatch with row.') for key in self._keys: self[key] = _ToStr(values[key]) elif isinstance(values, list) or isinstance(values, tuple): if len(values) != len(self._values): raise TypeError('Supplied list length != row length') for (index, value) in enumerate(values): self._values[index] = _ToStr(value) else: raise TypeError('Supplied argument must be Row, dict or list, not %s', type(values))
222,012
Initialises a new table. Args: row_class: A class to use as the row object. This should be a subclass of this module's Row() class.
def __init__(self, row_class=Row): self.row_class = row_class self.separator = ', ' self.Reset()
222,013
Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextTable() Raises: TableError: When an invalid row entry is Append()'d
def Filter(self, function=None): flat = lambda x: x if isinstance(x, str) else ''.join([flat(y) for y in x]) if function is None: function = lambda row: bool(flat(row.values)) new_table = self.__class__() # pylint: disable=protected-access new_table._table = [self.header] for row in self: if function(row) is True: new_table.Append(row) return new_table
222,014
Returns whole table as rows of name/value pairs. One (or more) column entries are used for the row prefix label. The remaining columns are each displayed as a row entry with the prefix labels appended. Use the first column as the label if label_list is None. Args: label_list: A list of prefix labels to use. Returns: Label/Value formatted table. Raises: TableError: If specified label is not a column header of the table.
def LabelValueTable(self, label_list=None): label_list = label_list or self._Header()[0] # Ensure all labels are valid. for label in label_list: if label not in self._Header(): raise TableError('Invalid label prefix: %s.' % label) sorted_list = [] for header in self._Header(): if header in label_list: sorted_list.append(header) label_str = '# LABEL %s\n' % '.'.join(sorted_list) body = [] for row in self: # Some of the row values are pulled into the label, stored in label_prefix. label_prefix = [] value_list = [] for key, value in row.items(): if key in sorted_list: # Set prefix. label_prefix.append(value) else: value_list.append('%s %s' % (key, value)) body.append(''.join( ['%s.%s\n' % ('.'.join(label_prefix), v) for v in value_list])) return '%s%s' % (label_str, ''.join(body))
222,020
Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry.
def index(self, name=None): # pylint: disable=C6409 try: return self.header.index(name) except ValueError: raise TableError('Unknown index name %s.' % name)
222,021
Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template was not found for the given command.
def _ParseCmdItem(self, cmd_input, template_file=None): # Build FSM machine from the template. fsm = textfsm.TextFSM(template_file) if not self._keys: self._keys = set(fsm.GetValuesByAttrib('Key')) # Pass raw data through FSM. table = texttable.TextTable() table.header = fsm.header # Fill TextTable from record entries. for record in fsm.ParseText(cmd_input): table.Append(record) return table
222,023
r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String of the format '(a(b(c(d)?)?)?)?'.
def _Completion(self, match): # pylint: disable=C6114 r # Strip the outer '[[' & ']]' and replace with ()? regexp pattern. word = str(match.group())[2:-2] return '(' + ('(').join(word) + ')?' * len(word)
222,025
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
def Parse(self, value): value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplateError('Expect at least 3 tokens on line.') if not value_line[2].startswith('('): # Options are present options = value_line[1] for option in options.split(','): self._AddOption(option) # Call option OnCreateOptions callbacks _ = [option.OnCreateOptions() for option in self.options] self.name = value_line[2] self.regex = ' '.join(value_line[3:]) else: # There were no valid options, so there are no options. # Treat this argument as the name. self.name = value_line[1] self.regex = ' '.join(value_line[2:]) if len(self.name) > self.max_name_len: raise TextFSMTemplateError( "Invalid Value name '%s' or name too long." % self.name) if (not re.match(r'^\(.*\)$', self.regex) or self.regex.count('(') != self.regex.count(')')): raise TextFSMTemplateError( "Value '%s' must be contained within a '()' pair." % self.regex) self.template = re.sub(r'^\(', '(?P<%s>' % self.name, self.regex) # Compile and store the regex object only on List-type values for use in nested matching if any(map(lambda x: isinstance(x, TextFSMOptions.List), self.options)): try: self.compiled_regex = re.compile(self.regex) except re.error as e: raise TextFSMTemplateError(str(e))
222,032
Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist.
def _AddOption(self, name): # Check for duplicate option declaration if name in [option.name for option in self.options]: raise TextFSMTemplateError('Duplicate option "%s"' % name) # Create the option object try: option = self._options_cls.GetOption(name)(self) except AttributeError: raise TextFSMTemplateError('Unknown option "%s"' % name) self.options.append(option)
222,033
Initialise a new rule object. Args: line: (str), a template rule line to parse. line_num: (int), Optional line reference included in error reporting. var_map: Map for template (${var}) substitutions. Raises: TextFSMTemplateError: If 'line' is not a valid format for a Value entry.
def __init__(self, line, line_num=-1, var_map=None): self.match = '' self.regex = '' self.regex_obj = None self.line_op = '' # Equivalent to 'Next'. self.record_op = '' # Equivalent to 'NoRecord'. self.new_state = '' # Equivalent to current state. self.line_num = line_num line = line.strip() if not line: raise TextFSMTemplateError('Null data in FSMRule. Line: %s' % self.line_num) # Is there '->' action present. match_action = self.MATCH_ACTION.match(line) if match_action: self.match = match_action.group('match') else: self.match = line # Replace ${varname} entries. self.regex = self.match if var_map: try: self.regex = string.Template(self.match).substitute(var_map) except (ValueError, KeyError): raise TextFSMTemplateError( "Duplicate or invalid variable substitution: '%s'. Line: %s." % (self.match, self.line_num)) try: # Work around a regression in Python 2.6 that makes RE Objects uncopyable. self.regex_obj = CopyableRegexObject(self.regex) except re.error: raise TextFSMTemplateError( "Invalid regular expression: '%s'. Line: %s." % (self.regex, self.line_num)) # No '->' present, so done. if not match_action: return # Attempt to match line.record operation. action_re = self.ACTION_RE.match(match_action.group('action')) if not action_re: # Attempt to match record operation. action_re = self.ACTION2_RE.match(match_action.group('action')) if not action_re: # Math implicit defaults with an optional new state. action_re = self.ACTION3_RE.match(match_action.group('action')) if not action_re: # Last attempt, match an optional new state only. raise TextFSMTemplateError("Badly formatted rule '%s'. Line: %s." % (line, self.line_num)) # We have an Line operator. if 'ln_op' in action_re.groupdict() and action_re.group('ln_op'): self.line_op = action_re.group('ln_op') # We have a record operator. if 'rec_op' in action_re.groupdict() and action_re.group('rec_op'): self.record_op = action_re.group('rec_op') # A new state was specified. if 'new_state' in action_re.groupdict() and action_re.group('new_state'): self.new_state = action_re.group('new_state') # Only 'Next' (or implicit 'Next') line operator can have a new_state. # But we allow error to have one as a warning message so we are left # checking that Continue does not. if self.line_op == 'Continue' and self.new_state: raise TextFSMTemplateError( "Action '%s' with new state %s specified. Line: %s." % (self.line_op, self.new_state, self.line_num)) # Check that an error message is present only with the 'Error' operator. if self.line_op != 'Error' and self.new_state: if not re.match(r'\w+', self.new_state): raise TextFSMTemplateError( 'Alphanumeric characters only in state names. Line: %s.' % (self.line_num))
222,036
Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid.
def _Parse(self, template): if not template: raise TextFSMTemplateError('Null template.') # Parse header with Variables. self._ParseFSMVariables(template) # Parse States. while self._ParseFSMState(template): pass # Validate destination states. self._ValidateFSM()
222,044
Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the top. Raises: TextFSMTemplateError: If syntax or semantic errors are found.
def _ParseFSMVariables(self, template): self.values = [] for line in template: self._line_num += 1 line = line.rstrip() # Blank line signifies end of Value definitions. if not line: return # Skip commented lines. if self.comment_regex.match(line): continue if line.startswith('Value '): try: value = TextFSMValue( fsm=self, max_name_len=self.MAX_NAME_LEN, options_class=self._options_cls) value.Parse(line) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) if value.name in self.header: raise TextFSMTemplateError( "Duplicate declarations for Value '%s'. Line: %s." % (value.name, self._line_num)) try: self._ValidateOptions(value) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) self.values.append(value) self.value_map[value.name] = value.template # The line has text but without the 'Value ' prefix. elif not self.values: raise TextFSMTemplateError('No Value definitions found.') else: raise TextFSMTemplateError( 'Expected blank line after last Value entry. Line: %s.' % (self._line_num))
222,045
Passes CLI output through FSM and returns list of tuples. First tuple is the header, every subsequent tuple is a row. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of Lists.
def ParseText(self, text, eof=True): lines = [] if text: lines = text.splitlines() for line in lines: self._CheckLine(line) if self._cur_state_name in ('End', 'EOF'): break if self._cur_state_name != 'End' and 'EOF' not in self.states and eof: # Implicit EOF performs Next.Record operation. # Suppressed if Null EOF state is instantiated. self._AppendRecord() return self._result
222,048
Calls ParseText and turns the result into list of dicts. List items are dicts of rows, dict key is column header and value is column value. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of dicts.
def ParseTextToDicts(self, *args, **kwargs): result_lists = self.ParseText(*args, **kwargs) result_dicts = [] for row in result_lists: result_dicts.append(dict(zip(self.header, row))) return result_dicts
222,049
Assigns variable into current record from a matched rule. If a record entry is a list then append, otherwise values are replaced. Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value.
def _AssignVar(self, matched, value): _value = self._GetValue(value) if _value is not None: _value.AssignVar(matched.group(value))
222,050
Takes a list of SGR values and formats them as an ANSI escape sequence. Args: command_list: List of strings, each string represents an SGR value. e.g. 'fg_blue', 'bg_yellow' Returns: The ANSI escape sequence. Raises: ValueError: if a member of command_list does not map to a valid SGR value.
def _AnsiCmd(command_list): if not isinstance(command_list, list): raise ValueError('Invalid list: %s' % command_list) # Checks that entries are valid SGR names. # No checking is done for sequences that are correct but 'nonsensical'. for sgr in command_list: if sgr.lower() not in SGR: raise ValueError('Invalid or unsupported SGR name: %s' % sgr) # Convert to numerical strings. command_str = [str(SGR[x.lower()]) for x in command_list] # Wrap values in Ansi escape sequence (CSI prefix & SGR suffix). return '\033[%sm' % (';'.join(command_str))
222,053
Wrap text in ANSI/SGR escape codes. Args: text: String to encase in sgr escape sequence. command_list: List of strings, each string represents an sgr value. e.g. 'fg_blue', 'bg_yellow' reset: Boolean, if to add a reset sequence to the suffix of the text. Returns: String with sgr characters added.
def AnsiText(text, command_list=None, reset=True): command_list = command_list or ['reset'] if reset: return '%s%s%s' % (_AnsiCmd(command_list), text, _AnsiCmd(['reset'])) else: return '%s%s' % (_AnsiCmd(command_list), text)
222,054
Break line to fit screen width, factoring in ANSI/SGR escape sequences. Args: text: String to line wrap. omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length. Returns: Text with additional line wraps inserted for lines grater than the width.
def LineWrap(text, omit_sgr=False): def _SplitWithSgr(text_line): token_list = sgr_re.split(text_line) text_line_list = [] line_length = 0 for (index, token) in enumerate(token_list): # Skip null tokens. if token is '': continue if sgr_re.match(token): # Add sgr escape sequences without splitting or counting length. text_line_list.append(token) text_line = ''.join(token_list[index +1:]) else: if line_length + len(token) <= width: # Token fits in line and we count it towards overall length. text_line_list.append(token) line_length += len(token) text_line = ''.join(token_list[index +1:]) else: # Line splits part way through this token. # So split the token, form a new line and carry the remainder. text_line_list.append(token[:width - line_length]) text_line = token[width - line_length:] text_line += ''.join(token_list[index +1:]) break return (''.join(text_line_list), text_line) # We don't use textwrap library here as it insists on removing # trailing/leading whitespace (pre 2.6). (_, width) = TerminalSize() text = str(text) text_multiline = [] for text_line in text.splitlines(): # Is this a line that needs splitting? while ((omit_sgr and (len(StripAnsiText(text_line)) > width)) or (len(text_line) > width)): # If there are no sgr escape characters then do a straight split. if not omit_sgr: text_multiline.append(text_line[:width]) text_line = text_line[width:] else: (multiline_line, text_line) = _SplitWithSgr(text_line) text_multiline.append(multiline_line) if text_line: text_multiline.append(text_line) return '\n'.join(text_multiline)
222,057
Constructor. Args: text: A string, the text that will be paged through. delay: A boolean, if True will cause a slight delay between line printing for more obvious scrolling.
def __init__(self, text=None, delay=None): self._text = text or '' self._delay = delay try: self._tty = open('/dev/tty') except IOError: # No TTY, revert to stdin self._tty = sys.stdin self.SetLines(None) self.Reset()
222,059
Set number of screen lines. Args: lines: An int, number of lines. If None, use terminal dimensions. Raises: ValueError, TypeError: Not a valid integer representation.
def SetLines(self, lines): (self._cli_lines, self._cli_cols) = TerminalSize() if lines: self._cli_lines = int(lines)
222,062