SKILL.md
CasADi + IPOPT for Nonlinear Programming
CasADi is a symbolic framework for nonlinear optimization. IPOPT is an interior-point solver for large-scale NLP.
Quick start (Linux)
apt-get update -qq && apt-get install -y -qq libgfortran5
pip install numpy==1.26.4 casadi==3.6.7
Building an NLP
1. Decision variables
import casadi as ca
n_bus, n_gen = 100, 20
Vm = ca.MX.sym("Vm", n_bus) # Voltage magnitudes
Va = ca.MX.sym("Va", n_bus) # Voltage angles (radians)
Pg = ca.MX.sym("Pg", n_gen) # Real power
Qg = ca.MX.sym("Qg", n_gen) # Reactive power
# Stack into single vector for solver
x = ca.vertcat(Vm, Va, Pg, Qg)
2. Objective function
Build symbolic expression:
# Quadratic cost: sum of c2*P^2 + c1*P + c0
obj = ca.MX(0)
for k in range(n_gen):
obj += c2[k] * Pg[k]**2 + c1[k] * Pg[k] + c0[k]
3. Constraints
Collect constraints in lists with bounds:
g_expr = [] # Constraint expressions
lbg = [] # Lower bounds
ubg = [] # Upper bounds
# Equality constraint: g(x) = 0
g_expr.append(some_expression)
lbg.append(0.0)
ubg.append(0.0)
# Inequality constraint: g(x) <= limit
g_expr.append(another_expression)
lbg.append(-ca.inf)
ubg.append(limit)
# Two-sided: lo <= g(x) <= hi
g_expr.append(bounded_expression)
lbg.append(lo)
ubg.append(hi)
g = ca.vertcat(*g_expr)
4. Variable bounds
# Stack bounds matching variable order
lbx = np.concatenate([Vm_min, Va_min, Pg_min, Qg_min]).tolist()
ubx = np.concatenate([Vm_max, Va_max, Pg_max, Qg_max]).tolist()
5. Create and call solver
nlp = {"x": x, "f": obj, "g": g}
opts = {
"ipopt.print_level": 0,
"ipopt.max_iter": 2000,
"ipopt.tol": 1e-7,
"ipopt.acceptable_tol": 1e-5,
"ipopt.mu_strategy": "adaptive",
"print_time": False,
}
solver = ca.nlpsol("solver", "ipopt", nlp, opts)
sol = solver(x0=x0, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg)
x_opt = np.array(sol["x"]).flatten()
obj_val = float(sol["f"])
