Python API reference

This page documents every name exported by gmatpy.__all__ in version 0.2.0. Import them from gmatpy. The reference describes the value-based interface; the broader SWIG interface is reached through native_session(). See Time, frames, units and scientific inputs for the shared time, frame and unit contracts.

The standard package includes all the supported Python operations documented below, together with native SPICE support. No feature profile or extra is needed. Capabilities.profile retains "extended" as an internal compatibility label.

Common error behavior

Numeric inputs must be finite; the scalar/vector validators reject booleans, NaN and infinity. Scalar inputs accepted by those validators are converted with float(). Names of formats, frames, bodies, scales and features are case-sensitive. Validation errors normally raise ValueError; wrong configuration object types raise TypeError as listed below.

Engine operations can also raise RuntimeError on initialization, missing bundled scientific data, failed native operations, non-finite native results, calls after fork, or entry from an active native session. Native errors may propagate as the SWIG API’s APIException (a Python exception); the facade does not translate every native failure into one exception type. See native_session() for lifetime and concurrency rules, and Time, frames, units and scientific inputs for scientific data limits.

Propagation configuration and results

class gmatpy.Spacecraft(mass_kg=1000.0, drag_area_m2=1.0, srp_area_m2=1.0, cd=2.2, cr=1.8)

Frozen dataclass containing constant spacecraft properties. The propagation wrappers use spherical drag/SRP models.

Parameters:
  • mass_kg (float) – Positive dry mass in kg.

  • drag_area_m2 (float) – Nonnegative drag area in m².

  • srp_area_m2 (float) – Nonnegative solar-radiation-pressure area in m².

  • cd (float) – Positive dimensionless drag coefficient.

  • cr (float) – Positive dimensionless reflectivity coefficient.

Raises:

ValueError – A property is non-finite or outside its range.

Validated numeric fields are stored as floats. No mass consumption is modeled by the value-based propagation or impulse wrappers.

mass_kg: float = 1000.0
drag_area_m2: float = 1.0
srp_area_m2: float = 1.0
cd: float = 2.2
cr: float = 1.8
class gmatpy.ForceModel(
gravity_model='EGM96',
degree=8,
order=None,
sun=True,
moon=True,
srp=True,
drag=False,
f107=150.0,
f107a=150.0,
kp=3.0,
)

Frozen dataclass selecting Earth gravity and optional perturbations.

Parameters:
  • gravity_model (str) – "EGM96" (degree/order through 360) or "JGM3" (through 70).

  • degree (int) – Gravity degree, from 0 through the selected model’s limit. Zero selects a monopole.

  • order (int or None) – Gravity order, from 0 through degree; None uses degree. Stored as the resolved integer after construction.

  • sun (bool) – Include Sun point-mass gravity, using native DE405.

  • moon (bool) – Include lunar point-mass gravity, using native DE405.

  • srp (bool) – Include spherical solar radiation pressure.

  • drag (bool) – Include Jacchia-Roberts atmospheric drag with constant solar-flux and geomagnetic indices.

  • f107 (float) – Positive daily F10.7 solar flux, in solar flux units.

  • f107a (float) – Positive average F10.7 solar flux, in solar flux units.

  • kp (float) – Constant Kp index, from 0 through 9 inclusive.

Raises:

ValueError – Unsupported gravity model, invalid integer degree/order, non-boolean switches, or invalid scalar properties.

With degree=0 and drag=False, the wrapper creates a native point-mass force. With drag enabled it uses a degree/order-zero gravity field to supply the primary-body dependency; this still supplies the monopole. No weather file is read by this configuration.

gravity_model: str = "EGM96"
degree: int = 8
order: int

Resolved order; defaults to 8 when degree is unchanged.

sun: bool = True
moon: bool = True
srp: bool = True
drag: bool = False
f107: float = 150.0
f107a: float = 150.0
kp: float = 3.0
class gmatpy.Sample(time_s, position_km, velocity_km_s)

Frozen result dataclass. Propagation functions populate it with copied Python values in EarthMJ2000Eq. Direct construction does not validate or normalize the fields.

Parameters:
  • time_s (float) – Elapsed SI seconds from the input epoch.

  • position_km – Cartesian position, a three-float tuple in km.

  • velocity_km_s – Cartesian velocity, a three-float tuple in km/s.

time_s: float
position_km: tuple[float, float, float]
velocity_km_s: tuple[float, float, float]
property state: tuple[float, ...]

Concatenates position_km + velocity_km_s into a six-component Cartesian tuple.

gmatpy.propagate(
state,
epoch,
times,
*,
forces=None,
spacecraft=None,
accuracy=1e-12,
max_step_s=60.0,
)

Start a fresh Earth-centered orbit and sample native Prince-Dormand 7/8 integration.

Parameters:
  • state – Iterable of six finite Cartesian components [x, y, z, vx, vy, vz] in EarthMJ2000Eq (km, km/s). The position must be nonzero.

  • epoch – Timezone-aware datetime or ISO 8601 string with a timezone.

  • times – Iterable of finite, nonnegative elapsed SI seconds from epoch, in nondecreasing order. These are output epochs, not step sizes.

  • forces – ForceModel, or None for ForceModel().

  • spacecraft – Spacecraft, or None for Spacecraft().

  • accuracy (float) – Positive native integrator accuracy setting; it is not a guaranteed position/velocity error bound.

  • max_step_s (float) – Positive maximum integration step in seconds.

Returns:

One Sample per requested time, including duplicates. Empty times returns [] after input validation.

Return type:

list[Sample]

Raises:
  • ValueError – Invalid state, epoch, times, accuracy or step limit.

  • TypeError – forces or spacecraft has the wrong type.

  • RuntimeError – Integration fails, yields an invalid state, or the requested time cannot be advanced at floating-point resolution.

A sample at zero is the input state. Each call owns a fresh setup and clears its native objects on completion or error. Engine access is serialized.

State, frame, time and ephemeris utilities

gmatpy.convert_state(
state,
from_type='Cartesian',
to_type='Keplerian',
*,
mu=None,
anomaly='TA',
)

Convert a six-component orbital representation with GMAT’s native state conversion routines.

Parameters:
  • state – Iterable of six finite numbers in from_type ordering.

  • from_type (str) – Input representation.

  • to_type (str) – Output representation. Supported values for both arguments are Cartesian, Keplerian, ModifiedKeplerian, Equinoctial, ModifiedEquinoctial, SphericalRADEC and SphericalAZFPA.

  • mu (float or None) – Positive central-body gravitational parameter in km³/s², or None to use GMAT’s Earth value.

  • anomaly (str) – "TA" (true), "MA" (mean), "EA" (eccentric) or "HA" (hyperbolic) anomaly for representations using an anomaly. Not every choice is valid for every conic.

Returns:

Six Python floats in to_type ordering.

Return type:

tuple[float, …]

Raises:
  • ValueError – Invalid vector, format, anomaly token or mu.

  • RuntimeError – Native output is non-finite.

Representation layouts and units are in State representations and units. A custom mu changes the two-body conversion parameter; it does not select a new force model, origin or frame. The call still passes Earth’s flattening and equatorial radius to the native routine. Singular or physically invalid element sets may raise a native APIException.

gmatpy.transform_state(state, epoch, *, from_frame='EarthMJ2000Eq', to_frame='EarthFixed')

Transform the full Cartesian position and velocity between supported Earth-centered frames.

Parameters:
  • state – Iterable of six finite Cartesian numbers, in km and km/s.

  • epoch – Timezone-aware datetime or ISO 8601 string with a timezone.

  • from_frame (str) – Input frame.

  • to_frame (str) – Output frame. Both accept EarthMJ2000Eq, EarthMJ2000Ec, EarthICRF or EarthFixed.

Returns:

A copied six-component Cartesian tuple in to_frame.

Return type:

tuple[float, …]

Raises:
  • ValueError – Invalid vector, epoch or frame token.

  • RuntimeError – Native coordinate conversion fails or is non-finite.

EarthFixed includes rotating-frame velocity terms and uses GMAT’s FK5/IAU1980 convention; do not label it ITRF or TEME. For the inherited FK5/MJ2000Eq-to-ICRF base conversion, the same interpolated matrix rotates position and velocity and the base rotation derivative is zero.

EarthICRF uses the exact original ICRF_Table.txt from the pinned NASA baseline, with its irregular grid and gaps up to 16 days. Native ninth-order Lagrange interpolation spans internal gaps; the table endpoints bound supported epochs. This is not the former ERFA-generated alternative. See Time, frames, units and scientific inputs for exact date limits and the separate SPICE Earth-PCK limit; that PCK is not the default EarthFixed rotation model.

gmatpy.epoch_mjd(epoch, scale='UTC')

Express an input UTC instant as conventional Modified Julian Date in a selected time scale.

Parameters:
  • epoch – Timezone-aware datetime or ISO 8601 string with a timezone.

  • scale (str) – UTC, TAI, TT, TDB, UT1 or GMAT’s A1.

Returns:

MJD using JD - 2400000.5, in days in the requested scale.

Return type:

float

Raises:

ValueError – Invalid epoch or scale token.

Offset-bearing input strings are normalized to UTC. The result does not expose GMAT’s internal ModJulian origin. Python datetime precision and the bundled leap-second/EOP snapshots apply; literal 23:59:60 input is unsupported.

gmatpy.body_state(body, epoch, *, origin='Earth')

Obtain a geometric ephemeris six-state with native DE405, available in the standard package.

Parameters:
  • body (str) – Sun, Mercury, Venus, Earth, Luna (or alias Moon), Mars, Jupiter, Saturn, Uranus, Neptune or Pluto.

  • epoch – Timezone-aware datetime or ISO 8601 string with a timezone.

  • origin (str) – Reference body, accepting the same body set and alias.

Returns:

body - origin in MJ2000Eq axes, position in km and velocity in km/s. Identical body and origin yield a zero six-state.

Return type:

tuple[float, …]

Raises:
  • ValueError – Unsupported body/origin or invalid epoch.

  • RuntimeError – Native state is non-finite.

No light-time or aberration correction is applied. Requests outside the bundled DE405 interval may raise a native exception. This helper does not depend on the SPICE kernel readers.

Mission workflows

The standard package includes the following mission functions, their result objects and Impulse.

class gmatpy.Impulse(time_s, delta_v_km_s, frame='EarthMJ2000Eq')

Frozen dataclass defining an instantaneous, constant-mass maneuver.

Parameters:
  • time_s (float) – Finite, nonnegative elapsed SI seconds from the initial propagation epoch.

  • delta_v_km_s – Iterable of three finite delta-v components in km/s; stored as a tuple of floats.

  • frame (str) – "EarthMJ2000Eq" or local "VNB".

Raises:
  • ValueError – Invalid burn time, vector length/components or frame.

  • TypeError – delta_v_km_s is not iterable.

VNB components follow velocity, orbit normal and their right-handed binormal, evaluated at the maneuver. No tank or mass depletion is modeled.

time_s: float
delta_v_km_s: tuple[float, float, float]
frame: str = "EarthMJ2000Eq"
gmatpy.propagate_mission(
state,
epoch,
times,
*,
impulses=(),
forces=None,
spacecraft=None,
accuracy=1e-12,
max_step_s=60.0,
)

Propagate one spacecraft with scheduled native impulsive maneuvers.

Parameters:
  • state – Six-component initial Cartesian state as in propagate().

  • epoch – Timezone-aware initial epoch as in propagate().

  • times – Nonnegative, nondecreasing elapsed seconds as in propagate().

  • impulses – Iterable of Impulse objects, all at or before the final requested output time. Default: no maneuvers.

  • forces – ForceModel or None for the default model.

  • spacecraft – Spacecraft or None for default properties.

  • accuracy (float) – Positive native integrator accuracy setting.

  • max_step_s (float) – Positive maximum integration step in seconds.

Returns:

One Sample per output time. Burn-time samples are post-burn. Equal-time burns retain input order; duplicate output times repeat the post-burn state. Empty times with no burns returns [].

Return type:

list[Sample]

Raises:
  • ValueError – Invalid propagation input or a burn beyond the sampled interval (including any burn with empty output times).

  • TypeError – Invalid forces, spacecraft or impulse object types.

  • RuntimeError – Native integration or maneuver fails.

gmatpy.propagate_many(
states,
epoch,
times,
*,
forces=None,
spacecraft=None,
impulses=None,
accuracy=1e-12,
max_step_s=60.0,
)

Co-propagate named spacecraft in one native propagator. This uses the core propagator, without the optional Formation plugin or spacecraft mutual gravity/collisions.

Parameters:
  • states – Nonempty mapping of nonempty string names to six-component EarthMJ2000Eq Cartesian states (km, km/s), with nonzero positions.

  • epoch – Shared timezone-aware initial epoch.

  • times – Shared iterable of nonnegative, nondecreasing elapsed seconds.

  • forces – Shared ForceModel, or None for the default.

  • spacecraft – Optional mapping of state names to Spacecraft values. Missing names receive default properties.

  • impulses – Optional mapping of state names to iterables of Impulse objects. Missing names receive no burns.

  • accuracy (float) – Positive native integrator accuracy setting.

  • max_step_s (float) – Positive maximum integration step in seconds.

Returns:

Mapping with the input names, each containing one Sample per output time. Empty times with no burns returns each name mapped to []. Samples at maneuvers are post-burn.

Return type:

dict[str, list[Sample]]

Raises:
  • ValueError – Invalid states/names/times, unknown names in the optional mappings, or a burn beyond the final sample.

  • TypeError – Invalid force, spacecraft or impulse object types.

  • RuntimeError – Native integration, maneuver or state extraction fails.

Burns are sorted by time. Ties retain their traversal order: the order of keys in the impulse mapping, then the order within each spacecraft schedule. Common forces do not imply identical spacecraft areas or mass.

class gmatpy.TargetResult(delta_v_km_s, final_state, achieved_sma_km, residual_km)

Frozen result dataclass returned by target_sma(). Direct construction does not validate or normalize fields.

Parameters:
  • delta_v_km_s (float) – Solved signed tangential VNB delta-v in km/s.

  • final_state – Post-burn Cartesian six-tuple in EarthMJ2000Eq (km, km/s) at the input epoch.

  • achieved_sma_km (float) – SMA calculated from final_state in km.

  • residual_km (float) – achieved_sma_km - target_sma_km.

delta_v_km_s: float
final_state: tuple[float, ...]
achieved_sma_km: float
residual_km: float
gmatpy.target_sma(state, epoch, target_sma_km, *, tolerance_km=1e-5, max_iterations=25)

Solve an instantaneous tangential VNB burn with GMAT’s DifferentialCorrector.

Parameters:
  • state – Six finite EarthMJ2000Eq Cartesian components (km, km/s) describing an Earth-centered elliptic initial orbit.

  • epoch – Timezone-aware initial epoch.

  • target_sma_km (float) – Positive target post-burn semi-major axis in km.

  • tolerance_km (float) – Positive maximum accepted absolute SMA residual in km, independently checked after the native solve.

  • max_iterations (int) – Integer from 1 through 100 inclusive; booleans are rejected.

Returns:

Burn and post-burn state at the input epoch.

Return type:

TargetResult

Raises:
  • ValueError – Invalid vector/epoch, non-elliptic initial orbit, invalid target/tolerance or iteration count.

  • RuntimeError – Script execution fails or the final residual exceeds tolerance_km.

Only VNB component 1 varies; the other components remain zero. The native solve bounds the signed burn to [-10, 10] km/s, with a maximum iteration change of 0.5 km/s. There is no coast interval, transfer-time solve, mass depletion or general fuel/multi-goal optimization.

gmatpy.run_script(path, *, outputs)

Run a trusted core GMAT mission script and copy selected runtime fields.

Parameters:
  • path – Filesystem path accepted by pathlib.Path. ~ is expanded; the path is resolved with strict=True before loading.

  • outputs – Mapping of nonempty runtime object names to iterables of nonempty field-name strings. A bare string is not a field sequence.

Returns:

Nested {object_name: {field_name: value_string}} dictionary. Values are native GetField strings; the wrapper does not parse units, numbers or arrays. An empty mapping requests execution without fields.

Return type:

dict[str, dict[str, str]]

Raises:
  • OSError – Path resolution fails, including a missing file.

  • TypeError – outputs is not a mapping, or a field list is a string or cannot be iterated.

  • ValueError – Empty/invalid object or field names, or a requested runtime object does not exist.

  • RuntimeError – Native script loading or execution reports failure.

Native field lookup can raise APIException. The wrapper clears owned native objects even if loading, execution or field extraction fails. Scripts can write files and run command loops. Use scripts you trust; this interface is not a sandbox. Core finite-burn and targeting commands can be used when configured correctly; optional-plugin and arbitrary GMAT script compatibility are outside this contract.

Capabilities and native access

class gmatpy.Capabilities(profile, features, deferred_plugins)

Frozen dataclass describing supported installation capabilities. capabilities() supplies normalized values; direct dataclass construction does not validate the fields.

Parameters:
  • profile (str) – "extended", the retained internal compatibility label for the standard package.

  • features – Frozen set of feature tokens.

  • deferred_plugins – Tuple of deferred plugin-family tokens.

profile: str
features: frozenset[str]
deferred_plugins: tuple[str, ...]
supports(feature)
Parameters:

feature (str) – Case-sensitive feature token.

Returns:

Whether feature belongs to features. Unknown string tokens return False.

Return type:

bool

gmatpy.capabilities()

Read the installed BUILD_PROFILE.json without initializing the engine. If the file is absent in a source overlay, the implementation defaults to extended; this fallback does not verify built native artifacts.

Returns:

Internal compatibility label and supported feature/deferred-plugin sets.

Return type:

Capabilities

Raises:

RuntimeError – Installed metadata requests an unsupported build profile. Historical minimal metadata is rejected.

The standard package reports propagation, state_conversion, frame_conversion, time_conversion, native_de405, native_session, impulsive_maneuvers, multi_spacecraft, targeting, mission_scripts and spice_kernels.

The deferred plugin tuple is estimation/ekf, station/measurement, tle_propagator, external_force_callbacks, optional_optimizers, csalt, matlab and gmat_functions. GUI workflows are outside the project scope. Reporting describes the supported build surface; it is not a security boundary or a complete inventory of every underlying C++ method.

exception gmatpy.UnsupportedCapabilityError

Subclass of RuntimeError retained for API compatibility when a convenience operation requests an unavailable capability. All currently documented mission operations are included in the standard package.

gmatpy.native_session()

Context manager giving access to the bundled core’s existing SWIG module.

Returns:

A context manager whose with ... as api value is the native GMAT API module. Configure and use all native objects inside that block.

Raises:

RuntimeError – Initialization fails, data are missing, a native operation is nested in this thread, or the process was forked after importing the runtime.

Setup, serialization and Clear() cleanup are automatic. Every native object handle belongs to the session and becomes invalid when it exits, including exceptional exit. Do not retain handles or dereference them later. Return copied Python values from your own adapter instead.

Convenience functions that enter the native engine and nested sessions are rejected inside an active session in the same thread. Engine operations across threads are serialized. Use multiprocessing.get_context("spawn") for independent parallel work; calling after fork is rejected. Do not load another GMAT installation/API in the same process.

Raw bindings retain GMAT’s native ownership rules, including ownership transfer when attaching some objects. Scoped cleanup does not remove that responsibility. GUI and optional-plugin APIs are unavailable, and the existence of a SWIG symbol does not establish supported or qualified behavior. Startup files and logs use a private temporary directory. Value-based helpers preserve the caller’s working directory.

The SPICE kernel pool is process-global. The native UnloadAllKernels() operation clears the entire pool, including kernels or inserted values furnished outside that interface; coordinate ownership with other SPICE users. An individual UnloadKernel() failure retains the inherited warning/recovery limitations and does not promise pool reconstruction or isolation. The bundled March Earth PCK ends at 2026-06-12 even though the separate EOP snapshot extends to September.