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, use_saved_stms: bool = False, max_interp_error: float | None = 0.001, per_body_spk: bool = False)#
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 Hermite interpolation, which constrains the position curve with the sampled velocities:
\[\mathbf{r}(t) \approx \sum_{k=0}^{d} c_k\,t^k, \qquad \mathbf{r}(t_i) = \mathbf{r}_i, \quad \dot{\mathbf{r}}(t_i) = \dot{\mathbf{r}}_i\]where \(d\) is
degree_poly(default 3). The degree is always odd: each node supplies both a position and a velocity, so a window of \((d+1)/2\) nodes fixes all \(d+1\) coefficients.The trajectory can be initialized using:
Explicit position, velocity, and epoch inputs.
A
StateArraydirectly from a propagator.
- Parameters:
- namestr
The name of the trajectory.
- ref_framestr, optional
The reference frame in which the trajectory is defined (e.g.,
"J2000"). Defaults toNone.- originstr, optional
The origin of the trajectory (e.g.,
"SUN"). Defaults toNone.- bodyCelestialBody, optional
The celestial body or spacecraft associated with this trajectory. Defaults to
None.- degree_polyint, optional
The degree of the Hermite polynomial used for SPICE interpolation. Must be odd; the interpolation window spans
(degree_poly + 1) // 2states. Defaults to3, the two-node cubic, which is the only degree whose interpolant is continuous across every node.- parameterslist of ArrayWUnits, optional
Additional estimated parameters related to the trajectory (e.g., range biases, solar radiation pressure coefficients). Defaults to
None.- offsetArrayWUnits, optional
A fixed position offset for coordinate transformations. Defaults to
None.- STMslist, optional
The state transition matrices (STMs) associated with the trajectory. Defaults to
None.- propagator_settings_dictdict, optional
A dictionary of propagator settings for numerical integration. Defaults to
None.- state_arrayStateArray, optional
If provided, initializes the trajectory from a propagated StateArray, extracting position, velocity, epoch, reference frame, and parameters. Defaults to
None.- per_body_spkbool, optional
When the trajectory holds several bodies, write one SPK per body rather than a single file with a segment per body. See
per_body_spk. Defaults toFalse.- max_interp_errorfloat or None, optional
Relative tolerance applied when an STM lookup falls between two stored epochs and has to interpolate. See
max_interp_error, which also sets it after construction.Noneskips the check. Defaults to1e-3.
- 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.
max_interp_errorRelative tolerance on linear interpolation of the STM.
offsetA fixed position offset for coordinate transformations.
originThe origin of the trajectory.
parameter_unitsPer-parameter units backing
parameters, in column order.parametersAdditional estimated parameters associated with the trajectory.
per_body_spkWhether a multi-body trajectory is written as one SPK per body.
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.
use_saved_stmsWhen
True,get_STMs()reads STMs from the saved_stms.jsonsidecar instead of the in-memorySTMslist.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])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, tol_time])Retrieve/interpolate the STM at epoch for BOTH:
get_STMs(epoch_input[, origin_input, ...])Retrieve the State Transition Matrix at a given epoch.
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[, stm_format, ...])Write the trajectory to disk as a SPICE SPK file plus JSON sidecars.
- Raises:
- ValueError
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.
See also
scarabaeus.MissionSequenceMulti-leg trajectory container.
scarabaeus.PropagatorNumerical propagator that produces trajectory data.
scarabaeus.StateArrayState vector passed to the propagator.
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-13 (unequally spaced Hermite) format. State at any epoch inside the covered arc is retrieved via SPICE polynomial interpolation, with the stored velocities constraining the position curve so that the velocity SPICE returns is the exact derivative of the position it returns.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)
- add_STMs(STMs: list, timestamps: List = None)#
Associates state transition matrices (STMs) with the trajectory.
- Parameters:
- STMslist or ArrayWFrame
A list of state transition matrices or a single ArrayWFrame object.
- timestampsEpochArray, optional
Epoch of each STM. Defaults to
None: a single ArrayWFrame is aligned 1:1 withepoch, with a warning.
- get_STM(epoch: float, idx: int = None) 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. An interpolated result is checked against
max_interp_error, this trajectory’s relative tolerance.- Parameters:
- epochfloat
The time at which to retrieve/interpolate the STM
- idxint, optional
Direct index into the STM array (used when timestamps unavailable)
- Returns:
- np.ndarray
The STM reshaped as a square matrix
- 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_inputEpochArray
The epoch at which to retrieve the STM.
- origin_inputstr, optional
Custom origin for the STM retrieval. Defaults to the trajectory’s origin.
- ref_frame_inputstr, optional
Custom reference frame for the STM retrieval. Default is the trajectory’s reference frame.
- idx_leg_inputint, optional
The index of the trajectory leg to retrieve if the trajectory is sequence-based. Defaults to
None.- folder_path_overridestr or os.PathLike or iterable, optional
Where to look for the STM and propagator-settings sidecars: an SPK, a file, a folder, or an iterable of those — see
SpiceManager.sidecar_files(). Defaults toNone, which uses this trajectory’s own SPK.
- Returns:
- stmdict
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.
- get_STM_sequence(epoch: float, idx: int = None, idx_leg: int = None, tol_time: float = 1e-09) ndarray#
Retrieve/interpolate the STM at epoch for BOTH:
non-sequence:
self._STMsis (N, n^2) andself._STMs_timestampis (N,)sequence:
self._STMsis a 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.
Interpolated results are checked against
max_interp_error, this trajectory’s relative tolerance.
- get_STMs(epoch_input: EpochArray, origin_input=None, ref_frame_input=None, folder_path_override=None)#
Retrieve the State Transition Matrix at a given epoch.
Mirrors
get_state()’s disk-vs-memory behaviour for STMs. Whenuse_saved_stmsisTrueand an associated SPK exists, the STM is read (and interpolated if needed) from the saved_stms.jsonsidecar viaSpiceManager.get_STMs(). Otherwise the in-memory STM nearest the requested epoch is returned.- Parameters:
- epoch_inputEpochArray
Scalar epoch at which to retrieve the STM.
- origin_input, ref_frame_inputoptional
Override origin / reference frame; default to the trajectory’s own.
- folder_path_overridestr or os.PathLike or iterable, optional
Where to look for the STM sidecar: an SPK, a file, a folder, or an iterable of those — see
SpiceManager.sidecar_files(). Defaults to this trajectory’s own SPK.
- Returns:
- numpy.ndarray
The
(n, n)State Transition Matrix at the requested epoch.
- 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_inputEpochArray
The epoch at which to compute the offset position.
- origin_inputstr, optional
Custom origin for position computation. Defaults to the trajectory’s origin.
- ref_frame_inputstr, optional
Custom reference frame for position computation. Defaults to the trajectory’s reference frame.
- Returns:
- offset_posArrayWUnits
The computed position including the constant offset. Expressed in units of kilometers.
- 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_inputEpochArray
The epoch at which to compute the state.
- origin_inputstr, optional
Custom origin for the state computation. Defaults to the trajectory’s origin.
- ref_frame_inputstr, optional
Custom reference frame for the state computation. Defaults to the trajectory’s reference frame.
- idx_leg_inputint, optional
The index of the trajectory leg to retrieve if the trajectory is sequence-based. Defaults to
None.- folder_path_overridestr or os.PathLike or iterable, optional
Where to look for the parameters and propagator-settings sidecars: an SPK, a file, a folder, or an iterable of those — see
SpiceManager.sidecar_files(). Defaults toNone, which uses this trajectory’s own SPK.
- Returns:
- statedict
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.
- set_offset(offset: ArrayWUnits) None#
Sets the constant position offset for the trajectory.
- Parameters:
- offsetArrayWUnits
The constant offset in position. Expressed in units of kilometers.
- Returns:
- None
- write_to_spk(spk_path: str, stm_format: str = 'json', sidecar_format: str = 'json', append_if_exists: bool = True, write_stms: bool = True, per_body_spk: bool = None) None#
Write the trajectory to disk as a SPICE SPK file plus JSON sidecars.
The
.bspfile contains the position/velocity time-series (SPICE type-13 Hermite segments). See Notes section for information on additional data that cannot be embedded in an SPK.- Parameters:
- spk_pathstr
Destination file path. Must end with
.bsp.- stm_format{“json”, “pickle”}, optional
On-disk format for the STM sidecar.
"json"(default) writes a human-readable_stms.json;"pickle"writes a compact binary_stms.pkl(lighter on disk for large STM histories). Either is read back transparently byget_STMs().- sidecar_format{“json”, “pickle”}, optional
On-disk format for the parameters / settings / mass-profile sidecars.
"json"(default) writes*_parameters.jsonetc.;"pickle"writes*_parameters.pkletc. (same content, binary). Read back transparently by theSpiceManagergetters.- append_if_existsbool, optional
- If the given spk_path already exists:
True: append the trajectory segment to that file.False: delete the existing file and write a new one in its place.
Defaults to
True.- write_stmsbool, optional
Whether to write the STM sidecar at all. It is by far the largest artifact a trajectory produces — one matrix per output epoch, growing with the square of the state size — so a run that only wants the state history can skip it entirely. Defaults to
True. The STMs held in memory are unaffected; only the file is skipped, so anything reading them back later (use_saved_stms) needs it.- per_body_spkbool, optional
When the trajectory holds several bodies, write one SPK per body —
mission_EARTH.bsp,mission_ORBITER.bsp— instead of a single file carrying one segment per body. Each file then owns its sidecars, which is what a downstream tool expecting one body per kernel wants. Defaults toper_body_spk, i.e.False: one file with a segment per body. Ignored for a single body.
- Raises:
- ValueError
If
spk_pathdoes not end with.bsp.- UserWarning
If this
Trajectoryalready has an associated SPK at a different path.
Notes
The written SPK is furnished. SPICE resolves each epoch from the last-loaded kernel that covers it, so within its time span this file shadows any SPK loaded earlier for the same body (a reconstructed mission ephemeris, for instance). Unload it, or write it to a path you can unload, if those earlier kernels must stay in effect.
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 andwrite_stmsisTrue).
Each sidecar is created only when the corresponding data is present. All files share the same directory and path prefix as the
.bsp.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 max_interp_error: float | None#
Relative tolerance on linear interpolation of the STM.
Every
get_STM/get_STM_sequencelookup that falls between two stored epochs interpolates, and rejects the result when the estimated relative error exceeds this value. The estimate is curvature-based and scales as \(dt^2\), so halving the STM grid step cuts it by four.The default,
1e-3, admits a grid step of roughly a minute on a low Earth orbit. Raise it to accept a looser fit on a coarser grid, or set it toNoneto skip the check entirely.Notes
This replaces an absolute threshold on the first difference
alpha (1 - alpha) ||Phi_1 - Phi_0||, which measured \(\|\Phi\|\) rather than the interpolation error and so failed on a long arc at any grid step. Values carried over from that scheme are not comparable.
- property offset: ArrayWUnits#
A fixed position offset for coordinate transformations.
- property parameter_units: list | None#
Per-parameter units backing
parameters, in column order.A list of
(name, dim, units), one entry per estimated parameter of the primary body. Parameters of one body need not share units — a spacecraft solving for a delta-v (km/s) and a maneuver-epoch correction (sec) is ordinary — and when they differ,parametersis deliberately unitless because no single label describes the stacked block. This is then the only faithful record, and it is what gets written to the parameters sidecar.Nonefor sequence trajectories, whose legs carry their own units, and for trajectories with no estimated parameters.
- 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 per_body_spk: bool#
Whether a multi-body trajectory is written as one SPK per body.
False(the default) writes a single.bspcarrying one segment per body — compact, and what SPICE is designed for.Truewritesmission_ORBITER.bsp,mission_EARTH.bspand so on, each with its own sidecars, for a downstream tool that expects one body per kernel.Either way the bodies’ parameter sidecars are kept apart: they are named per body whenever there is more than one, since every body writes
_parameters.jsonand a shared name would leave only the last.Ignored for a single-body trajectory, which always writes one file.
- 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 use_saved_stms: bool#
When
True,get_STMs()reads STMs from the saved_stms.jsonsidecar instead of the in-memorySTMslist.
- property velocity: ArrayWUnits#
The velocity history of the trajectory in the specified reference frame.