def testgp(opts): Aflr = 1000.0 Awall = 100.0 alpha = 0.5 beta = 2.0 gamma = 0.5 delta = 2.0 F = matrix( [[-1., 1., 1., 0., -1., 1., 0., 0.], [-1., 1., 0., 1., 1., -1., 1., -1.], [-1., 0., 1., 1., 0., 0., -1., 1.]]) g = log( matrix( [1.0, 2/Awall, 2/Awall, 1/Aflr, alpha, 1/beta, gamma, 1/delta]) ) K = [1, 2, 1, 1, 1, 1, 1] solvers.options.update(opts) sol = solvers.gp(K, F, g) #localcvx.options.update(opts) #sol = localcvx.gp(K, F, g, kktsolver='chol') if sol['status'] == 'optimal': x = sol['x'] print "x=\n", helpers.strSpe(x, "%.17f") h, w, d = exp(x) print("\n h = %f, w = %f, d = %f.\n" %(h,w,d)) print "\n *** running GO test ***" helpers.run_go_test("../testgp", {'x': x})
def computeoptgam(self,cinfo,xmin,iStar,mingrad): d,V=cinfo a=matrix(0.0,(d,1)) b=matrix(0.0,(d,1)) for j in range(d): a[j]= -math.log(V[j])-self.C*np.matrix(xmin)[0,j]*self.r[j] b[j]=math.log(V[j]) G=matrix([[1.0,-1.0]]) h=matrix([[1.0,0.0]]) K=[d] solvers.options['show_progress'] = False return (solvers.gp(G=G,h=h,g=b,F=a,K=K)['x'])[0]
def geometric_programming(): K = [4] F = matrix([[-1., 1., 1., 0.], [-1., 1., 0., 1.], [-1., 0., 1., 1.]]) g = matrix([log(40.), log(2.), log(2.), log(2.)]) solvers.options['show_progress'] = False sol = solvers.gp(K, F, g) print('Solution of GP:') print(np.exp(np.array(sol['x']))) print('\nchecking sol^5') print(np.exp(np.array(sol['x']))**5)
def solving_for_cloud_x(m, M): N, T = m.shape K = [1] for i in range(T): K.append(N) g = [1] for i in range(N * T): g.append(1 / M) F = np.zeros((N * T + 1, N * T)) F[0, :] = -1 * m.reshape(1, N * T) for i in range(T): for j in range(N): F[N * i + j + 1, j * T + i] = 1 solvers.options['show_progress'] = False sol_cloud = solvers.gp(K, matrix(F), log(matrix(g, tc='d'))) x_cloud = array(exp(sol_cloud['x'])).reshape((N, T)) return x_cloud
def cvxoptimize(c, A, k, *args, **kwargs): """Interface to the CVXOPT solver Definitions ----------- "[a,b] array of floats" indicates array-like data with shape [a,b] n is the number of monomials in the gp m is the number of variables in the gp p is the number of posynomial constraints in the gp Arguments --------- c : floats array of shape n Coefficients of each monomial A : floats array of shape (n, m) Exponents of the various free variables for each monomial. k : ints array of shape p+1 k[0] is the number of monomials (rows of A) present in the objective k[1:] is the number of monomials present in each constraint Returns ------- dict Contains the following keys "success": bool "objective_sol" float Optimal value of the objective "primal_sol": floats array of size m Optimal value of free variables. Note: not in logspace. "dual_sol": floats array of size p Optimal value of the dual variables, in logspace. """ g = log(matrix(c)) F = spmatrix(A.data, A.row, A.col, tc='d') solution = gp(k, F, g, *args, **kwargs) return dict(status=solution['status'], primal=np.ravel(solution['x']), la=solution['znl'])
from cvxopt import matrix, solvers P = matrix([[1., 0.], [0., 1.]]) q = matrix([-10., -10.]) G = matrix([[1., 2., 1., -1., 0.], [1., 1., 4., 0., -1.]]) h = matrix([10., 16., 32., 0., 0]) solvers.options['show_progress'] = False sol = solvers.qp(P, q, G, h) print('Solution:') print(sol['x']) # Geometric Programming from cvxopt import matrix, solvers from math import log, exp# gp from numpy import array import numpy as np K = [4] F = matrix([[-1., 1., 1., 0.], [-1., 1., 0., 1.], [-1., 0., 1., 1.]]) g = matrix([log(40.), log(2.), log(2.), log(2.)]) solvers.options['show_progress'] = False sol = solvers.gp(K, F, g) print('Solution:') print(np.exp(np.array(sol['x']))) print('\nchecking sol^5') print(np.exp(np.array(sol['x']))**5)
# The small GP of section 9.3 (Geometric programming). from cvxopt import matrix, log, exp, solvers Aflr = 1000.0 Awall = 100.0 alpha = 0.5 beta = 2.0 gamma = 0.5 delta = 2.0 F = matrix([[-1., 1., 1., 0., -1., 1., 0., 0.], [-1., 1., 0., 1., 1., -1., 1., -1.], [-1., 0., 1., 1., 0., 0., -1., 1.]]) g = log( matrix([ 1.0, 2 / Awall, 2 / Awall, 1 / Aflr, alpha, 1 / beta, gamma, 1 / delta ])) K = [1, 2, 1, 1, 1, 1, 1] h, w, d = exp(solvers.gp(K, F, g)['x']) print("\n h = %f, w = %f, d = %f.\n" % (h, w, d))
# The small GP of section 9.3 (Geometric programming). from cvxopt import matrix, log, exp, solvers Aflr = 1000.0 Awall = 100.0 alpha = 0.5 beta = 2.0 gamma = 0.5 delta = 2.0 F = matrix( [[-1., 1., 1., 0., -1., 1., 0., 0.], [-1., 1., 0., 1., 1., -1., 1., -1.], [-1., 0., 1., 1., 0., 0., -1., 1.]]) g = log( matrix( [1.0, 2/Awall, 2/Awall, 1/Aflr, alpha, 1/beta, gamma, 1/delta]) ) K = [1, 2, 1, 1, 1, 1, 1] h, w, d = exp( solvers.gp(K, F, g)['x'] ) print("\n h = %f, w = %f, d = %f.\n" %(h,w,d))
def minimize(self): """ The main function to compute the lower bound for an even degree polynomial, using Geometric Program. """ from cvxopt import solvers from time import time, clock from math import exp RealNumber = float # Required for CvxOpt Integer = int # Required for CvxOpt if 'Iterations' in self.Settings: solvers.options['maxiters'] = self.Settings['Iterations'] else: solvers.options['maxiters'] = 100 if 'Details' in self.Settings: solvers.options['show_progress'] = self.Settings['detail'] else: solvers.options['show_progress'] = False if 'tryKKT' in self.Settings: solvers.options['refinement'] = self.Settings['tryKKT'] else: solvers.options['refinement'] = 1 n = self.number_of_variables d = self.Ord f = self.polynomial GP = self.init_geometric_program() f0 = self.constant_term if not self.geometric_program: self.Info['status'] = 'Inapplicable' self.Info[ 'Message'] = 'The input data does not result in a geometric program' self.Info['gp'] = None self.fgp = None return self.fgp F = self.Matrix2CVXOPT(GP[1]) g = self.Matrix2CVXOPT(GP[0]) K = GP[2] start = time() start2 = clock() #if True: try: sol = solvers.gp(K=K, F=F, g=g) elapsed = (time() - start) elapsed2 = (clock() - start2) self.fgp = min(-f0 - exp(sol['primal objective']), -f0 - exp(sol['dual objective'])) self.Info = {"gp": self.fgp, "Wall": elapsed, "CPU": elapsed2} if (sol['status'] == 'unknown'): if (abs(sol['relative gap']) < self.error_bound) or (abs( sol['gap']) < self.error_bound): self.Info[ 'status'] = 'The solver did not converge to a solution' self.Info[ 'Message'] = 'A possible optimum value were found.' else: self.Info[ 'status'] = 'Singular KKT or non-convergent IP may occurd' self.Info[ 'Message'] = 'Maximum iteration has reached by solver or a singular KKT matrix occurred.' else: self.Info['status'] = 'Optimal' self.Info['Message'] = 'Optimal solution found by solver.' except: self.Info['Message'] = "An error has occurred on CvxOpt.GP solver." self.Info['status'] = 'Infeasible' self.Info['gp'] = None self.fgp = None return self.fgp
def optimize(*, c, A, k, meq_idxs, use_leqs=True, **kwargs): """Interface to the CVXOPT solver Definitions ----------- "[a,b] array of floats" indicates array-like data with shape [a,b] n is the number of monomials in the gp m is the number of variables in the gp p is the number of posynomial constraints in the gp Arguments --------- c : floats array of shape n Coefficients of each monomial A : floats array of shape (n, m) Exponents of the various free variables for each monomial. k : ints array of shape p+1 k[0] is the number of monomials (rows of A) present in the objective k[1:] is the number of monomials present in each constraint Returns ------- dict Contains the following keys "success": bool "objective_sol" float Optimal value of the objective "primal_sol": floats array of size m Optimal value of free variables. Note: not in logspace. "dual_sol": floats array of size p Optimal value of the dual variables, in logspace. """ log_c = np.log(np.array(c)) lse_mons, lin_mons, leq_mons = [], [], [] lse_posys, lin_posys, leq_posys = [], [], [] for i, n_monomials in enumerate(k): start = sum(k[:i]) mons = range(start, start + k[i]) if use_leqs and start in meq_idxs.all: if start in meq_idxs.first_half: leq_posys.append(i) leq_mons.extend(mons) elif i != 0 and n_monomials == 1: lin_mons.extend(mons) lin_posys.append(i) else: lse_mons.extend(mons) lse_posys.append(i) A = A.tocsr() maxcol = A.shape[1] - 1 if leq_mons: A_leq = A[leq_mons, :].tocoo() log_c_leq = log_c[leq_mons] kwargs["A"] = spmatrix([float(r) for r in A_leq.data] + [0], [int(r) for r in A_leq.row] + [0], [int(r) for r in A_leq.col] + [maxcol], tc="d") kwargs["b"] = matrix(-log_c_leq) if lin_mons: A_lin = A[lin_mons, :].tocoo() log_c_lin = log_c[lin_mons] kwargs["G"] = spmatrix([float(r) for r in A_lin.data] + [0], [int(r) for r in A_lin.row] + [0], [int(r) for r in A_lin.col] + [maxcol], tc="d") kwargs["h"] = matrix(-log_c_lin) k_lse = [k[i] for i in lse_posys] A_lse = A[lse_mons, :].tocoo() log_c_lse = log_c[lse_mons] F = spmatrix([float(r) for r in A_lse.data] + [0], [int(r) for r in A_lse.row] + [0], [int(r) for r in A_lse.col] + [maxcol], tc="d") g = matrix(log_c_lse) try: solution = gp(k_lse, F, g, **kwargs) except ValueError as e: raise DualInfeasible() from e if solution["status"] != "optimal": raise UnknownInfeasible("solution status " + repr(solution["status"])) la = np.zeros(len(k)) la[lin_posys] = list(solution["zl"]) la[lse_posys] = [1.] + list(solution["znl"]) for leq_posy, yi in zip(leq_posys, solution["y"]): if yi >= 0: la[leq_posy] = yi else: # flip it around to the other "inequality" la[leq_posy + 1] = -yi return dict(status=solution["status"], objective=np.exp(solution["primal objective"]), primal=np.ravel(solution["x"]), la=la)
#ex14 # c = matrix([-5.0, -3.0]) # G = matrix([[1.0, 2.0, 1.0, -1.0, 0.0], [1.0, 1.0, 4.0, 0.0, -1.0]]) # h = matrix([10.0, 16.0, 32.0, 0.0, 0.0]) # solln = solvers.lp(c, G, h) # print(solln['x']) #ex16 # c = matrix([1.0, -2.0, -4.0, 2.0]) # G = matrix([[1.0, 0.0, -2.0, -1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0, -1.0, 0.0, 0.0,], [-2.0, 0.0, 8, 0.0, 0.0, -1.0, 0.0], [0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0]]) # h = matrix([4.0, 8.0, 12.0, 0.0, 0.0, 0.0, 0.0]) # solln = solvers.lp(c, G, h) # print(solln['x']) #Geometry method #ex K = [1] F = matrix([[1.],[-1.]]) g = matrix([log(1.)]) G = matrix([[0.5, 0.], [-0.33, 0.]]) h = matrix([1., 1.]) solvers.options['show_progress'] = False solgp = solvers.gp(K, F, g) print('Solution:') print((solgp['x'])))
def minimize(self): """ The main function to compute the lower bound for an even degree polynomial, using Geometric Program. """ from cvxopt import solvers from time import time, clock from math import exp RealNumber = float # Required for CvxOpt Integer = int # Required for CvxOpt if 'Iterations' in self.Settings: solvers.options['maxiters'] = self.Settings['Iterations'] else: solvers.options['maxiters'] = 100 if 'Details' in self.Settings: solvers.options['show_progress'] = self.Settings['detail'] else: solvers.options['show_progress'] = False if 'tryKKT' in self.Settings: solvers.options['refinement'] = self.Settings['tryKKT'] else: solvers.options['refinement'] = 1 n = self.number_of_variables d = self.Ord f = self.polynomial GP = self.init_geometric_program() f0 = self.constant_term if not self.geometric_program: self.Info['status'] = 'Inapplicable' self.Info['Message'] = 'The input data does not result in a geometric program' self.Info['gp'] = None self.fgp = None return self.fgp F = self.Matrix2CVXOPT(GP[1]) g = self.Matrix2CVXOPT(GP[0]) K = GP[2] start = time() start2 = clock() #if True: try: sol = solvers.gp(K=K, F=F, g=g) elapsed = (time() - start) elapsed2 = (clock()-start2) self.fgp = min(-f0-exp(sol['primal objective']), -f0-exp(sol['dual objective'])) self.Info = {"gp":self.fgp, "Wall":elapsed, "CPU":elapsed2} if (sol['status'] == 'unknown'): if (abs(sol['relative gap']) < self.error_bound) or (abs(sol['gap']) < self.error_bound): self.Info['status'] = 'The solver did not converge to a solution' self.Info['Message'] = 'A possible optimum value were found.' else: self.Info['status'] = 'Singular KKT or non-convergent IP may occurd' self.Info['Message'] = 'Maximum iteration has reached by solver or a singular KKT matrix occurred.' else: self.Info['status'] = 'Optimal' self.Info['Message'] = 'Optimal solution found by solver.' except: self.Info['Message'] = "An error has occurred on CvxOpt.GP solver." self.Info['status'] = 'Infeasible' self.Info['gp'] = None self.fgp = None return self.fgp