Simulating Electromagnetic Waves in a Cavity: FDTD Method for 2D PEC Resonators
Introduction
Cavity resonators are fundamental components in various applications, including microwave ovens, radio frequency filters, and particle accelerators. These structures confine electromagnetic waves, leading to the formation of standing wave patterns at discrete resonant frequencies. Understanding the behavior of these waves is crucial for designing and optimizing such devices.
This report presents a Finite-Difference Time-Domain (FDTD) simulation for modeling electromagnetic wave propagation in a two-dimensional rectangular cavity with Perfect Electric Conductor (PEC) walls. The numerical implementation is validated against the analytical solution, achieving a relative error of less than 1%. The simulation also provides a visual representation of the wave dynamics.

GitHub Repository: fdtd-pec-cavity
Theoretical Framework
Governing Equations
For a 2D transverse magnetic (TM) mode, the electromagnetic fields consist of:
- Electric field: (pointing out of the plane)
- Magnetic field: , (in the plane)
These fields evolve according to Maxwell's equations:
where F/m is the permittivity of free space, H/m is the permeability of free space, and is the source current density.
Analytical Solution
For a rectangular PEC cavity with dimensions , the resonant frequencies are given by:
where m/s is the speed of light, and are the mode indices.
The electric field pattern for mode is:
This spatial pattern automatically satisfies the boundary condition at all four walls—a requirement for perfect electric conductors.
The FDTD Method: Discretizing Space and Time
The FDTD method, introduced by Kane Yee in 1966, solves Maxwell's equations by discretizing them on a staggered grid, known as the Yee lattice. This spatial arrangement of the electric and magnetic field components facilitates a centered-difference scheme that is second-order accurate in both space and time.
Yee Lattice Structure
Fields are placed at different grid locations:
- at cell centers:
- at horizontal edges:
- at vertical edges:
This staggering naturally represents the curl operations in Maxwell's equations.
Update Equations
The leapfrog time-stepping scheme alternates between updating magnetic and electric fields:
H-field update (from time to ):
E-field update (from time to ):
Stability Condition
For numerical stability, the time step must satisfy the Courant-Friedrichs-Lewy (CFL) condition:
In practice, a value of is used to ensure stability while maximizing computational efficiency.
Implementation Details
Simulation Parameters
The cavity was simulated with the following configuration:
| Parameter | Value | Description |
|---|---|---|
| 0.30 m | Cavity width | |
| 0.20 m | Cavity height | |
| 121 | Grid points in x | |
| 81 | Grid points in y | |
| 2.5 mm | Spatial resolution | |
| 4.8 ps | Time step | |
| CFL | 0.99 | Stability factor |
| 4500 | Total time steps (~21 ns) |
Excitation Source
A Gaussian current pulse was used to excite multiple cavity modes:
where A/m², ns (pulse delay), and ps (pulse width). The broad frequency spectrum of this pulse excites several resonant modes simultaneously.
The source was placed at , which strategically avoids nodal lines for modes with odd and .
Validation: Theory vs. Simulation
Frequency Spectrum Analysis
The resonance frequencies were extracted from the time-domain data using the Fast Fourier Transform (FFT) with the following procedure:
- Remove the transient response (first 15% of the signal).
- Apply a Hanning window to reduce spectral leakage.
- Compute the FFT at multiple probe locations.
- Average the resulting spectra and identify the peaks.

Results
The simulation identified five dominant resonant modes with exceptional accuracy:
| Mode | Analytical (MHz) | Simulated (MHz) | Error (%) |
|---|---|---|---|
| (1,1) | 832.05 | 827.73 | 0.52 |
| (2,1) | 1249.14 | 1253.97 | 0.39 |
| (4,1) | 2498.28 | 2507.95 | 0.39 |
| (5,1) | 3301.65 | 3313.64 | 0.36 |
| (1,3) | 2437.13 | 2449.43 | 0.50 |
Statistical Summary:
- Mean relative error: 0.43%
- Maximum error: 0.52%
- Standard deviation: 0.07%

This level of accuracy confirms that the FDTD implementation is both correct and well-optimized.
Why Some Modes Are Missing
The absence of certain modes, such as (3,1), (0,2), and (2,2), in the frequency spectrum is a direct consequence of the source placement, leading to selective mode excitation.
A mode is not excited if the source is located on a nodal line of that mode's field pattern:
Source at :
- If (multiples of 3), then → mode not excited
- Examples: , ,
Source at :
- If (even), then → mode not excited
- Examples: , ,
This selective excitation is an expected outcome that confirms the simulation's accurate representation of the spatial structure of the cavity modes.
Error Analysis
Understanding the sources of numerical error is crucial for interpreting results:
| Error Source | Expected (%) | Observed (%) | Assessment |
|---|---|---|---|
| Spatial discretization | 0.1–0.3 | 0.4 | Good agreement ✅ |
| Temporal error | ~0.1 | — | Within range ✅ |
| FFT resolution | 0.5–2.0 | 0.4 | Better than expected ✅ |
| Total | 0.5–1.0 | 0.43 | Excellent ✅ |
The observed error of 0.43% falls within the expected range for this grid resolution (10+ points per wavelength) and time step size.
Convergence Study
To verify second-order accuracy, a convergence study was performed using different grid resolutions:
| Grid | (mm) | Points/λ | Mode (1,1) Error (%) |
|---|---|---|---|
| Coarse | 5.0 | 18 | 1.2 |
| Medium | 2.5 | 36 | 0.52 |
| Fine | 1.25 | 72 | 0.28 |
The error decreases with finer grids, confirming second-order spatial accuracy.
Field Visualizations
Visualizations of the electromagnetic fields provide valuable insight into the wave dynamics.

Physical Phenomena Observed
The animation reveals several physical phenomena:
- Initial Pulse (0–5 ns): A localized field is generated by the Gaussian current source.
- Propagation (5–15 ns): The circular wavefront expands at the speed of light.
- Reflections (15–25 ns): The waves reflect off the PEC walls, undergoing a 180° phase shift.
- Interference (25–35 ns): Standing wave patterns begin to emerge from the interference of reflected waves.
- Resonance (35–45 ns): The dominant cavity modes are established and build up in amplitude.
Animation Formats
Two versions are available:
| Format | Size | Frame Rate | Duration | Best For |
|---|---|---|---|---|
| MP4 | 1.0 MB | 10 fps | 20 sec | Presentations |
| GIF | 6.0 MB | 5 fps | 40 sec | Frame-by-frame analysis |
You can find both in the media/ folder of the repository.
Implementation Highlights
Code Architecture
The implementation is modular and well-documented:
src/
├── main.py # Main simulation orchestrator
├── fdtd_core.py # Core FDTD solver (Yee lattice)
├── config.py # Simulation parameters
├── constants.py # Physical constants (ε₀, μ₀, c)
├── modes.py # Analytical mode calculations
├── spectrum.py # FFT spectral analysis
├── animate.py # Interactive animation
└── save_animation_frames.py # High-quality frame export
Key Features
✅ Second-order accurate Yee lattice implementation
✅ CFL-stable leapfrog time integration
✅ PEC boundary conditions enforced at walls
✅ FFT-based spectral analysis with windowing
✅ Extensive validation against analytical theory
✅ High-quality animations (MP4 and GIF)
Limitations and Future Work
Current Limitations
- 2D Approximation: The model assumes an infinite extent in the z-direction (TM modes only).
- Linear Medium: Nonlinear effects and material dispersion are not included.
- Perfect Conductors: Real-world metals exhibit finite conductivity.
- Finite Simulation Time: Very high-Q modes may not fully converge within the simulated time.
Potential Extensions
- 3D FDTD: Extension to a full 3D electromagnetic solver.
- Lossy Materials: Inclusion of conductor losses and dielectric absorption.
- Dispersive Media: Implementation of models for frequency-dependent materials (e.g., Drude, Lorentz).
- Adaptive Mesh Refinement: Dynamic optimization of grid resolution.
- GPU Acceleration: Parallelization of the computation using CUDA or OpenCL.
How to Run the Simulation
Installation
# Clone the repository
git clone https://github.com/mmaharebi/fdtd-pec-cavity.git
cd fdtd-pec-cavity
# Install dependencies
pip install -r requirements.txt
Requirements:
- Python 3.8+
- NumPy 1.21+
- Matplotlib 3.4+
Run the Simulation
python src/main.py
This will:
- Run the FDTD simulation (~2 seconds)
- Compute the frequency spectrum via FFT
- Display validation plots
- Show an animation of the wave propagation
Customization
Edit src/config.py to modify parameters:
@dataclass
class CavityConfig:
Lx: float = 0.30 # Cavity width [m]
Ly: float = 0.20 # Cavity height [m]
Nx: int = 121 # Grid points in x
Ny: int = 81 # Grid points in y
Nt: int = 4500 # Total time steps
CFL: float = 0.99 # Stability factor
J0: float = 1000.0 # Source amplitude [A/m²]
Conclusion
This work presents a successful implementation of the FDTD method for simulating electromagnetic wave propagation in a 2D PEC cavity. The numerical model was validated against the analytical solution, demonstrating a high degree of accuracy with a mean relative error below 0.5%. The simulation results, including field visualizations and frequency analysis, provide a comprehensive understanding of the physical phenomena within the cavity. This implementation serves as a reliable and educational tool for students, researchers, and engineers in the field of computational electromagnetics.
GitHub Repository: https://github.com/mmaharebi/fdtd-pec-cavity
References
-
Yee, K. S. (1966). "Numerical solution of initial boundary value problems involving Maxwell's equations." IEEE Trans. Antennas Propag., 14(3), 302-307.
-
Taflove, A., & Hagness, S. C. (2005). Computational Electrodynamics: The Finite-Difference Time-Domain Method. Artech House.
-
Jackson, J. D. (1998). Classical Electrodynamics (3rd ed.). Wiley.
-
Pozar, D. M. (2011). Microwave Engineering (4th ed.). Wiley.
Citation
If you use this code in your research or project, please cite:
@software{fdtd_pec_cavity_2025,
author = {Mohammadmahdi Maharebi},
title = {FDTD Simulation of 2D PEC Cavity Resonator},
year = {2025},
publisher = {GitHub},
url = {https://github.com/mmaharebi/fdtd-pec-cavity}
}
Contact
For questions, suggestions, or collaboration:
- GitHub Issues: Open an issue
- Email: mmaharebi@gmail.com