Trajectory#
- class Trajectory(ref_frame=None, origin=None, body=None, degree_poly: int = 3, parameters=None, offset=None, STMs=None, STMs_timestamp=None, propagator_settings_dict=None, state_array=None, leg_array=None, mass_profile=None)#
Bases:
objectRepresents a spacecraft or celestial object’s trajectory in a defined reference frame and origin.
This class encapsulates trajectory data, including position, velocity, estimated parameters, and state transition matrices (STMs). It supports both single-phase trajectories and multi-leg mission sequences.
The trajectory stores the discrete time history \(\{(t_i,\,\mathbf{r}_i,\,\dot{\mathbf{r}}_i)\}_{i=0}^{N}\) and writes it into a SPICE SPK kernel so that the state at any epoch \(t \in [t_0, t_N]\) can be retrieved via polynomial interpolation:
\[\mathbf{r}(t) \approx \sum_{k=0}^{d} c_k\,t^k\]where \(d\) is
degree_poly(default 3).The trajectory can be initialized using:
Explicit position, velocity, and epoch inputs.
A
StateArraydirectly from a propagator.
- Parameters:
name (
str) – The name of the trajectory.ref_frame (
str, optional) – The reference frame in which the trajectory is defined (e.g.,"J2000"). Defaults toNone.origin (
str, optional) – The origin of the trajectory (e.g.,"SUN"). Defaults toNone.body (
CelestialBody, optional) – The celestial body or spacecraft associated with this trajectory. Defaults toNone.degree_poly (
int, optional) – The degree of the polynomial used for SPICE interpolation. Defaults to3.parameters (
listofArrayWUnits, optional) – Additional estimated parameters related to the trajectory (e.g., range biases, solar radiation pressure coefficients). Defaults toNone.offset (
ArrayWUnits, optional) – A fixed position offset for coordinate transformations. Defaults toNone.STMs (
list, optional) – The state transition matrices (STMs) associated with the trajectory. Defaults toNone.propagator_settings_dict (
dict, optional) – A dictionary of propagator settings for numerical integration. Defaults toNone.state_array (
StateArray, optional) – If provided, initializes the trajectory from a propagated StateArray, extracting position, velocity, epoch, reference frame, and parameters. Defaults toNone.
- Raises:
If both
state_definitionandsequence_definitionare provided simultaneously.If both standard trajectory inputs and a
StateArrayare provided.If
StateArrayis missing position or velocity components.
Exception – If the trajectory contains fewer than two data points.
Notes
If
state_definitionis provided, the trajectory follows a single continuous model.If
sequence_definitionis used, the trajectory consists of multiple segments (e.g., before and after a maneuver).The trajectory is stored in a SPICE kernel format for interpolation and retrieval.
Saving to disk — SPK and JSON sidecars
Calling
write_to_spk()writes two kinds of files that always live next to each other:SPK binary (
<name>.bsp) — the position/velocity time-series in SPICE type-9 (Lagrange interpolating polynomial) format. State at any epoch inside the covered arc is retrieved via SPICE polynomial interpolation.JSON sidecars — plain-text files written alongside the
.bspwith the same base name and the suffixes listed below. They carry metadata that cannot be embedded in a standard SPK segment:<name>_parameters.json— time-history of estimated parameters (e.g. range biases, SRP coefficients, empirical accelerations), plus the full state definition that describes what each column represents.<name>_STMs.json— state transition matrices and their timestamps (written only when STMs are attached viaadd_STMs()).<name>_settings.json— serialisedpropagator_settings_dict(force model, integrator tolerances, etc.) so the trajectory can be reproduced.<name>_mass_profile.json— polynomial coefficients of the spacecraft mass as a function of time (written only when amass_profileis provided).
Each sidecar is optional: the file is created only when the corresponding data is not
None. All four sidecars share the same path prefix as the.bspso that loading the kernel and its associated metadata is unambiguous.Examples
Standard Initialization:
import scarabaeus as scb # Define epochs epoch_start = scb.SpiceManager.jd2et(2461809.72995654) epoch_end = scb.SpiceManager.jd2et(2461809.72995654 + 1) epochs = scb.EpochArray(np.linspace(epoch_start, epoch_end, 100),sys="TDB") # Define position and velocity position = scb.ArrayWUnits(np.random.rand(100, 3), "km") velocity = scb.ArrayWUnits(np.random.rand(100, 3), "km/s") # Initialize trajectory traj = scb.Trajectory( name="Test_Trajectory", position=position, velocity=velocity, epoch=epochs, ref_frame="J2000", origin="SUN", body=scb.CelestialBody.from_constants("EARTH") ) # Retrieve state at a given epoch state = traj.get_state(epochs[0]) >>> print("Position:", state["position"]) 'Position: [0.123, 0.456, 0.789] [km]'
Alternative Initialization from a Propagator:
# Initialize trajectory using propagated StateArray traj = scb.Trajectory("Orbiter_trajectory", state_array=propagated_state_array)
See also
scarabaeus.MissionSequenceMulti-leg trajectory container.
scarabaeus.PropagatorNumerical propagator that produces trajectory data.
scarabaeus.StateArrayState vector passed to the propagator.
- Attributes:
STMsThe state transition matrices (STMs) associated with the trajectory.
STMs_timestampThe epochs at which each STM was generated.
bodyThe celestial body or spacecraft associated with the trajectory.
end_epochThe end epoch of the trajectory.
epochThe epochs associated with the trajectory.
offsetA fixed position offset for coordinate transformations.
originThe origin of the trajectory.
parametersAdditional estimated parameters associated with the trajectory.
poly_degThe degree of the polynomial used for interpolation.
positionThe position history of the trajectory in the specified reference frame.
propagator_settings_dictThe dictionary of propagator settings for numerical integration.
ref_frameThe reference frame of the trajectory.
sequence_definitionThe mission sequence definition governing the trajectory’s structure.
spk_pathThe filepath for the Trajectory’s associated SPK file.
start_epochThe start epoch of the trajectory.
state_definitionThe definition of the trajectory’s state vector.
velocityThe velocity history of the trajectory in the specified reference frame.
Methods
add_STMs(STMs[, timestamps])Associates state transition matrices (STMs) with the trajectory.
get_STM(epoch[, idx, max_interp_error])Retrieve the State Transition Matrix (STM) at a given epoch or by index.
get_STM_JSON(epoch_input[, origin_input, ...])Retrieves the state transition matrix (STM) at a specified epoch from JSON file.
get_STM_sequence(epoch[, idx, idx_leg, ...])Retrieve/interpolate the STM at epoch for BOTH: - non-sequence: self._STMs is (N, n^2) and self._STMs_timestamp is (N,) - sequence: self._STMs is list-of-arrays, one per leg (or per segment-block)
get_offset_position(epoch_input[, ...])Computes the trajectory position with an applied constant offset.
get_state(epoch_input[, origin_input, ...])Retrieves the trajectory state at a specified epoch.
set_offset(offset)Sets the constant position offset for the trajectory.
write_to_spk(spk_path)Write the trajectory to disk as a SPICE SPK file plus JSON sidecars.
- add_STMs(STMs: list, timestamps: List = None)#
Associates state transition matrices (STMs) with the trajectory.
- Parameters:
STMs (
listorArrayWFrame) – A list of state transition matrices or a single ArrayWFrame object.
- get_STM(epoch: float, idx: int = None, max_interp_error: float = 2.0) ndarray#
Retrieve the State Transition Matrix (STM) at a given epoch or by index.
Uses binary search for efficient lookup and linear interpolation between stored STMs. Includes optional error checking for interpolation quality.
- Parameters:
epoch (
float) – The time at which to retrieve/interpolate the STMidx (
int, optional) – Direct index into the STM array (used when timestamps unavailable)max_interp_error (
float, optional) – Maximum allowable Frobenius norm error for interpolation (default: 1e-6) Set to None to disable error checking
- Returns:
The STM reshaped as a square matrix
- Return type:
np.ndarray- Raises:
ValueError – If neither timestamps nor index provided, epoch not found, or interpolation error exceeds threshold
- get_STM_JSON(epoch_input, origin_input=None, ref_frame_input=None, idx_leg_input=None, folder_path_override=None) dict#
Retrieves the state transition matrix (STM) at a specified epoch from JSON file.
Queries SpiceManager to obtain the STM corresponding to a given epoch, considering optional reference frame and origin transformations.
- Parameters:
epoch_input (
EpochArray) – The epoch at which to retrieve the STM.origin_input (
str, optional) – Custom origin for the STM retrieval. Defaults to the trajectory’s origin.ref_frame_input (
str, optional) – Custom reference frame for the STM retrieval. Default is the trajectory’s reference frame.idx_leg_input (
int, optional) – The index of the trajectory leg to retrieve if the trajectory is sequence-based. Defaults toNone.
- Returns:
stm – The queried STM, containing:
"STM": numpy.ndarray = The state transition matrix."epoch": EpochArray = The requested epoch."state_definition": dict = The state definition used."propagator_settings": dict = The settings used for propagation, if available.
- Return type:
- get_STM_sequence(epoch: float, idx: int = None, idx_leg: int = None, max_interp_error: float = 2, tol_time: float = 1e-09) ndarray#
Retrieve/interpolate the STM at epoch for BOTH: - non-sequence: self._STMs is (N, n^2) and self._STMs_timestamp is (N,) - sequence: self._STMs is list-of-arrays, one per leg (or per segment-block)
Behavior (sequence): - if idx_leg is given: interpolate within that leg - else: auto-detect leg from self._legs[*][“epoch_leg”] if available,
otherwise fall back to using global timestamps if provided.
Notes
Works with flat STMs stored as length n^2 vectors.
Uses linear interpolation in coefficient space.
Handles exact hits within tol_time.
- get_offset_position(epoch_input, origin_input=None, ref_frame_input=None) ArrayWUnits#
Computes the trajectory position with an applied constant offset.
If a reference frame transformation is required, the offset is rotated accordingly. The method also accounts for origin shifts when necessary.
- Parameters:
epoch_input (
EpochArray) – The epoch at which to compute the offset position.origin_input (
str, optional) – Custom origin for position computation. Defaults to the trajectory’s origin.ref_frame_input (
str, optional) – Custom reference frame for position computation. Defaults to the trajectory’s reference frame.
- Returns:
offset_pos – The computed position including the constant offset. Expressed in units of kilometers.
- Return type:
- get_state(epoch_input: EpochArray, origin_input=None, ref_frame_input=None, idx_leg_input=None, folder_path_override=None)#
Retrieves the trajectory state at a specified epoch.
Queries SPICE to obtain position, velocity, and any associated parameters for a given epoch, considering optional reference frame and origin transformations.
- Parameters:
epoch_input (
EpochArray) – The epoch at which to compute the state.origin_input (
str, optional) – Custom origin for the state computation. Defaults to the trajectory’s origin.ref_frame_input (
str, optional) – Custom reference frame for the state computation. Defaults to the trajectory’s reference frame.idx_leg_input (
int, optional) – The index of the trajectory leg to retrieve if the trajectory is sequence-based. Defaults toNone.folder_path_override (
str, optional) – Override path for JSON sidecar retrieval. If provided, this path will be used instead of the SPK’s directory when looking for parameters and propagator settings JSON files. Defaults toNone.
- Returns:
state – The queried state, containing:
"position": ArrayWUnits = The position vector. Expressed in units of kilometers."velocity": ArrayWUnits = The velocity vector. Expressed in units of \(\frac{km}{s}\)"epoch": EpochArray = The requested epoch."parameters"= Any estimated parameters, if available."state_definition": dict = The state definition used."propagator_settings": dict = The settings used for propagation, if available.
- Return type:
- set_offset(offset: ArrayWUnits) None#
Sets the constant position offset for the trajectory.
- Parameters:
offset (
ArrayWUnits) – The constant offset in position. Expressed in units of kilometers.- Return type:
- write_to_spk(spk_path: str) None#
Write the trajectory to disk as a SPICE SPK file plus JSON sidecars.
The
.bspfile contains the position/velocity time-series (SPICE type-9 Lagrange segments). Additional data that cannot be embedded in an SPK segment is written as plain-text JSON files with the same base path:<spk_path base>_parameters.json— estimated parameters and state definition (written whenparametersis notNone).<spk_path base>_settings.json— propagator settings dictionary (written whenpropagator_settings_dictis notNone).<spk_path base>_mass_profile.json— spacecraft mass polynomial (written when amass_profilewas passed at construction time).<spk_path base>_STMs.json— state transition matrices (written when STMs are attached; currently disabled pending refactor).
Each sidecar is created only when the corresponding data is present. All files share the same directory and path prefix as the
.bsp.- Parameters:
spk_path (
str) – Destination file path. Must end with.bsp.- Raises:
ValueError – If
spk_pathdoes not end with.bsp.UserWarning – If this
Trajectoryalready has an associated SPK at a different path.
Examples
traj.write_to_spk("/output/mission.bsp") # Produces: mission.bsp, mission_parameters.json, # mission_settings.json (if propagator settings exist)
- property STMs_timestamp: List | None#
The epochs at which each STM was generated. Must correspond one-to-one with the STMs list.
- property end_epoch: EpochArray#
The end epoch of the trajectory.
- property epoch: EpochArray#
The epochs associated with the trajectory.
- property offset: ArrayWUnits#
A fixed position offset for coordinate transformations.
- property parameters: list#
Additional estimated parameters associated with the trajectory. These parameters include mission-specific estimated values, such as:
Ground station range biases (e.g., clock offsets, tropospheric delays).
Additional environmental parameters (e.g., solar radiation pressure coefficients).
Model calibration parameters (e.g., empirical accelerations).
If no additional parameters exist, returns
None.
- property position: ArrayWUnits#
The position history of the trajectory in the specified reference frame.
- property propagator_settings_dict: dict | None#
The dictionary of propagator settings for numerical integration.
- property sequence_definition: MissionSequence#
The mission sequence definition governing the trajectory’s structure. This property is used when the trajectory consists of multiple segments (legs), where different state definitions or models are required for each segment. It is typically used for:
Handling maneuvers (e.g., impulsive burns).
Multi-phase missions with different dynamical regimes.
Modeling spacecraft transitions between different reference frames.
- property spk_path: str | None#
The filepath for the Trajectory’s associated SPK file. Returns
Noneif no file exists.
- property start_epoch: EpochArray#
The start epoch of the trajectory.
- property state_definition: dict#
The definition of the trajectory’s state vector. This describes the structure of the estimated state, specifying:
Which variables are included in the state (e.g., position, velocity, parameters).
Whether they are dynamic or static.
Their associated reference objects (e.g., spacecraft, ground stations).
- property velocity: ArrayWUnits#
The velocity history of the trajectory in the specified reference frame.