Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
309 changes: 231 additions & 78 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -1,83 +1,236 @@
# Copilot Instructions for ComputationalPhysics2016
# Copilot Instructions for ComputationalPhysics2016 - Modern Edition v2.0

## Project Overview
This repository contains Python implementations of computational physics tasks from 2016, covering topics such as:
- Classical dynamics (kicked rotor, driven double-well potential)
- Quantum mechanics (1D potentials, time evolution, periodic potentials)
- Statistical mechanics (Ising model)
- Numerical methods (derivatives, integrals, diffusion)
- Particle simulations

## Key Technologies
- **Python 3.8+**: Primary programming language
- **NumPy 2.2+**: Numerical computations and arrays
- **Matplotlib 3.10+**: Scientific plotting and visualization
- **SciPy 1.15+**: Advanced scientific computing functions
- **SymPy 1.14+**: Symbolic mathematics

This repository contains **modernized** Python implementations of computational physics algorithms, fully updated to current industry standards. The package provides type-safe, well-documented implementations of quantum mechanics, classical dynamics, and numerical methods for educational and research use.

### **🎯 Modern Architecture (v2.0+)**
- **Package Structure**: `src/computational_physics/` layout with modular organization
- **Python Requirements**: 3.11+ with modern scientific stack (NumPy 2.0+, SciPy 1.14+, Matplotlib 3.8+)
- **Type Safety**: Comprehensive type hints (90%+ coverage) with runtime validation
- **Testing**: pytest-based suite with unit and integration tests
- **CI/CD**: GitHub Actions pipeline with automated quality checks
- **Documentation**: Interactive Jupyter notebooks and comprehensive API docs

### **📁 Current File Structure**
```
ComputationalPhysics2016/
├── src/computational_physics/ # Main package (modern)
│ ├── __init__.py # Package exports
│ ├── core/ # Physics implementations
│ │ ├── quantum_mechanics.py # Quantum systems
│ │ ├── classical_mechanics.py # Dynamical systems
│ │ ├── numerical_methods.py # Numerical algorithms
│ │ └── __init__.py
│ ├── utils/ # Utilities
│ │ ├── physics_constants.py # CODATA constants
│ │ ├── validation.py # Parameter validation
│ │ └── __init__.py
│ ├── config/ # Configuration
│ ├── visualization/ # Plotting tools
│ └── cli.py # Command-line interface
├── tests/ # Modern test suite
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── legacy/ # Legacy test files
├── notebooks/ # Jupyter demonstrations
├── legacy_scripts/ # Original 2016 scripts
├── pyproject.toml # Modern configuration
├── pytest.ini # Test configuration
└── README.md # Modern documentation
```

## Key Technologies & Modern Standards

### **Core Scientific Computing**
- **NumPy 2.0+**: Modern array operations with improved performance
- **SciPy 1.14+**: Advanced scientific algorithms
- **Matplotlib 3.8+**: Scientific visualization with modern backends
- **SymPy 1.13+**: Symbolic mathematics

### **Development & Quality**
- **Python 3.11+**: Modern language features (typed self, exception groups, etc.)
- **Type Hints**: Comprehensive typing with `from __future__ import annotations`
- **pytest**: Modern testing framework with fixtures and markers
- **black**: Code formatting (88 character line length)
- **ruff**: Fast linting and code analysis
- **mypy**: Static type checking
- **pre-commit**: Automated quality hooks

### **Documentation & Examples**
- **Jupyter Notebooks**: Interactive demonstrations with IPython widgets
- **Google/NumPy Style**: Standardized docstring format with LaTeX equations
- **CLI Interface**: Command-line access for quick calculations
- **GitHub Actions**: Automated testing and deployment

## Coding Standards and Conventions

### Code Style
- Follow existing German naming conventions for variables and comments where present
- Maintain consistency with existing docstring format (German comments are acceptable)
- Use type hints for function parameters and return values
- Keep class and function names descriptive and meaningful

### File Naming Pattern
- Main scripts follow pattern: `{task_number}_1_martin_roebke.py`
- Test files use standard Python naming: `test_*.py`
- Keep existing naming conventions when modifying files

### Dependencies
- **DO NOT install new dependencies** without explicit approval
- Use only the packages specified in `requirements.txt` and `stable_requirements.txt`
- Prefer stable, exact versions from `stable_requirements.txt` for reproducibility
- Use matplotlib with 'Agg' backend for headless environments in tests

### Physics and Mathematics
- Maintain physical accuracy and proper units
- Include clear comments explaining physics concepts and equations
- Use NumPy arrays for efficient numerical computations
- Follow standard physics notation where possible
- Document any approximations or numerical methods used

### Testing Guidelines
- All scripts should be testable with the existing test framework
- Use `matplotlib.use('Agg')` backend for tests to avoid GUI dependencies
- Ensure scripts can run without interactive elements for automated testing
- Maintain compatibility with the integration test suite in `run_all_tests.py`

### Performance Considerations
- Optimize NumPy operations for large arrays
- Use vectorized operations instead of loops where possible
- Consider memory usage for large simulations
- Profile code for computational bottlenecks in physics simulations

### Error Handling
- Handle numerical edge cases (division by zero, overflow)
- Provide meaningful error messages for physics parameter validation
- Ensure graceful degradation when visualization fails

### Documentation
- Explain physics concepts in comments for educational purposes
- Document function parameters, especially physics quantities and units
- Include references to relevant physics literature or equations
- Maintain existing German documentation style where present

## File Structure Guidelines
- Keep computational logic separate from visualization when possible
- Use classes to encapsulate related physics calculations
- Maintain clear separation between physics models and plotting code
- Follow the existing pattern of combining computation and visualization in single files

## Common Physics Libraries Usage
- **NumPy**: Use for arrays, linear algebra, FFT operations
- **SciPy**: Use for integration, optimization, special functions
- **Matplotlib**: Use for scientific plots, animations, interactive widgets
- **SymPy**: Use for symbolic calculations and analytical solutions

## Specific to This Project
- Maintain compatibility with both Conda and pip installation methods
- Ensure scripts work with the existing test infrastructure
- Keep resource files (figures) in the `resources/` directory
- Follow the existing pattern for script execution and parameter handling
### **Modern Python Style**
- **Type Hints**: All functions must have complete type annotations
- **Dataclasses**: Use for configuration and data containers
- **f-strings**: All string formatting must use f-string syntax
- **pathlib**: Use `Path` objects for file operations
- **Context Managers**: Use `with` statements for resource management

### **Physics Code Guidelines**
- **Units & Constants**: Use `utils.physics_constants` for all physical constants
- **Validation**: All physics functions must validate input parameters
- **Documentation**: Include physics explanations with LaTeX equations
- **Accuracy**: Validate numerical results against analytical solutions where possible
- **Error Handling**: Use `ValidationError` for physics parameter violations

### **Package Organization**
- **Modular Design**: Separate core physics from utilities and visualization
- **Type Safety**: Runtime validation using `utils.validation` module
- **Configuration**: Use dataclass-based configuration in `config/`
- **Legacy Support**: Maintain compatibility warnings for deprecated functions

### **Testing Requirements**
- **Unit Tests**: All physics classes and functions must have unit tests
- **Integration Tests**: Test cross-module functionality and package imports
- **Physics Validation**: Compare numerical results with analytical solutions
- **Error Testing**: Verify proper error handling and validation
- **Performance**: Basic benchmarking for computationally intensive functions

### **Documentation Standards**
- **Docstrings**: Google/NumPy style with complete Args/Returns/Raises/Examples
- **LaTeX Equations**: Include mathematical formulations in docstrings
- **Physics Context**: Explain physical meaning and applications
- **Examples**: Provide working code examples in docstrings
- **Type Information**: Complete type hints for all parameters and returns

## Modern Physics Implementation Patterns

### **Quantum Mechanics Example**
```python
from dataclasses import dataclass
from typing import Optional
from computational_physics.utils import ValidationError, validate_physics_parameters

@dataclass(frozen=True)
class QuantumState:
"""Immutable quantum state with validation."""
wavefunction: ComplexArray
energy: float
position_grid: RealArray
quantum_numbers: Optional[dict[str, int]] = None

def __post_init__(self) -> None:
if len(self.wavefunction) != len(self.position_grid):
raise ValidationError("Array length mismatch")
```

### **Classical Mechanics Example**
```python
class StandardMap(DynamicalSystem):
"""Type-safe standard map with comprehensive validation."""

def __init__(self, kick_strength: float) -> None:
validate_physics_parameters({"kick_strength": kick_strength})
super().__init__(kick_strength=kick_strength)
self.kick_strength = kick_strength

def iterate_once(self, theta: float, momentum: float) -> tuple[float, float]:
"""Perform one iteration with proper typing."""
new_theta = (theta + momentum) % TWO_PI
new_momentum = (momentum + self.kick_strength * np.sin(new_theta)) % TWO_PI
return new_theta, new_momentum
```

### **Testing Pattern**
```python
class TestHarmonicOscillator:
"""Modern test class with physics validation."""

def test_analytical_vs_numerical(self) -> None:
"""Compare numerical results with analytical solutions."""
oscillator = HarmonicOscillator(omega=1.0)
x = discretize_position(-5, 5, 1000)
states = oscillator.solve_eigenvalue_problem(x, n_states=3)

for i, state in enumerate(states):
analytical = oscillator.analytical_energy(i)
error = abs(state.energy - analytical) / analytical
assert error < 1e-3, f"Energy error too large: {error}"
```

## Development Workflow

### **Setup and Installation**
```bash
# Modern development setup
pip install -e ".[dev]" # Install with dev dependencies
pre-commit install # Set up code quality hooks
pytest tests/ # Run test suite
```

### **Code Quality Checks**
```bash
black src/ tests/ # Format code
ruff check src/ tests/ # Lint code
mypy src/computational_physics # Type checking
pytest --cov=src/ # Test with coverage
```

### **CLI Usage**
```bash
python -m computational_physics.cli info # Package info
python -m computational_physics.cli quantum harmonic -f 2.0 # Solve oscillator
python -m computational_physics.cli demo quantum # Run demo
```

## Breaking Changes from Legacy (v1.x → v2.0)

### **Import Changes**
```python
# Legacy (deprecated)
from quantenmechanik import diskretisierung
from computational_physics.legacy import standard_abbildung

# Modern (required)
from computational_physics import discretize_position, iterate_standard_map
```

### **Type Safety Requirements**
```python
# Legacy (weakly typed)
states = solve_oscillator(1.0, [-5, 5], 3)

# Modern (strongly typed with validation)
states = solve_harmonic_oscillator(
omega=1.0,
x_range=(-5.0, 5.0),
n_levels=3
)
```

## Educational Philosophy

This modernized package serves multiple educational purposes:

1. **Modern Python Practices**: Demonstrates current industry standards
2. **Type Safety**: Shows benefits of static typing in scientific computing
3. **Testing Culture**: Emphasizes importance of comprehensive testing
4. **Documentation**: Models excellent scientific code documentation
5. **Physics Education**: Enhanced with interactive notebooks and examples

## Performance Considerations

- **Vectorized Operations**: Use NumPy array operations over Python loops
- **Memory Efficiency**: Consider memory usage for large-scale simulations
- **Type Checking**: Runtime validation only where necessary for physics safety
- **Caching**: Strategic caching for expensive computations
- **Profiling**: Profile performance-critical code sections

## Future Extensions

The modular architecture supports easy addition of:
- Statistical mechanics modules
- Advanced visualization tools
- Parallel computing implementations
- Additional physics domains
- Interactive web interfaces

---

**This package represents the gold standard for modernizing scientific Python code while maintaining educational value and physics accuracy.**
Loading