Skip to content

Two-Line Element Sets, OMMs, and SGP4

API reference for the SGP4 analytic propagator and its inputs. For background, see:

TLE

Two-Line Element Set (TLE) representing a satellite ephemeris

A Two-Line Element Set is a satellite ephemeris format from the 1970s that is still in wide use. Its mean elements are propagated with the "Simplified General Perturbations-4" (SGP4) model (satkit.sgp4), which gives position and velocity in the "TEME" frame (not-quite GCRF).

For details, see: https://en.wikipedia.org/wiki/Two-line_element_set

Catalogs in this format are publicly available at https://www.space-track.org (registration required) and https://celestrak.org (no registration needed).

TLEs sometimes have a "line 0" that includes the name of the satellite.

Load TLEs with TLE.from_lines, TLE.from_file or TLE.from_url; each returns a list[TLE], even for a single element set.

Example
tle = satkit.TLE.from_lines([
    "0 ISS (ZARYA)",
    "1 25544U 98067A   21264.51782528  .00002893  00000-0  58680-4 0  9996",
    "2 25544  51.6442 208.5856 0001458  47.2277  50.1624 15.48919419302874",
])[0]
print(tle.name)
# ISS (ZARYA)

satnum property writable

Satellite number, or equivalently the NORAD catalog number

A number above 339999 (the end of the Alpha-5 scheme) is allowed, as OMM carries up to nine digits, but cannot be written by to_2line.

intl_desig property writable

International designator as written in the TLE (line 1, columns 10-17)

For example "98067A": the last two digits of the launch year, the three-digit launch number of that year and the piece of the launch (one to three letters). An empty string if the element set has none, as for an analyst object or a new TLE().

This string is the stored value: to_2line writes it and to_omm derives OBJECT_ID from it. desig_year, desig_launch and desig_piece are read from it, and setting any of them rewrites it.

desig_year property writable

Launch year from the international designator, two digits as in the TLE

The first two characters of intl_desig (98 for "98067A"): 57-99 are 1957-1999 and 0-56 are 2000-2056. None if the designator is blank or does not start with two digits.

desig_launch property writable

Launch number of the year from the international designator

Characters 3-5 of intl_desig (67 for "98067A"). None if the designator is blank or does not hold three digits there.

desig_piece property writable

Piece of the launch from the international designator (e.g. "A")

What follows the year and launch number in intl_desig; an empty string if the designator is blank or has no piece.

classification property writable

Classification (line 1, column 8): "U", "C" or "S" in practice, but any single ASCII letter round-trips

ephem_type property writable

Ephemeris type (usually 0). A value of 4 marks an SGP4-XP element set, which sgp4 rejects: satkit implements classic SGP4 only.

element_num property writable

Element set number

rev_num property writable

Revolution number at epoch

raan property writable

Right Ascension of Ascending Node, in degrees

eccentricity property writable

Orbit eccentricity, unitless, in range [0, 1)

eccentricity is the same value under its full name; eccen is an alias of it, kept for existing code.

eccen property writable

Orbit eccentricity, unitless, in range [0, 1); an alias of eccentricity

mean_anomaly property writable

Mean anomaly in degrees

mean_motion property writable

Mean motion in revs / day

inclination property writable

Inclination, in degrees

epoch property writable

TLE epoch

arg_of_perigee property writable

Argument of Perigee, in degrees

mean_motion_dot property writable

1/2 of first derivative of mean motion, in revs/day^2

Notes

The "1/2" is because that is how number is stored in the TLE.

mean_motion_dot_dot property writable

1/6 of 2nd derivative of mean motion, in revs/day^3

Notes

The "1/6" is because that is how number is stored in the TLE.

name property writable

The name of the satellite: the name line of a 3-line element set

"none" for an element set that has no name (one read from two lines, or a new TLE()).

bstar property writable

Drag term (B*) of the satellite, in units of 1 / Earth radii

should be rho0 * Cd * A / 2 / m

Units (which are strange) is multiples of 1 / Earth radius

__init__(*, name=None, satnum=None, intl_desig=None, classification=None, epoch=None, inclination=None, raan=None, eccen=None, arg_of_perigee=None, mean_anomaly=None, mean_motion=None, mean_motion_dot=None, mean_motion_dot_dot=None, bstar=None, ephem_type=None, element_num=None, rev_num=None)

An element set built from keyword arguments, or an empty one to fill in

Every argument is keyword-only and optional, and is the property of the same name: it is checked exactly as setting that property is, so a bad value raises the setter's exception. An argument left out (or None) keeps the value of an empty TLE(): the name "none", satellite number 0, a blank international designator, classification "U", the epoch J2000 (2000-01-01 12:00:00 TT) and every element zero. An empty element set cannot be propagated until at least mean_motion and epoch are set. Element sets are normally loaded with TLE.from_lines, TLE.from_file, TLE.from_url or TLE.from_omm, or fitted with TLE.fit_from_states.

The designator is given whole as intl_desig; desig_year, desig_launch and desig_piece are parts of it and are not arguments.

Parameters:

Name Type Description Default
name str | None

satellite name ("none" if absent)

None
satnum int | None

satellite (NORAD catalog) number, 0 to 999999999

None
intl_desig str | None

international designator, e.g. "98067A"

None
classification str | None

a single ASCII letter, usually "U"

None
epoch TimeScalar | None

epoch, a single time, datetime.datetime or numpy.datetime64

None
inclination float | None

inclination, degrees

None
raan float | None

right ascension of the ascending node, degrees

None
eccen float | None

eccentricity, in [0, 1)

None
arg_of_perigee float | None

argument of perigee, degrees

None
mean_anomaly float | None

mean anomaly, degrees

None
mean_motion float | None

mean motion, revs / day, not negative

None
mean_motion_dot float | None

half the first derivative of mean motion, revs / day^2

None
mean_motion_dot_dot float | None

one sixth of the second derivative of mean motion, revs / day^3

None
bstar float | None

drag term B*, 1 / Earth radii

None
ephem_type int | None

ephemeris type, 0 to 255

None
element_num int | None

element set number

None
rev_num int | None

revolution number at epoch

None

Raises:

Type Description
ValueError

if a value is out of the range its property accepts (see each property)

TypeError

if a value has the wrong type, e.g. epoch is not a single time

OverflowError

if ephem_type is outside 0..255, or an integer does not fit 32 bits

Example
tle = satkit.TLE(
    name="ISS (ZARYA)", satnum=25544, intl_desig="98067A",
    epoch=satkit.time(2021, 9, 21, 12, 25, 40.104192),
    inclination=51.6442, raan=208.5856, eccen=0.0001458,
    arg_of_perigee=47.2277, mean_anomaly=50.1624,
    mean_motion=15.48919419, bstar=5.868e-5,
)
pos, vel = satkit.sgp4(tle, tle.epoch)

# Or start empty and set the properties
tle = satkit.TLE()
tle.satnum = 99999
tle.epoch = satkit.time(2024, 1, 1)
tle.inclination = 51.6
tle.mean_motion = 15.5
pos, vel = satkit.sgp4(tle, tle.epoch)

__eq__(other)

True if other is a TLE with the same name and element set

Every field is compared exactly. The SGP4 initialization that sgp4 caches in the object is not part of the comparison, so a TLE equals its copy or pickle whether or not it has been propagated. A TLE is mutable, so it is not hashable.

__repr__()

One line naming the satellite and epoch

For example TLE(name="ISS (ZARYA)", satnum=25544, intl_desig="98067A", epoch=2021-09-21T12:25:40.104192Z). str(tle) is the multi-line listing of every element.

__str__()

Multi-line listing of the name, epoch and every element

from_file(filename, *, check_checksum=False, on_error='raise') staticmethod

Load TLEs from a text file, parsed as TLE.from_lines does

Parameters:

Name Type Description Default
filename str | PathLike

path of the text file holding the TLE lines

required
check_checksum bool

as in TLE.from_lines

False
on_error str

as in TLE.from_lines

'raise'

Returns:

Type Description
list[TLE]

one TLE per element set in the file

Raises:

Type Description
FileNotFoundError

if the file does not exist; the exception names the path. Another I/O failure raises the matching OSError (PermissionError, IsADirectoryError, ...)

ValueError

with on_error="raise", if a record fails to parse or the file holds no TLEs; see TLE.from_lines

Example
tles = satkit.TLE.from_file("gps-ops.txt")
for tle in tles:
    print(tle.name, tle.satnum)

from_lines(lines, *, check_checksum=False, on_error='raise') staticmethod

Load TLEs from a list of lines

TLE.from_file and TLE.from_url parse their text the same way. See the class docstring for an example.

Parameters:

Name Type Description Default
lines Sequence[str]

the TLE lines (2-line or 3-line format, any number of element sets; any sequence type is accepted, e.g. list or tuple)

required
check_checksum bool

also verify the checksum digit (column 69) of every data line. Default False.

False
on_error str

what to do with input that is not a valid element set. "raise" (default) raises ValueError at the first record that fails to parse, and also if the lines hold no element sets at all. "warn" leaves a bad record out and emits a TLEWarning with the same message (one more if the lines hold no element sets at all). "skip" leaves bad records out silently. Only "raise" raises for what the lines contain: "warn" and "skip" always return a list

'raise'

Returns:

Type Description
list[TLE]

one TLE per element set, even if there is only one. With on_error="warn" or "skip", one per element set that parsed: an empty list if none did, or if the lines (empty, or text that is not TLE data) held none to begin with.

Raises:

Type Description
ValueError

with on_error="raise", if a record fails to parse (or, with check_checksum, has a wrong checksum), where the message gives the line the record starts on and its satellite, or if the lines hold no element sets; with any on_error, if it is not one of the three values

TypeError

if lines is not a sequence of strings

Example
import warnings

lines = [
    "1 25544U 98067A   21264.51782528  .00002893  00000-0  58680-4 0  9996",
    "2 25544  51.6442 208.5856 0001458  47.2277  50.1624 15.48919419302874",
    # A letter O in the epoch day
    "1 49140U 21082L   24O30.39663557  .00000076  00000-0  14180-4 0  9995",
    "2 49140  70.0008  34.1139 0002663 260.3521  99.7337 14.98327656131736",
]
with warnings.catch_warnings(record=True) as skipped:
    warnings.simplefilter("always")
    tles = satkit.TLE.from_lines(lines, on_error="warn")
print(len(tles), len(skipped))
# 1 1

from_url(url, *, on_error='raise') staticmethod

Load TLEs from a URL, parsing the response as TLE.from_lines does

Works with any URL that returns plain-text TLE data.

Parameters:

Name Type Description Default
url str

URL to fetch TLE data from

required
on_error str

as in TLE.from_lines

'raise'

Returns:

Type Description
list[TLE]

one TLE per element set in the response

Raises:

Type Description
ValueError

with on_error="raise", if a record fails to parse or the response holds no TLEs; see TLE.from_lines

RuntimeError

if offline mode is on (SATKIT_OFFLINE=1 or satkit.utils.set_offline(True); no connection is opened) or the request fails

Example
tles = sk.TLE.from_url("https://celestrak.org/NORAD/elements/gp.php?GROUP=stations&FORMAT=tle")

from_omm(omm) staticmethod

Build a TLE from an OMM (Orbital Mean-Element Message) dictionary

The dictionary is the same shape sgp4 accepts: the flat CCSDS keys of a Space-Track / CelesTrak JSON record (see OMMDict), or the nested groups of an xmltodict rendering of the XML form. Numbers may be strings.

The six mean elements, epoch, BSTAR, MEAN_MOTION_DOT, MEAN_MOTION_DDOT, NORAD_CAT_ID, ELEMENT_SET_NO, REV_AT_EPOCH and EPHEMERIS_TYPE carry over; of these, the optional ones become zero when absent. OBJECT_NAME becomes the name, and the unnamed-TLE name "none" when it is absent, empty or UNKNOWN. OBJECT_ID in YYYY-NNNP form becomes the international designator (1998-067A gives 98067A, and 1998-067, with no piece, gives 98067); any other form leaves the designator empty. CLASSIFICATION_TYPE becomes the classification, "U" unless it is a single ASCII letter. Other metadata is dropped.

This inverts to_omm: TLE.from_omm(tle.to_omm()) == tle for a TLE read from two or three lines.

Parameters:

Name Type Description Default
omm OMMDict | dict

OMM dictionary

required

Returns:

Type Description
TLE

the equivalent two-line element set

Raises:

Type Description
TypeError

if omm is not a dict

ValueError

if a required key (EPOCH or one of the six mean elements) is missing or a value cannot be read

Example
omm = sk.omm_from_url("https://celestrak.org/NORAD/elements/gp.php?CATNR=25544&FORMAT=json")[0]
tle = sk.TLE.from_omm(omm)
print("\n".join(tle.to_2line()))

to_omm()

Render this TLE as an OMM (Orbital Mean-Element Message) dictionary

The result uses the flat CCSDS keys (see OMMDict) with EPOCH as an RFC 3339 string, angles in degrees and mean motion in revolutions per day, and can be passed back to sgp4 or serialized with json.dumps. OBJECT_ID is derived from the international designator (98067A becomes 1998-067A, 98067 1998-067, a blank one UNKNOWN), OBJECT_NAME is the name (UNKNOWN for an unnamed TLE), and CLASSIFICATION_TYPE is the TLE's classification letter. A negative satnum, element_num or rev_num and an ephem_type above 9 have no OMM form and are left out.

Returns:

Type Description
OMMDict

OMM dictionary

to_2line()

Output as 2 canonical TLE Lines

The element set number (4 columns) and revolution number (5 columns) are written modulo 10,000 and 100,000, so a larger value wraps around the way catalog TLEs roll the revolution counter over.

Returns:

Type Description
list[str]

2 canonical TLE Lines

Raises:

Type Description
ValueError

if the element set does not fit the format: satnum is 340000 or above (Alpha-5, used for the 5-character satellite number field, ends at Z9999 = 339999; use to_omm() instead) or negative, eccen is outside [0, 1), or the epoch year is outside 1957-2056 (the span of the two-digit year)

Example
lines = tle.to_2line()
print(lines[0])
# 1 25544U 98067A  ...
print(lines[1])
# 2 25544  51.6442 ...

to_3line()

Output as 2 canonical TLE lines preceded by a name line (3-line element set)

Returns:

Type Description
3-line element set

the name ("none" for an unnamed TLE), then the 2 canonical TLE lines of to_2line

Raises:

Type Description
ValueError

as to_2line

Example
lines = tle.to_3line()
for line in lines:
    print(line)

fit_from_states(states, times, epoch, *, gravconst=sgp4_gravconst.wgs72, opsmode=sgp4_opsmode.afspc, satnum=None, name=None, intl_desig=None) staticmethod

Perform non-linear least squares fit of TLE parameters to a list of GCRF states

Parameters:

Name Type Description Default
states ArrayLike

GCRF states to fit to: an Nx6 array, or a list of 6-element vectors. The first 3 values are positions in meters. The last 3 values are velocities in meters / second.

required
times TimeInput

Times corresponding to the states, one per state: a list or array of times (a single time is accepted for a single state)

required
epoch TimeScalar

Epoch time for the TLE: a single time, within the range of times

required

Other Parameters:

Name Type Description
gravconst sgp4_gravconst

gravity model SGP4 uses in the fit. Default is sgp4_gravconst.wgs72

opsmode sgp4_opsmode

SGP4 ops mode used in the fit. Default is sgp4_opsmode.afspc

satnum int | None

satellite number of the fitted TLE (0 if omitted); checked as setting the satnum property is

name str | None

name of the fitted TLE ("none" if omitted)

intl_desig str | None

international designator of the fitted TLE (blank if omitted); checked as setting the intl_desig property is

Returns:

Type Description
tuple[TLE, TLEFitResult]

Fitted TLE and the fit results, a dictionary (see TLEFitResult). The fitted TLE has the satnum, name and intl_desig given; those left out are satellite number 0, the name "none" and a blank international designator.

Raises:

Type Description
TypeError

if states is not a sequence of 6-element vectors, times or epoch is not a time (epoch must be a single time, not a list), or gravconst / opsmode is not the enum

ValueError

if states is empty, states and times differ in length, epoch is outside the range of times, or satnum or intl_desig is a value its property refuses (checked before the fit)

OverflowError

if satnum does not fit 32 bits

RuntimeError

if the fit itself fails (SGP4 cannot evaluate the elements, singular normal equations, or it ends on elements a TLE cannot hold)

Notes

SGP4 propagator is used to match TLE to the states. The fitted TLE reproduces the states when propagated with sgp4 under the same gravconst and opsmode; the defaults match sgp4's. satkit before 0.24 fitted with WGS84. Input GCRF states are rotated into TEME frame used by SGP4, with the full IERS 2010 rotation. First and second derivatives of mean motion are ignored, as they are not used by SGP4.

Non-linear Levenberg-Marquardt optimization fits the orbital elements, mean motion and drag (bstar) to the provided states. The solver is parameterized in equinoctial elements, which are not singular for circular or equatorial (e.g. geostationary) orbits, and converts to the classical TLE elements at the end. It is built on top of the numeris linear algebra crate.

The results dictionary (TLEFitResult) has the keys status (a tlefitstatus), converged (bool), orig_norm, best_norm, grad_norm (floats), n_iter and n_res_evals (ints).

Example
import numpy as np

# Given a list of GCRF states and times
states = [np.array([pos0[0], pos0[1], pos0[2], vel0[0], vel0[1], vel0[2]])]
times = [satkit.time(2024, 1, 1)]
epoch = satkit.time(2024, 1, 1)

tle, results = satkit.TLE.fit_from_states(states, times, epoch)
if results["converged"]:
    print("Fit successful")

TLEWarning

Warning for a TLE record skipped by a loader called with on_error="warn"

The message is the one on_error="raise" raises as ValueError: it gives the input line the record starts on, its satellite and what failed to parse. With on_error="warn", input that holds no element sets at all also gets one, saying so.

tlefitstatus

Termination status of the TLE non-linear least-squares fit performed by TLE.fit_from_states.

Values:

  • GradientConverged: converged on gradient norm tolerance
  • StepConverged: converged on relative step size tolerance
  • CostConverged: converged on relative cost change tolerance
  • MaxIterations: maximum number of iterations reached
  • DampingSaturated: Levenberg-Marquardt damping parameter saturated

their integer value (int(m), 0 to 4 in the order above), and tlefitstatus(value) turns a value back into a member. their integer value (int(m), 0 to 4 in the order above).

GradientConverged class-attribute

Converged on gradient norm tolerance

StepConverged class-attribute

Converged on relative step size tolerance

CostConverged class-attribute

Converged on relative cost change tolerance

MaxIterations class-attribute

Maximum number of iterations reached

DampingSaturated class-attribute

Levenberg-Marquardt damping parameter saturated

converged property

True for the three ...Converged members, False for MaxIterations and DampingSaturated

__new__(value)

The member with integer value value

For example satkit.tlefitstatus(3) is tlefitstatus.MaxIterations.

Raises:

Type Description
ValueError

if value is not one of the values 0 to 4

__int__()

The member's integer value

__eq__(other)

Equal to the same member, or to its integer value

__hash__()

Members are hashable and immutable; one hashes like the integer it equals

sgp4(tle, time, *, gravconst=sgp4_gravconst.wgs72, opsmode=sgp4_opsmode.afspc, errflag)

sgp4(tle: TLE | OMMDict | dict[str, Any] | list[TLE] | list[OMMDict] | list[dict[str, Any]] | list[TLE | OMMDict | dict[str, Any]], time: TimeInput, *, gravconst: sgp4_gravconst = sgp4_gravconst.wgs72, opsmode: sgp4_opsmode = sgp4_opsmode.afspc, errflag: typing.Literal[True]) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.int32]]
sgp4(tle: TLE | OMMDict | dict[str, Any] | list[TLE] | list[OMMDict] | list[dict[str, Any]] | list[TLE | OMMDict | dict[str, Any]], time: TimeInput, *, gravconst: sgp4_gravconst = sgp4_gravconst.wgs72, opsmode: sgp4_opsmode = sgp4_opsmode.afspc, errflag: typing.Literal[False] = False) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]
sgp4(tle: TLE | OMMDict | dict[str, Any] | list[TLE] | list[OMMDict] | list[dict[str, Any]] | list[TLE | OMMDict | dict[str, Any]], time: TimeInput, *, gravconst: sgp4_gravconst = sgp4_gravconst.wgs72, opsmode: sgp4_opsmode = sgp4_opsmode.afspc, errflag: bool) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]] | tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.int32]]

SGP-4 propagator for TLE

Run Simplified General Perturbations (SGP)-4 propagator on Two-Line Element Set to output satellite position and velocity at given time in the "TEME" coordinate system.

A detailed description is in Vallado, Crawford, Hujsak and Kelso, "Revisiting Spacetrack Report #3", AIAA 2006-6753 (AIAA/AAS Astrodynamics Specialist Conference, 2006).

Parameters:

Name Type Description Default
tle TLE | OMMDict | list[TLE | OMMDict]

element set(s) to propagate: a TLE object, an OMM dictionary (see OMMDict), or a list of either (or mixing both). Must be a list; tuples and other sequences are not accepted

required
time time | datetime | datetime64 | list | tuple | ndarray

time(s) at which to compute position and velocity: a single time, a list or tuple of times, a 1-D numpy object array of times or a 1-D datetime64 array. A naive datetime is local time, not UTC (see time.from_datetime); a numpy.datetime64 is UTC

required

Other Parameters:

Name Type Description
gravconst sgp4_gravconst

gravity constant to use. Default is sgp4_gravconst.wgs72

opsmode sgp4_opsmode

sgp4_opsmode.afspc (Air Force Space Command) or sgp4_opsmode.improved. Default is sgp4_opsmode.afspc

errflag bool

whether or not to output error conditions for each TLE and time output. Default is False (this is likely rarely needed, but can be useful for debugging)

Returns:

Type Description
tuple[NDArray[float64], NDArray[float64]]

position and velocity in meters and meters/second, respectively, in the TEME frame at each of the "Ntime" input times and each of the "Ntle" tles. Shape is (3,) for a single TLE and single time, (Ntime, 3) for a single TLE and multiple times, (Ntle, 3) for a list of TLEs and a single time, and (Ntle, Ntime, 3) for a list of TLEs and multiple times. A list keeps its axis even with one element ("list in, list out"): sgp4([tle], t) is (1, 3) and sgp4([tle], [t]) is (1, 1, 3). Empty lists give empty arrays of the matching shape, e.g. sgp4(tle, []) is (0, 3) and sgp4([tle], []) is (1, 0, 3). If errflag is True, a third element is returned: an int32 numpy array of error codes, one per TLE and time — shape (1,) for a single TLE and time, (Ntime,), (Ntle,) or (Ntle, Ntime) otherwise. 0 is success. The codes are the integer values of sgp4_error, so comparing against the enum works elementwise: err == satkit.sgp4_error.success is a boolean array.

Notes
  • Units: the canonical Vallado SGP4 implementation (and most other SGP4 libraries) return position in kilometers and velocity in kilometers/second. satkit converts these to meters and meters/second so that SGP4 output is consistent with every other position and velocity in the library.
  • OMM dictionaries: any dict with the CCSDS keys EPOCH, MEAN_MOTION, ECCENTRICITY, INCLINATION, RA_OF_ASC_NODE, ARG_OF_PERICENTER and MEAN_ANOMALY (plus optional BSTAR, MEAN_MOTION_DOT, MEAN_MOTION_DDOT) is accepted, whether it came from omm_from_url / omm_from_file / omm_from_text, from json.load on a CelesTrak or Space-Track response (numbers may be strings), or from xmltodict.parse on the XML form: the whole result (root key omm, or ndm holding one omm) or any node below it, the nested header / body / segment / metadata / data / meanElements / tleParameters groups being understood. An ndm holding several messages is not one element set: pass sgp4 the list [{"omm": m} for m in d["ndm"]["omm"]]. EPOCH may be an RFC 3339 string, a CCSDS day-of-year string (YYYY-DDDThh:mm:ss), a satkit.time, a datetime (naive = local time) or a numpy.datetime64 (UTC). Other keys are ignored, except that MEAN_ELEMENT_THEORY must be SGP4, TIME_SYSTEM must be UTC, REF_FRAME must be TEME, CENTER_NAME must be EARTH and EPHEMERIS_TYPE must not be 4 (SGP4-XP) when present.
  • The "TEME" frame of the SGP4 state vectors is not a truly inertial frame. It is a "True Equator Mean Equinox" frame: its axes are the true equator and the mean equinox of date, i.e. of each output time (not of the TLE epoch), so the frame itself moves with precession and nutation. Rotate to GCRF with frametransform.rotation(frame.TEME, frame.GCRF, time).
  • Errors are reported per element set and per time, in two ways. A time at which propagation fails (e.g. the orbit has decayed by then) never raises, with or without errflag: its position and velocity rows are NaN, and with errflag True its code is in the error array. Without errflag, check the output for NaN. An element set that cannot be initialized at all (e.g. zero mean motion or an eccentricity out of range at epoch, an SGP4-XP set, or OMM metadata SGP4 cannot use) raises RuntimeError when errflag is False; for a list, the message names its index (element set 1 of the list: ...) and nothing is returned for the others. With errflag True it does not raise: its rows are NaN at every time and every time carries its init code (sgp4_error.unsupported for an SGP4-XP set or OMM metadata SGP4 cannot use), so one bad element set does not fail a list.
  • Leap seconds: the time since epoch is the physical (SI) time elapsed. Across a leap second this is one second more than the difference of the UTC labels that Vallado's reference code and python-sgp4 use, so satkit differs from them by 1 s of along-track motion (~7.6 km at LEO) per leap second between epoch and time. This is deliberate: the satellite really flies 86,401 s over such a day, and the SGP4 mean motion is per SI day.

Raises:

Type Description
TypeError

if tle is not a TLE, a dict or a list of them, time is not a time or a list / array of times, or gravconst / opsmode is not a member of its enum

ValueError

if an OMM dictionary lacks a required key or holds a value that cannot be read

RuntimeError

with errflag False, if an element set cannot be initialized (see Errors above)

Example
import numpy as np
import satkit

lines = [
    "0 INTELSAT 902",
    "1 26900U 01039A   06106.74503247  .00000045  00000-0  10000-3 0  8290",
    "2 26900   0.0164 266.5378 0003319  86.1794 182.2590  1.00273847 16981",
]

tle = satkit.TLE.from_lines(lines)[0]  # from_lines always returns a list
tm = tle.epoch

# Compute TEME position & velocity at epoch
pteme, vteme = satkit.sgp4(tle, tm)

# Rotate to ITRF frame; the velocity also loses the Earth-rotation term
q = satkit.frametransform.qteme2itrf(tm)
pitrf = q * pteme
vitrf = q * vteme - np.cross(np.array([0, 0, satkit.consts.omega_earth]), pitrf)

# convert to ITRF coordinate object
coord = satkit.itrfcoord(pitrf)

# Print ITRF coordinate object location
print(coord)
# ITRFCoord(lat:  -0.0362 deg, lon:  62.0172 deg, hae: 35799.52 km)

# Error codes per output
pteme, vteme, err = satkit.sgp4(tle, tm, errflag=True)
assert (err == satkit.sgp4_error.success).all()
# Query the OMM for the International Space Station (ISS)
url = "https://celestrak.org/NORAD/elements/gp.php?CATNR=25544&FORMAT=json"
omm = satkit.omm_from_url(url)[0]
# Get a representative time from the output
epoch = satkit.time(omm["EPOCH"])
# Compute TEME position & velocity at epoch
pteme, vteme = satkit.sgp4(omm, epoch)

sgp4_error

Error codes of SGP4 propagation, as in the error array of sgp4(..., errflag=True)

That array holds plain int32 codes; a member compares equal to its code, so err == satkit.sgp4_error.success works elementwise, and satkit.sgp4_error(code) turns one code back into a member.

Example
print(int(satkit.sgp4_error.orbit_decay))
# 6
print(satkit.sgp4_error.orbit_decay == 6)
# True
print(satkit.sgp4_error(6))
# sgp4_error.orbit_decay

success class-attribute

Success (code 0)

eccen class-attribute

Mean eccentricity at the requested time is 1 or more, or below -0.001 (code 1)

mean_motion class-attribute

Mean motion is zero or negative (code 2)

perturb_eccen class-attribute

Perturbed eccentricity outside [0, 1] (code 3)

semi_latus_rectum class-attribute

Semi-latus rectum negative (code 4)

unused class-attribute

Not produced (code 5); kept because the reference code numbers it

orbit_decay class-attribute

Orbit decayed: the computed radius is less than one Earth radius (code 6)

unsupported class-attribute

Only in the error array of sgp4(..., errflag=True): the element set cannot be propagated by classic SGP4 at all (an SGP4-XP set, or OMM metadata naming another theory, time system, frame or center) (code 7)

__new__(code)

The member with integer code code

For example satkit.sgp4_error(int(err[0])) for an element of the error array of sgp4(..., errflag=True).

Raises:

Type Description
ValueError

if code is not one of the codes 0 to 7

__int__()

The member's integer code

__eq__(other)

Equal to the same member, or to its integer code

__hash__()

Members are hashable and immutable; one hashes like the integer it equals

sgp4_gravconst

Gravity constants (Earth radius, mu, J2-J4) used by SGP4 propagation

Element sets are generated with WGS-72, so wgs72 (the default of sgp4 and TLE.fit_from_states) is the one that reproduces the orbit a TLE or OMM describes.

Members compare equal to their integer value (int(m)), and sgp4_gravconst(value) turns a value back into a member.

wgs72 class-attribute

WGS-72, the default (value 0)

wgs72old class-attribute

WGS-72 with the older, lower-precision constants of the original Spacetrack Report #3 code (value 1)

wgs84 class-attribute

WGS-84 (value 2)

__new__(value)

The member with integer value value

For example satkit.sgp4_gravconst(2) is sgp4_gravconst.wgs84.

Raises:

Type Description
ValueError

if value is not one of the values 0 to 2

__int__()

The member's integer value

__eq__(other)

Equal to the same member, or to its integer value

__hash__()

Members are hashable and immutable; one hashes like the integer it equals

sgp4_opsmode

Ops mode for SGP4 propagation

Selects between the two variants of Vallado's SGP4 code. They differ only for deep-space element sets (period of 225 minutes or more), in how the ascending node is wrapped in the lunar-solar periodic terms.

Members compare equal to their integer value (int(m)), and sgp4_opsmode(value) turns a value back into a member.

afspc class-attribute

Reproduces the Air Force Space Command code that generates TLEs; the default (value 0)

improved class-attribute

Vallado's "improved" mode (value 1)

__new__(value)

The member with integer value value

For example satkit.sgp4_opsmode(1) is sgp4_opsmode.improved.

Raises:

Type Description
ValueError

if value is not 0 or 1

__int__()

The member's integer value

__eq__(other)

Equal to the same member, or to its integer value

__hash__()

Members are hashable and immutable; one hashes like the integer it equals

omm_from_url(url)

Load OMM(s) from a URL as a list of dictionaries

Fetches the content at the given URL and auto-detects the format (JSON, XML or CSV), as omm_from_text does. A CelesTrak GP query with no FORMAT answers in CSV. Returns a list of dictionaries that can be passed directly to sgp4.

Parameters:

Name Type Description Default
url str

URL to fetch OMM data from (e.g. CelesTrak or Space-Track endpoint)

required

Returns:

Type Description
list[dict[str, Any]]

one dictionary per message, with every CCSDS field the source provided (the keys of OMMDict) plus the source's extra keys

Raises:

Type Description
RuntimeError

if offline mode is on (SATKIT_OFFLINE=1 or satkit.utils.set_offline(True); no connection is opened) or the request fails

ValueError

if the response is not JSON, XML or CSV, or is malformed

Example
import satkit as sk

omms = sk.omm_from_url("https://celestrak.org/NORAD/elements/gp.php?GROUP=stations&FORMAT=json")
pos, vel = sk.sgp4(omms[0], sk.time(2024, 1, 1))

omm_from_file(filename)

Load OMM(s) from a JSON, XML or CSV file as a list of dictionaries

The format is detected from the content, not the file extension, as omm_from_text does: a file starting with [ or { is JSON (one message or an array of them), one starting with < is a CCSDS NDM/XML document, and one whose first line holds a comma is a CSV table. KVN is not supported.

Parameters:

Name Type Description Default
filename str | PathLike

path to the file

required

Returns:

Type Description
list[dict[str, Any]]

one dictionary per message, as omm_from_text returns

Raises:

Type Description
FileNotFoundError

if the file does not exist; the exception names the path. Another I/O failure raises the matching OSError

ValueError

if the content is none of the three formats or is malformed

Example
import satkit as sk

omms = sk.omm_from_file("gp.xml")   # saved from Space-Track or CelesTrak
pos, vel = sk.sgp4(omms, sk.time(2024, 1, 1))

omm_from_text(text)

Parse OMM(s) from JSON, XML or CSV text as a list of dictionaries

Text starting with [ or { is parsed as JSON (one message or an array of them), text starting with < as a CCSDS NDM/XML document, and text whose first line holds a comma as CSV. KVN is not supported.

The CSV form is a header row of OMM keywords and one row per message, as CelesTrak (its default for GP queries) and Space-Track serve it. Fields may be quoted and columns may come in any order. An empty cell is an absent field, except OBJECT_NAME and OBJECT_ID, which stay empty strings; columns that are not OMM fields are kept as strings (None where empty).

Parameters:

Name Type Description Default
text str

the document

required

Returns:

Type Description
list[dict[str, Any]]

one dictionary per message. The CCSDS fields have the keys and value types of OMMDict, with EPOCH an RFC 3339 string; keys that are not CCSDS fields (Space-Track's OBJECT_TYPE, TLE_LINE1, ...; XML USER_DEFINED parameters; extra CSV columns) are kept as the source gave them, which is why the type is a plain dict and not OMMDict

Raises:

Type Description
ValueError

if the text is none of the three formats or is malformed; for CSV the message gives the line of the bad row, and a table with no EPOCH or MEAN_MOTION column is refused

Example
import satkit as sk
import requests

r = requests.get("https://celestrak.org/NORAD/elements/gp.php?CATNR=25544&FORMAT=xml")
omm = sk.omm_from_text(r.text)[0]

OMMDict

An Orbital Mean-Element Message (OMM) as a plain dictionary

This is the shape returned by TLE.to_omm and accepted by sgp4 and TLE.from_omm. It is an ordinary dict (this class exists for type checking only): the keys are the CCSDS 502.0-B-3 field names, so json.load on a Space-Track or CelesTrak JSON response produces one directly. Every key is optional in the type; sgp4 needs EPOCH and the six mean elements.

omm_from_url, omm_from_file and omm_from_text return dictionaries with these keys and whatever other keys their source had, so they are typed dict[str, Any], which sgp4 and TLE.from_omm accept as well. To have a type checker verify the CCSDS keys of one, use typing.cast(OMMDict, omm).

Units follow the TLE convention: angles in degrees, MEAN_MOTION in revolutions per day, MEAN_MOTION_DOT in rev/day² and MEAN_MOTION_DDOT in rev/day³ (the TLE fields, i.e. ṅ/2 and n̈/6), BSTAR in inverse Earth radii, GM in km³/s², MASS in kg, areas in m², BTERM and AGOM in m²/kg.

The loaders return numbers as float / int (Space-Track quotes them as strings in its JSON; sgp4 accepts either), EPOCH as an RFC 3339 string, absent optional fields omitted, and every key that is not one of the fields below (Space-Track's OBJECT_TYPE, RCS_SIZE, LAUNCH_DATE, TLE_LINE1, ...; XML USER_DEFINED parameters; extra CSV columns, as strings) kept verbatim.

As input, EPOCH may also be a satkit.time, a datetime.datetime (naive = local time) or a numpy.datetime64 (UTC).

TLEFitResult

Results of TLE.fit_from_states, returned next to the fitted TLE

An ordinary dict (this class exists for type checking only). The norms are those of the residual vector the Levenberg-Marquardt solver minimizes.

status instance-attribute

Why the solver stopped

converged instance-attribute

status.converged: True if it stopped on a convergence tolerance

orig_norm instance-attribute

Residual norm at the initial guess

best_norm instance-attribute

Residual norm at the fitted elements

grad_norm instance-attribute

Norm of the gradient at the fitted elements

n_iter instance-attribute

Number of iterations taken

n_res_evals instance-attribute

Number of residual evaluations (SGP4 runs over all the states)