lower
Symbolic expression lowering to executable code.
This module provides the main entry point for converting symbolic expressions (AST nodes) into executable code for different backends (JAX, CVXPy, etc.). The lowering process translates the symbolic expression tree into functions that can be executed during optimization.
Architecture
The lowering process follows a visitor pattern where each backend implements
a lowerer class (e.g., JaxLowerer, CVXPyLowerer) with visitor methods for
each expression type. The lower() function dispatches expression nodes
to the appropriate backend.
Lowering Flow:
- Symbolic expressions are built during problem specification
- lower_symbolic_expressions() coordinates the full lowering process
- Backend-specific lowerers convert each expression node to executable code
- Automatic differentiation creates Jacobians for dynamics and constraints
- Result is a set of executable functions ready for numerical optimization
Backends
- JAX: For dynamics and non-convex constraints (with automatic differentiation)
- CVXPy: For convex constraints (with disciplined convex programming)
Example
Basic lowering to JAX::
import openscvx as ox
from openscvx.symbolic.lower import lower_to_jax
# Define symbolic expression
x = ox.State("x", shape=(3,))
u = ox.Control("u", shape=(2,))
expr = ox.Norm(x)**2 + 0.1 * ox.Norm(u)**2
# Lower to JAX function
f = lower_to_jax(expr)
# f is now a callable: f(x_val, u_val, node, params) -> scalar
Full problem lowering::
# After building symbolic problem...
lowered = lower_symbolic_problem(
dynamics_aug, states_aug, controls_aug,
constraints, parameters, N,
dynamics_prop, states_prop, controls_prop
)
# Access via LoweredProblem dataclass
dynamics = lowered.dynamics
jax_constraints = lowered.jax_constraints
# Now have executable JAX functions with Jacobians
create_cvxpy_variables(N: int, n_states: int, n_controls: int, S_x: np.ndarray, c_x: np.ndarray, S_u: np.ndarray, c_u: np.ndarray, n_nodal_constraints: int, n_cross_node_constraints: int, A_d_sparsity: Optional[tuple] = None, B_d_sparsity: Optional[tuple] = None, C_d_sparsity: Optional[tuple] = None, constraint_sparsity: Optional[list] = None) -> CVXPyVariables
¶
Create CVXPy variables and parameters for the optimal control problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N
|
int
|
Number of discretization nodes |
required |
n_states
|
int
|
Number of state variables |
required |
n_controls
|
int
|
Number of control variables |
required |
S_x
|
ndarray
|
State scaling matrix |
required |
c_x
|
ndarray
|
State offset vector |
required |
S_u
|
ndarray
|
Control scaling matrix |
required |
c_u
|
ndarray
|
Control offset vector |
required |
n_nodal_constraints
|
int
|
Number of non-convex nodal constraints (for linearization params) |
required |
n_cross_node_constraints
|
int
|
Number of non-convex cross-node constraints |
required |
A_d_sparsity
|
Optional[tuple]
|
Optional CVXPY sparsity indices for A_d parameter (from _tile_sparsity) |
None
|
B_d_sparsity
|
Optional[tuple]
|
Optional CVXPY sparsity indices for B_d parameter |
None
|
C_d_sparsity
|
Optional[tuple]
|
Optional CVXPY sparsity indices for C_d parameter |
None
|
constraint_sparsity
|
Optional[list]
|
Optional list of |
None
|
Returns:
| Type | Description |
|---|---|
CVXPyVariables
|
CVXPyVariables dataclass containing all CVXPy variables and parameters for the OCP |
Source code in openscvx/symbolic/lower.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
lower(expr: Expr, lowerer: Any) -> Any
¶
Dispatch an expression node to the appropriate lowerer backend.
This is the main entry point for lowering a single symbolic expression to
executable code. It delegates to the lowerer's lower() method, which
uses the visitor pattern to dispatch based on expression type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
Symbolic expression to lower (any Expr subclass) |
required |
lowerer
|
Any
|
Backend lowerer instance (e.g., JaxLowerer, CVXPyLowerer) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Backend-specific representation of the expression. For JaxLowerer, |
Any
|
returns a callable with signature (x, u, node, params) -> result. |
Any
|
For CVXPyLowerer, returns a CVXPy expression object. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the lowerer doesn't support the expression type |
Example
Lower an expression to the appropriate backend (here JAX):
from openscvx.symbolic.lowerers.jax import JaxLowerer
x = ox.State("x", shape=(3,))
expr = ox.Norm(x)
lowerer = JaxLowerer()
f = lower(expr, lowerer)
f is now callable: f(x_val, u_val, node, params) -> scalar
Source code in openscvx/symbolic/lower.py
lower_cvxpy_constraints(constraints: ConstraintSet, x_cvxpy: List, u_cvxpy: List, parameters: dict = None) -> Tuple[List, dict]
¶
Lower symbolic convex constraints to CVXPy constraints.
Converts symbolic convex constraint expressions to CVXPy constraint objects that can be used in the optimal control problem. This function handles both nodal constraints (applied at specific trajectory nodes) and cross-node constraints (relating multiple nodes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraints
|
ConstraintSet
|
ConstraintSet containing nodal_convex and cross_node_convex |
required |
x_cvxpy
|
List
|
List of CVXPy expressions for state at each node (length N). Typically the x_nonscaled list from create_cvxpy_variables(). |
required |
u_cvxpy
|
List
|
List of CVXPy expressions for controls at each node (length N). Typically the u_nonscaled list from create_cvxpy_variables(). |
required |
parameters
|
dict
|
Optional dict of parameter values to use for any Parameter expressions in the constraints. If None, uses Parameter default values. |
None
|
Returns:
| Type | Description |
|---|---|
List
|
Tuple of: |
dict
|
|
Tuple[List, dict]
|
|
Example
After creating CVXPy variables::
ocp_vars = create_cvxpy_variables(settings)
cvxpy_constraints, cvxpy_params = lower_cvxpy_constraints(
constraint_set,
ocp_vars.x_nonscaled,
ocp_vars.u_nonscaled,
parameters,
)
Note
This function only processes convex constraints (nodal_convex and cross_node_convex). Non-convex constraints are lowered to JAX in lower_symbolic_expressions() and handled via linearization in the SCP.
Source code in openscvx/symbolic/lower.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
lower_symbolic_problem(problem: SymbolicProblem, solver: ConvexSolver, byof: Optional[ByofSpec] = None) -> LoweredProblem
¶
Lower symbolic problem specification to executable JAX and CVXPy code.
This is the main orchestrator for converting a preprocessed SymbolicProblem into executable numerical code. It coordinates the lowering of dynamics, constraints, and state/control interfaces from symbolic AST representations to JAX functions (with automatic differentiation) and CVXPy constraints.
This is pure translation - no validation, shape checking, or augmentation occurs here. The input problem must be preprocessed (problem.is_preprocessed == True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
SymbolicProblem
|
Preprocessed SymbolicProblem from preprocess_symbolic_problem(). Must have is_preprocessed == True. |
required |
solver
|
ConvexSolver
|
ConvexSolver instance to create backend-specific variables.
The solver's |
required |
byof
|
Optional[ByofSpec]
|
Optional dict of raw JAX functions for expert users. Supported keys: - "dynamics": Dict of state name -> f(x, u, node, params) -> xdot_component - "dynamics_discrete": Dict of state name -> f(x, u, node, params) -> x_next_component - "nodal_constraints": List of f(x, u, node, params) -> residual - "cross_nodal_constraints": List of f(X, U, params) -> residual - "ctcs_constraints": List of dicts with "constraint_fn", "penalty", "bounds" |
None
|
Returns:
| Type | Description |
|---|---|
LoweredProblem
|
LoweredProblem dataclass containing lowered problem |
Example
After preprocessing::
solver = CVXPySolver()
problem = preprocess_symbolic_problem(...)
lowered = lower_symbolic_problem(problem, solver)
# Access dynamics
dx = lowered.dynamics.f(x_val, u_val, node=0, params={...})
# Solver now owns the CVXPy variables
ocp_vars = solver.ocp_vars
Raises:
| Type | Description |
|---|---|
AssertionError
|
If problem.is_preprocessed is False |
Source code in openscvx/symbolic/lower.py
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 | |
lower_to_jax(exprs: Union[Expr, Sequence[Expr]]) -> Union[callable, list[callable]]
¶
Lower symbolic expression(s) to JAX callable(s).
Convenience wrapper that creates a JaxLowerer and lowers one or more symbolic expressions to JAX functions. The resulting functions can be JIT-compiled and automatically differentiated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exprs
|
Union[Expr, Sequence[Expr]]
|
Single expression or sequence of expressions to lower |
required |
Returns:
| Type | Description |
|---|---|
Union[callable, list[callable]]
|
|
Union[callable, list[callable]]
|
|
Example
Single expression::
x = ox.State("x", shape=(3,))
expr = ox.Norm(x)**2
f = lower_to_jax(expr)
# f(x_val, u_val, node_idx, params_dict) -> scalar
Multiple expressions::
exprs = [ox.Norm(x), ox.Norm(u), x @ A @ x]
fns = lower_to_jax(exprs)
# fns is [f1, f2, f3], each with same signature
Note
All returned JAX functions have a uniform signature (x, u, node, params) regardless of whether they use all arguments. This standardization simplifies vectorization and differentiation.