Add wave equation example (PDE via method of lines)#279
Add wave equation example (PDE via method of lines)#279gpartin wants to merge 2 commits intortqichen:masterfrom
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a new torchdiffeq example demonstrating solving a 1D PDE (wave equation) via the method of lines (spatial finite differences + odeint time integration), plus documentation in the examples README.
Changes:
- Added
examples/wave_equation.pyforward-solve + visualization + optional Neural ODE training loop. - Documented how to run the new example in
examples/README.md.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| examples/wave_equation.py | New wave-equation method-of-lines example with optional Neural ODE training and visualization utilities. |
| examples/README.md | Added a section describing how to run/visualize/train the new wave equation example. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
You can also share your feedback on Copilot code review. Take the survey.
| """Two Gaussian pulses traveling in opposite directions.""" | ||
| L = 2.0 * np.pi | ||
| u0 = torch.exp(-40.0 * (x - L / 3.0) ** 2) + 0.5 * torch.exp(-40.0 * (x - 2.0 * L / 3.0) ** 2) | ||
| v0 = torch.zeros(n_grid) |
There was a problem hiding this comment.
initial_condition creates u0 from x (float64 in generate_data) but creates v0 with torch.zeros(n_grid) (default float32). torch.cat([u0, v0]) requires matching dtypes and will raise an error. Create v0 with the same dtype/device as u0 (e.g., using torch.zeros_like(u0) or specifying dtype=u0.dtype and device=u0.device).
| v0 = torch.zeros(n_grid) | |
| v0 = torch.zeros(n_grid, dtype=u0.dtype, device=u0.device) |
Match v0 dtype and device to u0 to avoid errors when u0 is float64 or on GPU. Addresses Copilot review suggestion.
Summary
Adds a new example demonstrating how to solve the 1D wave equation using
torchdiffeq. This fills a gap in the examples directory — currently all examples are ODE systems, buttorchdiffeqis equally useful for solving PDEs via the method of lines: discretize in space, integrate in time withodeint.What the example does
The wave equation
u_tt = c^2 * u_xxis converted to a first-order ODE system:du/dt = vdv/dt = c^2 * Laplacian(u)where the spatial Laplacian uses second-order finite differences with periodic boundary conditions.
Two modes of operation
python wave_equation.py --vizpython wave_equation.py --train --vizResults
--adjointfor O(1)-memory backpropagation--method(dopri5, adams, rk4),--gpu,--n_grid,--c(wave speed)Files changed
examples/wave_equation.py— New example (305 lines)examples/README.md— Added Wave Equation sectionNotes
ode_demo.pynn.Modulefor both physics and neural dynamics (compatible withodeint_adjoint)