Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
eps = 1e-2
dim = facet.shape[1] # num vertices in facet
# create alpha weights for vertices of facet
G = facet.T.dot(facet)
grasp_matrix = G + eps * np.eye(G.shape[0])
# Solve QP to minimize .5 x'Px + q'x subject to Gx <= h, Ax = b
P = cvx.matrix(2 * grasp_matrix) # quadratic cost for Euclidean dist
q = cvx.matrix(np.zeros((dim, 1)))
G = cvx.matrix(-np.eye(dim)) # greater than zero constraint
h = cvx.matrix(np.zeros((dim, 1)))
A = cvx.matrix(np.ones((1, dim))) # sum constraint to enforce convex
b = cvx.matrix(np.ones(1)) # combinations of vertices
sol = cvx.solvers.qp(P, q, G, h, A, b)
min_norm = sol['primal objective']
return abs(min_norm)
def projection_in_norm(self, x, M):
""" Projection of x to simplex indiced by matrix M. Uses quadratic programming.
"""
m = M.shape[0]
P = matrix(2*M)
q = matrix(-2 * M * x)
G = matrix(-np.eye(m))
h = matrix(np.zeros((m,1)))
A = matrix(np.ones((1,m)))
b = matrix(1.)
sol = solvers.qp(P, q, G, h, A, b)
return np.squeeze(sol['x'])
q = cvxopt.matrix(numpy.array(q).astype(float)).T
n = len(q)
# G and h constrain:
# 1) sum of probs is less then 1
# 2) All probs bigger than 0
# 3) Honesty (measured using fidelity, if given)
G_data = [[1] * n] + [([-1 if i == k else 0 for i in range(n)])
for k in range(n)]
h_data = [1] + [0] * n
if self.fidelity_data is not None:
G_data.append(self.fidelity_data['coefficients'])
h_data.append(self.fidelity_data['goal'])
G = cvxopt.matrix(numpy.array(G_data).astype(float))
h = cvxopt.matrix(numpy.array(h_data).astype(float))
cvxopt.solvers.options['show_progress'] = False
return cvxopt.solvers.qp(P, q, G, h)['x']
G[m:2*m,:n] = -A
G[m:2*m,n:n+m] = spmatrix(-1.0, range(m), range(m))
G[m:2*m,n+m:] = spmatrix(-1.0, range(m), range(m))
h[m:2*m] = -b
# u >= 0
G[2*m:3*m,n:n+m] = spmatrix(-1.0, range(m), range(m))
# u <= 1
G[3*m:4*m,n:n+m] = spmatrix(1.0, range(m), range(m))
h[3*m:4*m] = 1.0
# v >= 0
G[4*m:,n+m:] = spmatrix(-1.0, range(m), range(m))
xh = solvers.qp(P, q, G, h)['x'][:n]
try: import pylab
except ImportError: pass
else:
pylab.figure(1,facecolor='w')
pylab.plot(u, v,'o',
[-11,11], [xh[0]-11*xh[1], xh[0]+11*xh[1]], '-g',
[-11,11], [xls[0]-11*xls[1], xls[0]+11*xls[1]], '--r',
markerfacecolor='w', markeredgecolor='b')
pylab.axis([-11, 11, -20, 25])
pylab.xlabel('t')
pylab.ylabel('f(t)')
pylab.title('Robust regression (fig. 6.5)')
pylab.show()
# Use conelp
z = lambda m,n: cv.spmatrix([],[],[],(m,n))
G = cv.sparse([[-A,z(2,n),M,z(nB+2,n)],[z(n+2,nC),C,z(nB+2,nC)],
[z(n,1),-1,1,z(n+nB+2,1)],[z(2*n+2,1),-1,1,z(nB,1)],
[z(n+2,nB),B,z(2,nB),cv.spmatrix(1.0, range(nB), range(nB))]])
h = cv.matrix([z(n,1),.5,.5,z_eda,.5,.5,z(nB,1)])
c = cv.matrix([(cv.matrix(alpha, (1,n)) * A).T,z(nC,1),1,gamma,z(nB,1)])
res = cv.solvers.conelp(c, G, h, dims={'l':n,'q':[n+2,nB+2],'s':[]})
obj = res['primal objective']
else:
# Use qp
Mt, Ct, Bt = M.T, C.T, B.T
H = cv.sparse([[Mt*M, Ct*M, Bt*M], [Mt*C, Ct*C, Bt*C],
[Mt*B, Ct*B, Bt*B+gamma*cv.spmatrix(1.0, range(nB), range(nB))]])
f = cv.matrix([(cv.matrix(alpha, (1,n)) * A).T - Mt*z_eda, -(Ct*z_eda), -(Bt*z_eda)])
res = cv.solvers.qp(H, f, cv.spmatrix(-A.V, A.I, A.J, (n,len(f))),
cv.matrix(0., (n,1)), solver=solver)
obj = res['primal objective'] + .5 * (z_eda.T * z_eda)
cv.solvers.options.clear()
cv.solvers.options.update(old_options)
l = res['x'][-nB:]
d = res['x'][n:n+nC]
tonic = B*l + C*d
q = res['x'][:n]
p = A * q
phasic = M * q
e = z_eda - phasic - tonic
phasic = np.array(phasic)[:,0]
# results = (np.array(a).ravel() for a in (r, t, p, l, d, e, obj))
if umax is not None:
tG = np.eye(N * nu)
th = np.kron(np.ones((N * nu, 1)), umax)
G = np.vstack([G, tG])
h = np.vstack([h, th])
if umin is not None:
tG = np.eye(N * nu) * -1.0
th = np.kron(np.ones((N * nu, 1)), umin * -1.0)
G = np.vstack([G, tG])
h = np.vstack([h, th])
G = matrix(G)
h = matrix(h)
sol = cvxopt.solvers.qp(P, q, G, h)
u = np.array(sol["x"])
# recover x
xx = AA @ x0 + BB @ u
x = np.vstack((x0.T, xx.reshape(N, nx)))
return x, u
AiB = A * AiB
BB += np.kron(np.diag(np.ones(N - i), -i), AiB)
# print(BB)
RR = np.kron(np.eye(N), R)
QQ = scipy.linalg.block_diag(np.kron(np.eye(N - 1), Q), P)
H = (BB.T * QQ * BB + RR)
# print(H)
gx0 = BB.T * QQ * AA * x0
# print(gx0)
P = matrix(H)
q = matrix(gx0)
sol = cvxopt.solvers.qp(P, q)
# print(sol)
u = np.matrix(sol["x"])
# recover x
xx = AA * x0 + BB * u
x = np.concatenate((x0.T, xx.reshape(N, 2)), axis=0)
x1 = np.array(x[:, 0]).flatten()
x2 = np.array(x[:, 1]).flatten()
# flg, ax = plt.subplots(1)
plt.plot(x1, '*r', label="x1")
plt.plot(x2, '*b', label="x2")
plt.plot(u, '*k', label="u")
plt.legend()
QQ = Q.T * Q
Py = RankAggregator.generateTransitionMatrix(topQList, itemList)
s = numpy.array(Py.todense()).ravel()
s = cvxopt.matrix(s)
G = cvxopt.spdiag((-numpy.ones(ell)).tolist())
h = cvxopt.matrix(numpy.zeros(ell))
A = cvxopt.matrix(numpy.ones(ell), (1, ell))
b = cvxopt.matrix(numpy.ones(1))
q = -Q.T * s
sol = cvxopt.solvers.qp(QQ, q, G, h, A, b)
alpha = numpy.array(sol['x'])
#Combine the matrices
P = numpy.zeros((n, n))
for j, Pj in enumerate(PList):
Util.printIteration(j, 1, ell)
P += alpha[j] * numpy.array(Pj.todense())
P /= ell
outputList, scores = RankAggregator.computeOutputList(P, itemList)
if verbose:
return outputList, scores, PList
def update_single_w(i):
""" compute single W[:,i] """
# optimize beta using qp solver from cvxopt
FB = base.matrix(np.float64(np.dot(-self.data.T, W_hat[:,i])))
be = solvers.qp(HB, FB, INQa, INQb, EQa, EQb)
self.beta[i,:] = np.array(be['x']).reshape((1, self._num_samples))