CasADi

3.7.2 · active · verified Sat Apr 11

CasADi is an open-source symbolic framework for numerical optimization and automatic differentiation. It enables users to formulate complex optimization problems (e.g., optimal control, nonlinear programming) using symbolic expressions and then efficiently solve them using state-of-the-art numerical solvers. It is actively maintained with several releases per year. Current version: 3.7.2.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple nonlinear programming problem (NLP) using CasADi's symbolic `MX` variables, formulate it, and solve it using the IPOPT optimizer. It includes defining an objective function and a constraint.

import casadi as ca
import numpy as np

# Declare symbolic variables
x = ca.MX.sym("x")
y = ca.MX.sym("y")

# Define objective function (e.g., Rosenbrock function)
f = (x - 1)**2 + 10*(y - x**2)**2

# Define constraints (e.g., x + y >= 0)
g = x + y

# Formulate NLP problem
nlp = {'x': ca.vertcat(x,y), 'f': f, 'g': g}

# Choose a solver (IPOPT is common, ensure it's available)
solver_opts = {'ipopt': {'print_level': 0}, 'print_time': 0}
solver = ca.nlpsol('solver', 'ipopt', nlp, solver_opts)

# Solve the NLP
# Set lower/upper bounds for variables (lbx, ubx) and constraints (lbg, ubg)
sol = solver(
    lbx=[-ca.inf, -ca.inf], ubx=[ca.inf, ca.inf],
    lbg=[0], ubg=[ca.inf] # g >= 0
)

print(f"Optimal solution x: {sol['x'].full().flatten()}")
print(f"Optimal objective f: {sol['f'].full().item()}")

view raw JSON →