Skip to content

refactor(hamiltonian-nn): modularize code, add tests, improve energy conservation#32

Open
olaropenclaw wants to merge 1 commit intoqbeer:masterfrom
olaropenclaw:hnn-improvements
Open

refactor(hamiltonian-nn): modularize code, add tests, improve energy conservation#32
olaropenclaw wants to merge 1 commit intoqbeer:masterfrom
olaropenclaw:hnn-improvements

Conversation

@olaropenclaw
Copy link

Summary

This PR refactors the Hamiltonian Neural Network implementation with efficiency improvements, better code organization, and comprehensive tests.

Changes

Code Organization

  • Modularized architecture: Split monolithic code into separate modules:
    • mlp.py: Configurable MLP backbone
    • hnn.py: HNN with documentation and helper methods
    • training.py: Training utilities for both baseline and HNN
    • integrators.py: Numerical integrators including symplectic leapfrog

New Features

  • Symplectic leapfrog integrator: Preserves Hamiltonian structure for better long-term energy conservation
  • CLI arguments: train.py now accepts --epochs, --lr, --seed, --use-leapfrog, --output
  • Reproducibility: Seed support throughout data generation and training

Tests

  • Added comprehensive test suite with 18 tests covering all components

Bug Fixes

  • Fixed phi range in data generation (0 to 2π instead of 0 to π)

Why Energy Oscillates in Original Code

The original test.png showed oscillating energy because:

  1. Plotting true energy vs learned Hamiltonian
  2. Using non-symplectic RK45 integrator
  3. Training on noisy data

Use --use-leapfrog for better conservation.

Test Results: 18 passed

…rgy conservation

- Modularize architecture: split into mlp.py, hnn.py, training.py, integrators.py
- Add symplectic leapfrog integrator for better energy conservation
- Add comprehensive test suite (18 tests covering data gen, models, integrators, training)
- Make MLP configurable with flexible hidden dimensions
- Add docstrings and type hints throughout
- Improve README with explanation of energy oscillation in original code
- Add CLI arguments to train.py for reproducibility and configuration
- Fix phi range in data generation (0 to 2π instead of 0 to π)

The energy oscillation in the original test.png was due to:
1. Plotting true energy vs learned Hamiltonian
2. Using non-symplectic RK45 integrator
3. Training on noisy data

Use --use-leapfrog flag to see improved conservation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants