-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_safety.py
More file actions
548 lines (433 loc) · 16.4 KB
/
Copy pathtest_safety.py
File metadata and controls
548 lines (433 loc) · 16.4 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
"""Comprehensive tests for failure safety system."""
import pytest
import numpy as np
from unittest.mock import Mock
from dataclasses import dataclass
from kernel.safety import (
FailureSafetyMonitor, SafetyThresholds, SafetyStatus, SafetyAlert, SafetyReport
)
@dataclass
class MockState:
"""Mock spacecraft state."""
position: np.ndarray
velocity: np.ndarray
mass: float
# ============================================================================
# SAFETY THRESHOLDS TESTS
# ============================================================================
class TestSafetyThresholds:
"""Test safety threshold configuration."""
def test_default_thresholds(self):
"""Test creating default thresholds."""
thresholds = SafetyThresholds()
assert thresholds.max_position_magnitude == 1e15
assert thresholds.max_velocity_magnitude == 1e8
assert thresholds.min_mass == 1e-6
assert thresholds.max_energy_drift_percent == 5.0
def test_custom_thresholds(self):
"""Test custom threshold configuration."""
thresholds = SafetyThresholds(
max_velocity_magnitude=1e7,
min_mass=0.1
)
assert thresholds.max_velocity_magnitude == 1e7
assert thresholds.min_mass == 0.1
assert thresholds.max_position_magnitude == 1e15 # Default
# ============================================================================
# SAFETY ALERT TESTS
# ============================================================================
class TestSafetyAlert:
"""Test safety alert creation."""
def test_create_alert(self):
"""Test creating a safety alert."""
alert = SafetyAlert(
severity="warning",
check_name="test_check",
message="Test message",
value=1.5,
threshold=1.0,
step_number=100
)
assert alert.severity == "warning"
assert alert.check_name == "test_check"
assert alert.value == 1.5
# ============================================================================
# SAFETY REPORT TESTS
# ============================================================================
class TestSafetyReport:
"""Test safety report generation."""
def test_report_creation(self):
"""Test creating a safety report."""
report = SafetyReport()
assert report.total_warnings == 0
assert report.total_criticals == 0
assert report.simulation_halted is False
def test_report_status_nominal(self):
"""Test nominal status."""
report = SafetyReport()
assert report.overall_status() == SafetyStatus.NOMINAL
def test_report_status_warning(self):
"""Test warning status."""
report = SafetyReport(total_warnings=1)
assert report.overall_status() == SafetyStatus.WARNING
def test_report_status_danger(self):
"""Test danger status."""
report = SafetyReport(total_criticals=1)
assert report.overall_status() == SafetyStatus.DANGER
def test_report_status_halted(self):
"""Test halted status."""
report = SafetyReport(simulation_halted=True)
assert report.overall_status() == SafetyStatus.HALTED
def test_report_summary(self):
"""Test report summary generation."""
report = SafetyReport(
total_warnings=2,
total_criticals=1,
simulation_halted=True
)
summary = report.summary()
assert "HALTED" in summary.upper()
assert "2" in summary
assert "1" in summary
# ============================================================================
# FAILURE SAFETY MONITOR TESTS
# ============================================================================
class TestFailureSafetyMonitor:
"""Test main failure safety monitor."""
def test_monitor_creation(self):
"""Test creating safety monitor."""
monitor = FailureSafetyMonitor()
assert monitor.auto_halt is True
assert monitor.halt_triggered is False
assert len(monitor.alerts) == 0
def test_nominal_step(self):
"""Test nominal step processing."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=100.0,
acceleration_magnitude=0.01,
energy=-1e20,
time_value=0.0
)
assert result is True # Should continue
assert len(monitor.alerts) == 0
assert monitor.get_status() == SafetyStatus.NOMINAL
def test_position_divergence(self):
"""Test position divergence detection."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([2e15, 0, 0]), # Way too far
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert result is False # Should halt
assert monitor.halt_triggered is True
assert monitor.get_status() == SafetyStatus.HALTED
assert len(monitor.alerts) > 0
assert monitor.alerts[0].check_name == "position_divergence"
def test_velocity_divergence(self):
"""Test velocity divergence detection."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([1e9, 0, 0]), # Way too fast
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert result is False
assert monitor.halt_triggered is True
assert monitor.alerts[0].check_name == "velocity_divergence"
def test_negative_mass(self):
"""Test negative mass detection."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=-50.0 # Negative!
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert result is False
assert monitor.halt_triggered is True
assert monitor.alerts[0].check_name == "negative_or_zero_mass"
def test_nan_detection(self):
"""Test NaN in state detection."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([np.nan, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert result is False
assert monitor.halt_triggered is True
assert monitor.alerts[0].check_name == "nan_inf_detection"
def test_cfl_warning(self):
"""Test CFL condition warning."""
monitor = FailureSafetyMonitor(
thresholds=SafetyThresholds(cfl_max_ratio=1.0)
)
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([1e7, 0, 0]), # Fast
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=100.0, # Large time step
acceleration_magnitude=0.01,
time_value=0.0
)
assert result is True # Warning doesn't halt
assert monitor.get_status() == SafetyStatus.WARNING
assert any(a.check_name == "cfl_violation" for a in monitor.alerts)
def test_high_acceleration_warning(self):
"""Test excessive acceleration detection."""
monitor = FailureSafetyMonitor(
thresholds=SafetyThresholds(max_acceleration_magnitude=1e3)
)
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=1e4, # Very high
time_value=0.0
)
assert result is True
assert len(monitor.alerts) > 0
assert monitor.alerts[0].check_name == "acceleration_high"
def test_energy_drift_warning(self):
"""Test energy drift detection."""
monitor = FailureSafetyMonitor(
thresholds=SafetyThresholds(max_energy_drift_percent=2.0)
)
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result1 = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
energy=1e20,
time_value=0.0
)
# Energy drift significantly
result2 = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
energy=1.1e20, # 10% change
time_value=1.0
)
assert result1 is True
assert result2 is True # Warning doesn't halt
assert any(a.check_name == "energy_drift_high" for a in monitor.alerts)
def test_callbacks_on_warning(self):
"""Test warning callbacks."""
monitor = FailureSafetyMonitor(
thresholds=SafetyThresholds(max_acceleration_magnitude=100)
)
callback_called = False
def on_warning_callback(alert):
nonlocal callback_called
callback_called = True
monitor.on_warning.append(on_warning_callback)
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=1e3,
time_value=0.0
)
assert callback_called is True
def test_callbacks_on_critical(self):
"""Test critical callbacks."""
monitor = FailureSafetyMonitor()
callback_called = False
def on_critical_callback(alert):
nonlocal callback_called
callback_called = True
monitor.on_critical.append(on_critical_callback)
state = MockState(
position=np.array([2e15, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert callback_called is True
def test_callbacks_on_halt(self):
"""Test halt callbacks."""
monitor = FailureSafetyMonitor()
halt_reason = None
def on_halt_callback(reason):
nonlocal halt_reason
halt_reason = reason
monitor.on_halt.append(on_halt_callback)
state = MockState(
position=np.array([2e15, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
assert halt_reason is not None
assert "Position divergence" in halt_reason
def test_auto_halt_disabled(self):
"""Test disabling auto-halt."""
monitor = FailureSafetyMonitor(auto_halt=False)
state = MockState(
position=np.array([2e15, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
time_value=0.0
)
# Alert created but halt not triggered
assert len(monitor.alerts) > 0
assert monitor.halt_triggered is False
assert result is True
def test_get_report(self):
"""Test generating safety report."""
monitor = FailureSafetyMonitor(
thresholds=SafetyThresholds(max_acceleration_magnitude=100)
)
state = MockState(
position=np.array([1e11, 0, 0]),
velocity=np.array([30000, 0, 0]),
mass=1000.0
)
# Generate warning
monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=1e3,
time_value=0.0
)
report = monitor.get_report()
assert report.total_warnings == 1
assert report.total_criticals == 0
assert report.simulation_halted is False
def test_multiple_steps(self):
"""Test monitoring multiple simulation steps."""
monitor = FailureSafetyMonitor()
state = MockState(
position=np.array([1e11, 1e9, 0]),
velocity=np.array([30000, 1000, 0]),
mass=1000.0
)
# Run 50 nominal steps
for i in range(50):
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=0.01,
energy=-1e20,
time_value=float(i)
)
assert result is True
assert monitor.step_count == 50
assert len(monitor.alerts) == 0
assert monitor.get_status() == SafetyStatus.NOMINAL
# ============================================================================
# INTEGRATION TESTS
# ============================================================================
class TestSafetyIntegration:
"""Integration tests with simulation scenarios."""
def test_moon_encounter_safety(self):
"""Test safety monitoring during Moon encounter."""
monitor = FailureSafetyMonitor()
# Spacecraft approaching Moon
# Position: 384,400 km from Earth → Moon
times = np.linspace(0, 100000, 1000)
for i, t in enumerate(times):
# Simple circular trajectory approaching
distance = 3.84e8 - t * 1000 # Approaching
state = MockState(
position=np.array([distance, 0, 0]),
velocity=np.array([0, 1000, 0]),
mass=1000.0
)
result = monitor.on_step_complete(
state=state,
dt=100.0,
acceleration_magnitude=0.01,
time_value=t
)
if not result:
break
# Should run to completion without halt
assert monitor.halt_triggered is False
assert monitor.get_status() == SafetyStatus.NOMINAL
def test_unstable_orbit_detection(self):
"""Test detecting unstable orbit conditions."""
monitor = FailureSafetyMonitor()
# Simulate degrading orbit
for i in range(100):
velocity_magnitude = 30000 + i * 500 # Increasing velocity
state = MockState(
position=np.array([6.371e6 + 400e3, 0, 0]),
velocity=np.array([0, velocity_magnitude, 0]),
mass=1000.0 - i * 1.0 # Losing mass
)
result = monitor.on_step_complete(
state=state,
dt=1.0,
acceleration_magnitude=1.0 + i * 0.1,
time_value=float(i),
energy=-1e20 - i * 1e18
)
if not result:
# Should halt on mass loss or other issue
assert monitor.halt_triggered is True
break
if __name__ == "__main__":
pytest.main([__file__, "-v"])