alpaqa 0.0.1
Nonconvex constrained optimization
getting-started.py
Go to the documentation of this file.
1## @example simple_optimization/python/getting-started.py
2# This code contains a minimal example of an optimization problem that can be
3# built and solved using `alpaqa`.
4
5# %% Build the problem for PANOC+ALM (CasADi code, independent of alpaqa)
6import casadi as cs
7
8# Make symbolic decision variables
9x1, x2 = cs.SX.sym("x1"), cs.SX.sym("x2")
10# Make a parameter symbol
11p = cs.SX.sym("p")
12
13# Expressions for the objective function f and the constraints g
14f_expr = (1 - x1) ** 2 + p * (x2 - x1 ** 2) ** 2
15g_expr = cs.vertcat(
16 (x1 - 0.5) ** 3 - x2 + 1,
17 x1 + x2 - 1.5,
18)
19
20# Collect decision variables into one vector
21x = cs.vertcat(x1, x2)
22# Convert the symbolic expressions to CasADi functions
23f = cs.Function("f", [x, p], [f_expr])
24g = cs.Function("g", [x, p], [g_expr])
25
26# %% Generate and compile C-code for the objective and constraints using alpaqa
27import alpaqa as pa
28
29# Compile and load the problem
30prob = pa.generate_and_compile_casadi_problem(f, g)
31
32# Set the bounds
33import numpy as np
34prob.C.lowerbound = [-0.25, -0.5] # -0.25 <= x1 <= 1.5
35prob.C.upperbound = [1.5, 2.5] # -0.5 <= x2 <= 2.5
36prob.D.lowerbound = [-np.inf, -np.inf] # g1 <= 0
37prob.D.upperbound = [0, 0] # g2 <= 0
38
39# Set parameter to some value
40prob.param = [10.]
41
42# %% Build a solver with the default parameters
43innersolver = pa.StructuredPANOCLBFGSSolver()
44solver = pa.ALMSolver(innersolver)
45
46# %% Build a solver with custom parameters
47inner_solver = pa.StructuredPANOCLBFGSSolver(
48 panoc_params={
49 'max_iter': 1000,
50 'stop_crit': pa.PANOCStopCrit.ApproxKKT,
51 },
52 lbfgs_params={
53 'memory': 10,
54 },
55)
56
57solver = pa.ALMSolver(
58 alm_params={
59 'ε': 1e-10,
60 'δ': 1e-10,
61 'Σ_0': 0,
62 'σ_0': 2,
63 'Δ': 20,
64 },
65 inner_solver=inner_solver
66)
67
68# %% Compute a solution
69
70# Set initial guesses at arbitrary values
71x0 = np.array([0.1, 1.8]) # decision variables
72y0 = np.zeros((prob.m,)) # Lagrange multipliers for g(x)
73
74# Solve the problem
75x_sol, y_sol, stats = solver(prob, x0, y0)
76
77# Print the results
78print(stats["status"])
79print(f"Solution: {x_sol}")
80print(f"Multipliers: {y_sol}")
81print(f"Cost: {prob.f(x_sol)}")
82print(f"ε: {stats['ε']}")
83print(f"δ: {stats['δ']}")