def linear_programming(self, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: dictionary of saturated edges that maps team pairs to the amount of additional games they have against each other returns True if team is eliminated, False otherwise ''' maxflow=pc.Problem() c={} for e in self.G.edges(data=True): c[(e[0], e[1])] = e[2]['capacity'] # Convert the capacities to a PICOS expression. cc=pc.new_param('c',c) f={} for e in self.G.edges(): f[e]=maxflow.add_variable('f[{0}]'.format(e)) # Add another variable for the total flow. F=maxflow.add_variable('F') # Enforce edge capacities. maxflow.add_list_of_constraints([f[e] <= cc[e] for e in self.G.edges()]) # Enforce flow conservation. maxflow.add_list_of_constraints([ pc.sum([f[p,i] for p in self.G.predecessors(i)]) == pc.sum([f[i,j] for j in self.G.successors(i)]) for i in self.G.nodes() if i not in ("Source","Sink")]) # Set source flow at s. maxflow.add_constraint( F == pc.sum([f["Source",j] for j in self.G.successors("Source")])) # Set sink flow at t. maxflow.add_constraint( pc.sum([f[p,"Sink"] for p in self.G.predecessors("Sink")]) == F) # Enforce flow nonnegativity. maxflow.add_list_of_constraints([f[e] >= 0 for e in self.G.edges()]) # Set the objective. maxflow.set_objective('max', F) # Solve the problem. maxflow.solve(solver='cvxopt') #calculate the value of the edges leaving the source comparing_value = 0 for matchup in saturated_edges.keys(): comparing_value += saturated_edges[matchup] return comparing_value > round(F)
def DOBSS(AttackerRF, DefenderRF, Prob): prob = pic.Problem() l = len(DefenderRF[0]) m = len(DefenderRF[0][0]) tnum = len(DefenderRF) x = prob.add_variable('x', l, lower=0, upper=1) na = prob.add_variable('na', (tnum, m), 'binary') v = prob.add_variable('v', tnum) rfa = pic.new_param('rfa', AttackerRF) rfd = pic.new_param('rfd', DefenderRF) pr = pic.new_param('pr', Prob) prob.add_constraint(pic.sum([x[i] for i in range(l)], 'i', '[l]') == 1) for j in range(0, tnum): prob.add_constraint( pic.sum([na[j, i] for i in range(m)], 'i', '[m]') == 1) for j in range(0, tnum): prob.add_list_of_constraints( [v[j] - (x.T * rfa[j])[i] > 0 for i in range(m)], 'i', '[m]') prob.add_list_of_constraints([ v[j] - (x.T * rfa[j])[i] < 1000000 * (1 - na[j, i]) for i in range(m) ], 'i', '[m]') obj = 0 for j in range(0, tnum): obj = obj + pr[j] * x.T * rfd[j] * (na[j, :]).T #obj = pic.sum([pr[p]*x.T*rfd[p]*(na[p,:]).T for p in range(tnum)],'p','[tnum]') prob.set_objective('max', obj) prob.solve(verbose=0) return np.array(x), np.array(obj)
def linear_programming(self, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: dictionary of saturated edges that maps team pairs to the amount of additional games they have against each other returns True if team is eliminated, False otherwise ''' maxflow = pic.Problem() # Add the flow variables. f = {} for edge in self.G.edges(): upperVal = self.G[edge[0]][edge[1]]['capacity'] if (upperVal < sys.maxsize): f[edge] = maxflow.add_variable( 'f[{0}]'.format(edge), 1, lower=0, upper=self.G[edge[0]][edge[1]]['capacity']) else: f[edge] = maxflow.add_variable('f[{0}]'.format(edge), 1, lower=0) # Add another variable for the total flow. F = maxflow.add_variable('F', 1) s = 'S' t = 'T' # Enforce flow conservation. maxflow.add_list_of_constraints([ pic.sum([f[p, i] for p in self.G.predecessors(i)], 'p', 'pred(i)') == pic.sum([f[i, j] for j in self.G.successors(i)], 'j', 'succ(i)') for i in self.G.nodes() if i not in (s, t) ], 'i', 'nodes-(s,t)') # Set source flow at s. maxflow.add_constraint( pic.sum([f[p, s] for p in self.G.predecessors(s)], 'p', 'pred(s)') + F == pic.sum([f[s, j] for j in self.G.successors(s)], 'j', 'succ(s)')) # Set the objective. maxflow.set_objective('max', F) # Solve the problem. maxflow.solve(verbose=0, solver='cvxopt') for x in f: a, b = x if (a == 'S'): if abs(self.G[a][b]['capacity'] - f[x].value) > 1e-4: return True return False
def solve_RMCFP_L_inf(G, s, t, mu, delta, Gamma): ''' This function solves the Robust MCFP with L_inf uncertainty set :param G: bidirectional graph object :param s: source node (0) :param t: sink (terminal) node (N-1) :param mu: nominal edges costs :param delta: costs deviations (uncertainty amplification) :param Gamma: uncertainty ball size :return: ''' # Define problem using PICOS P = pic.Problem() # Add the flow variables x = {} for e in G.edges(): x[e] = P.add_variable('x[{0}]'.format(e), 1) # --- Add constraints --- # Enforce flow conservation P.add_list_of_constraints([ pic.sum([x[i, j] for i in G.predecessors(j)], 'i', 'pred(j)') == pic.sum([x[j, k] for k in G.successors(j)], 'k', 'succ(j)') for j in G.nodes() if j not in (s, t) ], 'i', 'nodes-(s,t)') # Set source flow at s P.add_constraint( pic.sum([x[s, j] for j in G.successors(s)], 'j', 'succ(s)') == 1) # Set sink flow at t P.add_constraint( pic.sum([x[i, t] for i in G.predecessors(t)], 'i', 'pred(t)') == 1) # Enforce edge capacities P.add_list_of_constraints( [x[e[:2]] <= e[2]['capacity'] for e in G.edges(data=True)], # list of constraints [('e', 2)], # e is a double index 'edges') # set the index belongs to # Enforce flow non-negativity P.add_list_of_constraints( [x[e] >= 0 for e in G.edges()], # list of constraints [('e', 2)], # e is a double index 'edges') # set the index belongs to # Define objective and solve costs = mu + Gamma * delta objective = pic.sum( [cost_ij * x_ij for (cost_ij, x_ij) in zip(costs, x.values())]) P.set_objective('min', objective) sol = P.solve(verbose=0, solver='cvxopt') # Unpack solution vector x = np.array(sol['cvxopt_sol']['x']).reshape(-1) return P, x
def LPSolverDietEurope(eu_country): ''' Solver for Europe diet. Find kilocalories quantities to send to each African countries. It creates the optimal diet ''' country_giveup_val = food_opt_distribution_df.loc[eu_country].values country_giveup_index = food_opt_distribution_df.loc[eu_country].index prices_val = final_prices.loc[eu_country].values.reshape(-1, 1) prices_index = final_prices.loc[eu_country].index prod_diet_val = prod_diet_final.to_numpy() / 10**-6 prod_diet_index = prod_diet_final.index prob = pic.Problem() #initalize convex problem Y = prob.add_variable('Y', (prices_val.size, country_giveup_val.size )) #definition of decision matrix of variables nxm obj = pic.sum(prices_val.T * Y) #define obj function prob.set_objective("min", obj) #set objective function #Initialize constraints constraints = [] #Define non-negativity constraint constraints.append(prob.add_constraint(Y >= 0)) #Define constraints proteins,carbs and fats #Define shares of proteins,carbs and fat as an absolute variable (not subject to optimization) shares = np.array([0.55, 0.25, 0.2]) for i in range(0, country_giveup_val.size): for j in range(0, shares.size): constraints.append( prob.add_constraint( Y[:, i].T * prod_diet_val[:, j].reshape(-1, 1) == shares[j] * country_giveup_val[i])) #Define constraints to provide an upper bound (every product has to be sent at most to cover the 20% of the final demand) for i in range(0, country_giveup_val.size): for j in range(0, prices_val.size): constraints.append( prob.add_constraint( pic.sum(Y[j, i] * prod_diet_val[j, :].reshape(1, -1)) <= 0.355 * country_giveup_val[i])) constraints.append( prob.add_constraint( pic.sum(Y[j, i] * prod_diet_val[j, :].reshape(1, -1)) >= 0.0001 * country_giveup_val[i])) #Solving problem with gurobi solver (License available for free academic use) solution = prob.solve(verbose=0, solver='gurobi') Y_opt_diet = Y.value result_diet = np.array(Y_opt_diet) result_diet_df = pd.DataFrame(data=result_diet, index=prod_diet_index) result_diet_df.columns = country_giveup_index return result_diet_df
def linear_programming(self, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: returns True if team is eliminated, false otherwise ''' maxflow=pic.Problem() # creating helper dictionaries for flows and capacities for picos f = {} source_edges = [] for edge in self.G.edges(): #print(edge) # if max capacity is not infinity, then set lower bound to 0 and upper to capacity if self.G[edge[0]][edge[1]]['capacity'] < sys.maxsize: # add to flow dict, a picos variable f[edge] = maxflow.add_variable( 'f[{0}]'.format(edge),1,lower=0,upper =self.G[edge[0]][edge[1]]['capacity']) # if max capacity is infinity, then only set lower bound to 0 else: f[edge] = maxflow.add_variable( 'f[{0}]'.format(edge),1,lower=0) # list of edges coming out of source if edge[0] is 'source': source_edges.append(edge) # adding variables, contraints, and objective F = maxflow.add_variable('F', 1) for i in self.G.nodes(): if i == 'source': # add constraint, such that flow coming into the source and flow that source # generates is equal to flow coming out of source maxflow.add_constraint(pic.sum([f[p,i] for p in self.G.predecessors(i)]) + F == pic.sum([f[i,p] for p in self.G.successors(i)])) elif i != 'sink': # add constraint, such that flow coming into the node is equal to flow coming out of node maxflow.add_constraint(pic.sum([f[p,i] for p in self.G.predecessors(i)]) == pic.sum([f[i,p] for p in self.G.successors(i)])) # maximize flow that source generates maxflow.set_objective('max', F) # solve the problem maxflow.solve(verbose=0, solver='cvxopt') flag = False for flow in source_edges: # check to see if capacity is saturated, if not (aka diff is bigger than 0) it is eliminated if abs(self.G[flow[0]][flow[1]]['capacity'] - f[flow].value) > 1e-5: flag = True return flag
def linear_programming(self, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: dictionary of saturated edges that maps team pairs to the amount of additional games they have against each other returns True if team is eliminated, False otherwise ''' maxflow=pic.Problem() f={} for edge in self.G.edges(): constriant = self.G[edge[0]][edge[1]]['capacity'] if(constriant < sys.maxsize): f[edge]=maxflow.add_variable('f[{0}]'.format(edge),1, lower=0, upper=self.G[edge[0]][edge[1]]['capacity']) else: f[edge]=maxflow.add_variable('f[{0}]'.format(edge),1, lower=0) #total flow F =maxflow.add_variable('F',1) s = 'S' t = 'T' for i in self.G.nodes: if i == s: # set source flow maxflow.add_constraint( pic.sum([f[p,i] for p in self.G.predecessors(i)],'p','pred(i)') + F == pic.sum([f[i,j] for j in self.G.successors(i)],'j','succ(i)')) elif i != t: # conservation of flow maxflow.add_constraint( pic.sum([f[p,i] for p in self.G.predecessors(i)],'p','pred(i)') == pic.sum([f[i,j] for j in self.G.successors(i)],'j','succ(i)')) # Set the objective. maxflow.set_objective('max',F) # Solve the problem. maxflow.solve(verbose=0,solver='cvxopt') # edge to flow flow = pic.tools.eval_dict(f) for edge in self.G.edges('S'): u, v = edge if not abs(flow[u,v]- self.G.edges[u, v]['capacity']) < 1e-7: return True return False
def setUp(self): # Data. c = picos.new_param("c", cvxopt.matrix([1, 2, 3, 4, 5])) A = picos.new_param("A", [ cvxopt.matrix([1, 0, 0, 0, 0]).T, cvxopt.matrix([0, 0, 2, 0, 0]).T, cvxopt.matrix([0, 0, 0, 2, 0]).T, cvxopt.matrix([1, 0, 0, 0, 0]).T, cvxopt.matrix([1, 0, 2, 0, 0]).T, cvxopt.matrix([0, 1, 1, 1, 0]).T, cvxopt.matrix([1, 2, 0, 0, 0]).T, cvxopt.matrix([1, 0, 3, 0, 1]).T ]) self.n = n = len(A) self.m = m = c.size[0] # Primal problem. self.P = P = picos.Problem() self.u = u = P.add_variable("u", m) P.set_objective("min", c | u) self.C = P.add_list_of_constraints( [abs(A[i] * u) < 1 for i in range(n)], "i", "[n]") # Dual problem. self.D = D = picos.Problem() self.z = z = [D.add_variable("z[{}]".format(i)) for i in range(n)] self.mu = mu = D.add_variable("mu", n) D.set_objective("min", 1 | mu) D.add_list_of_constraints([abs(z[i]) < mu[i] for i in range(n)], "i", "[n]") D.add_constraint( picos.sum([A[i].T * z[i] for i in range(n)], "i", "[n]") == c)
def solveCompleteGame(DefenderRF, AttackerRF, PureStrategyList, BoundList, Prob): rewardmax = -10000000 deltamax = [] for i in range(0, len(PureStrategyList)): #print(BoundList[i]) if (np.array(BoundList[i].value) < np.array(rewardmax)): continue try: prob = pic.Problem() m = len(DefenderRF[0][0]) l = len(DefenderRF[0]) t = len(DefenderRF) delta = prob.add_variable('delta', l, lower=0, upper=1) rfa = pic.new_param('rfa', AttackerRF) rfd = pic.new_param('rfd', DefenderRF) probs = pic.new_param('prob', Prob) sigma = pic.new_param('sigma', PureStrategyList[i]) purestrategylist = pic.new_param('purestrategylist', PureStrategyList) prob.add_constraint( pic.sum([delta[j] for j in range(l)], 'j', '[l]') == 1) attrew = pic.sum([ probs[p] * delta.T * rfa[p] * (sigma[p, :]).T for p in range(t) ], 'p', '[t]') for k in range(0, len(PureStrategyList)): prob.add_constraint(attrew > pic.sum([ probs[p] * delta.T * rfa[p] * (purestrategylist[k][p, :]).T for p in range(t) ], 'p', '[t]')) obj = 0 for j in range(0, t): obj = obj + probs[j] * delta.T * rfd[j] * (sigma[j, :]).T #obj = pic.sum([probs[p]*delta.T*rfd[p]*(sigma[p,:]).T for p in range(t)],'p','[t]') prob.set_objective('max', obj) #print(prob) prob.solve(verbose=0) print(obj) if ((obj.value[0]) > rewardmax): rewardmax = (obj.value[0]) deltamax = np.array(delta) except: print("boohoo") return deltamax, rewardmax
def MultipleLPSolver(AttackerRF, DefenderRF, Prob): PureStrategyList = generatePureStrategyMLP(AttackerRF) rewardmax = -10000000 deltamax = [] for i in range(0, len(PureStrategyList)): try: prob = pic.Problem() m = len(DefenderRF[0][0]) l = len(DefenderRF[0]) t = len(DefenderRF) delta = prob.add_variable('delta', l, lower=0, upper=1) pr = pic.new_param('pr', Prob) rfa = pic.new_param('rfa', AttackerRF) rfd = pic.new_param('rfd', DefenderRF) sigma = pic.new_param('sigma', PureStrategyList[i]) purestrategylist = pic.new_param('purestrategylist', PureStrategyList) prob.add_constraint( pic.sum([delta[j] for j in range(l)], 'j', '[l]') == 1) attrew = pic.sum( [pr[p] * delta.T * rfa[p] * (sigma[p, :]).T for p in range(t)], 'p', '[t]') for k in range(0, len(PureStrategyList)): prob.add_constraint(attrew > pic.sum([ pr[p] * delta.T * rfa[p] * (purestrategylist[k][p, :]).T for p in range(t) ], 'p', '[t]')) obj = pic.sum( [pr[p] * delta.T * rfd[p] * (sigma[p, :]).T for p in range(t)], 'p', '[t]') prob.set_objective('max', obj) #print(prob) prob.solve(verbose=0) print(obj) print(rewardmax) if ((obj.value[0]) > rewardmax): rewardmax = (obj.value[0]) deltamax = np.array(delta) else: print("Kaboom") except: print("boohoo") return deltamax, rewardmax
def learnMMMF(y, c): n,m = y.shape n_obs = np.count_nonzero(y) obs = np.nonzero(y) prob = pic.Problem() #create a Problem instance # vars A = prob.add_variable('A', (n,n)) B = prob.add_variable('B', (m,m)) X = prob.add_variable('X', (n,m)) t = prob.add_variable('t', 1) e = [] for i in range(n_obs): e.append(prob.add_variable('e[{0}]'.format(i))) # constraints prob.add_constraint(((A & X)//(X.T & B)) >> 0) prob.add_constraint(pic.diag_vect(A) <= t) prob.add_constraint(pic.diag_vect(B) <= t) for i in e: prob.add_constraint(i >= 0) for x in enumerate(zip(obs[0], obs[1])): # each observation ind = x[0] i, a = int(x[1][0]), int(x[1][1]) prob.add_constraint((y[i,a] * X[i,a]) >= (1 - e[ind])) # objective prob.set_objective('min', t + c * pic.sum(e)) # solve time_start = time.clock() prob.solve(verbose=1, solver='sdpa', solve_via_dual = False, noduals=True) time_end = time.clock() ORIG = mat MATLAB = matlab PYTHON = X.value print('orig') print(ORIG) print('matlab') print(MATLAB) print('python') print(PYTHON) print('diff') print(MATLAB - PYTHON)
def picos(self, data, mu): P = picos.Problem() print(self.pixels, self.clusters) self.W = picos.BinaryVariable("W", (self.pixels, self.clusters)) e = picos.sum([ self.W[i, j] * (1 / 2) for i, j in itertools.product( range(self.pixels), range(self.clusters)) ]) print(e) self.mu = picos.BinaryVariable("mu", self.clusters) P.set_objective("min", (self.W - 5) * 2 - self.mu[i]) print(P)
def learnMMMF(y, c): n, m = y.shape n_obs = np.count_nonzero(y) obs = np.nonzero(y) prob = pic.Problem() #create a Problem instance # vars A = prob.add_variable('A', (n, n)) B = prob.add_variable('B', (m, m)) X = prob.add_variable('X', (n, m)) t = prob.add_variable('t', 1) e = [] for i in range(n_obs): e.append(prob.add_variable('e[{0}]'.format(i))) # constraints prob.add_constraint(((A & X) // (X.T & B)) >> 0) prob.add_constraint(pic.diag_vect(A) <= t) prob.add_constraint(pic.diag_vect(B) <= t) for i in e: prob.add_constraint(i >= 0) for x in enumerate(zip(obs[0], obs[1])): # each observation ind = x[0] i, a = int(x[1][0]), int(x[1][1]) prob.add_constraint((y[i, a] * X[i, a]) >= (1 - e[ind])) # objective prob.set_objective('min', t + c * pic.sum(e)) # solve time_start = time.clock() prob.solve(verbose=1, solver='sdpa', solve_via_dual=False, noduals=True) time_end = time.clock() ORIG = mat MATLAB = matlab PYTHON = X.value print('orig') print(ORIG) print('matlab') print(MATLAB) print('python') print(PYTHON) print('diff') print(MATLAB - PYTHON)
def linear_programming(self, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: dictionary of saturated edges that maps team pairs to the amount of additional games they have against each other returns True if team is eliminated, False otherwise ''' maxflow = pic.Problem() f = {} for e in self.G.edges(): f[e] = maxflow.add_variable('f[{0}]'.format(e), 1) F = maxflow.add_variable('F', 1) caps = dict(nx.get_edge_attributes(self.G, 'capacity')) maxflow.add_list_of_constraints( [f[e] < caps[e] for e in self.G.edges()], [('e', 2)], 'edges') maxflow.add_list_of_constraints([ pic.sum([f[p, i] for p in self.G.predecessors(i)], 'p', 'pred(i)') == pic.sum([f[i, j] for j in self.G.successors(i)], 'j', 'succ(i)') for i in self.G.nodes() if i not in ('s', 't') ], 'i', 'nodes-(s,t)') # Set source flow at s. maxflow.add_constraint( pic.sum([f[p, 's'] for p in self.G.predecessors('s')], 'p', 'pred(s)') + F == pic.sum([f['s', j] for j in self.G.successors('s')], 'j', 'succ(s)')) # Set sink flow at t. maxflow.add_constraint( pic.sum([f[p, 't'] for p in self.G.predecessors('t')], 'p', 'pred(t)') == pic.sum([f['t', j] for j in self.G.successors('t')], 'j', 'succ(t)') + F) # Enforce flow nonnegativity. maxflow.add_list_of_constraints([f[e] > 0 for e in self.G.edges()], [('e', 2)], 'edges') # Set the objective. maxflow.set_objective('max', F) maxflow.solve(verbose=0, solver='glpk') return (int(F) < sum(saturated_edges.values()))
def solveRestrictedGame(DefenderRF, AttackerRF): PureStrategyList = generatePureStrategy(AttackerRF) Delete = [] Bound = [10000000] * len(PureStrategyList) rewardmax = -10000000 deltamax = [] count = 0 for i in range(0, len(PureStrategyList)): try: prob = pic.Problem() m = len(DefenderRF[0]) l = len(DefenderRF) t = 1 delta = prob.add_variable('delta', l, lower=0, upper=1) rfa = pic.new_param('rfa', AttackerRF) rfd = pic.new_param('rfd', DefenderRF) sigma = pic.new_param('sigma', PureStrategyList[i]) purestrategylist = pic.new_param('purestrategylist', PureStrategyList) prob.add_constraint( pic.sum([delta[j] for j in range(l)], 'j', '[l]') == 1) attrew = delta.T * rfa * (sigma) #print(purestrategylist) for k in range(0, len(PureStrategyList)): prob.add_constraint(attrew > delta.T * rfa * (purestrategylist[k].T)) obj = delta.T * rfd * (sigma) prob.set_objective('max', obj) prob.solve(verbose=0) print(obj) if (np.array(obj) > rewardmax): rewardmax = np.array(obj) deltamax = np.array(delta) Bound[count] = np.array(obj) count += 1 except: Delete.append(PureStrategyList[i]) print("boohoo") for i in range(0, len(Delete)): PureStrategyList.remove(Delete[i]) return PureStrategyList, Bound[0:len(PureStrategyList)], deltamax
def compressed_sensing_tomography(measurement_ops, measurement_avgs, epsilon=.5): """Compressed Sensing based tomography, this should reproduce the results of standard_tomography in the limit of more measurements.""" if not picos_available: raise Exception( "picos package not installed, please ensure picos and cvxopt are installed." ) if not cvx_available: raise Exception( "cvxopt package not installed, please ensure picos and cvxopt are installed." ) def e(dim=2, initial_state=0): """Return the state vector of a system in a pure state""" assert dim > 0 state = np.matrix(np.zeros(dim, dtype='complex')).T state[initial_state % dim] = 1 return state n = np.shape(measurement_ops)[1] # dimension of space cvx_pops = cvx.matrix(measurement_avgs) reshaped_matrix = np.array(measurement_ops).reshape(-1, n) F = picos.Problem() Z = F.add_variable('Z', (n, n), 'hermitian') # This does the trace of the measurement matricies * Z, # which should result in the populations measured meas_opt = picos.sum([ cvx.matrix(reshaped_matrix[i::n, :]) * Z * cvx.matrix(e(n, i)) for i in range(n) ], 'i') F.set_objective("min", pic.trace(Z)) F.add_constraint(picos.norm(meas_opt - cvx_pops) < epsilon) F.add_constraint(Z >> 0) F.solve(verbose=0) return np.matrix(Z.value) / trace(Z.value)
def find_w_from_ps(ps, B, m): # Algorithm from "Affine Formation Maneuver Control of Multiagent Systems" # Transactions on Automatic Control 2017 # Author: Shiyu Zhao numAgents = B.shape[0] P = ps.reshape(numAgents, m) Pbar = np.concatenate((P.T, np.ones(numAgents).T), axis=None) Pbar = Pbar.reshape(m + 1, numAgents).T H = B.T E = Pbar.T.dot(H.T).dot(np.diag(H[:, 0])) for i in range(1, H.shape[1]): aux = Pbar.T.dot(H.T).dot(np.diag(H[:, i])) E = np.concatenate((E, aux)) ker_E = la.null_space(E) [U, s, Vh] = la.svd(Pbar) U2 = U[:, m + 1:] M = [] for i in range(ker_E.shape[1]): aux = U2.T.dot(H.T).dot(np.diag(ker_E[:, i])).dot(H).dot(U2) M.append(aux) Mc = pic.new_param('Mc', M) lmi_problem = pic.Problem() c = lmi_problem.add_variable("c", len(M)) lmi_problem.add_constraint( pic.sum([c[i] * Mc[i] for i in range(len(M))]) >> 0) lmi_problem.set_objective('find', c) lmi_problem.solve(verbose=0, solver='smcp') w = np.zeros(ker_E.shape[0]) for i in range(ker_E.shape[1]): w = w + (c[i].value * ker_E[:, i]) return w
def MT_hopkins(x, r, Z): # implementation of SDP relaxation of MTE problem /!\ as found in Hopkins[2018] k, d = Z.shape Z_c = Z - x sdp = pic.Problem() z_c = pic.new_param('z_c', cvx.matrix(Z_c)) X = sdp.add_variable('X', (1 + k + d, 1 + k + d), vtype="symmetric") sdp.add_constraint(X >> 0) sdp.add_constraint(X[0, 0] == 1) sdp.add_list_of_constraints([X[i, i] <= 1 for i in range(1, k + 1)]) sdp.add_constraint(pic.trace(X[k + 1:, k + 1:]) <= 1) sdp.add_list_of_constraints([ (z_c[i, :].T | X[k + 1:, i + 1]) >= r * X[0, i + 1] for i in range(k) ]) sdp.set_objective('max', pic.sum([X[0, i] for i in range(1, k + 1)])) sdp.solve(verbose=0, solver='cvxopt') return X.value, sdp.obj_value()
def cvrp_ip(C,q,K,Q,obj=True): ''' Solves the capacitated vehicle routing problem using an integer programming approach. C: matrix of edge costs, that represent distances between each node q: list of demands associated with each client node K: number of vehicles Q: capacity of each vehicle obj: whether to set objective (ignore unless you are doing local search) returns: objective_value: value of the minimum travel cost x: matrix representing number of routes that use each arc ''' q=np.append(q,0) new_row = [C[0][:]] C=np.concatenate((C,new_row)) rowl=len(C) rowli=rowl-1 newcol=np.zeros((rowl,1)) C=np.concatenate((C,newcol),axis=1) new_col = C[:,0] C[:,rowli]=new_col prob = pic.Problem() x = [] u=[] x=prob.add_variable("x",size=(rowl,rowl),vtype='binary') u=prob.add_variable("u",size=(rowl),vtype='continuous',upper=Q, lower=q) objective_value = 0 prob.add_constraint(sum([x[0,i]for i in range (0,rowl)])<=K) prob.add_constraint(sum([x[i, rowl-1]for i in range (0,rowl)])<=K) prob.add_constraint(sum([x[0,i]for i in range (0,rowl)])==sum([x[i, rowl-1]for i in range (0,rowl)])) prob.add_list_of_constraints([sum([x[i,j]for i in range (0,rowl)]) ==1 for j in range (1,rowl-1)]) prob.add_list_of_constraints([sum([x[j,i]for i in range (0,rowl)]) ==1 for j in range (1,rowl-1)]) prob.add_constraint(sum([x[i,0]for i in range (0,rowl)])==0) prob.add_list_of_constraints([u[i]-u[j]+Q*x[i,j] <= Q-q[i] for i in range (0,rowl) for j in range (0,rowl)]) prob.set_objective("min",pic.sum([C[i,j]*x[i,j] for i in range(0,rowl) for j in range(0,rowl)])) prob.solve(solver='cplex') objective_value=prob.obj_value() return objective_value, x
def add_sdd_picos(prob, var, sdd_str = ''): """ Make sure that the expression matVar is sdd by adding constraints to the model M. Additional variables Mij of size n*(n-1)/2 x 3 are required, where each row represents a symmetric 2x2 matrix Mij(k,:) is the vector Mii Mjj Mij representing [Mii Mij; Mij Mjj] for (i,j) = _k_to_ij(k)""" # Length of vec(M) num_vars = var.size[0] if num_vars == 1: # scalar case prob.add_constraint('', var >= 0) return None # Side of M n = int((np.sqrt(1+8*num_vars) - 1)/2) assert(n == (np.sqrt(1+8*num_vars) - 1)/2) # Number of submatrices required num_Mij = n*(n-1)/2 Mij = prob.add_variable('Mij_' + sdd_str, (num_Mij, 3)) # add pos and cone constraints ensuring that each Mij(k,:) is psd prob.add_list_of_constraints( [Mij[k,0] >= 0 for k in range(num_Mij)], 'k', '[' + str(num_Mij) + ']' ) prob.add_list_of_constraints( [Mij[k,1] >= 0 for k in range(num_Mij)], 'k', '[' + str(num_Mij) + ']' ) prob.add_list_of_constraints( [Mij[k,0] * Mij[k,1] >= Mij[k,2]**2 for k in range(num_Mij)], 'k', '[' + str(num_Mij) + ']' ) prob.add_list_of_constraints( [ var[ _ij_to_k(i,j,num_vars) ] == picos.sum( [ Mij[k,l] for k,l in _sdd_index(i,j,n) ], 'k,l', '_sdd_index(i,j,n)') for i in range(n) for j in range(i,n) ], 'i,j', 'i,j : 0 <= i <= j < n' ) return Mij
x[0]=[10,0] d = dist.cdist(x,x) d = np.c_[d,d[:,0]] d = np.r_[d,np.atleast_2d(d[0,:])] G = nx.complete_graph(n) G = nx.relabel_nodes(G,{i:i+1 for i in range(n)}) G = nx.DiGraph(G) G.add_edges_from([(0,i) for i in range(1,n+1)]) G.add_edges_from([(i,n+1) for i in range(1,n+1)]) P = pic.Problem() f = {e:P.add_variable('f['+str(e)+']',1) for e in G.edges()} P.add_constraint(pic.tools.flow_Constraint(G,f,0,range(1,n+2),w[1:]+[w[0]],None,'G')) P.set_objective('min',pic.sum([f[i,j]*d[i,j] for i,j in G.edges()],'e')) P._make_cplex_instance() c = P.cplex_Instance c.SOS.add(type='1',SOS=[['f[(0, {0})]_0'.format(i) for i in range(1,n+1)],range(1,n+1)]) for i in range(1,n+1): c.SOS.add(type='1',SOS=[['f[({0}, {1})]_0'.format(i,j) for j in range(1,n+2) if j!=i],range(1,n+1)]) c.solve() nam = c.variables.get_names() ff = c.solution.get_values() flow = [nam[i].split('(')[1].split(')')[0] for i,fi in enumerate(ff) if fi>0] successor = {int(f.split(',')[0]):int(f.split(',')[1]) for f in flow} tour = [0] nxt=0
for e in G.edges(): f[e] = maxflow.add_variable('f[{0}]'.format(e), 1) #flow value F = maxflow.add_variable('F', 1) #upper bound on the flows maxflow.add_list_of_constraints( [f[e] < cc[e] for e in G.edges()], #list of constraints [('e', 2)], #e is a double index (start and end node of the edges) 'edges' #set the index belongs to ) #flow conservation maxflow.add_list_of_constraints([ pic.sum([f[p, i] for p in G.predecessors(i)], 'p', 'pred(i)') == pic.sum( [f[i, j] for j in G.successors(i)], 'j', 'succ(i)') for i in G.nodes() if i not in (s, t) ], 'i', 'nodes-(s,t)') #source flow at s maxflow.add_constraint( pic.sum([f[p, s] for p in G.predecessors(s)], 'p', 'pred(s)') + F == pic.sum([f[s, j] for j in G.successors(s)], 'j', 'succ(s)')) #sink flow at t maxflow.add_constraint( pic.sum([f[p, t] for p in G.predecessors(t)], 'p', 'pred(t)') == pic.sum([f[t, j] for j in G.successors(t)], 'j', 'succ(t)') + F) #nonnegativity of the flows
def ntf_fir_from_digested(order, osrs, H_inf, f0s, zf, **opts): """ Synthesize FIR NTF with minmax approach from predigested specification Version for the cvxpy_tinoco modeler. """ verbose = 1 if opts.get('show_progress', True) else 0 if 'maxiters' in opts['picos_opts']: opts['picos_opts']['maxit'] = opts['picos_opts']['maxiters'] del opts['picos_opts']['maxiters'] # State space representation of NTF A = cvxopt.matrix(np.eye(order, order, 1)) B = cvxopt.matrix(np.vstack((np.zeros((order - 1, 1)), 1.))) # C contains the NTF coefficients D = cvxopt.matrix(1.) p = picos.Problem() # Set up the problem bands = len(f0s) c = p.add_variable('c', (1, order)) gg = p.add_variable('gg', bands) for idx in range(bands): f0 = f0s[idx] osr = osrs[idx] omega0 = 2 * f0 * np.pi Omega = 1. / osr * np.pi P = p.add_variable('P[{}]'.format(idx), (order, order), vtype='symmetric') Q = p.add_variable('Q[{}]'.format(idx), (order, order), vtype='symmetric') if f0 == 0: # Lowpass modulator M1 = A.T * P * A + Q * A + A.T * Q - P - 2 * Q * np.cos(Omega) M2 = A.T * P * B + Q * B M3 = B.T * P * B - gg[idx, 0] M = ((M1 & M2 & c.T) // (M2.T & M3 & D) // (c & D & -1.0)) p.add_constraint(Q >> 0) p.add_constraint(M << 0) if zf: # Force a zero at DC p.add_constraint(picos.sum(c[i] for i in range(order)) == -1) else: # Bandpass modulator M1r = (A.T * P * A + Q * A * np.cos(omega0) + A.T * Q * np.cos(omega0) - P - 2 * Q * np.cos(Omega)) M2r = A.T * P * B + Q * B * np.cos(omega0) M3r = B.T * P * B - gg[idx] M1i = A.T * Q * np.sin(omega0) - Q * A * np.sin(omega0) M21i = -Q * B * np.sin(omega0) M22i = B.T * Q * np.sin(omega0) Mr = ((M1r & M2r & c.T) // (M2r.T & M3r & D) // (c & D & -1.0)) Mi = ((M1i & M21i & cvxopt.matrix(np.zeros((order, 1)))) // (M22i & 0.0 & 0.0) // (cvxopt.matrix(np.zeros( (1, order + 2))))) M = ((Mr & Mi) // (-Mi & Mr)) p.add_constraint(Q >> 0.0) p.add_constraint(M << 0.0) if zf: # Force a zero at z=np.exp(1j*omega0) nn = np.arange(order).reshape((order, 1)) vr = cvxopt.matrix(np.cos(omega0 * nn)) vi = cvxopt.matrix(np.sin(omega0 * nn)) vn = cvxopt.matrix( [-np.cos(omega0 * order), -np.sin(omega0 * order)]) p.add_constraint(c * (vr & vi) == vn) if H_inf < np.inf: # Enforce the Lee constraint R = p.add_variable('R', (order, order), vtype='symmetric') p.add_constraint(R >> 0) MM = ((A.T * R * A - R & A.T * R * B & c.T) // (B.T * R * A & -H_inf**2 + B.T * R * B & D) // (c & D & -1)) p.add_constraint(MM << 0) mx = p.add_variable('mx') p.add_constraint(picos.NormP_Exp(gg, 100) < mx) p.set_objective('min', mx) p.set_options(**opts['picos_opts']) p.solve(verbose=verbose) return np.hstack((1, np.asarray(c.value)[0, ::-1]))
l = [ Ai.size[1] for Ai in A ] r = K.size[1] #creates a problem and the optimization variables prob = pic.Problem() mu = prob.add_variable('mu',s) Z = [prob.add_variable('Z[' + str(i) + ']', (l[i],r)) for i in range(s)] #convert the constants into params of the problem A = pic.new_param('A',A) K = pic.new_param('K',K) #add the constraints prob.add_constraint( pic.sum([ A[i]*Z[i] for i in range(s)], #summands 'i', #name of the index '[s]' #set to which the index belongs ) == K ) prob.add_list_of_constraints( [ abs(Z[i]) < mu[i] for i in range(s)], #constraints 'i', #index of the constraints '[s]' #set to which the index belongs ) #sets the objective prob.set_objective('min', 1 | mu ) # scalar product of the vector of all ones with mu #display the problem print prob #call to the solver cvxopt sol = prob.solve(solver='cvxopt', verbose = 0)
def convexify(mu, nu): # mu, nu are I x d respective J x d size np arrays # I, J are size of samples, d is dimension of dists if len(mu.shape) > 1: (I, d) = mu.shape else: I = len(mu) d = 1 J = len(nu) prob = pic.Problem() q = prob.add_variable('x', size=[I, J]) obj = 0 if d == 17: # For some reason that doesn't work... obj = 1 / I * pic.sum( [(mu[i] - pic.sum([q[i, j] * nu[j] for j in range(J)], 'j', '[J]'))**2 for i in range(I)], 'i', '[I]') elif d == 1: for i in range(I): obj += 1 / I * mu[i]**2 for i in range(I): for j in range(J): obj -= 2 / I * q[i, j] * mu[i] * nu[j] for i in range(I): print(i) for j in range(J): for j2 in range(J): obj += 1 / I * q[i, j] * q[i, j2] * nu[j] * nu[j2] else: print('Haste noch net implementiert Junge') return 0 for i in range(I): for j in range(J): prob.add_constraint(q[i, j] > 0) for i in range(I): prob.add_constraint( pic.sum([q[i, j] for j in range(J)], 'j', '0...(J-1)') == 1) for j in range(J): prob.add_constraint( pic.sum([q[i, j] for i in range(J)], 'i', '0...(I-1)') == I / J) prob.set_objective('min', obj) print(prob) sol = prob.solve(solver='mosek') qv = q.value new_mu = np.zeros(shape=mu.shape) for i in range(I): for j in range(J): if d > 1: new_mu[i, :] += qv[i, j] * nu[j, :] else: new_mu[i] += qv[i, j] * nu[j] return new_mu, qv
prob = picos.Problem() # Add variables rho = prob.add_variable( 'rho', n_rho ) b = prob.add_variable( 'b', 1 ) K_pos = prob.add_variable( 'K_pos', n_max_sq) K_neg = prob.add_variable( 'K_neg', n_max_sq) sig_pos_i = [ prob.add_variable( 'sig_pos[%d]' %i, n_sigma_sq[i] ) for i in range(len(A_sidi_si)) ] sig_neg_i = [ prob.add_variable( 'sig_neg[%d]' %i, n_sigma_sq[i] ) for i in range(len(A_sidi_si)) ] # Add init constraint prob.add_constraint( A_rho0_rho*rho == b_rho0 ) # Add eq constraints prob.add_constraint( A_Lfrho_rho * rho + A_b_b * b - picos.sum([A_sidi_si[i] * sig_pos_i[i] for i in range(len(A_sidi_si))], 'i', '[' + str(len(A_sidi_si)) + ']') == A_poly_K * K_pos ) prob.add_constraint( -A_Lfrho_rho * rho + A_b_b * b - picos.sum([A_sidi_si[i] * sig_neg_i[i] for i in range(len(A_sidi_si))], 'i', '[' + str(len(A_sidi_si)) + ']') == A_poly_K * K_neg ) # Make Ks sdd sdd_pos = add_sdd_picos( prob, K_pos, 'K_pos') sdd_neg = add_sdd_picos( prob, K_neg, 'K_neg') # Make sigmas sdd for i in range(len(A_sidi_si)): add_sdd_picos( prob, sig_pos_i[i], 'sig_pos_' + str(i)) add_sdd_picos( prob, sig_neg_i[i], 'sig_neg_' + str(i))
def solve_multicut(W, T, solver='cvxopt'): '''Solves the LP relaxation (LP2 of [1]) of the minimum multiway cut problem associated to the graph given by its adjacency matrix W. Args: - W (ndarray): the adjacency matrix - T (list): the list of terminal nodes Output: - ndarray: the solution of the LP ''' G = nx.from_numpy_matrix(W) n = W.shape[0] K = len(T) def s2i(row_col, array_shape=(n, n)): '''Equivalent of Matlab sub2ind. From rows and cols (n, n) indices to linear index. ''' row, col = row_col ind = row*array_shape[1] + col return int(ind) node_triples = [ (i, j, k) for i in range(n) for j in range(n) for k in range(n)] node_couples = [(i, j) for i in range(n) for j in range(n)] terminal_couples = [(i, j) for i in T for j in T if i < j] prob = pic.Problem() # Picos params and variables d = prob.add_variable('d', n**2) d_prime = {} for t in T: d_prime[t] = prob.add_variable('d_prime[{0}]'.format(t), n**2) # Objective prob.set_objective('min', pic.sum([W[e]*d[s2i(e)] for e in G.edges()], [('e', 2)], 'edges')) # (V, d) semimetric (1) # distance between a node and itself must be 0. prob.add_list_of_constraints( [d[s2i((u, u))] == 0 for u in G.nodes()], 'u', 'nodes') # distance must be symmetric prob.add_list_of_constraints( [d[s2i(c)] == d[s2i((c[1], c[0]))] for c in node_couples if c[0] < c[1]], [('c', 2)], 'node couples') # positivity is redundant when introducing d prime variable # distance must satisfy triangle inequality prob.add_list_of_constraints( [d[s2i((u, w))] <= d[s2i((u, v))] + d[s2i((v, w))] for (u, v, w) in node_triples], ['u', 'v', 'w'], 'nodes x nodes x nodes') # (2) terminals are far apart prob.add_list_of_constraints( [d[s2i(c)] == 1 for c in terminal_couples], [('c', 2)], 'terminal couples') # (3) distance should be inferior to 1 prob.add_list_of_constraints( [d[s2i(c)] <= 1 for c in node_couples if (not((c[0] in T) and (c[1] in T)) and c[0] != c[1])]) # (4) prob.add_list_of_constraints( [pic.sum([d[s2i((u, t))] for t in T], 't', 'terminals') == K-1 for u in G.nodes() if u not in T], 'u', 'nodes') # (5') with d_prime prob.add_list_of_constraints( [d[s2i(c)] >= pic.sum([d_prime[t][s2i(c)] for t in T], 't', 'terminals') for c in node_couples], [('c', 2)], 'node couples') # (6') constraints on d_prime prob.add_list_of_constraints( [d_prime[t] >= 0 for t in T], 't', 'terminals') prob.add_list_of_constraints( [d_prime[t][s2i((u, v))] >= d[s2i((u, t))] - d[s2i((v, t))] for (u, v) in node_couples for t in T], ['u', 'v', 't'], 'node couples x terminals') print(prob.solve(solver=solver, verbose=0)) return d.value
#one-potential at source mincut.add_constraint(p[s] == 1) #zero-potential at sink mincut.add_constraint(p[t] == 0) #nonnegativity mincut.add_constraint(p > 0) mincut.add_list_of_constraints( [d[e] > 0 for e in G.edges()], #list of constraints [('e', 2)], #e is a double index (origin and desitnation of the edges) 'edges' #set the index belongs to ) #objective mincut.set_objective( 'min', pic.sum([c[e] * d[e] for e in G.edges()], [('e', 2)], 'edges')) #print mincut mincut.solve(verbose=0) cut = [e for e in G.edges() if d[e].value[0] == 1] #display the graph import pylab fig = pylab.figure(figsize=(11, 8)) node_colors = ['w'] * N node_colors[s] = 'g' #source is green node_colors[t] = 'b' #sink is blue #a Layout for which the graph is planar (or use pos=nx.spring_layout(G) with another graph)
def setUpModelPicos(A, B, Q, R, N, C=None, rho=1e-3, constr=True): """ Description :param A: :param B: :param Q: :param R: :param N: :param dP: :param C: :param constr: :rtype: """ # extract data nx = A[0].shape[0] nu = B[0].shape[1] period = len(A) # create model M = picos.Problem() # scaling scaling = autoScaling(Q, R, N) # model variables alpha = M.add_variable('alpha', 1, vtype='continuous') beta = M.add_variable('beta', 1, vtype='continuous') dP = [ M.add_variable('dP' + str(i), (nx, nx), vtype='symmetric') for i in range(period) ] # alpha should be positive M.add_constraint(alpha > 1e-8) # add regularisation in null space of constraints if (C is not None) and (constr is True): # TODO check if this is correct F, t = [], [] for i in range(period): if C[i] is not None: nc = C[i].shape[0] # number of active constraints at index F.append( M.add_variable('F' + str(i), (nc, 1), vtype='continuous')) M.add_constraint(F[i] > 0) else: F.append(None) # objective obj = beta # minimize condition number if constr is True: for i in range(period): obj = picos.sum(obj, abs(rho * F[i])) M.set_objective('min', obj) # formulate convexified Hessian expression if not constr: HcE = [convexHessianExprPicos(Q, R, N, A, B, dP, alpha, scaling, index = i) \ for i in range(period)] else: HcE = [convexHessianExprPicos(Q, R, N, A, B, dP, alpha, scaling, C = C, F = F, index = i) \ for i in range(period)] # formulate constraints for i in range(period): M.add_constraint((HcE[i] - np.eye(nx + nu)) / scaling['alpha'] >> 0) M.add_constraint((scaling['beta'] * beta * np.eye(nx + nu) - HcE[i]) / scaling['alpha'] >> 0) return M
def cvrp_ip(C,q,K,Q,obj=True): ''' Solves the capacitated vehicle routing problem using an integer programming approach. C: matrix of edge costs, that represent distances between each node q: list of demands associated with each client node K: number of vehicles Q: capacity of each vehicle obj: whether to set objective (ignore unless you are doing local search) returns: objective_value: value of the minimum travel cost x: matrix representing number of routes that use each arc ''' # Add in destination node # It should have the same distances as source and its demand equals 0 q2 = np.append(q, 0) col = C[:,0] C2 = np.hstack((C, np.atleast_2d(col).T)) row = C2[0,:] C3 = np.vstack ((C2, row) ) # set up the picos problem prob = pic.Problem() K_value = K Q_value = Q # define variables N = Constant("N", range(len(q2))) # clients {1,2,...N} plus destination, column vector K = Constant("K", K_value) # number of vehicles Q = Constant("Q", Q_value) # vehicle capacity q = Constant("q", q2) # demand for each client c = Constant("c", C3, C3.shape) # travel cost from i to j x = BinaryVariable("x", C3.shape) # whether edge is in the tour u = RealVariable("u", len(q2)) # cumulative quantity of good delivered between origin and client i prob.set_objective("min", pic.sum([c[i,j]*x[i,j] for j in range(C3.shape[1]) for i in range(C3.shape[0])])) # double check this # add constraints # all u values should be >= q and <= Q for i in range(len(q2)): prob.add_constraint(u[i] >= q[i]) prob.add_constraint(u[i] <= Q) # for all edges, u_i-u_j+Q*x <= Q - qj for i in range(C3.shape[0]) : for j in range(C3.shape[1]): prob.add_constraint(u[i] - u[j] + Q * x[i,j] <= Q - q[j]) # make sure that only 1 vehicle leaves every client # make sure rows of x sum to 1 for n in N[1:-1]: prob.add_constraint(pic.sum(x[n,:])==1) # make sure that only 1 vehicle enters every client # make sure cols of x sum to 1 for n in N[1:-1]: prob.add_constraint(pic.sum(x[:,n])==1) # make sure that no more than K vehicles leave the origin prob.add_constraint(pic.sum(x[0,:]) <= K) # make sure that no more than K vehicles enter the origin prob.add_constraint(pic.sum(x[:,-1]) <= K) # make sure that the number of vehicles that leave the origin should # equal the number of vehicles coming back in prob.add_constraint(pic.sum(x[0,:]) == pic.sum(x[:,-1])) # solve integer program res = prob.solve(solver='cplex') objective_value = pic.sum([c[i,j]*x[i,j] for j in range(C3.shape[1]) for i in range(C3.shape[0])]) return objective_value, x
def linear_programming(self, teamID, saturated_edges): '''Uses linear programming to determine if the team with given team ID has been eliminated. We recommend using a picos solver to solve the linear programming problem once you have it set up. Do not use the flow_constraint method that Picos provides (it does all of the work for you) We want you to set up the constraint equations using picos (hint: add_constraint is the method you want) saturated_edges: dictionary of saturated edges that maps team pairs to the amount of additional games they have against each other returns True if team is eliminated, False otherwise ''' # based on <https://picos-api.gitlab.io/picos/graphs.html#max-flow-min-cut-lp> # BUILD GRAPH self._build_graph(teamID, saturated_edges) G = self.G capped_edges = { e_view[0:2]: e_view[2] for e_view in G.edges(data='capacity') if e_view[2] is not None } cc = pic.new_param('c', capped_edges) s = 'source' t = 'sink' maxflow = pic.Problem() # Add the flow variables. f = {} for e_view in G.edges(data='capacity'): edge = e_view[0:2] capacity = e_view[2] f[edge] = maxflow.add_variable('f[{0}]'.format(edge), 1, lower=0, upper=capacity) # Add another variable for the total flow. F = maxflow.add_variable('F', 1, lower=0) # Enforce flow conservation. maxflow.add_list_of_constraints([ pic.sum([f[p, i] for p in G.predecessors(i)], 'p', 'pred(i)') == pic.sum([f[i, j] for j in G.successors(i)], 'j', 'succ(i)') for i in G.nodes() if i not in (s, t) ], 'i', 'nodes-(s,t)') # Set source flow at s. maxflow.add_constraint( pic.sum([f[p, s] for p in G.predecessors(s)], 'p', 'pred(s)') + F == pic.sum([f[s, j] for j in G.successors(s)], 'j', 'succ(s)')) # Set the objective. maxflow.set_objective('max', F) # Solve the problem. solution = maxflow.solve(verbose=0, solver='cvxopt') if solution['status'] not in ('optimal', 'unknown'): raise Exception('Could not reach optimal solution: {!r}'.format( solution['status'])) max_flow = solution['primals']['F'][0] # max capacity of leftmost edges ideal_flow = sum(saturated_edges.values()) # max_flow is a float, so check equality w/ threshold EPSILON = 1e-5 result = max_flow < ideal_flow - EPSILON return result
#one-potential at source mincut.add_constraint(p[s]==1) #zero-potential at sink mincut.add_constraint(p[t]==0) #nonnegativity mincut.add_constraint(p>0) mincut.add_list_of_constraints( [d[e]>0 for e in G.edges()], #list of constraints [('e',2)], #e is a double index (origin and desitnation of the edges) 'edges' #set the index belongs to ) #objective mincut.set_objective('min', pic.sum([c[e]*d[e] for e in G.edges()], [('e',2)],'edges') ) #print mincut mincut.solve(verbose=0) cut=[e for e in G.edges() if d[e].value[0]==1] #display the graph import pylab fig=pylab.figure(figsize=(11,8)) node_colors=['w']*N node_colors[s]='g' #source is green node_colors[t]='b' #sink is blue
[p[s][s]==1 for s in sources], 's','sources') #zero-potentials at sink multicut.add_list_of_constraints( [p[s][t]==0 for (s,t) in pairs], ['s','t'],'pairs') #nonnegativity multicut.add_list_of_constraints( [p[s]>0 for s in sources], 's','sources') #objective multicut.set_objective('min', pic.sum([cc[e]*y[e] for e in G.edges()], [('e',2)],'edges') ) #print multicut multicut.solve(verbose=0) #print 'The minimal multicut has capacity {0}'.format(multicut.obj_value()) cut=[e for e in G.edges() if y[e].value[0]==1] #display the cut import pylab fig=pylab.figure(figsize=(11,8))
l = [ Ai.size[1] for Ai in A ] r = K.size[1] #creates a problem and the optimization variables prob = pic.Problem() mu = prob.add_variable('mu',s) Z = [prob.add_variable('Z[' + str(i) + ']', (l[i],r)) for i in range(s)] #convert the constants into params of the problem A = pic.new_param('A',A) K = pic.new_param('K',K) #add the constraints prob.add_constraint( pic.sum([ A[i]*Z[i] for i in range(s)], #summands 'i', #name of the index '[s]' #set to which the index belongs ) == K ) prob.add_list_of_constraints( [ abs(Z[i]) < mu[i] for i in range(s)], #constraints 'i', #index of the constraints '[s]' #set to which the index belongs ) #sets the objective prob.set_objective('min', 1 | mu ) # scalar product of the vector of all ones with mu #call to the solver cvxopt sol = prob.solve(solver=SOLVER, verbose = 0) assert( max([abs(v) for v in (mu.value - cvx.matrix([[0.66017],[ 2.4189],[ 0.1640]]).T)]) < 1e-4)
# D-optimal design # #--------------------------------------# prob_D = pic.Problem() AA = [cvx.sparse(a, tc='d') for a in A] s = len(AA) m = AA[0].size[0] AA = pic.new_param('A', AA) mm = pic.new_param('m', m) L = prob_D.add_variable('L', (m, m)) V = [prob_D.add_variable('V[' + str(i) + ']', AA[i].T.size) for i in range(s)] w = prob_D.add_variable('w', s) u = {} for k in ['01', '23', '4.', '0123', '4...', '01234']: u[k] = prob_D.add_variable('u[' + k + ']', 1) prob_D.add_constraint( pic.sum([AA[i] * V[i] for i in range(s)], 'i', '[s]') == L) #L lower inferior prob_D.add_list_of_constraints( [L[i, j] == 0 for i in range(m) for j in range(i + 1, m)], ['i', 'j'], 'upper triangle') prob_D.add_list_of_constraints( [abs(V[i]) < (mm**0.5) * w[i] for i in range(s)], 'i', '[s]') prob_D.add_constraint(1 | w < 1) #SOC constraints to define u['01234'] such that u['01234']**8 < t[0] t[1] t[2] t[3] t[4] prob_D.add_constraint(u['01']**2 < L[0, 0] * L[1, 1]) prob_D.add_constraint(u['23']**2 < L[2, 2] * L[3, 3]) prob_D.add_constraint(u['4.']**2 < L[4, 4]) prob_D.add_constraint(u['0123']**2 < u['01'] * u['23']) prob_D.add_constraint(u['4...']**2 < u['4.']) prob_D.add_constraint(u['01234']**2 < u['0123'] * u['4...'])
# D-optimal design # #--------------------------------------# prob_D = pic.Problem() AA=[cvx.sparse(a,tc='d') for a in A] s=len(AA) m=AA[0].size[0] AA=pic.new_param('A',AA) mm=pic.new_param('m',m) L=prob_D.add_variable('L',(m,m)) V=[prob_D.add_variable('V['+str(i)+']',AA[i].T.size) for i in range(s)] w=prob_D.add_variable('w',s) u={} for k in ['01','23','4.','0123','4...','01234']: u[k] = prob_D.add_variable('u['+k+']',1) prob_D.add_constraint( pic.sum([AA[i]*V[i] for i in range(s)],'i','[s]') == L) #L lower inferior prob_D.add_list_of_constraints( [L[i,j] == 0 for i in range(m) for j in range(i+1,m)],['i','j'],'upper triangle') prob_D.add_list_of_constraints([abs(V[i])<(mm**0.5)*w[i] for i in range(s)],'i','[s]') prob_D.add_constraint(1|w<1) #SOC constraints to define u['01234'] such that u['01234']**8 < t[0] t[1] t[2] t[3] t[4] prob_D.add_constraint(u['01']**2 <L[0,0]*L[1,1]) prob_D.add_constraint(u['23']**2 <L[2,2]*L[3,3]) prob_D.add_constraint(u['4.']**2 <L[4,4]) prob_D.add_constraint(u['0123']**2 <u['01']*u['23']) prob_D.add_constraint(u['4...']**2 <u['4.']) prob_D.add_constraint(u['01234']**2<u['0123']*u['4...'])
def solve_RMCFP_L_2(G, s, t, mu, delta, Gamma): ''' This function solves the Robust MCFP with L_2 uncertainty set :param G: bidirectional graph object :param s: source node (0) :param t: sink (terminal) node (N-1) :param mu: nominal edges costs :param delta: costs deviations (uncertainty amplification) :param Gamma: uncertainty ball size :return: ''' # Define problem using PICOS P = pic.Problem() # Add the flow variables and auxiliary variable x = {} for e in G.edges(): x[e] = P.add_variable('x[{0}]'.format(e), 1) v = P.add_variable('v', 1) # Add "dummy" variables which will be exactly x in a vector form # to easily add the robust feasibility constraint x_vector = P.add_variable('x', len(G.edges)) # Add parameter to PICOS mu_pic = pic.new_param('mu', mu) delta_pic = pic.new_param('delta', delta) Gamma_pic = pic.new_param('Gamma', Gamma) # --- Add constraints --- # Robust feasibility constraint (its equivalent) P.add_constraint( abs(pic.diag(Gamma_pic * delta_pic) * x_vector) <= v - (mu_pic | x_vector)) # Enforce x_vector elements to be equal to all x variables P.add_list_of_constraints([ x_vector[i] == x[e] for (i, e) in zip(range(len(x_vector)), G.edges()) ]) # Enforce flow conservation P.add_list_of_constraints([ pic.sum([x[i, j] for i in G.predecessors(j)], 'i', 'pred(j)') == pic.sum([x[j, k] for k in G.successors(j)], 'k', 'succ(j)') for j in G.nodes() if j not in (s, t) ], 'j', 'nodes-(s,t)') # Set source flow at s P.add_constraint( pic.sum([x[s, j] for j in G.successors(s)], 'j', 'succ(s)') == 1) # Set sink flow at t P.add_constraint( pic.sum([x[i, t] for i in G.predecessors(t)], 'i', 'pred(t)') == 1) # Enforce edge capacities P.add_list_of_constraints( [x[e[:2]] <= e[2]['capacity'] for e in G.edges(data=True)], # list of constraints [('e', 2)], # e is a double index 'edges') # set the index belongs to # Enforce flow non-negativity P.add_list_of_constraints( [x[e] >= 0 for e in G.edges()], # list of constraints [('e', 2)], # e is a double index 'edges') # set the index belongs to # Solve P.set_objective('min', v) sol = P.solve(verbose=0, solver='cvxopt') # Unpack solution vector x = np.array(sol['cvxopt_sol']['x']).reshape(-1)[:len(G.edges())] return P, x
def ntf_fir_from_digested(order, osrs, H_inf, f0s, zf, **opts): """ Synthesize FIR NTF with minmax approach from predigested specification Version for the cvxpy_tinoco modeler. """ verbose = 1 if opts.get('show_progress', True) else 0 if 'maxiters' in opts['picos_opts']: opts['picos_opts']['maxit'] = opts['picos_opts']['maxiters'] del opts['picos_opts']['maxiters'] # State space representation of NTF A = cvxopt.matrix(np.eye(order, order, 1)) B = cvxopt.matrix(np.vstack((np.zeros((order-1, 1)), 1.))) # C contains the NTF coefficients D = cvxopt.matrix(1.) p = picos.Problem() # Set up the problem bands = len(f0s) c = p.add_variable('c', (1, order)) gg = p.add_variable('gg', bands) for idx in range(bands): f0 = f0s[idx] osr = osrs[idx] omega0 = 2*f0*np.pi Omega = 1./osr*np.pi P = p.add_variable('P[{}]'.format(idx), (order, order), vtype='symmetric') Q = p.add_variable('Q[{}]'.format(idx), (order, order), vtype='symmetric') if f0 == 0: # Lowpass modulator M1 = A.T*P*A+Q*A+A.T*Q-P-2*Q*np.cos(Omega) M2 = A.T*P*B + Q*B M3 = B.T*P*B - gg[idx, 0] M = ((M1 & M2 & c.T) // (M2.T & M3 & D) // (c & D & -1.0)) p.add_constraint(Q >> 0) p.add_constraint(M << 0) if zf: # Force a zero at DC p.add_constraint(picos.sum(c[i] for i in range(order)) == -1) else: # Bandpass modulator M1r = (A.T*P*A + Q*A*np.cos(omega0) + A.T*Q*np.cos(omega0) - P - 2*Q*np.cos(Omega)) M2r = A.T*P*B + Q*B*np.cos(omega0) M3r = B.T*P*B - gg[idx] M1i = A.T*Q*np.sin(omega0) - Q*A*np.sin(omega0) M21i = -Q*B*np.sin(omega0) M22i = B.T*Q*np.sin(omega0) Mr = ((M1r & M2r & c.T) // (M2r.T & M3r & D) // (c & D & -1.0)) Mi = ((M1i & M21i & cvxopt.matrix(np.zeros((order, 1)))) // (M22i & 0.0 & 0.0) // (cvxopt.matrix(np.zeros((1, order+2))))) M = ((Mr & Mi) // (-Mi & Mr)) p.add_constraint(Q >> 0.0) p.add_constraint(M << 0.0) if zf: # Force a zero at z=np.exp(1j*omega0) nn = np.arange(order).reshape((order, 1)) vr = cvxopt.matrix(np.cos(omega0*nn)) vi = cvxopt.matrix(np.sin(omega0*nn)) vn = cvxopt.matrix( [-np.cos(omega0*order), -np.sin(omega0*order)]) p.add_constraint(c*(vr & vi) == vn) if H_inf < np.inf: # Enforce the Lee constraint R = p.add_variable('R', (order, order), vtype='symmetric') p.add_constraint(R >> 0) MM = ((A.T*R*A-R & A.T*R*B & c.T) // (B.T*R*A & -H_inf**2+B.T*R*B & D) // (c & D & -1)) p.add_constraint(MM << 0) mx = p.add_variable('mx') p.add_constraint(picos.NormP_Exp(gg, 100) < mx) p.set_objective('min', mx) p.set_options(**opts['picos_opts']) p.solve(verbose=verbose) return np.hstack((1, np.asarray(c.value)[0, ::-1]))