A minimal, versatile Python library for calculating partial derivatives of mathematical expressions using numerical differentiation methods. Built as part of quantum photonics studies to understand mathematical foundations of wave functions and field equations.
Author: Rithul Kamesh [email protected]
License: MIT License
Academic Context: Developed during quantum photonics coursework to explore mathematical tools for analyzing electromagnetic field derivatives and wave function gradients.
While studying quantum photonics, I frequently encountered complex mathematical expressions involving partial derivatives of electromagnetic fields, wave functions, and optical potentials. Existing tools were either too heavyweight (requiring large dependencies) or too specialized. This library provides a lightweight, educational tool for:
- Electromagnetic Field Analysis: Computing field gradients and divergences
- Wave Function Studies: Analyzing quantum state derivatives
- Optical System Modeling: Understanding how optical parameters change
- Mathematical Learning: Hands-on exploration of numerical differentiation
- 🚀 Zero Dependencies: Pure Python standard library
- 🧠 Smart Variable Detection: Automatically identifies variables in expressions
- 📐 Multiple Methods: Forward, backward, and central difference approximations
- 🎯 Comprehensive Calculations: Partial derivatives, gradients, and Hessian matrices
- 🔧 Flexible Input: String expressions or callable functions
- 💻 Interactive CLI: Command-line interface for experimentation
- 📚 Educational Focus: Clear documentation and examples for learning
- ⚡ High Precision: Optimized numerical methods for accuracy
git clone https://github.com/yourusername/pde-calc.git
cd pde-calc
pip install -e .
from partial_derivatives import Expression, PartialDerivativeCalculator
# Example: Electromagnetic field potential V(x,y) = x²y + sin(xy)
expr = Expression("x**2 * y + sin(x * y)")
calc = PartialDerivativeCalculator()
# Calculate electric field components: E = -∇V
point = {'x': 1.0, 'y': 0.5}
Ex = -calc.partial_derivative(expr, 'x')(**point) # -∂V/∂x
Ey = -calc.partial_derivative(expr, 'y')(**point) # -∂V/∂y
print(f"Electric field: E = ({Ex:.4f}, {Ey:.4f})")
# Run examples
python main.py --demo
# Interactive calculator
python main.py
# Gaussian wave packet: ψ(x,t) = exp(-(x-vt)²/σ²) * exp(ikx)
# Simplified to spatial part for demonstration
psi = Expression("exp(-x**2 / 2)")
calc = PartialDerivativeCalculator()
# Probability current density involves ∂ψ/∂x
dpsi_dx = calc.partial_derivative(psi, 'x')
result = dpsi_dx(x=1.0)
print(f"∂ψ/∂x at x=1: {result:.6f}")
# Electric field potential in 2D
V = Expression("x**2 + y**2 + x*y") # Simple quadratic potential
calc = PartialDerivativeCalculator()
# Electric field E = -∇V
grad_V = calc.gradient(V)
E_field = [-component for component in grad_V(x=2, y=1)]
print(f"Electric field: {E_field}")
# Gaussian beam intensity: I(x,y) = I₀ * exp(-2(x²+y²)/w²)
I = Expression("exp(-2 * (x**2 + y**2))")
calc = PartialDerivativeCalculator()
# Beam divergence analysis
hessian = calc.hessian(I)
curvature = hessian(x=0, y=0)
print(f"Beam curvature at center: {curvature}")
Category | Functions | Example Usage |
---|---|---|
Basic | + , - , * , / , ** |
x**2 + y*z |
Trigonometric | sin , cos , tan |
sin(x)*cos(y) |
Exponential | exp , log |
exp(-x**2) |
Other | sqrt , abs |
sqrt(x**2 + y**2) |
Constants | pi , e |
sin(pi*x) |
Expression(expression, variables=None)
Create a mathematical expression for differentiation.
Parameters:
expression
: String formula or callable functionvariables
: Variable names (auto-detected for strings)
Methods:
evaluate(**kwargs)
: Compute expression value at given point
PartialDerivativeCalculator(h=1e-8)
Key Methods:
Calculate ∂f/∂variable using finite differences.
Calculate ∇f (vector of all partial derivatives).
Calculate ∇²f (matrix of second partial derivatives).
# Potential energy: V(x) = ½kx²
V = Expression("0.5 * x**2")
calc = PartialDerivativeCalculator()
# Force: F = -dV/dx
F = calc.partial_derivative(V, 'x')
force_at_x1 = -F(x=1.0)
print(f"Force at x=1: {force_at_x1}") # Should be -1.0
# Potential: φ(x,y) = xy + x² - y²
phi = Expression("x*y + x**2 - y**2")
calc = PartialDerivativeCalculator()
# Electric field components
Ex = calc.partial_derivative(phi, 'x')
Ey = calc.partial_derivative(phi, 'y')
point = {'x': 1, 'y': 2}
print(f"E-field: ({-Ex(**point):.2f}, {-Ey(**point):.2f})")
# Gaussian beam: I(r) = I₀ exp(-2r²/w²)
I = Expression("exp(-2 * (x**2 + y**2))")
calc = PartialDerivativeCalculator()
# Intensity gradient (for beam steering analysis)
grad_I = calc.gradient(I)
gradient_at_edge = grad_I(x=1, y=0)
print(f"Intensity gradient: {gradient_at_edge}")
The library implements three finite difference schemes:
Method | Formula | Accuracy | Use Case |
---|---|---|---|
Forward | (f(x+h) - f(x))/h |
O(h) | Boundary conditions |
Backward | (f(x) - f(x-h))/h |
O(h) | Boundary conditions |
Central | (f(x+h) - f(x-h))/(2h) |
O(h²) | Interior points (default) |
Step Size Optimization:
- First derivatives:
h = 1e-8
(optimal for double precision) - Second derivatives:
h = 1e-5
(larger to avoid numerical noise)
# Run all tests
python -m pytest tests/ -v
# Run specific test categories
python -m pytest tests/test_basic.py -v # Basic functionality
python -m pytest tests/test_physics.py -v # Physics applications
python -m pytest tests/test_numerical.py -v # Numerical accuracy
# Run with coverage
python -m pytest tests/ --cov=partial_derivatives --cov-report=html
- Accuracy vs Speed: Central differences are most accurate but require 2× evaluations
- Step Size: Automatically optimized for single/double precision
- Memory: O(1) for derivatives, O(n²) for Hessian matrices
- Scalability: Linear in number of variables for gradients
This project was developed as part of quantum photonics studies. Key learning outcomes:
- Numerical Methods: Understanding finite difference approximations
- Error Analysis: Balancing truncation vs roundoff errors
- Physical Applications: Connecting math to electromagnetic theory
- Software Design: Building modular, testable scientific code
Contributions welcome! This is an educational project, so clarity and learning value are prioritized.
- Fork the repository
- Create a feature branch:
git checkout -b feature-name
- Add tests for new functionality
- Ensure code passes all tests:
pytest
- Submit a pull request
git clone https://github.com/yourusername/pde-calc.git
cd pde-calc
pip install -e ".[dev]"
pre-commit install
- Numerical Analysis: Burden & Faires, "Numerical Analysis"
- Quantum Mechanics: Griffiths, "Introduction to Quantum Mechanics"
- Electromagnetism: Jackson, "Classical Electrodynamics"
- Optics: Hecht, "Optics"
- Discontinuous Functions: May not differentiate correctly at discontinuities
- Complex Numbers: Currently supports real-valued functions only
- Symbolic Math: Uses numerical approximation, not symbolic differentiation
- Very Large/Small Values: May encounter numerical precision issues
MIT License - see LICENSE file for details.
- Developed during quantum photonics coursework
- Inspired by the need for lightweight mathematical tools in physics
- Thanks to the Python scientific computing community
Built with ❤️ for learning and scientific exploration