A fault-tolerant parser for complex-valued mathematical functions with human-friendly notation support
Project description
complex-expr-parser
A fault-tolerant parser for complex-valued mathematical functions with human-friendly notation support.
Features
- Human-friendly syntax: Accepts natural mathematical notation
- Implicit multiplication:
2zbecomes2*z - Power notation:
z^2becomesz**2 - Absolute value:
|z|becomesAbs(z) - Conjugate shorthand:
z*becomesconjugate(z) - Unicode support:
pi,sqrt,oo(infinity) - Function aliases:
ln->log,arcsin->asin, etc. - Special functions: Gamma, Zeta, and more via mpmath
- Vectorized evaluation: Works with NumPy arrays for fast computation
Installation
pip install complex-expr-parser
With optional dependencies:
# For numpy array support (recommended)
pip install complex-expr-parser[numpy]
# For special functions (gamma, zeta)
pip install complex-expr-parser[mpmath]
# All optional dependencies
pip install complex-expr-parser[all]
Quick Start
from complex_expr_parser import parse_complex_function, get_callable, validate_expression
# Parse an expression to a sympy object
expr = parse_complex_function("z^2 + 2z + 1")
print(expr) # z**2 + 2*z + 1
# Get a callable function
f = get_callable("sin(z)/z")
print(f(1+1j)) # (0.6349639147847361+0.2988350886551747j)
# Validate user input
is_valid, error = validate_expression("z^2 + 1")
if is_valid:
print("Expression is valid!")
else:
print(f"Invalid: {error}")
Supported Notations
Basic Operations
from complex_expr_parser import get_callable
# Power notation
f = get_callable("z^2") # or z**2
f = get_callable("z^3 - 1")
# Implicit multiplication
f = get_callable("2z + 3") # 2*z + 3
f = get_callable("z(z+1)") # z*(z+1)
f = get_callable("(z+1)(z-1)") # (z+1)*(z-1)
# Rational functions
f = get_callable("(z-1)/(z+1)")
f = get_callable("1/z")
Trigonometric Functions
f = get_callable("sin(z)")
f = get_callable("cos(z)")
f = get_callable("tan(z)")
# Inverse trig (multiple notations)
f = get_callable("asin(z)")
f = get_callable("arcsin(z)") # alias
Hyperbolic Functions
f = get_callable("sinh(z)")
f = get_callable("cosh(z)")
f = get_callable("tanh(z)")
f = get_callable("asinh(z)")
Exponential and Logarithmic
f = get_callable("exp(z)")
f = get_callable("e^z") # equivalent to exp(z)
f = get_callable("log(z)") # natural log
f = get_callable("ln(z)") # alias for log
f = get_callable("sqrt(z)")
Complex-Specific Operations
# Absolute value
f = get_callable("|z|")
f = get_callable("Abs(z)")
# Conjugate
f = get_callable("z*") # z* notation
f = get_callable("conjugate(z)")
f = get_callable("conj(z)") # alias
# Real and imaginary parts
f = get_callable("re(z)")
f = get_callable("Re(z)") # alias
f = get_callable("real(z)") # alias
f = get_callable("im(z)")
f = get_callable("Im(z)") # alias
f = get_callable("imag(z)") # alias
# Argument (phase)
f = get_callable("arg(z)")
f = get_callable("phase(z)") # alias
f = get_callable("angle(z)") # alias
Constants
# Imaginary unit
f = get_callable("z + i")
f = get_callable("z + j") # j also works
# Euler's number
f = get_callable("e^(i*pi)")
# Pi
f = get_callable("exp(i*pi*z)")
# Unicode supported
f = get_callable("z + \u03c0") # pi symbol
Special Functions (requires mpmath)
# Gamma function
f = get_callable("gamma(z)")
# Riemann zeta function
f = get_callable("zeta(z)")
Using with NumPy Arrays
The parser generates vectorized functions that work efficiently with NumPy arrays:
import numpy as np
from complex_expr_parser import get_callable
# Create a complex grid
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = X + 1j * Y
# Evaluate function over the grid
f = get_callable("z^2 + 1")
result = f(Z) # Returns 100x100 complex array
Using the Parser Class Directly
For more control, use the ComplexFunctionParser class:
from complex_expr_parser import ComplexFunctionParser
parser = ComplexFunctionParser()
# Parse to sympy expression
expr = parser.parse("z^2 + 2z + 1")
print(expr) # z**2 + 2*z + 1
print(expr.expand()) # z**2 + 2*z + 1
print(expr.factor()) # (z + 1)**2
# Convert to callable
f = parser.to_callable(expr, use_numpy=True)
print(f(1+1j)) # (3+4j)
# Access the preprocessing step
preprocessed = parser.preprocess("2z^2 + |z|")
print(preprocessed) # 2*z**2 + Abs(z)
Input Validation
Use validate_expression to check user input before processing:
from complex_expr_parser import validate_expression
# Valid expression
is_valid, error = validate_expression("sin(z)/z")
assert is_valid and error is None
# Empty expression
is_valid, error = validate_expression("")
assert not is_valid
print(error) # "Expression cannot be empty"
# Invalid syntax
is_valid, error = validate_expression("z +* 1")
assert not is_valid
print(error) # Error details
Integration with Domain Coloring
This parser is ideal for domain coloring visualizations of complex functions:
import numpy as np
import matplotlib.pyplot as plt
from complex_expr_parser import get_callable
def domain_coloring(expr_str, xlim=(-2, 2), ylim=(-2, 2), resolution=500):
"""Simple domain coloring plot."""
f = get_callable(expr_str)
x = np.linspace(*xlim, resolution)
y = np.linspace(*ylim, resolution)
X, Y = np.meshgrid(x, y)
Z = X + 1j * Y
W = f(Z)
# Color by argument, brightness by magnitude
H = np.angle(W) / (2 * np.pi) + 0.5
S = np.ones_like(H)
V = 1 - 1 / (1 + np.abs(W)**0.3)
# Convert HSV to RGB (simplified)
# ... plotting code ...
return W
# Plot z^2 - 1
W = domain_coloring("z^2 - 1")
API Reference
Functions
parse_complex_function(expr_str)- Parse string to sympy expressionget_callable(expr_str, use_numpy=True)- Parse and return callable functionvalidate_expression(expr_str)- Validate expression, returns(bool, error_msg)
Classes
ComplexFunctionParser- Main parser class withparse()andto_callable()methods
Constants
z- The sympy Symbol for the complex variableKNOWN_FUNCTIONS- List of recognized function names
Development
# Clone the repository
git clone https://github.com/yourusername/complex-expr-parser
cd complex-expr-parser
# Install with dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run tests with coverage
pytest --cov=complex_expr_parser
License
MIT License - see LICENSE file for details.
Changelog
0.1.0
- Initial release
- ComplexFunctionParser class with fault-tolerant parsing
- Support for human-friendly notation
- NumPy vectorized evaluation
- Special function support via mpmath
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file complex_expr_parser-0.1.0.tar.gz.
File metadata
- Download URL: complex_expr_parser-0.1.0.tar.gz
- Upload date:
- Size: 11.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0022937e6ac071b19e7ec694e9b27973390e543d964d06b0a1c7620f8a35c3ed
|
|
| MD5 |
95c17f175d7bee31575a0dae86a1bcc1
|
|
| BLAKE2b-256 |
144c08f8c9a85b953a532f6505503eb4896a1534662c0e246a1fa08f8354b142
|
File details
Details for the file complex_expr_parser-0.1.0-py3-none-any.whl.
File metadata
- Download URL: complex_expr_parser-0.1.0-py3-none-any.whl
- Upload date:
- Size: 10.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e41914ef138285b7d520fcd9fe59e0abe86ae782916fd2bdc08287f32b7db683
|
|
| MD5 |
427257f153b2c68d6ff43e932d35f9ec
|
|
| BLAKE2b-256 |
be08defbc71ce93eae5551a429b9ed2a5efb57dd52f1df5769186d3c4de82e96
|