JACOBIAN
Overview
The JACOBIAN function calculates the Jacobian matrix of one or more mathematical expressions with respect to specified variables. The Jacobian matrix is a fundamental concept in multivariable calculus that represents all first-order partial derivatives of a vector-valued function, providing essential information about how the function changes locally.
For a vector-valued function \mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m with components f_1, f_2, \ldots, f_m, the Jacobian matrix \mathbf{J} is defined as:
\mathbf{J} = \begin{bmatrix}
\frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_n} \\
\vdots & \ddots & \vdots \\
\frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_n}
\end{bmatrix}
The Jacobian is also the key object behind local linearization. For a small perturbation \Delta\mathbf{x} around a point \mathbf{x}, the change in the output is approximated by:
\mathbf{f}(\mathbf{x}+\Delta\mathbf{x}) \approx \mathbf{f}(\mathbf{x}) + \mathbf{J}(\mathbf{x})\,\Delta\mathbf{x}
This linear approximation is the basis for many numerical methods, including the Newton-Raphson method for solving systems of nonlinear equations. In that context, the Jacobian tells us how to adjust the input variables to move closer to a root of the function.
This implementation uses CasADi, an open-source software framework for numerical optimization and algorithmic differentiation. CasADi’s symbolic framework allows expressions to be constructed using its SX symbolics, enabling efficient computation of derivatives through automatic differentiation rather than numerical approximation. This ensures high precision and avoids the pitfalls of finite-difference methods, such as truncation and round-off errors. For more details, see the CasADi documentation.
The function parses mathematical expressions as strings, converts Excel-style exponentiation (^) to Python syntax (**), and evaluates the Jacobian at a specified point. It supports common mathematical functions including trigonometric functions (sin, cos, tan), exponentials (exp), logarithms (log), square roots (sqrt), and their inverses.
Jacobian matrices have widespread applications in optimization, robotics (for mapping joint velocities to end-effector velocities), control systems (for linearizing nonlinear plants), and machine learning (for backpropagation in neural networks). They are essential for gradient-based optimization algorithms, coordinate transformations, sensitivity analysis, and linearization of nonlinear systems.
This example function is provided as-is without any representation of accuracy.
Excel Usage
=JACOBIAN(expressions, var_values)
expressions(list[list], required): One or more mathematical expressions (as strings) for which to compute the Jacobian. Can be a single expression or a 2D list of expressions.var_values(list[list], required): A 2D list with two rows - the first row contains variable names (strings), and the second row contains their corresponding numeric values at which to evaluate the Jacobian.
Returns (list[list]): The Jacobian matrix as a 2D list of floats. str: Error message if calculation fails.
Examples
Example 1: Demo case 1
Inputs:
| expressions | var_values | |
|---|---|---|
| x^2 * y | x | y |
| 2 | 3 |
Excel formula:
=JACOBIAN("x^2 * y", {"x","y";2,3})
Expected output:
| Result | |
|---|---|
| 12 | 4 |
Example 2: Demo case 2
Inputs:
| expressions | var_values | |
|---|---|---|
| sin(x) + y^3 | x | y |
| 1 | 2 |
Excel formula:
=JACOBIAN("sin(x) + y^3", {"x","y";1,2})
Expected output:
| Result | |
|---|---|
| 0.5403 | 12 |
Example 3: Demo case 3
Inputs:
| expressions | var_values | |
|---|---|---|
| x^2 * y | x | y |
| sin(x) + y^3 | 2 | 3 |
Excel formula:
=JACOBIAN({"x^2 * y";"sin(x) + y^3"}, {"x","y";2,3})
Expected output:
| Result | |
|---|---|
| 12 | 4 |
| -0.4161 | 27 |
Example 4: Demo case 4
Inputs:
| expressions | var_values | |
|---|---|---|
| x^2 * y | x | y |
| sin(x) + y^3 | 1.5 | 1 |
Excel formula:
=JACOBIAN({"x^2 * y";"sin(x) + y^3"}, {"x","y";1.5,1})
Expected output:
| Result | |
|---|---|
| 3 | 2.25 |
| 0.0707 | 3 |
Python Code
import re
import casadi as ca
def jacobian(expressions, var_values):
"""
Calculate the Jacobian matrix of mathematical expressions with respect to specified variables.
See: https://web.casadi.org/docs/
This example function is provided as-is without any representation of accuracy.
Args:
expressions (list[list]): One or more mathematical expressions (as strings) for which to compute the Jacobian. Can be a single expression or a 2D list of expressions.
var_values (list[list]): A 2D list with two rows - the first row contains variable names (strings), and the second row contains their corresponding numeric values at which to evaluate the Jacobian.
Returns:
list[list]: The Jacobian matrix as a 2D list of floats. str: Error message if calculation fails.
"""
def to2d(x):
"""Normalize input to ensure it's a 2D list."""
return [[x]] if not isinstance(x, list) else x
# Normalize expressions input
if isinstance(expressions, str):
expr_list = [expressions]
elif isinstance(expressions, list):
normalized_exprs = to2d(expressions)
expr_list = [item for sublist in normalized_exprs for item in (sublist if isinstance(sublist, list) else [sublist]) if isinstance(item, str)]
else:
return "Error: expressions must be a string or a 2D list of strings."
if not expr_list:
return "Error: Expression list is empty or contains non-string elements."
if not isinstance(var_values, list) or len(var_values) != 2:
return "Error: var_values should be a list of two lists: [[variable_names], [values]]"
var_names = var_values[0]
var_point_values = var_values[1]
if not isinstance(var_names, list) or not isinstance(var_point_values, list):
return "Error: var_values must be [[variable_names], [values]]."
if len(var_names) == 0:
return "Error: At least one variable name is required."
if len(var_names) != len(var_point_values):
return "Error: Mismatch between number of variable names and number of values."
if not all(isinstance(name, str) and name.strip() for name in var_names):
return "Error: Variable names must be non-empty strings."
try:
var_vals = [float(v) for v in var_point_values]
except (TypeError, ValueError):
return "Error: Variable values must be numeric."
sym_vars = [ca.SX.sym(name) for name in var_names]
casadi_exprs = []
# Create evaluation context with symbolic variables and supported functions
evaluation_context = {name: sym_vars[idx] for idx, name in enumerate(var_names)}
evaluation_context.update({
"ca": ca,
"sin": ca.sin,
"cos": ca.cos,
"tan": ca.tan,
"exp": ca.exp,
"log": ca.log,
"sqrt": ca.sqrt,
"atan": ca.atan,
"asin": ca.asin,
"acos": ca.acos,
"sinh": ca.sinh,
"cosh": ca.cosh,
"tanh": ca.tanh,
"fabs": ca.fabs,
"floor": ca.floor,
"ceil": ca.ceil
})
for expr in expr_list:
try:
# Convert Excel exponentiation (^) to Python exponentiation (**)
converted_expr = re.sub(r'\^', '**', expr)
expr_obj = eval(converted_expr, {"__builtins__": {}, **evaluation_context})
casadi_exprs.append(expr_obj)
except Exception as e:
return f"Error: Invalid expression '{expr}': {str(e)}"
if not casadi_exprs:
return "Error: Failed to parse any expressions."
try:
casadi_expr_vector = ca.vertcat(*casadi_exprs)
J = ca.jacobian(casadi_expr_vector, ca.vertcat(*sym_vars))
jacobian_func = ca.Function('jacobian_func', sym_vars, [J])
result = jacobian_func(*var_vals)
if isinstance(result, ca.DM):
return result.full().tolist()
else:
return "Error during CasADi calculation: Unexpected result type."
except Exception as e:
return f"Error: Error computing Jacobian: {str(e)}"