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