math
Mathematical functions for symbolic expressions.
This module provides common mathematical operations used in optimization problems, including trigonometric functions, exponential functions, and smooth approximations of non-differentiable operations. All functions are element-wise and preserve the shape of their inputs.
Function Categories
- Trigonometric:
Sin,Cos,Tan- Standard trigonometric functions - Exponential and Roots:
Exp,Log,Sqrt,Square- Exponential, logarithm, square root, and squaring operations - Absolute Value:
Abs- Element-wise absolute value function - Smooth Approximations:
PositivePart,Huber,SmoothReLU- Smooth, differentiable approximations of non-smooth functions like max(0, x) and absolute value - Reductions:
Max- Maximum over elements - Smooth Maximum:
LogSumExp- Log-sum-exp function, a smooth approximation to maximum
Example
Using trigonometric functions in dynamics::
import openscvx as ox
# Pendulum dynamics: theta_ddot = -g/L * sin(theta)
theta = ox.State("theta", shape=(1,))
theta_dot = ox.State("theta_dot", shape=(1,))
g, L = 9.81, 1.0
theta_ddot = -(g / L) * ox.Sin(theta)
Smooth penalty functions for constraints::
# Soft constraint using smooth ReLU
x = ox.Variable("x", shape=(3,))
penalty = ox.SmoothReLU(ox.Norm(x) - 1.0) # Penalize norm > 1
Abs
¶
Bases: Expr
Element-wise absolute value function for symbolic expressions.
Computes the absolute value (|x|) of each element in the operand. Preserves the shape of the input expression. The absolute value function is convex and DCP-compliant in CVXPy.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply absolute value to |
Example
Define an Abs expression:
x = Variable("x", shape=(3,))
abs_x = Abs(x) # Element-wise |x|
Source code in openscvx/symbolic/expr/math.py
Bilerp
¶
Bases: Expr
2D bilinear interpolation for symbolic expressions.
Performs bilinear interpolation on a regular 2D grid. Given grid points (xp, yp) and corresponding values fp, computes the bilinearly interpolated value at query point (x, y). For values outside the grid, boundary values are returned (clamping, no extrapolation).
This is useful for incorporating 2D tabulated data (e.g., engine thrust as a function of altitude and Mach number, aerodynamic coefficients as a function of angle of attack and sideslip) into trajectory optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Query x-coordinate (symbolic expression) |
|
y |
Query y-coordinate (symbolic expression) |
|
xp |
1D array of x grid coordinates (must be increasing), length N |
|
yp |
1D array of y grid coordinates (must be increasing), length M |
|
fp |
2D array of values with shape (N, M), where fp[i, j] is the value at grid point (xp[i], yp[j]) |
Example
Interpolate engine thrust from altitude and Mach number::
import openscvx as ox
import numpy as np
# Grid coordinates
alt_grid = np.array([0, 5000, 10000, 15000, 20000]) # meters
mach_grid = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
# Thrust values: thrust_table[i, j] = thrust at (alt_grid[i], mach_grid[j])
thrust_table = np.array([...]) # shape (5, 5)
altitude = ox.State("altitude", shape=(1,))
mach = ox.State("mach", shape=(1,))
thrust = ox.Bilerp(altitude[0], mach[0], alt_grid, mach_grid, thrust_table)
Note
- xp and yp must be strictly increasing
- fp must have shape (len(xp), len(yp))
- For query points outside the grid, boundary values are returned
- This node is only supported in JAX lowering (dynamics/cost), not CVXPy
Source code in openscvx/symbolic/expr/math.py
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 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 | |
__init__(x: Union[Expr, float, int, np.ndarray], y: Union[Expr, float, int, np.ndarray], xp: Union[Expr, float, int, np.ndarray], yp: Union[Expr, float, int, np.ndarray], fp: Union[Expr, float, int, np.ndarray])
¶
Initialize a 2D bilinear interpolation node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Expr, float, int, ndarray]
|
Query x-coordinate. Can be a scalar symbolic expression. |
required |
y
|
Union[Expr, float, int, ndarray]
|
Query y-coordinate. Can be a scalar symbolic expression. |
required |
xp
|
Union[Expr, float, int, ndarray]
|
1D array of x grid coordinates. Must be increasing. |
required |
yp
|
Union[Expr, float, int, ndarray]
|
1D array of y grid coordinates. Must be increasing. |
required |
fp
|
Union[Expr, float, int, ndarray]
|
2D array of values with shape (len(xp), len(yp)). |
required |
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Canonicalize by canonicalizing all operands.
Source code in openscvx/symbolic/expr/math.py
check_shape() -> Tuple[int, ...]
¶
Output shape is scalar (single interpolated value).
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[int, ...]
|
Empty tuple (scalar output) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If grid arrays have invalid shapes |
Source code in openscvx/symbolic/expr/math.py
Cos
¶
Bases: Expr
Element-wise cosine function for symbolic expressions.
Computes the cosine of each element in the operand. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply cosine function to |
Example
Define a Cos expression:
theta = Variable("theta", shape=(3,))
cos_theta = Cos(theta)
Source code in openscvx/symbolic/expr/math.py
Exp
¶
Bases: Expr
Element-wise exponential function for symbolic expressions.
Computes e^x for each element in the operand, where e is Euler's number. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply exponential function to |
Example
Define an Exp expression:
x = Variable("x", shape=(3,))
exp_x = Exp(x)
Source code in openscvx/symbolic/expr/math.py
Huber
¶
Bases: Expr
Huber penalty function for symbolic expressions.
The Huber penalty is a smooth approximation to the absolute value function that is quadratic for small values (|x| < delta) and linear for large values (|x| >= delta). This makes it more robust to outliers than squared penalties while maintaining smoothness.
The Huber function is defined as: - (x^2) / (2*delta) for |x| <= delta - |x| - delta/2 for |x| > delta
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Expression to apply Huber penalty to |
|
delta |
Threshold parameter controlling the transition point (default: 0.25) |
Example
Define a Huber penalty expression:
residual = y_measured - y_predicted
penalty = Huber(residual, delta=0.5)
Source code in openscvx/symbolic/expr/math.py
__init__(x: Union[Expr, float, int, np.ndarray], delta: float = 0.25)
¶
Initialize a Huber penalty operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Expr, float, int, ndarray]
|
Expression to apply Huber penalty to |
required |
delta
|
float
|
Threshold parameter for quadratic-to-linear transition (default: 0.25) |
0.25
|
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Linterp
¶
Bases: Expr
1D linear interpolation for symbolic expressions.
Computes the linear interpolant of data points (xp, fp) evaluated at x, equivalent to jax.numpy.interp(x, xp, fp). For values outside the data range, the boundary values are returned (no extrapolation).
This is useful for incorporating tabulated data (e.g., atmospheric properties, engine thrust curves, aerodynamic coefficients) into trajectory optimization dynamics and constraints.
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Query point(s) at which to evaluate the interpolant (symbolic expression) |
|
xp |
1D array of x-coordinates of data points (must be increasing) |
|
fp |
1D array of y-coordinates of data points (same length as xp) |
Example
Interpolate atmospheric density from altitude table::
import openscvx as ox
import numpy as np
# US 1976 Standard Atmosphere data
alt_data = np.array([0, 5000, 10000, 15000, 20000]) # meters
rho_data = np.array([1.225, 0.736, 0.414, 0.195, 0.089]) # kg/m^3
altitude = ox.State("altitude", shape=(1,))
rho = ox.Linterp(altitude[0], alt_data, rho_data)
# rho can now be used in dynamics expressions
drag = 0.5 * rho * v**2 * Cd * S
Note
- xp must be strictly increasing
- For query points outside [xp[0], xp[-1]], boundary values are returned
Source code in openscvx/symbolic/expr/math.py
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 | |
__init__(x: Union[Expr, float, int, np.ndarray], xp: Union[Expr, float, int, np.ndarray], fp: Union[Expr, float, int, np.ndarray])
¶
Initialize a 1D linear interpolation node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Expr, float, int, ndarray]
|
Query point(s) at which to evaluate the interpolant. Can be a scalar or array symbolic expression. |
required |
xp
|
Union[Expr, float, int, ndarray]
|
1D array of x-coordinates of data points. Must be increasing. Can be a numpy array or Constant expression. |
required |
fp
|
Union[Expr, float, int, ndarray]
|
1D array of y-coordinates of data points. Must have same length as xp. Can be a numpy array or Constant expression. |
required |
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Canonicalize by canonicalizing all operands.
check_shape() -> Tuple[int, ...]
¶
Output shape matches the query point shape.
The interpolation is element-wise over x, so the output has the same shape as the query points.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[int, ...]
|
Shape of the query point x |
Raises:
| Type | Description |
|---|---|
ValueError
|
If xp and fp have different lengths or are not 1D |
Source code in openscvx/symbolic/expr/math.py
Log
¶
Bases: Expr
Element-wise natural logarithm function for symbolic expressions.
Computes the natural logarithm (base e) of each element in the operand. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply logarithm to |
Example
Define a Log expression:
x = Variable("x", shape=(3,))
log_x = Log(x)
Source code in openscvx/symbolic/expr/math.py
LogSumExp
¶
Bases: Expr
Log-sum-exp function for symbolic expressions.
Computes the log-sum-exp (LSE) of multiple operands, which is a smooth, differentiable approximation to the maximum function. The log-sum-exp is defined as:
logsumexp(x₁, x₂, ..., xₙ) = log(exp(x₁) + exp(x₂) + ... + exp(xₙ))
This function is numerically stable and is commonly used in optimization as a smooth alternative to the non-differentiable maximum function. It satisfies the inequality:
max(x₁, x₂, ..., xₙ) ≤ logsumexp(x₁, x₂, ..., xₙ) ≤ max(x₁, x₂, ..., xₙ) + log(n)
The log-sum-exp is convex and is particularly useful for: - Smooth approximations of maximum constraints - Soft maximum operations in neural networks - Relaxing logical OR operations in STL specifications
Attributes:
| Name | Type | Description |
|---|---|---|
operands |
List of expressions to compute log-sum-exp over |
Example
Define a LogSumExp expression:
x = Variable("x", shape=(3,))
y = Variable("y", shape=(3,))
z = Variable("z", shape=(3,))
lse = LogSumExp(x, y, z) # Smooth approximation to max(x, y, z)
Use in STL relaxation:
import openscvx as ox
# Relax: Or(φ₁, φ₂) using log-sum-exp
phi1 = ox.Norm(x - goal1) - 0.5
phi2 = ox.Norm(x - goal2) - 0.5
relaxed_or = LogSumExp(phi1, phi2) >= 0
Source code in openscvx/symbolic/expr/math.py
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
__init__(*args: Union[Expr, float, int, np.ndarray])
¶
Initialize a log-sum-exp operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Union[Expr, float, int, ndarray]
|
Two or more expressions to compute log-sum-exp over |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than two operands are provided |
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Canonicalize log-sum-exp: flatten nested LogSumExp, fold constants.
Source code in openscvx/symbolic/expr/math.py
check_shape() -> Tuple[int, ...]
¶
LogSumExp broadcasts shapes like NumPy, preserving element-wise shape.
Source code in openscvx/symbolic/expr/math.py
Max
¶
Bases: Expr
Element-wise maximum function for symbolic expressions.
Computes the element-wise maximum across two or more operands. Supports broadcasting following NumPy rules. During canonicalization, nested Max operations are flattened and constants are folded.
Attributes:
| Name | Type | Description |
|---|---|---|
operands |
List of expressions to compute maximum over |
Example
Define a Max expression:
x = Variable("x", shape=(3,))
y = Variable("y", shape=(3,))
max_xy = Max(x, y, 0) # Element-wise max(x, y, 0)
Source code in openscvx/symbolic/expr/math.py
__init__(*args: Union[Expr, float, int, np.ndarray])
¶
Initialize a maximum operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Union[Expr, float, int, ndarray]
|
Two or more expressions to compute maximum over |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than two operands are provided |
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Canonicalize max: flatten nested Max, fold constants.
Source code in openscvx/symbolic/expr/math.py
check_shape() -> Tuple[int, ...]
¶
Max broadcasts shapes like NumPy.
Source code in openscvx/symbolic/expr/math.py
PositivePart
¶
Bases: Expr
Positive part function for symbolic expressions.
Computes max(x, 0) element-wise, effectively zeroing out negative values while preserving positive values. This is also known as the ReLU (Rectified Linear Unit) function and is commonly used as a penalty function building block in optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Expression to apply positive part function to |
Example
Define a PositivePart expression:
constraint_violation = x - 10
penalty = PositivePart(constraint_violation) # Penalizes x > 10
Source code in openscvx/symbolic/expr/math.py
Sin
¶
Bases: Expr
Element-wise sine function for symbolic expressions.
Computes the sine of each element in the operand. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply sine function to |
Example
Define a Sin expression:
theta = Variable("theta", shape=(3,))
sin_theta = Sin(theta)
Source code in openscvx/symbolic/expr/math.py
SmoothReLU
¶
Bases: Expr
Smooth approximation to the ReLU (positive part) function.
Computes a smooth, differentiable approximation to max(x, 0) using the formula: sqrt(max(x, 0)^2 + c^2) - c
The parameter c controls the smoothness: smaller values give a sharper transition, while larger values produce a smoother approximation. As c approaches 0, this converges to the standard ReLU function.
This is particularly useful in optimization contexts where smooth gradients are required, such as in penalty methods for constraint handling (CTCS).
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Expression to apply smooth ReLU to |
|
c |
Smoothing parameter (default: 1e-8) |
Example
Define a smooth ReLU expression:
constraint_violation = x - 10
penalty = SmoothReLU(constraint_violation, c=1e-6)
Source code in openscvx/symbolic/expr/math.py
__init__(x: Union[Expr, float, int, np.ndarray], c: float = 1e-08)
¶
Initialize a smooth ReLU operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Expr, float, int, ndarray]
|
Expression to apply smooth ReLU to |
required |
c
|
float
|
Smoothing parameter controlling transition sharpness (default: 1e-8) |
1e-08
|
Source code in openscvx/symbolic/expr/math.py
canonicalize() -> Expr
¶
Sqrt
¶
Bases: Expr
Element-wise square root function for symbolic expressions.
Computes the square root of each element in the operand. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply square root to |
Example
Define a Sqrt expression:
x = Variable("x", shape=(3,))
sqrt_x = Sqrt(x)
Source code in openscvx/symbolic/expr/math.py
Square
¶
Bases: Expr
Element-wise square function for symbolic expressions.
Computes the square (x^2) of each element in the operand. Preserves the shape of the input expression. This is more efficient than using Power(x, 2) for some optimization backends.
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Expression to square |
Example
Define a Square expression:
v = Variable("v", shape=(3,))
v_squared = Square(v) # Equivalent to v ** 2
Source code in openscvx/symbolic/expr/math.py
Tan
¶
Bases: Expr
Element-wise tangent function for symbolic expressions.
Computes the tangent of each element in the operand. Preserves the shape of the input expression.
Attributes:
| Name | Type | Description |
|---|---|---|
operand |
Expression to apply tangent function to |
Example
Define a Tan expression:
theta = Variable("theta", shape=(3,))
tan_theta = Tan(theta)
Note
Tan is only supported for JAX lowering. CVXPy lowering will raise NotImplementedError since tangent is not DCP-compliant.