alpaqa 1.0.0a9
Nonconvex constrained optimization
Loading...
Searching...
No Matches
Python/simple_optimization/getting-started.py

This is a minimal example of an optimization problem that can be built and solved using the alpaqa Python interface.

This is a minimal example of an optimization problem that can be built and solved using the alpaqa Python interface.

1# %% Build the problem (CasADi code, independent of alpaqa)
2import casadi as cs
3import numpy as np
4
5# Make symbolic decision variables
6x1, x2 = cs.SX.sym("x1"), cs.SX.sym("x2")
7x = cs.vertcat(x1, x2) # Collect decision variables into one vector
8# Make a parameter symbol
9p = cs.SX.sym("p")
10
11# Objective function f and the constraints function g
12f = (1 - x1) ** 2 + p * (x2 - x1**2) ** 2
13g = cs.vertcat(
14 (x1 - 0.5) ** 3 - x2 + 1,
15 x1 + x2 - 1.5,
16)
17
18# Define the bounds
19C = [-0.25, -0.5], [1.5, 2.5] # -0.25 <= x1 <= 1.5, -0.5 <= x2 <= 2.5
20D = [-np.inf, -np.inf], [0, 0] # g1 <= 0, g2 <= 0
21
22# %% Generate and compile C-code for the objective and constraints using alpaqa
23from alpaqa import minimize
24
25problem = (
26 minimize(f, x) # Objective function f(x)
27 .subject_to_box(C) # Box constraints x ∊ C
28 .subject_to(g, D) # General ALM constraints g(x) ∊ D
29 .with_param(p, [1]) # Parameter with default value (can be changed later)
30).compile()
31
32# You can change the bounds and parameters after loading the problem
33problem.param = [10.0]
34problem.D.lowerbound[1] = -1e20
35
36# %% Build a solver with the default parameters
37import alpaqa as pa
38
39inner_solver = pa.PANOCSolver()
40solver = pa.ALMSolver(inner_solver)
41
42# %% Build a solver with custom parameters
43inner_solver = pa.PANOCSolver(
44 panoc_params={
45 'max_iter': 1000,
46 'stop_crit': pa.PANOCStopCrit.ApproxKKT,
47 'print_interval': 1,
48 },
49 lbfgs_params={
50 'memory': 10,
51 },
52)
53
54solver = pa.ALMSolver(
55 alm_params={
56 'tolerance': 1e-10,
57 'dual_tolerance': 1e-10,
58 'initial_penalty': 50,
59 'penalty_update_factor': 20,
60 'print_interval': 1,
61 },
62 inner_solver=inner_solver
63)
64
65# %% Compute a solution
66
67# Set initial guesses at arbitrary values
68x0 = [0.1, 1.8] # decision variables
69y0 = [0.0, 0.0] # Lagrange multipliers for g(x)
70
71# Solve the problem
72x_sol, y_sol, stats = solver(problem, x0, y0)
73
74# Print the results
75print(stats["status"])
76print(f"Solution: {x_sol}")
77print(f"Multipliers: {y_sol}")
78print(f"Cost: {problem.eval_f(x_sol):.5f}")