-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
803 lines (639 loc) · 31.7 KB
/
Copy pathcore.py
File metadata and controls
803 lines (639 loc) · 31.7 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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
"""Core data models for Heliosail-RX simulations.
MASTER DATA MODEL (STRICT CONTRACT)
═══════════════════════════════════════════════════════════════════════════════
This module defines IMMUTABLE STATE CONTAINERS that form the contracts between:
- Kernel (state manager) ← → Physics modules (computation units)
- Kernel ← → Storage layer (persistence)
- API ← → Kernel (mission execution)
KEY PRINCIPLE: Single Authority Rule
────────────────────────────────────
The Kernel is the ONLY component authorized to mutate state.
Physics modules are PURE FUNCTIONS: (state, environment, config) → output
No module-to-module communication allowed. Data flows ONLY through kernel.
DATA CONTAINERS
────────────────────────────────────
1. SpacecraftState (immutable)
- position, velocity: [position, velocity]
- attitude_quaternion, angular_velocity: [orientation, rotation rate]
- mass, power_available: [spacecraft properties]
- thermal_state, structural_modes: [internal subsystems]
- propulsion: [thrust capability]
2. EnvironmentState (immutable)
- solar_flux, magnetic_field: [solar conditions]
- solar_wind_density, radiation_index: [plasma/radiation]
3. PropulsionState (immutable)
- thrust_vector, mass_flow_rate, efficiency: [propulsion capability]
4. StateDerivative (immutable)
- velocity_derivative, acceleration: [dynamics rates]
- angular_acceleration: [attitude rates]
- power_derivative, mass_derivative: [property changes]
PHYSICS MODULE CONTRACT
────────────────────────────────────
Every physics module MUST:
1. Accept: PhysicsInput(state, environment, t_epoch, params)
2. Return: PhysicsOutput(state_derivative, diagnostics, events, valid)
3. Guarantee: Deterministic, reproducible computation
4. Never: Modify input state, communicate with other modules
INTEGRATION GUARANTEE
────────────────────────────────────
Freeze all dataclasses to prevent accidental mutations.
Kernel combines StateDerivatives from all modules via ODE integrator.
Result: Composable, testable, parallelize-able physics framework.
═══════════════════════════════════════════════════════════════════════════════
These dataclasses define the interface contracts between:
- Kernel and physics modules
- Physics modules and each other
- API and kernel
- Data storage and retrieval
All data is immutable (frozen dataclasses) to ensure thread-safety
and prevent accidental mutations. Physics computations are pure functions.
"""
from dataclasses import dataclass, field
from typing import Dict, List, Any, Optional, Tuple
from abc import ABC, abstractmethod
import time
from enum import Enum
# ============================================================================
# Enums & Constants
# ============================================================================
class SolverType(Enum):
"""Numerical integration schemes."""
RK4 = "rk4"
RK4_SYMPLECTIC = "rk4_symplectic"
RK45_ADAPTIVE = "rk45_adaptive"
BACKWARD_EULER = "backward_euler"
BDF = "bdf"
class PhysicsModuleType(Enum):
"""Category of physics computation."""
ORBITAL_MECHANICS = "orbital_mechanics"
SAIL_AERODYNAMICS = "sail_aerodynamics"
SAIL_THERMAL = "sail_thermal"
PROPULSION = "propulsion"
ENVIRONMENT = "environment"
GNC = "gnc"
STRUCTURE = "structure"
class EventType(Enum):
"""Types of discrete events in simulation."""
MANEUVER = "maneuver"
CME_ARRIVAL = "cme_arrival"
DEPLOYMENT = "deployment"
COLLISION = "collision"
ANOMALY = "anomaly"
MILESTONE = "milestone"
# ============================================================================
# Type Aliases (Master Data Model)
# ============================================================================
Vector3 = Tuple[float, float, float] # [x, y, z]
Quaternion = Tuple[float, float, float, float] # [q0, q1, q2, q3] (scalar first)
# ============================================================================
# MASTER DATA MODEL (STRICT CONTRACT)
# ============================================================================
# All physics modules receive these immutable state containers.
# No module-to-module communication; all data flows through kernel.
# ============================================================================
@dataclass(frozen=True)
class EnvironmentState:
"""Environmental conditions affecting spacecraft.
This captures the external environment the spacecraft experiences.
All environment models (solar cycle, CME, radiation) contribute to this.
"""
solar_flux: float # [W/m²] solar irradiance at spacecraft
magnetic_field: Vector3 # [T] inertial frame magnetic field
solar_wind_density: float # [kg/m³] plasma density
radiation_index: float # [0-10] radiation belt index (Kp-like)
epoch_sec: float = 0.0 # absolute time [s since J2000]
def to_dict(self) -> Dict[str, Any]:
return {
"solar_flux": self.solar_flux,
"magnetic_field": self.magnetic_field,
"solar_wind_density": self.solar_wind_density,
"radiation_index": self.radiation_index,
"epoch_sec": self.epoch_sec,
}
@dataclass(frozen=True)
class PropulsionState:
"""Propulsion system state.
Captures current thrust capability and performance.
"""
thrust_vector: Vector3 # [N] thrust in inertial frame
mass_flow_rate: float # [kg/s] propellant consumption
efficiency: float # [0-1] thruster efficiency
fuel_remaining_kg: float = 0.0 # [kg] remaining propellant
def to_dict(self) -> Dict[str, Any]:
return {
"thrust_vector": self.thrust_vector,
"mass_flow_rate": self.mass_flow_rate,
"efficiency": self.efficiency,
"fuel_remaining_kg": self.fuel_remaining_kg,
}
@dataclass(frozen=True)
class SpacecraftState:
"""Complete spacecraft state - the central data contract.
This immutable state container is passed into EVERY physics module.
No module has write access; the kernel is the single point of mutation.
Strict Contract:
- All vectors in inertial frame unless noted
- All physical quantities in SI units
- Attitude represented as normalized quaternion [q0, q1, q2, q3]
- All fields are frozen (immutable) to prevent accidental mutations
"""
# PRIMARY DYNAMICS
position: Vector3 # [m] inertial frame
velocity: Vector3 # [m/s] inertial frame
# ATTITUDE
attitude_quaternion: Quaternion # [q0, q1, q2, q3] unitless, normalized
angular_velocity: Vector3 # [rad/s] inertial frame
# SPACECRAFT PROPERTIES
mass: float # [kg] total spacecraft mass
power_available: float # [W] available electrical power
# INTERNAL STATES
thermal_state: Dict[str, float] # [K] subsystem temperatures
structural_modes: Tuple[float, ...] # structural deformation modes (FEM)
# PROPULSION
propulsion: PropulsionState = field(default_factory=lambda: PropulsionState(
thrust_vector=(0.0, 0.0, 0.0),
mass_flow_rate=0.0,
efficiency=0.0,
fuel_remaining_kg=0.0
))
# METADATA
degradation_factor: float = 1.0 # [0-1] optical health multiplier
epoch_sec: float = 0.0 # [s] absolute time since J2000
mission_elapsed_sec: float = 0.0 # [s] time since mission start
valid: bool = True # state is physically valid
# (LEGACY COMPATIBILITY - deprecated, kept for backward compatibility)
r: Vector3 = field(init=False) # reference to position
v: Vector3 = field(init=False) # reference to velocity
q: Quaternion = field(init=False) # reference to attitude_quaternion
omega: Vector3 = field(init=False) # reference to angular_velocity
membrane_state: Optional[Dict[str, float]] = None # [DEPRECATED] use thermal_state
power_state: Optional[Dict[str, float]] = None # [DEPRECATED] use power_available
def __post_init__(self):
"""Set up legacy field references for backward compatibility."""
object.__setattr__(self, 'r', self.position)
object.__setattr__(self, 'v', self.velocity)
object.__setattr__(self, 'q', self.attitude_quaternion)
object.__setattr__(self, 'omega', self.angular_velocity)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"position": self.position,
"velocity": self.velocity,
"attitude_quaternion": self.attitude_quaternion,
"angular_velocity": self.angular_velocity,
"mass": self.mass,
"power_available": self.power_available,
"degradation_factor": self.degradation_factor,
"thermal_state": self.thermal_state,
"structural_modes": self.structural_modes,
"propulsion": self.propulsion.to_dict() if self.propulsion else None,
"epoch_sec": self.epoch_sec,
"mission_elapsed_sec": self.mission_elapsed_sec,
"valid": self.valid,
}
# ============================================================================
# Physics Module Interface (Strict Contract)
# ============================================================================
@dataclass(frozen=True)
class StateDerivative:
"""Change in state (delta_state) - output of physics computation.
This represents dr/dt, dv/dt, etc. for ODE integration.
All physics modules return this format.
"""
velocity_derivative: Vector3 # dr/dt = v [m/s]
acceleration: Vector3 # dv/dt [m/s²]
angular_acceleration: Vector3 # dω/dt [rad/s²]
power_derivative: float = 0.0 # dP/dt [W] (negative = consumption)
mass_derivative: float = 0.0 # dm/dt [kg/s] (negative = mass loss)
degradation_rate: float = 0.0 # d(deg)/dt [1/s] (negative = health loss)
thermal_derivatives: Dict[str, float] = field(default_factory=dict) # dT/dt [K/s]
def to_dict(self) -> Dict[str, Any]:
return {
"velocity_derivative": self.velocity_derivative,
"acceleration": self.acceleration,
"angular_acceleration": self.angular_acceleration,
"power_derivative": self.power_derivative,
"mass_derivative": self.mass_derivative,
"degradation_rate": self.degradation_rate,
"thermal_derivatives": self.thermal_derivatives,
}
@dataclass(frozen=True)
class PhysicsInput:
"""STRICT INTERFACE CONTRACT: Input to physics module.
Every physics module receives:
- state: Complete spacecraft state (immutable)
- environment: Current environmental conditions
- config: Module-specific configuration
Pattern: module.compute(PhysicsInput) -> PhysicsOutput
"""
state: SpacecraftState # current spacecraft state
environment: EnvironmentState # current environment
t_epoch: float # absolute time [s]
params: Dict[str, Any] # module-specific configuration
# (LEGACY COMPATIBILITY)
_legacy_params: Optional[Dict[str, Any]] = None
@dataclass(frozen=True)
class PhysicsOutput:
"""STRICT INTERFACE CONTRACT: Output from physics module.
Every physics module returns:
- state_derivative: Change in state (for ODE integration)
- diagnostics: Scalar measurements for logging
- events: Discrete occurrences detected
- valid: Whether computation succeeded
"""
state_derivative: StateDerivative # change in state (delta_state)
# Additional measurements
diagnostics: Dict[str, float] = field(default_factory=dict)
"""Scalar quantities: irradiance, drag force, temperature, efficiency, etc."""
# Event detection
events: List['Event'] = field(default_factory=list)
"""Discrete occurrences (deployment, threshold crossing, anomaly)"""
# Success indicator
valid: bool = True
"""Computation succeeded and output is physically reasonable"""
# ============================================================================
# Abstract Physics Module Interface (Contract Definition)
# ============================================================================
# This defines what every physics module MUST implement.
# ============================================================================
# MODULE INTERFACE CONTRACT
# ============================================================================
# Every physics module MUST implement these methods. No exceptions.
# ============================================================================
class PhysicsModule(ABC):
"""Abstract base class for physics modules.
MODULE INTERFACE CONTRACT (MANDATORY METHODS):
═════════════════════════════════════════════════════════════════════════
All physics modules MUST implement:
1. initialize(config: Dict) → None
- Called once at module startup
- Setup internal state, validate configuration
- Return silently on success; raise exception if invalid
2. compute_derivatives(state: SpacecraftState, environment: EnvironmentState,
t: float) → StateDerivative
- Pure function: same inputs → identical output
- No exceptions: must handle edge cases gracefully
- Return valid StateDerivative or zero-derivatives on failure
3. compute_outputs(state: SpacecraftState, environment: EnvironmentState,
t: float) → Dict[str, Any]
- Return diagnostic/telemetry data only (no state mutation)
- Should mirror diagnostics() but takes state parameters
- Use for real-time output in simulation loops
4. validate() → bool
- Check module internal state is consistent
- Return True if valid, False otherwise
- Used before/after integration steps for data integrity
5. diagnostics() → Dict[str, Any]
- Return module-specific metrics (for logging/debugging)
- Must return Dict (empty dict if no diagnostics)
- Called after each compute step for telemetry
6. get_required_state_fields() → List[str]
- Declare which state fields this module reads
- Example: ['position', 'velocity', 'mass', 'sail_normal']
- Used for dependency analysis and validation
7. get_updated_state_fields() → List[str]
- Declare which derivative fields this module contributes
- Example: ['acceleration', 'angular_acceleration']
- Used for dependency analysis and field tracking
LEGACY INTERFACE (Deprecated but supported):
8. compute(physics_input: PhysicsInput) → PhysicsOutput
- Old interface, kept for backward compatibility
- New modules should use compute_derivatives() instead
- Kernel will route PhysicsInput → (state, environment) → compute_derivatives
STRICT GUARANTEES:
─────────────────────────────────────────────────────────────────────────
✓ Deterministic: f(x) = f(x) always, for same seed
✓ Pure: No side effects, no module communication
✓ Immutable: All inputs are frozen dataclasses
✓ Idempotent diagnostics: Can call multiple times safely
✓ No exceptions on failure: Graceful degradation always
✓ Thread-safe: No shared mutable state with other modules
ERROR HANDLING (No Exceptions):
─────────────────────────────────────────────────────────────────────────
Modules MUST NOT raise exceptions. Instead:
- In compute_derivatives: Return StateDerivative with zero/default values
Include error info in accompanying diagnostics
- In initialize/validate: Log errors, set internal flag, continue
- Always return a valid dict/bool/StateDerivative, never None
IMPLEMENTATION PATTERN:
─────────────────────────────────────────────────────────────────────────
class MyPhysicsModule(PhysicsModule):
def __init__(self):
self.config = None
self.is_valid = False
self.last_error = None
def initialize(self, config: Dict):
try:
# Validate config, setup internal state
self.config = config
self.is_valid = True
except Exception as e:
self.last_error = str(e)
self.is_valid = False
# Log but don't raise
def compute_derivatives(self, state: SpacecraftState,
environment: EnvironmentState, t: float) -> StateDerivative:
try:
# Compute physics
result = StateDerivative(...)
self.last_error = None
except Exception as e:
# Return zero-derivatives on failure
result = StateDerivative(
velocity_derivative=(0, 0, 0),
acceleration=(0, 0, 0),
angular_acceleration=(0, 0, 0)
)
self.last_error = str(e)
return result
def validate(self) -> bool:
return self.is_valid
def diagnostics(self) -> Dict[str, Any]:
diags = {
'is_valid': self.is_valid,
'last_error': self.last_error,
# ... add module-specific metrics
}
return diags
def get_module_type(self) -> PhysicsModuleType:
return PhysicsModuleType.ORBITAL_MECHANICS
═════════════════════════════════════════════════════════════════════════
INPUT/OUTPUT TYPES:
─────────────────────────────────────────────────────────────────────────
- Input: PhysicsInput(state, environment, t_epoch, params)
- Output: PhysicsOutput(state_derivative, diagnostics, events, valid)
- Constraint: NO module-to-module communication
- Constraint: Module is a pure function (no side effects on kernel state)
"""
@abstractmethod
def initialize(self, config: Dict[str, Any]) -> None:
"""Initialize module with configuration.
Called once at startup. Must not raise exceptions.
Set internal error flag and continue if config is invalid.
Args:
config: Configuration dictionary for this module
Raises:
None (log errors internally, no exceptions)
"""
pass
@abstractmethod
def compute_derivatives(self, state: 'SpacecraftState',
environment: 'EnvironmentState', t: float) -> 'StateDerivative':
"""Compute state derivatives.
Pure function: same inputs MUST produce same output.
MUST NOT raise exceptions. Return zero-derivatives on failure.
Args:
state: Current spacecraft state (immutable)
environment: Current environment state (immutable)
t: Absolute simulation time [seconds]
Returns:
StateDerivative with computed derivatives (never None)
Raises:
None (handle all errors gracefully, return zero-derivatives)
"""
pass
@abstractmethod
def compute_outputs(self, state: 'SpacecraftState',
environment: 'EnvironmentState', t: float) -> Dict[str, Any]:
"""Compute diagnostic outputs.
Return diagnostic/telemetry data based on state and environment.
Pure function: no side effects, no state mutation.
MUST NOT raise exceptions.
Args:
state: Current spacecraft state (immutable)
environment: Current environment state (immutable)
t: Absolute simulation time [seconds]
Returns:
Dictionary of diagnostic outputs (never None, empty dict acceptable)
Raises:
None (handle all errors gracefully)
"""
pass
@abstractmethod
def validate(self) -> bool:
"""Validate module state consistency.
Check that internal state is valid and module is ready to compute.
Called before/after integration steps.
Returns:
True if module is valid, False if internal error detected
"""
pass
@abstractmethod
def diagnostics(self) -> Dict[str, Any]:
"""Get module diagnostics and metrics.
Called after each compute step. Return module-specific metrics
for logging, debugging, and telemetry.
Returns:
Dictionary of diagnostic data (never None, empty dict acceptable)
"""
pass
@abstractmethod
def compute(self, physics_input: PhysicsInput) -> PhysicsOutput:
"""Compute physics for this step.
Args:
physics_input: Complete state snapshot + environment + config
Returns:
physics_output: State derivatives + diagnostics + events
Guarantees:
- No modification of input state (immutable dataclass)
- No communication with other modules
- Deterministic output given same input and seed
"""
pass
@abstractmethod
def get_module_type(self) -> PhysicsModuleType:
"""Return the type of physics this module computes."""
pass
@abstractmethod
def get_required_state_fields(self) -> List[str]:
"""Declare which state fields this module reads.
Example: ['position', 'velocity', 'mass', 'sail_normal', 'sail_area']
Returns:
List of state field names this module depends on
"""
pass
@abstractmethod
def get_updated_state_fields(self) -> List[str]:
"""Declare which derivative fields this module contributes.
Example: ['acceleration', 'angular_acceleration', 'mass_rate']
Returns:
List of state derivative field names this module updates
"""
pass
def get_name(self) -> str:
"""Return human-readable name. Override for custom names."""
return self.__class__.__name__
# ============================================================================
# Events & Actions
# ============================================================================
@dataclass(frozen=True)
class Event:
"""Discrete occurrence during simulation."""
type: EventType
t_epoch: float # when it occurred [s]
description: str # human-readable summary
data: Dict[str, Any] = field(default_factory=dict) # event-specific data
handler_fn: Optional[str] = None # name of callback to invoke
@dataclass(frozen=True)
class StateAction:
"""Directive to modify state (e.g., from GNC, deployment)."""
description: str
apply_fn: str # name of action function
args: Dict[str, Any] # arguments to apply_fn
t_epoch: float = 0.0
# ============================================================================
# Configuration
# ============================================================================
@dataclass(frozen=True)
class SpacecraftConfig:
"""Spacecraft parameters (mass, geometry, materials)."""
name: str = "spacecraft"
mass_dry_kg: float = 260.0 # kg
mass_fuel_kg: float = 0.0 # kg
# Sail
sail_area_m2: float = 196.0 # m²
sail_reflectivity: float = 0.85 # [0, 1]
sail_thickness_um: float = 2.5
# Moment of inertia (principal axes)
inertia_kgm2: Tuple[float, float, float] = (100.0, 100.0, 100.0)
@dataclass(frozen=True)
class EnvironmentConfig:
"""Environmental model selections."""
use_solar_cycle: bool = True
use_cme: bool = False
use_radiation_belts: bool = True
use_atmospheric_drag: bool = True
use_third_body: bool = True
use_relativistic: bool = False
@dataclass(frozen=True)
class PhysicsConfig:
"""Which physics modules to enable."""
enabled_modules: Dict[PhysicsModuleType, bool] = field(
default_factory=lambda: {
PhysicsModuleType.ORBITAL_MECHANICS: True,
PhysicsModuleType.SAIL_AERODYNAMICS: True,
PhysicsModuleType.ENVIRONMENT: True,
}
)
module_params: Dict[str, Dict[str, Any]] = field(default_factory=dict)
@dataclass(frozen=True)
class SolverConfig:
"""Numerical integration settings."""
solver: SolverType = SolverType.RK4_SYMPLECTIC
dt_nominal: float = 10.0 # nominal time step [s]
dt_min: float = 0.1 # minimum (adaptive)
dt_max: float = 100.0 # maximum (adaptive)
max_steps: int = 1_000_000
rtol: float = 1e-6 # relative tolerance
atol: float = 1e-9 # absolute tolerance
energy_monitor: bool = True
@dataclass(frozen=True)
class SimulationConfig:
"""Top-level simulation configuration."""
name: str = "mission"
t_start: float = 0.0
t_end: float = 86400.0 # 1 day by default
spacecraft: SpacecraftConfig = field(default_factory=SpacecraftConfig)
environment: EnvironmentConfig = field(default_factory=EnvironmentConfig)
physics: PhysicsConfig = field(default_factory=PhysicsConfig)
solver: SolverConfig = field(default_factory=SolverConfig)
# Initialization
initial_state: Optional[SpacecraftState] = None
# Output
telemetry_step_s: float = 100.0 # log every N seconds
checkpoint_step_s: float = 86400.0 # checkpoint every N seconds
# Reproducibility
seed: int = 42
commit_hash: Optional[str] = None
description: str = ""
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"name": self.name,
"t_start": self.t_start,
"t_end": self.t_end,
"telemetry_step_s": self.telemetry_step_s,
"checkpoint_step_s": self.checkpoint_step_s,
"seed": self.seed,
"description": self.description,
}
# ============================================================================
# Time Management
# ============================================================================
@dataclass(frozen=True)
class TimeStep:
"""Information for a completed time step."""
t_epoch: float # absolute time [s]
mission_elapsed: float # since t_start [s]
dt: float # time step taken [s]
step_num: int # step counter
converged: bool = True # integration converged
# ============================================================================
# Simulation Results
# ============================================================================
@dataclass(frozen=True)
class SimulationStep:
"""Result of one time step."""
time_info: TimeStep
state: SpacecraftState
accelerations: Dict[str, Tuple[float, float, float]] # acceleration from each module
events: List[Event] = field(default_factory=list)
diagnostics: Dict[str, float] = field(default_factory=dict)
"""Aggregated diagnostics from all physics modules"""
@dataclass
class SimulationResult:
"""Complete simulation output."""
config: SimulationConfig
trajectory: List[SimulationStep] # all states + output
telemetry: Dict[str, List[Tuple[float, float]]] # (t, value) pairs
events: List[Event] = field(default_factory=list)
audit_log: List[Dict[str, Any]] = field(default_factory=list)
# Metadata
run_start_time: float = field(default_factory=time.time)
run_end_time: float = 0.0
elapsed_wall_time_sec: float = 0.0
n_steps: int = 0
success: bool = True
error_message: str = ""
def summary(self) -> Dict[str, Any]:
"""Return summary statistics."""
if not self.trajectory:
return {"error": "empty trajectory"}
first = self.trajectory[0]
last = self.trajectory[-1]
return {
"mission_name": self.config.name,
"t_start": self.config.t_start,
"t_end": self.config.t_end,
"n_steps": len(self.trajectory),
"wall_time_sec": self.elapsed_wall_time_sec,
"final_state_valid": last.state.valid,
"n_events": len(self.events),
}
# ============================================================================
# Audit & Reproducibility
# ============================================================================
@dataclass(frozen=True)
class AuditEntry:
"""Single entry in audit log."""
timestamp: float # when action occurred
action_type: str # e.g., "init", "event", "error"
description: str
data: Dict[str, Any] = field(default_factory=dict)
# ============================================================================
# API Request/Response Models
# ============================================================================
@dataclass
class MissionRequest:
"""Request to execute a mission."""
config: SimulationConfig
job_name: str = "default_run"
tags: Dict[str, str] = field(default_factory=dict)
@dataclass
class MissionResponse:
"""Response from mission execution."""
job_id: str
status: str # "pending", "running", "complete", "failed"
result: Optional[SimulationResult] = None
error: Optional[str] = None
timestamp: float = field(default_factory=time.time)