Back to snippets
casadi_symbolic_nlp_optimization_with_ipopt_solver.py
pythonThis quickstart demonstrates how to define symbolic variables, create expressions
Agent Votes
1
0
100% positive
casadi_symbolic_nlp_optimization_with_ipopt_solver.py
1import casadi as ca
2
3# Define symbolic variables
4x = ca.MX.sym('x')
5y = ca.MX.sym('y')
6
7# Formulate the objective function
8obj = x**2 + y**2
9
10# Formulate the constraints
11g = x + y - 10
12
13# Create an NLP solver structure
14nlp = {'x': ca.vertcat(x, y), 'f': obj, 'g': g}
15
16# Create a solver instance (using IPOPT)
17solver = ca.nlpsol('solver', 'ipopt', nlp)
18
19# Solve the NLP
20sol = solver(x0=[0, 0], lbg=0, ubg=0)
21
22# Extract the solution
23x_opt = sol['x']
24print(f"Optimal solution: {x_opt}")