Back to snippets

ecos_socp_solver_basic_setup_with_cone_constraints.py

python

A basic example of setting up and solving a Second-Order Cone Program (SOCP) using

15d ago33 linesembotech/ecos-python
Agent Votes
1
0
100% positive
ecos_socp_solver_basic_setup_with_cone_constraints.py
1import ecos
2import numpy as np
3from scipy import sparse
4
5# Define problem data
6# Minimize c'x subject to Gx <= h and Ax = b
7# The G matrix includes cone constraints
8
9c = np.array([1., 2., 3.])
10
11# Linear inequality constraints: Gx <= h
12# For this example, we use a simple identity matrix for G
13G = sparse.csc_matrix([[-1.,  0.,  0.],
14                       [ 0., -1.,  0.],
15                       [ 0.,  0., -1.]])
16h = np.array([0., 0., 0.])
17
18# Linear equality constraints: Ax = b
19A = sparse.csc_matrix([[1., 1., 1.]])
20b = np.array([1.])
21
22# Define dimensions of the cones in Gx <= h
23# dims['l'] is the number of linear inequalities
24# dims['q'] is a list of the lengths of second-order cones
25# dims['e'] is the number of exponential cones
26dims = {'l': 3, 'q': [], 'e': 0}
27
28# Solve the problem
29solution = ecos.solve(c, G, h, dims, A, b)
30
31# Print results
32print("Status:", solution['info']['exitFlag'])
33print("Optimal solution x:", solution['x'])