Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import picos as pic
P = pic.Problem()
X = P.add_variable('X',(N,N),'symmetric')
P.add_constraint(A*X == est*pic.diag_vect(X).T)
P.add_constraint(A*pic.diag_vect(X)==est)
P.add_constraint(X<1)
#P.add_constraint(X>>0)
P.add_constraint(X>0)
#P.set_objective('max', (L|X))
P.set_objective('max', (L|X))
#P.add_constraint(X[1,4]==0)
#P.add_constraint(X[2,5]==0)
#P.add_constraint(X[2,7]==0)
P.solve()
H = cvx.sparse([[MMP[:]] for MMP in MP])
bX = X.value[:]
Q = pic.Problem()
lbd = Q.add_variable('lbd',H.size[1],lower=0)
delta = Q.add_variable('delta',1)
Q.add_constraint(pic.norm(H*lbd-bX,1)dmax:
dmax = delta
Lmax = L
if delta > 1e-3:
break
"""
#series of parallel arcs
# (4 x 4)-affine expression: Diag(x -y) #
>>> pic.tools.diag(x//y)
# (2 x 2)-affine expression: Diag([x;y]) #
"""
from .expression import AffinExp
if not isinstance(exp, AffinExp):
mat, name = _retrieve_matrix(exp)
exp = AffinExp({}, constant=mat[:], size=mat.size, string=name)
(n, m) = exp.size
expcopy = AffinExp(exp.factors.copy(), exp.constant, exp.size,
exp.string)
idx = cvx.spdiag([1.] * dim * n * m)[:].I
for k in exp.factors.keys():
# ensure it's sparse
mat = cvx.sparse(expcopy.factors[k])
I, J, V = list(mat.I), list(mat.J), list(mat.V)
newI = []
for d in range(dim):
for i in I:
newI.append(idx[i + n * m * d])
expcopy.factors[k] = spmatrix(
V * dim, newI, J * dim, ((dim * n * m)**2, exp.factors[k].size[1]))
expcopy.constant = cvx.matrix(0., ((dim * n * m)**2, 1))
if not exp.constant is None:
for k, i in enumerate(idx):
expcopy.constant[i] = exp.constant[k % (n * m)]
expcopy._size = (dim * n * m, dim * n * m)
expcopy.string = 'Diag(' + exp.string + ')'
return expcopy
# Many optionals for what c might be, not yet determined really
if filter is None:
c = matrix(np.ones((MM.num_matrix_monos, 1)))
else:
c = matrix([monomial_filter(yi, filter='even') for yi in MM.matrix_monos], tc='d')
Anp,bnp = MM.get_Ab(constraints)
#_, residual, _, _ = scipy.linalg.lstsq(Anp, bnp)
b = matrix(bnp)
indicatorlist = MM.get_LMI_coefficients()
Glnp,hlnp = MM.get_Ab_slack(constraints, abs_slack = slack, rel_slack = slack)
hl = matrix(hlnp)
if sparsemat:
G = [sparse(indicatorlist).trans()]
A = sparse(matrix(Anp))
Gl = sparse(matrix(Glnp))
else:
G = [matrix(indicatorlist).trans()]
A = matrix(Anp)
Gl = matrix(Glnp)
num_row_monos = len(MM.row_monos)
h = [matrix(np.zeros((num_row_monos,num_row_monos)))]
return {'c':c, 'G':G, 'h':h, 'A':A, 'b':b, 'Gl':Gl, 'hl':hl}
def calc_inc(self):
"""
Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b``
"""
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[system.dae.Fy, system.dae.Gy]])
inc = matrix([system.dae.f, system.dae.g])
if system.dae.factorize:
try:
self.F = self.solver.symbolic(A)
system.dae.factorize = False
except NotImplementedError:
pass
except ValueError:
if A.size == (0, 0):
logger.error("Loaded case file contains no element.")
return None
try:
Convert everything to
cvxopt-style matrices
"""
P = cvxmat(H)
q = cvxmat(f)
if Aeq is None:
A = None
else:
A = cvxmat(Aeq)
if beq is None:
b = None
else:
b = cvxmat(beq)
n = lb.size
G = sparse([-speye(n), speye(n)])
h = cvxmat(vstack([-lb, ub]))
return P, q, G, h, A, b
c = matrix(np.ones((MM.num_matrix_monos, 1)))
else:
c = matrix([monomial_filter(yi, filter='even') for yi in MM.matrix_monos], tc='d')
Anp,bnp = MM.get_Ab(constraints)
#_, residual, _, _ = scipy.linalg.lstsq(Anp, bnp)
b = matrix(bnp)
indicatorlist = MM.get_LMI_coefficients()
Glnp,hlnp = MM.get_Ab_slack(constraints, abs_slack = slack, rel_slack = slack)
hl = matrix(hlnp)
if sparsemat:
G = [sparse(indicatorlist).trans()]
A = sparse(matrix(Anp))
Gl = sparse(matrix(Glnp))
else:
G = [matrix(indicatorlist).trans()]
A = matrix(Anp)
Gl = matrix(Glnp)
num_row_monos = len(MM.row_monos)
h = [matrix(np.zeros((num_row_monos,num_row_monos)))]
return {'c':c, 'G':G, 'h':h, 'A':A, 'b':b, 'Gl':Gl, 'hl':hl}
def sparse2cvxopt(value):
"""Converts a SciPy sparse matrix to a CVXOPT sparse matrix.
Parameters
----------
sparse_mat : SciPy sparse matrix
The matrix to convert.
Returns
-------
CVXOPT spmatrix
The converted matrix.
"""
import cvxopt
if isinstance(value, (np.ndarray, np.matrix)):
return cvxopt.sparse(cvxopt.matrix(value.astype('float64')), tc='d')
# Convert scipy sparse matrices to coo form first.
elif sp.issparse(value):
value = value.tocoo()
return cvxopt.spmatrix(value.data.tolist(), value.row.tolist(),
value.col.tolist(), size=value.shape, tc='d')
def _utri(mat):
"""
return elements of the (strict) upper triangular part of a cvxopt matrix
"""
m, n = mat.size
if m != n:
raise ValueError('mat must be square')
v = []
for j in range(1, n):
for i in range(j):
v.append(mat[i, j])
return cvx.sparse(v)
def __or__(self,fact):#scalar product
selfcopy=self.copy()
if isinstance(fact,AffinExp):
if fact.isconstant():
fac,facString=cvx.sparse(fact.constant),fact.string
elif self.isconstant():
return fact.__ror__(self)
else:
dotp = self[:].T*fact[:]
dotp.string='〈 '+self.string+' | '+fact.string+' 〉'
return dotp
#raise Exception('not implemented')
else:
fac,facString=_retrieve_matrix(fact,self.size)
if selfcopy.size<>fac.size:
raise Exception('incompatible dimensions')
cfac=fac[:].T
for k in selfcopy.factors:
newfac=cfac*selfcopy.factors[k]
selfcopy.factors[k]=newfac
if selfcopy.constant is None:
# q contains loss from margin-rescaling
q = cvxopt.matrix(-np.array(losses, dtype=np.float))
# constraints: all alpha must be >zero
idy = np.identity(n_constraints)
tmp1 = np.zeros(n_constraints)
# positivity constraints:
if self.negativity_constraint is None:
#empty constraints
zero_constr = np.zeros(0)
joint_features_constr = np.zeros((0, n_constraints))
else:
joint_features_constr = joint_feature_matrix.T[self.negativity_constraint]
zero_constr = np.zeros(len(self.negativity_constraint))
# put together
G = cvxopt.sparse(cvxopt.matrix(np.vstack((-idy, joint_features_constr))))
h = cvxopt.matrix(np.hstack((tmp1, zero_constr)))
# equality constraint: sum of all alpha must be = C
A = cvxopt.matrix(np.ones((1, n_constraints)))
b = cvxopt.matrix([C])
# solve QP model
cvxopt.solvers.options['feastol'] = 1e-5
#if hasattr(self, 'old_solution'):
#s = self.old_solution['s']
## put s slightly inside the cone..
#s = cvxopt.matrix(np.vstack([s, [[1e-10]]]))
#z = self.old_solution['z']
#z = cvxopt.matrix(np.vstack([z, [[1e-10]]]))
#initvals = {'x': self.old_solution['x'], 'y':
#self.old_solution['y'], 'z': z,