casadi function that optimizes x^2 in python

main.py
import casadi as ca

# Define the symbolic variable
x = ca.SX.sym('x')

# Define the quadratic objective function
f = x**2

# Construct the optimization problem
opt_prob = {'f': f, 'x': x}

# Configure the IPOPT solver
opts = {'ipopt': {'print_level': 0}}

# Create the solver object
solver = ca.nlpsol('solver', 'ipopt', opt_prob, opts)

# Solve the optimization problem
sol = solver(x0=2)

# Extract the optimal solution
x_opt = sol['x']

print("Optimal solution:", x_opt)
475 chars
25 lines

In the above code, we first define a symbolic variable x using the sym method of casadi. We then define the objective function f as x**2, which is a basic quadratic function.

We then construct an optimization problem with f as the objective and x as the optimization variable using a dictionary.

We configure the IPOPT solver to solve the optimization problem, and create a solver object using the nlpsol method with the solver type (ipopt), optimization problem, and solver options as arguments.

Finally, we solve the optimization problem using the solver object with an initial guess of 2 for the optimization variable x. The optimal solution is then extracted from the solution dictionary returned by the solver and printed to the console.

gistlibby LogSnag