Expression Usage¶
qxcore module provides the Expression class, which allows for parsing and evaluating symbolic mathematical expressions. It relies on sympy for parsing and numpy (by default) for evaluation, making it suitable for handling configuration parameters that depend on other variables.
import numpy as np
from qxcore import Expression
Basic Usage¶
You can initialize an Expression with a string representing the mathematical formula. The class automatically detects the symbols involved. Standard mathematical functions supported by sympy and numpy (like sin, cos, exp, sqrt) can be used in the expression string.
expr = Expression("cos(2 * pi * f * t + phi)")
expr
The symbols property returns the detected symbols in the expression.
print(f"Detected symbols: {expr.symbols}")
Evaluating Expressions¶
Use the resolve method to evaluate the expression. You must provide a dictionary mapping all symbol names to their values.
params = {
"f": 5.0,
"t": 0.0,
"phi": np.pi,
}
result = expr.resolve(params)
print(f"Result for {params}: {result}")
Vectorized Evaluation¶
Since the evaluation typically uses numpy as a backend, you can pass numpy arrays as parameters to perform vectorized calculations.
params = {
"f": 1.0,
"t": np.linspace(0, 1, 9),
"phi": 0.0,
}
result_vector = expr.resolve(params)
print(f"Input t: {params['t']}")
print(f"Result: {result_vector}")
Error Handling¶
If you fail to provide a value for a required symbol, resolve raises a ValueError.
try:
# Missing 'phi'
expr.resolve({"f": 1.0, "t": 0.0})
except ValueError as e:
print(f"Caught expected error: {e}")