Skip to content
/ two_particles_MD Public template

A Simple Molecular Dynamics Simulator Using Vibe Coding

License

Notifications You must be signed in to change notification settings

tengssh/two_particles_MD

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Two-Particle Molecular Dynamics Simulation in 2D Box

Tests Python 3.9+ License: MIT Streamlit App AI-Assisted Built with Claude AI-Assisted Built with Claude

Overview

This is an educational implementation of a simplified molecular dynamics (MD) simulation featuring:

  • Two particles starting at random positions (based on random seed)
  • Custom initial velocities for each particle (configurable)
  • Lennard-Jones potential for particle interactions
  • Elastic wall collisions to keep particles in the box
  • Comprehensive test suite with pytest (32 tests, 55% coverage)
  • CI/CD pipeline with GitHub Actions

🚀 Quick Links

Class Structure

1. Particle Class

Represents a single particle in 2D space with:

  • Position: [x, y] coordinates in Angstroms
  • Velocity: [vx, vy] in Angstroms/femtosecond
  • Mass: in atomic mass units (amu)
  • is_fixed: Boolean flag to make particle immobile

2. LennardJonesPotential Class

Implements the Lennard-Jones 6-12 potential:

U(r) = 4*epsilon * [(sigma/r)^12 - (sigma/r)^6]
  • epsilon: Depth of potential well (energy scale)
  • sigma: Zero-crossing distance (length scale)
  • Provides methods for potential energy and force calculations

3. TwoParticleMD Class

Main simulation engine that:

  • Uses Velocity Verlet algorithm for time integration
  • Handles wall collisions elastically for both particles
  • Tracks energy conservation
  • Records trajectory history for both particles
  • Provides visualization methods showing both trajectories

Note:

  • Uses setattr and getattr to handle wall collision counters internally

Key Features

Physics Implementation

  1. Velocity Verlet Integration: Time-reversible, symplectic integrator with good energy conservation
  2. Lennard-Jones Forces: Realistic atomic interactions with attractive and repulsive components
  3. Elastic Wall Collisions: Velocity reversal at boundaries conserves kinetic energy
  4. Energy Monitoring: Tracks kinetic, potential, and total energy to verify simulation accuracy

Visualization

  • plot_trajectory(): Shows both particle paths in 2D box with walls, start and end positions
  • plot_energy(): Displays energy components and conservation over time
  • plot_distance(): Plots inter-particle distance vs time

🌐 Interactive Streamlit App

🚀 Try the Live Demo - No installation required!

An interactive web interface is available for running simulations with real-time parameter adjustment and visualization:

Run Locally:

streamlit run src/streamlit_app.py
# Or using make
make app

Features:

  • 🎛️ Interactive Controls: Adjust all simulation parameters through a web UI
  • 📊 Real-time Visualization: Static plots and interactive Plotly animations
  • 🚀 One-click Execution: Run simulations with progress tracking
  • 📈 Energy Metrics: Monitor energy conservation and drift
  • 🎬 Animated Trajectories: Frame-by-frame playback with play/pause controls

Deployment:

See STREAMLIT_APP.md for complete documentation, deployment guides, and CI/CD testing details.

Running the Simulation

Quick Start with Make

# Run command-line simulation
make run

# Launch interactive web app
make app

# Run tests
make test

# See all available commands
make help

Command Line

# Using make (recommended)
make run

# Or directly with Python
python -m src.md_simulation

# Or from the src directory
cd src
python md_simulation.py

This will:

  1. Create a 20×20 Angstrom box
  2. Generate random starting positions for both particles (using seed 42)
  3. Set custom initial velocities for each particle
  4. Simulate for 5000 time steps (5 picoseconds)
  5. Generate plots showing trajectories, energy, and distance

Interactive Web App

# Using make (recommended)
make app

# Or directly with streamlit
streamlit run src/streamlit_app.py

Opens an interactive web interface at http://localhost:8501 with full parameter control and visualization options.

Example Usage

import numpy as np
from src.md_simulation import Particle, LennardJonesPotential, TwoParticleMD

# Set random seed for reproducibility
np.random.seed(42)

# Create Lennard-Jones potential (Argon parameters)
lj = LennardJonesPotential(epsilon=0.238, sigma=3.4)

# Generate random positions (ensuring minimum separation)
pos1 = np.array([7.99, 17.21])
pos2 = np.array([13.71, 11.58])

# Custom initial velocities for each particle
velocity1 = np.array([0.02, 0.02])  # Particle 1 moving
velocity2 = np.array([0.0, 0.0])    # Particle 2 initially at rest

# Create particles
particle1 = Particle(
    position=pos1,
    velocity=velocity1,
    mass=39.948,
    is_fixed=False
)

particle2 = Particle(
    position=pos2,
    velocity=velocity2,
    mass=39.948,
    is_fixed=True  # Can be set to False for two moving particles
)

# Run simulation
sim = TwoParticleMD(particle1, particle2, lj, box_size=(20.0, 20.0), dt=1.0)
sim.run(n_steps=5000)

# Visualize
sim.plot_trajectory()  # Shows both particle paths
sim.plot_energy()
sim.plot_distance()

Educational Highlights

Comments explain:

  • Physics concepts: Kinetic energy, potential energy, forces
  • Numerical methods: Why Velocity Verlet is better than Euler
  • Algorithm details: Step-by-step breakdown of integration
  • Energy conservation: Why it matters and how to check it

Key Observations

  1. Wall bounces: Particles' velocities reverse at boundaries (for non-fixed particles)
  2. Particle interaction: Attraction at long range, repulsion at short range
  3. Energy conservation: Total energy should remain nearly constant
  4. Trajectory comparison: Particles follow different paths based on their initial velocities and positions
  5. Collision dynamics: Particles may collide, scatter, or orbit each other depending on initial conditions

Parameters

Typical Values

  • Time step (dt): 0.1-1.0 fs (smaller = better energy conservation)
  • Argon mass: 39.948 amu
  • Argon LJ parameters: ε = 0.238 kcal/mol, σ = 3.4 Å
  • Box size: 10-50 Å (depends on application)
  • Initial velocity: 0.001-0.1 Å/fs (room temperature ≈ 0.01 Å/fs)

Extending the Code

Possible enhancements:

  1. Add temperature control (thermostat)
  2. Implement different potentials (harmonic, Morse, etc.)
  3. Add more particles (N-body simulation)
  4. Include external forces (gravity, electric field)
  5. Implement periodic boundary conditions instead of walls
  6. Add animation of particle motion
  7. Calculate and plot velocity distributions

Testing

This project includes a comprehensive test suite using pytest:

# Install test dependencies
make install

# Run all tests
make test

# Run with coverage report
make coverage

# Or use pytest directly
pytest tests/ -v
pytest tests/ --cov=src --cov-report=term

Test Coverage:

  • ✅ 49 tests covering all major components
  • ✅ 75% code coverage
  • ✅ Tests for Particle, LennardJonesPotential, TwoParticleMD, and Streamlit app

See tests/README.md for detailed testing documentation.

Continuous Integration

GitHub Actions workflows automatically run tests on every push and pull request:

  • tests.yml: Comprehensive testing on multiple OS (Ubuntu, Windows, macOS) and Python versions (3.9-3.12)
  • tests-simple.yml: Quick testing on Ubuntu with Python 3.11

See .github/workflows/README.md for CI/CD documentation.

Dependencies

  • numpy>=1.20.0: Numerical computations
  • matplotlib>=3.3.0: Visualization
  • streamlit>=1.28.0: Interactive web app
  • plotly>=5.0.0: Interactive visualizations
  • pytest>=7.0.0: Testing framework
  • pytest-cov>=3.0.0: Coverage reporting

Install all dependencies:

make install
# Or directly with pip
pip install -r requirements.txt

Documentation

📚 Complete Documentation Index

📖 Quick Links

Project Structure

two_particles_MD/
├── src/                      # Source code
│   ├── __init__.py
│   ├── md_simulation.py      # Main simulation code
│   └── streamlit_app.py      # Interactive web app
├── tests/                    # Test suite
│   ├── __init__.py
│   ├── README.md             # Test documentation
│   ├── test_particle.py      # Particle class tests
│   ├── test_potential.py     # Potential class tests
│   ├── test_simulation.py    # Simulation class tests
│   └── test_streamlit_app.py # Streamlit app tests
├── examples/                 # Example scripts and notebooks
│   ├── parallel_examples.py  # Parallelization examples
│   ├── profile_md.py         # Profiling examples
│   └── test_encoding.py      # Encoding test script
├── docs/                     # Documentation
│   ├── DOCUMENTATION_INDEX.md    # Complete documentation index
│   ├── PROJECT_SUMMARY.md        # Project overview with diagrams
│   ├── STREAMLIT_APP.md          # Streamlit app guide
│   ├── USAGE.md                  # Quick start guide
│   ├── CONTRIBUTING.md           # Contribution guidelines
│   ├── TESTING.md                # Testing guide
│   ├── PROFILING_GUIDE.md        # Performance profiling guide
│   ├── PARALLELIZATION_GUIDE.md  # Parallelization guide
│   └── ...                       # Other documentation
├── requirements.txt          # Python dependencies
├── Makefile                  # Convenient commands
├── README.md                 # This file
├── LICENSE                   # MIT License
├── .gitignore                # Git ignore rules
└── .github/
    └── workflows/            # CI/CD workflows
        ├── README.md         # Workflow documentation
        ├── tests.yml         # Comprehensive test suite
        └── tests-simple.yml  # Simple test suite

Acknowledgments

This project was developed with assistance from two AI coding assistants using different Claude models:

Augment Agent (Augment Code)

Initial Development & Streamlit App - Developed with Augment Agent, an agentic coding AI assistant by Augment Code, using both Claude Sonnet 4.5 and Claude Opus 4.5 by Anthropic.

Claude Sonnet 4.5 was used for:

  • 🏗️ Architecture Design: Educational class structure with comprehensive documentation
  • 🧪 Test Suite: Complete pytest-based testing infrastructure for core simulation (32 tests)
  • 🔄 CI/CD Pipeline: GitHub Actions workflows for multi-platform, multi-version testing
  • 📚 Documentation: Comprehensive guides including README, TESTING, CONTRIBUTING, and deployment checklists
  • 🎨 Visualization: Matplotlib-based trajectory and energy plotting with customized styling
  • 🔧 Code Quality: Integration of black, isort, and flake8 for maintaining code standards

Claude Opus 4.5 was used for:

  • 🌐 Streamlit Web App: Interactive parameter controls, real-time visualization, and animated trajectories
  • 🧪 Streamlit Tests: Comprehensive test suite for the web app (17 additional tests)

Antigravity (Google DeepMind)

CI/CD Fixes & Documentation - Bug fixes and documentation updates were developed with Antigravity, an agentic coding AI assistant by Google DeepMind, using Claude Sonnet 4.5 by Anthropic.

Antigravity assisted with:

  • 🔧 CI/CD Fixes: Resolved platform-specific test failures on Linux, macOS, and Windows
  • 📚 Documentation: CI troubleshooting documentation, updated README and workflow docs
  • 📊 Test Optimization: Adjusted test parameters for CI environments

AI-Assisted Development

This project demonstrates the capabilities of AI-assisted software development, including:

  • Rapid prototyping of scientific computing code
  • Automated test generation and conversion (unittest → pytest)
  • Professional CI/CD setup with multi-platform testing matrices
  • Interactive web application development
  • Platform-specific debugging and optimization
  • Comprehensive documentation generation
  • Best practices implementation for Python projects

Detailed Attribution:


License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License Summary

  • Commercial use - Use for commercial purposes
  • Modification - Modify the software
  • Distribution - Distribute the software
  • Private use - Use privately
  • ⚠️ Liability - No warranty provided
  • ⚠️ Attribution - Must include copyright notice

Performance & Parallelization

While the current 2-particle system is already very fast, this project can be extended to N-body simulations with various parallelization techniques:

Parallelization Techniques Covered:

  • NumPy Vectorization - 10-100x speedup, easy to implement
  • Numba JIT Compilation - 10-100x speedup for complex loops
  • GPU Acceleration - 50-500x speedup for large systems (PyTorch/CuPy)
  • Spatial Decomposition - O(N²) → O(N) scaling for force calculations
  • MPI (Distributed Computing) - 10-1000x speedup on HPC clusters
  • Ensemble Parallelism - Perfect scaling for parameter studies
  • Async I/O - Non-blocking data operations

Profiling Tools Covered:

  • cProfile - Function-level profiling (built-in)
  • line_profiler - Line-by-line analysis
  • memory_profiler - Memory usage tracking
  • py-spy - Production profiling with flame graphs
  • pyinstrument - Statistical profiling with call stacks
  • GPU profilers - NVIDIA Nsight, PyTorch Profiler

See the guides for detailed explanations, code examples, and benchmarks!


Branches

This repository maintains the following branches:

  • main: The stable production branch containing the core implementation and Streamlit app
  • research: Active development branch for exploring new features and improvements
  • feature/streamlit-app: Development branch for the interactive Streamlit web application (merged to main)

Development Workflow

  1. The main branch contains the stable, production-ready code
  2. New features and research are developed in feature branches (e.g., feature/streamlit-app)
  3. The research branch is used for experimental features and improvements
  4. Tested and validated improvements are merged back to main via pull requests

Recent Developments

  • Streamlit App: Interactive web interface merged from feature/streamlit-app branch
    • Added comprehensive test suite (17 tests)
    • Platform-specific CI/CD fixes for Linux, macOS, and Windows
    • Increased test coverage from 55% to 75%

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

Quick Start

# Install dependencies
make install

# Run simulation
make run

# Or launch interactive app
make app

# Run tests
make test

For a detailed guide, see USAGE.md.

About

A Simple Molecular Dynamics Simulator Using Vibe Coding

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published