-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_quantum_modernization.py
More file actions
107 lines (84 loc) · 3.95 KB
/
Copy pathtest_quantum_modernization.py
File metadata and controls
107 lines (84 loc) · 3.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""
Test the modernized quantum mechanics module.
This test verifies that the new type-safe implementation produces
correct results for standard quantum mechanical systems.
"""
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
import matplotlib.pyplot as plt
# Test basic functionality without full installation
def test_quantum_harmonic_oscillator():
"""Test quantum harmonic oscillator eigenvalues."""
# Add the package to path for testing
sys.path.insert(0, '/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016')
try:
from computational_physics.core.quantum_mechanics import (
discretize_space, solve_schrodinger_eigenvalue
)
# Set up harmonic oscillator
x = discretize_space(-5.0, 5.0, 200)
V = 0.5 * x**2 # V(x) = 1/2 * x^2
hbar_eff = 1.0
# Solve eigenvalue problem
eigenvalues, eigenfunctions = solve_schrodinger_eigenvalue(hbar_eff, x, V)
# Verify first few eigenvalues are close to analytical values
# For harmonic oscillator: E_n = hbar*omega*(n + 1/2)
# With omega = 1, expect E_0 ≈ 0.5, E_1 ≈ 1.5, E_2 ≈ 2.5
expected = [0.5, 1.5, 2.5]
print("Testing Harmonic Oscillator Eigenvalues:")
for i, (computed, expected_val) in enumerate(zip(eigenvalues[:3], expected)):
error = abs(computed - expected_val)
print(f" E_{i}: computed={computed:.6f}, expected={expected_val:.1f}, error={error:.6f}")
# Check if errors are reasonable (within 5% for finite difference method)
for i, (computed, expected_val) in enumerate(zip(eigenvalues[:3], expected)):
relative_error = abs(computed - expected_val) / expected_val
assert relative_error < 0.05, f"E_{i} error too large: {relative_error:.3f}"
print("✓ Harmonic oscillator test passed!")
# Test error handling
try:
solve_schrodinger_eigenvalue(-1.0, x, V) # negative hbar_eff
assert False, "Should have raised ValueError for negative hbar_eff"
except ValueError:
print("✓ Error handling test passed!")
return True
except ImportError as e:
print(f"Import error: {e}")
print("Running with fallback implementation...")
return test_fallback_implementation()
def test_fallback_implementation():
"""Test original implementation with type hints."""
# Test original quantenmechanik module with improvements
import quantenmechanik as qm
# Test discretization
x = qm.diskretisierung(-2.0, 2.0, 100)
assert len(x) == 100, f"Expected 100 points, got {len(x)}"
x, dx = qm.diskretisierung(-2.0, 2.0, 100, retstep=True)
expected_dx = 4.0 / 101 # (xmax - xmin) / (N + 1)
assert abs(dx - expected_dx) < 1e-10, f"Grid spacing error: {dx} != {expected_dx}"
# Test eigenvalue calculation
V = 0.5 * x**2 # Harmonic oscillator
ew, ef = qm.diagonalisierung(1.0, x, V)
print("Testing Legacy Implementation:")
print(f" First eigenvalue: {ew[0]:.6f}")
print(f" Second eigenvalue: {ew[1]:.6f}")
print(f" Third eigenvalue: {ew[2]:.6f}")
# Verify eigenvalues are reasonable for harmonic oscillator
assert 0.4 < ew[0] < 0.6, f"First eigenvalue out of range: {ew[0]}"
assert 1.4 < ew[1] < 1.6, f"Second eigenvalue out of range: {ew[1]}"
print("✓ Legacy implementation test passed!")
return True
if __name__ == "__main__":
try:
success = test_quantum_harmonic_oscillator()
if success:
print("\n✓ All quantum mechanics tests passed!")
else:
print("\n✗ Some tests failed!")
sys.exit(1)
except Exception as e:
print(f"\n✗ Test failed with error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)