Skip to content

Commit 30b08d4

Browse files
committed
add changes to the jacobian computation
1 parent 0962e16 commit 30b08d4

6 files changed

Lines changed: 43 additions & 24 deletions

File tree

cvxpy/reductions/solvers/nlp_solvers/ipopt_nlpif.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -214,27 +214,31 @@ def constraints(self, x):
214214
def jacobian(self, x):
215215
"""Returns the Jacobian of the constraints with respect to x."""
216216
# Convert to torch tensor with gradient tracking
217-
offset = 0
218-
torch_vars_dict = {}
219-
torch_exprs = []
220-
221-
for var in self.main_var:
222-
size = var.size
223-
slice = x[offset:offset+size].reshape(var.shape, order='F')
224-
torch_tensor = torch.from_numpy(slice.astype(np.float64)).requires_grad_(True)
225-
torch_vars_dict[var.id] = torch_tensor # Map CVXPY variable ID to torch tensor
226-
torch_exprs.append(torch_tensor)
227-
offset += size
228-
217+
x = torch.from_numpy(x.astype(np.float64)).requires_grad_(True)
218+
229219
# Define a function that computes all constraint values
230-
def constraint_function(*args):
220+
def constraint_function(x):
221+
from cvxtorch.utils.torch_utils import tensor_reshape_fortran
222+
offset = 0
223+
torch_vars_dict = {}
224+
torch_exprs = []
225+
for var in self.main_var:
226+
size = var.size
227+
slice = x[offset:offset+size].reshape(var.shape)
228+
#slice = x[offset:offset+size].reshape(var.shape, order='F')
229+
torch_vars_dict[var.id] = slice # Map CVXPY variable ID to torch tensor
230+
torch_exprs.append(slice)
231+
offset += size
232+
231233
# Create mapping from torch tensors back to CVXPY variables
232234
torch_to_var = {}
233235
for i, var in enumerate(self.main_var):
234-
torch_to_var[var.id] = args[i]
236+
torch_to_var[var.id] = torch_exprs[i]
235237

236238
constraint_values = []
237239
for constraint in self.problem.constraints:
240+
# all constraints have a single argument
241+
# because they are "normalized" in the reduction
238242
constraint_expr = constraint.args[0]
239243
constraint_vars = constraint_expr.variables()
240244

@@ -255,8 +259,7 @@ def constraint_function(*args):
255259

256260
# Compute Jacobian using torch.autograd.functional.jacobian
257261
if len(self.problem.constraints) > 0:
258-
jacobian_tuple = torch.autograd.functional.jacobian(constraint_function,
259-
tuple(torch_exprs))
262+
jacobian_tuple = torch.autograd.functional.jacobian(constraint_function, x)
260263
# Handle the case where jacobian_tuple is a tuple (multiple variables)
261264
if isinstance(jacobian_tuple, tuple):
262265
# Concatenate along the last dimension (variable dimension)

cvxpy/sandbox/control_of_car.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import cvxpy as cp
55

66

7-
def solve_car_control(x_final, L=0.1, N=25, h=0.1, gamma=10):
7+
def solve_car_control(x_final, L=0.1, N=2, h=0.1, gamma=10):
88
"""
99
Solve the nonlinear optimal control problem for car trajectory planning.
1010

cvxpy/sandbox/control_of_car_matrix.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import matplotlib.pyplot as plt
44

55

6-
def solve_car_control(x_final, L=0.1, N=10, h=0.1, gamma=10):
6+
def solve_car_control(x_final, L=0.1, N=2, h=0.1, gamma=10):
77
"""
88
Solve the nonlinear optimal control problem for car trajectory planning.
99
@@ -73,7 +73,7 @@ def solve_car_control(x_final, L=0.1, N=10, h=0.1, gamma=10):
7373

7474
# Solve using an appropriate solver
7575
# For nonlinear problems, we might need special solver options
76-
problem.solve(solver=cp.SCS, verbose=True)
76+
problem.solve(solver=cp.IPOPT, nlp=True, verbose=True)
7777

7878
# Extract solution
7979
x_opt = x.value
@@ -165,7 +165,7 @@ def plot_trajectory(x_opt, u_opt, L, h, title="Car Trajectory"):
165165

166166
except Exception as e:
167167
print(f"Error: {e}")
168-
168+
"""
169169
# Additional analysis: plot control inputs
170170
if x_opt is not None and u_opt is not None:
171171
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))
@@ -184,3 +184,4 @@ def plot_trajectory(x_opt, u_opt, L, h, title="Car Trajectory"):
184184
185185
plt.tight_layout()
186186
plt.show()
187+
"""

cvxpy/sandbox/direct_ipopt_call.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import cvxpy as cp
22

33
# Define variables
4-
x = cp.Variable(1)
5-
y = cp.Variable(1)
4+
x = cp.Variable(3)
5+
y = cp.Variable(3)
66

7-
objective = cp.Maximize(cp.maximum(x, y))
7+
objective = cp.Maximize(cp.sum(cp.maximum(x, y)))
88

9-
constraints = [x - 14 == 0, y - 6 == 0]
9+
constraints = [x <= 14, y <= 6]
1010

1111
problem = cp.Problem(objective, constraints)
1212
print(cp.installed_solvers())

cvxpy/sandbox/entr_max.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import cvxpy as cp
2+
import numpy as np
3+
4+
k = 5
5+
x = cp.Variable((k, k))
6+
x.value = np.ones((k, k)) / k**2
7+
left = np.ones(k) / k
8+
right = np.exp(-np.linspace(-1, 1, k)**2)
9+
right = right / np.sum(right)
10+
obj = cp.entr(x).sum()
11+
constr = [cp.sum(x, axis=1) == right,
12+
cp.sum(x, axis=0) == left]
13+
problem = cp.Problem(cp.Maximize(obj), constr)
14+
problem.solve(solver=cp.IPOPT, nlp=True)
15+
assert problem.status == cp.OPTIMAL

cvxpy/sandbox/train_MLP/trainMLP.py

Whitespace-only changes.

0 commit comments

Comments
 (0)