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: object

Represents 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 StateArray directly 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 to None.

  • origin (str, optional) – The origin of the trajectory (e.g., "SUN"). Defaults to None.

  • body (CelestialBody, optional) – The celestial body or spacecraft associated with this trajectory. Defaults to None.

  • degree_poly (int, optional) – The degree of the polynomial used for SPICE interpolation. Defaults to 3.

  • parameters (list of ArrayWUnits, optional) – Additional estimated parameters related to the trajectory (e.g., range biases, solar radiation pressure coefficients). Defaults to None.

  • offset (ArrayWUnits, optional) – A fixed position offset for coordinate transformations. Defaults to None.

  • STMs (list, optional) – The state transition matrices (STMs) associated with the trajectory. Defaults to None.

  • propagator_settings_dict (dict, optional) – A dictionary of propagator settings for numerical integration. Defaults to None.

  • state_array (StateArray, optional) – If provided, initializes the trajectory from a propagated StateArray, extracting position, velocity, epoch, reference frame, and parameters. Defaults to None.

Raises:
  • ValueError

    • If both state_definition and sequence_definition are provided simultaneously.

    • If both standard trajectory inputs and a StateArray are provided.

    • If StateArray is missing position or velocity components.

  • Exception – If the trajectory contains fewer than two data points.

Notes

  • If state_definition is provided, the trajectory follows a single continuous model.

  • If sequence_definition is 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:

  1. 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.

  2. JSON sidecars — plain-text files written alongside the .bsp with 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 via add_STMs()).

    • <name>_settings.json — serialised propagator_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 a mass_profile is 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 .bsp so 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.MissionSequence

Multi-leg trajectory container.

scarabaeus.Propagator

Numerical propagator that produces trajectory data.

scarabaeus.StateArray

State vector passed to the propagator.

Attributes:
STMs

The state transition matrices (STMs) associated with the trajectory.

STMs_timestamp

The epochs at which each STM was generated.

body

The celestial body or spacecraft associated with the trajectory.

end_epoch

The end epoch of the trajectory.

epoch

The epochs associated with the trajectory.

offset

A fixed position offset for coordinate transformations.

origin

The origin of the trajectory.

parameters

Additional estimated parameters associated with the trajectory.

poly_deg

The degree of the polynomial used for interpolation.

position

The position history of the trajectory in the specified reference frame.

propagator_settings_dict

The dictionary of propagator settings for numerical integration.

ref_frame

The reference frame of the trajectory.

sequence_definition

The mission sequence definition governing the trajectory’s structure.

spk_path

The filepath for the Trajectory’s associated SPK file.

start_epoch

The start epoch of the trajectory.

state_definition

The definition of the trajectory’s state vector.

velocity

The 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 (list or ArrayWFrame) – 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 STM

  • idx (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 to None.

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:

dict

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:

ArrayWUnits

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 to None.

  • 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 to None.

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:

dict

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:

None

write_to_spk(spk_path: str) None#

Write the trajectory to disk as a SPICE SPK file plus JSON sidecars.

The .bsp file 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 when parameters is not None).

  • <spk_path base>_settings.json — propagator settings dictionary (written when propagator_settings_dict is not None).

  • <spk_path base>_mass_profile.json — spacecraft mass polynomial (written when a mass_profile was 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_path does not end with .bsp.

  • UserWarning – If this Trajectory already 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: list | None#

The state transition matrices (STMs) associated with the trajectory.

property STMs_timestamp: List | None#

The epochs at which each STM was generated. Must correspond one-to-one with the STMs list.

property body: Body#

The celestial body or spacecraft associated with the trajectory.

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 origin: str#

The origin of the trajectory.

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 poly_deg: int#

The degree of the polynomial used for interpolation.

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 ref_frame: Frame#

The reference frame of the trajectory.

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 None if 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.