Skip to content

Repository files navigation

Differentiable Physics Engine

A real-time Lorenz attractor simulation where a neural network learns the chaotic dynamics from scratch — entirely in the browser.

The green trail is the true physics (RK4 integrator). The red trail is a neural ODE trying to keep up. Watch them diverge as chaos takes over.

Live Demo

How it works

The Lorenz system is a set of three coupled ODEs famous for producing chaotic, butterfly-shaped trajectories:

dx/dt = σ(y − x)       σ = 10
dy/dt = x(ρ − z) − y   ρ = 28
dz/dt = xy − βz         β = 8/3

The true trajectory is computed with a standard RK4 integrator. Alongside it, a 3-layer MLP (3 → 64 → 64 → 3) learns to approximate the vector field f(x,y,z) → (dx/dt, dy/dt, dz/dt) by training on trajectory samples. The network is trained from scratch on page load using backpropagation and Adam — no ML libraries, just raw matrix math in JavaScript.

Once trained, the neural ODE is integrated with an Euler step (intentionally less accurate than RK4) so you can see it gradually diverge from the true trajectory. Because the Lorenz system is chaotic (λ₁ ≈ 0.906), even a well-trained network can't track the true trajectory forever — small errors compound exponentially.

Getting started

npm install
npm run dev

Controls

  • Drag to rotate, scroll to zoom
  • R to reset the trajectory
  • Space to pause/resume
  • All parameters (σ, ρ, β, initial conditions, timestep, learning rate) are adjustable via the sidebar sliders

Deploy to GitHub Pages

The repo includes a GitHub Actions workflow that builds and deploys automatically on push to main. To enable it:

  1. Push this repo to GitHub
  2. Go to Settings → Pages → Source and select GitHub Actions

That's it. Every push to main will redeploy.

To build locally:

npm run build    # outputs to dist/
npm run preview  # preview the production build

Project structure

src/
  main.js       RK4 solver, neural network, Three.js renderer, training loop
  style.css     UI styling
index.html      app shell and control panels
neural_ode.py   standalone PyTorch/Streamlit prototype (see below)

The JavaScript implementation includes a from-scratch Matrix class, He weight initialization, manual forward/backward passes, and an Adam optimizer — all in ~400 lines with no dependencies beyond Three.js.

Python prototype

There's also a standalone Streamlit app (neural_ode.py) that does the same thing using PyTorch. It backpropagates through the RK4 solver using torch.autograd, which is the "proper" differentiable physics approach.

pip install -r requirements.txt
streamlit run neural_ode.py

References

License

MIT

About

Browser-based differentiable physics demo: neural network learns and simulates chaotic dynamics alongside the true system.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages