Skip to content

rithulkamesh/pde-calc

Repository files navigation

🧮 Partial Derivatives Calculator

Python License: MIT Code Style: Black

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.

🎯 Why This Project?

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

✨ Features

  • 🚀 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

🚀 Quick Start

Installation

git clone https://github.com/yourusername/pde-calc.git
cd pde-calc
pip install -e .

Basic Usage

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})")

Interactive Mode

# Run examples
python main.py --demo

# Interactive calculator
python main.py

📖 Quantum Photonics Applications

1. Wave Function Analysis

# 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}")

2. Electromagnetic Field Gradients

# 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}")

3. Optical Beam Analysis

# 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}")

🔬 Supported Mathematical Functions

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)

📊 API Reference

Expression Class

Expression(expression, variables=None)

Create a mathematical expression for differentiation.

Parameters:

  • expression: String formula or callable function
  • variables: Variable names (auto-detected for strings)

Methods:

  • evaluate(**kwargs): Compute expression value at given point

PartialDerivativeCalculator Class

PartialDerivativeCalculator(h=1e-8)

Key Methods:

partial_derivative(expression, variable, method='central')

Calculate ∂f/∂variable using finite differences.

gradient(expression)

Calculate ∇f (vector of all partial derivatives).

hessian(expression)

Calculate ∇²f (matrix of second partial derivatives).

🧪 Examples & Test Cases

Example 1: Quantum Harmonic Oscillator

# 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

Example 2: 2D Electromagnetic Potential

# 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})")

Example 3: Optical Intensity Distribution

# 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}")

🔧 Numerical Methods

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)

🧪 Running Tests

# 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

📈 Performance Considerations

  • 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

🎓 Educational Notes

This project was developed as part of quantum photonics studies. Key learning outcomes:

  1. Numerical Methods: Understanding finite difference approximations
  2. Error Analysis: Balancing truncation vs roundoff errors
  3. Physical Applications: Connecting math to electromagnetic theory
  4. Software Design: Building modular, testable scientific code

🤝 Contributing

Contributions welcome! This is an educational project, so clarity and learning value are prioritized.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Add tests for new functionality
  4. Ensure code passes all tests: pytest
  5. Submit a pull request

Development Setup

git clone https://github.com/yourusername/pde-calc.git
cd pde-calc
pip install -e ".[dev]"
pre-commit install

📚 References & Further Reading

  • Numerical Analysis: Burden & Faires, "Numerical Analysis"
  • Quantum Mechanics: Griffiths, "Introduction to Quantum Mechanics"
  • Electromagnetism: Jackson, "Classical Electrodynamics"
  • Optics: Hecht, "Optics"

🐛 Known Limitations

  • 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

📄 License

MIT License - see LICENSE file for details.

🙏 Acknowledgments

  • 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

About

A simple partial derivative calculator

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published