Examples

This page contains various examples demonstrating the capabilities of complex-expr-parser.

Basic Function Plotting

Create a simple magnitude plot of a complex function:

import numpy as np
import matplotlib.pyplot as plt
from complex_expr_parser import get_callable

# Create complex grid
x = np.linspace(-2, 2, 400)
y = np.linspace(-2, 2, 400)
X, Y = np.meshgrid(x, y)
Z = X + 1j * Y

# Evaluate function
f = get_callable("(z^2 - 1)/(z^2 + 1)")
W = f(Z)

# Plot magnitude
plt.figure(figsize=(8, 8))
plt.imshow(np.abs(W), extent=[-2, 2, -2, 2], origin='lower',
           cmap='viridis', vmax=3)
plt.colorbar(label='|f(z)|')
plt.xlabel('Re(z)')
plt.ylabel('Im(z)')
plt.title('|(z^2 - 1)/(z^2 + 1)|')
plt.show()

Domain Coloring

A complete domain coloring implementation:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb
from complex_expr_parser import get_callable

def domain_coloring(expr_str, xlim=(-2, 2), ylim=(-2, 2), resolution=500):
    """Create a domain coloring plot of a complex function."""
    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)

    # Hue from argument
    H = (np.angle(W) + np.pi) / (2 * np.pi)

    # Saturation constant
    S = np.ones_like(H) * 0.9

    # Value from magnitude with periodic shading
    r = np.log2(np.abs(W) + 1)
    V = 1 - 0.3 * (r - np.floor(r))

    # Handle singularities
    V = np.where(np.isnan(V) | np.isinf(V), 0, V)

    # Convert to RGB
    HSV = np.stack([H, S, V], axis=-1)
    RGB = hsv_to_rgb(HSV)

    plt.figure(figsize=(10, 10))
    plt.imshow(RGB, extent=[*xlim, *ylim], origin='lower')
    plt.xlabel('Re(z)')
    plt.ylabel('Im(z)')
    plt.title(f'Domain coloring: {expr_str}')
    plt.show()

# Examples
domain_coloring("z^3 - 1")
domain_coloring("sin(z)")
domain_coloring("gamma(z)")

Interactive Expression Evaluation

Build an interactive expression evaluator:

from complex_expr_parser import validate_expression, get_callable

def interactive_evaluator():
    """Simple interactive complex function evaluator."""
    print("Complex Function Evaluator")
    print("Enter 'quit' to exit")
    print("-" * 40)

    while True:
        expr_str = input("\nEnter function f(z): ").strip()
        if expr_str.lower() == 'quit':
            break

        # Validate first
        is_valid, error = validate_expression(expr_str)
        if not is_valid:
            print(f"Invalid expression: {error}")
            continue

        # Get callable
        f = get_callable(expr_str)

        while True:
            z_str = input("Enter z (or 'new' for new function): ").strip()
            if z_str.lower() == 'new':
                break

            try:
                z_val = complex(z_str.replace('i', 'j'))
                result = f(z_val)
                print(f"f({z_val}) = {result}")
            except ValueError:
                print("Invalid complex number. Use format: a+bj")

if __name__ == "__main__":
    interactive_evaluator()

Special Functions

Working with gamma and zeta functions:

import numpy as np
import matplotlib.pyplot as plt
from complex_expr_parser import get_callable

# Gamma function
f_gamma = get_callable("gamma(z)")

# Known values
print(f"gamma(5) = {f_gamma(5)} (should be 24)")
print(f"gamma(0.5) = {f_gamma(0.5)} (should be sqrt(pi) = {np.sqrt(np.pi)})")

# Plot |gamma(z)| in complex plane
x = np.linspace(-4, 4, 200)
y = np.linspace(-4, 4, 200)
X, Y = np.meshgrid(x, y)
Z = X + 1j * Y

W = f_gamma(Z)

plt.figure(figsize=(10, 8))
plt.imshow(np.log10(np.abs(W) + 1e-10), extent=[-4, 4, -4, 4],
           origin='lower', cmap='hot', vmin=-2, vmax=2)
plt.colorbar(label='log10(|Gamma(z)|)')
plt.title('Gamma Function in Complex Plane')
plt.xlabel('Re(z)')
plt.ylabel('Im(z)')
plt.show()

Combining with SymPy

Access the full power of sympy for symbolic manipulation:

from complex_expr_parser import parse_complex_function, ComplexFunctionParser, z
from sympy import simplify, expand, factor, diff, integrate, series

# Parse and manipulate
expr = parse_complex_function("(z^2 - 1)/(z - 1)")

# Simplify
print(f"Simplified: {simplify(expr)}")  # z + 1

# Expand
expr2 = parse_complex_function("(z + 1)^3")
print(f"Expanded: {expand(expr2)}")  # z**3 + 3*z**2 + 3*z + 1

# Factor
expr3 = parse_complex_function("z^3 - 1")
print(f"Factored: {factor(expr3)}")  # (z - 1)*(z**2 + z + 1)

# Differentiate
expr4 = parse_complex_function("sin(z)*exp(z)")
print(f"Derivative: {diff(expr4, z)}")

# Integrate
expr5 = parse_complex_function("z^2")
print(f"Integral: {integrate(expr5, z)}")  # z**3/3

# Series expansion
expr6 = parse_complex_function("sin(z)")
print(f"Taylor series: {series(expr6, z, 0, 6)}")

Batch Processing

Process multiple expressions efficiently:

from complex_expr_parser import validate_expression, get_callable
import numpy as np

expressions = [
    "z^2",
    "z^3 - 1",
    "sin(z)/z",
    "(z-1)/(z+1)",
    "exp(i*pi*z)",
    "gamma(z)",
]

test_point = 1 + 0.5j

print(f"Evaluating at z = {test_point}")
print("-" * 50)

for expr_str in expressions:
    is_valid, error = validate_expression(expr_str)
    if is_valid:
        f = get_callable(expr_str)
        result = f(test_point)
        print(f"{expr_str:20s} -> {result:.6f}")
    else:
        print(f"{expr_str:20s} -> ERROR: {error}")