-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_io_simple.py
More file actions
272 lines (213 loc) · 7.65 KB
/
Copy pathtest_io_simple.py
File metadata and controls
272 lines (213 loc) · 7.65 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Test I/O infrastructure: Configuration, trajectory export, audit logging.
Simpler version that avoids naming conflicts with Python's built-in io module.
"""
import sys
import logging
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def test_yaml_loading():
"""Test YAML configuration loading."""
print("\n" + "="*80)
print("TEST 1: YAML Configuration Loading")
print("="*80)
try:
import yaml
except ImportError:
print("⚠ PyYAML not installed")
return None
config_file = Path("missions/solar_sail_2body.yaml")
if not config_file.exists():
print(f"✗ Config file not found: {config_file}")
return None
with open(config_file, 'r') as f:
config_data = yaml.safe_load(f)
print(f"✓ YAML loaded successfully")
print(f" Mission name: {config_data['mission']['name']}")
print(f" Duration: {config_data['mission']['t_end']} s ({config_data['mission']['t_end'] / 86400:.1f} days)")
print(f" Spacecraft: {config_data['spacecraft']['name']}")
print(f" Sail area: {config_data['spacecraft']['sail_area_m2']} m²")
print(f" Initial position: {config_data['initial_state']['r']}")
print(f" Initial velocity: {config_data['initial_state']['v']}")
return config_data
def test_hdf5_capabilities():
"""Test HDF5 availability."""
print("\n" + "="*80)
print("TEST 2: HDF5 Export Capabilities")
print("="*80)
try:
import h5py
import numpy as np
print(f"✓ h5py version: {h5py.__version__}")
# Create test HDF5 file
test_file = Path("test_outputs/test_simple.h5")
test_file.parent.mkdir(exist_ok=True)
with h5py.File(test_file, 'w') as f:
# Create simple dataset
r_data = np.random.randn(100, 3)
f.create_dataset("r", data=r_data, compression="gzip")
# Add attributes
f.attrs["mission_name"] = "test_mission"
f.attrs["n_steps"] = 100
file_size = test_file.stat().st_size / 1e3
print(f"✓ Created test HDF5 file: {test_file}")
print(f" File size: {file_size:.2f} KB")
# Reload
with h5py.File(test_file, 'r') as f:
r_loaded = f["r"][:]
attrs = dict(f.attrs)
print(f"✓ Reloaded HDF5 successfully")
print(f" Data shape: {r_loaded.shape}")
print(f" Metadata: {attrs}")
return True
except ImportError as e:
print(f"⚠ h5py not installed: {e}")
return False
def test_sqlite_capabilities():
"""Test SQLite capabilities."""
print("\n" + "="*80)
print("TEST 3: SQLite Audit Export Capabilities")
print("="*80)
import sqlite3
import json
test_file = Path("test_outputs/test_audit.db")
test_file.parent.mkdir(exist_ok=True)
conn = sqlite3.connect(test_file)
cursor = conn.cursor()
# Create simple schema
cursor.execute("""
CREATE TABLE IF NOT EXISTS mission_metadata (
mission_name TEXT,
n_steps INTEGER,
wall_time_sec REAL,
success BOOLEAN
)
""")
# Insert test data
cursor.execute("""
INSERT INTO mission_metadata (mission_name, n_steps, wall_time_sec, success)
VALUES (?, ?, ?, ?)
""", ("test_mission", 60480, 2.67, True))
conn.commit()
conn.close()
file_size = test_file.stat().st_size / 1e3
print(f"✓ Created test SQLite database: {test_file}")
print(f" File size: {file_size:.2f} KB")
# Query
conn = sqlite3.connect(test_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM mission_metadata")
rows = cursor.fetchall()
print(f"✓ Queried database: {len(rows)} rows")
for row in rows:
print(f" {dict(row)}")
conn.close()
return True
def test_existing_demo():
"""Test that existing demo still works."""
print("\n" + "="*80)
print("TEST 4: Existing Architecture Demo")
print("="*80)
import subprocess
result = subprocess.run(
[sys.executable, "architecture_demo.py"],
cwd=Path(__file__).parent,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
print(f"✓ Architecture demo ran successfully")
# Extract summary from output
lines = result.stdout.split('\n')
for line in lines:
if 'Steps' in line or 'Wall time' in line or 'Success' in line:
print(f" {line.strip()}")
return True
else:
print(f"✗ Architecture demo failed: {result.stderr}")
return False
def test_existing_wrappers():
"""Test that existing wrapper tests still pass."""
print("\n" + "="*80)
print("TEST 5: Existing Physics Module Wrappers")
print("="*80)
import subprocess
result = subprocess.run(
[sys.executable, "test_wrappers_simple.py"],
cwd=Path(__file__).parent,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
print(f"✓ Wrapper tests passed")
lines = result.stdout.split('\n')
for line in lines:
if 'PASS' in line or 'FAIL' in line:
print(f" {line.strip()}")
return True
else:
print(f"✗ Wrapper tests failed: {result.stderr}")
return False
def main():
"""Run all I/O infrastructure tests."""
print("\n" + "="*80)
print("HELIOSAIL-RX I/O INFRASTRUCTURE TEST SUITE")
print("="*80)
results = []
# Test 1: YAML
config_data = test_yaml_loading()
results.append(("YAML Loading", config_data is not None))
# Test 2: HDF5
h5_result = test_hdf5_capabilities()
results.append(("HDF5 Export", h5_result))
# Test 3: SQLite
try:
sqlite_result = test_sqlite_capabilities()
results.append(("SQLite Audit", sqlite_result))
except Exception as e:
print(f"✗ SQLite test failed: {e}")
results.append(("SQLite Audit", False))
# Test 4: Demo
try:
demo_result = test_existing_demo()
results.append(("Architecture Demo", demo_result))
except Exception as e:
print(f"✗ Demo test failed: {e}")
results.append(("Architecture Demo", False))
# Test 5: Wrappers
try:
wrapper_result = test_existing_wrappers()
results.append(("Physics Wrappers", wrapper_result))
except Exception as e:
print(f"✗ Wrapper test failed: {e}")
results.append(("Physics Wrappers", False))
# Summary
print("\n" + "="*80)
print("TEST SUMMARY")
print("="*80)
passed = sum(1 for _, r in results if r)
total = len(results)
for test_name, result in results:
status = "✓ PASS" if result else "✗ FAIL"
print(f"{status} {test_name}")
print(f"\nTotal: {passed}/{total} tests passed")
if passed == total:
print("\n✓ ALL TESTS PASSED")
print("\nI/O Infrastructure Summary:")
print(" ✓ YAML configuration loading")
print(" ✓ HDF5 trajectory export")
print(" ✓ SQLite audit trail export")
print(" ✓ Existing architecture demo still works")
print(" ✓ Existing physics wrappers still work")
return 0
else:
print(f"\n✗ {total - passed} test(s) failed")
return 1
if __name__ == "__main__":
sys.exit(main())