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 ...
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 ...
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.addV...
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 Retur...
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 f...
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 poin...
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 selec...
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.ap...
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...
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 approximati...
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...
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,bb...
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[...
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...
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): ...
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: ...
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 so...
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 = m...
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", ...
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...
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] ...
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[...
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 ite...
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) #...
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...
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 whi...
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 de...
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(quic...
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...
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(...
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 jo...
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]...
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 -...
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...
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 star...
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) ...
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...
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.a...
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.addV...
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 b...
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.addV...
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: SCI...
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...
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) + ...
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[...
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...
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....
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 ...
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 sol...
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 soluti...
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("...
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 solut...
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("optimizi...
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) ...
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() ...
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 ...
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)...
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...
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 ...
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)) ...
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 bise...
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: ...
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 quanti...
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...
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 ...
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...
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]: lates...
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)) fo...
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 visitin...
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(...
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]....
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] = mo...
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.co...
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...
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 ...
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] ...
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...
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...
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]: holdi...
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 ...
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...
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: m...
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 rela...
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()) ...
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 ...
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....
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 rel...
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=-mo...
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]...
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.ad...
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 pie...
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") mod...
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 re...
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]...
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(quick...
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() ...
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_ins...
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("#### "): ...
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. b...
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 ...
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(d...
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 valu...
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: pas...
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("QtCo...
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_m...
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: {}".f...
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 outsid...
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() ...
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...
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...
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: ...
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') ...
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') ...
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') ...
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.get...
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 define...
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',...
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....
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.ite...
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) st...
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 isinsta...
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: Wh...
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 ...
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 pref...
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(): ...
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 ...
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._Add...
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 AttributeErr...
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...
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 ...
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): con...
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. Rai...
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 perfo...
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 trig...
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 Val...
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 a...
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...
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