Serialization#

Shared JSON serialization helpers.

Scarabaeus persists most artifacts as JSON (trajectory sidecars, propagator settings, STMs, filter datasets, OD solutions). These helpers give every save path one numpy-aware encoder and a single dump_json / load_json entry point so the on-disk convention stays consistent.

class SCBJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#

Bases: JSONEncoder

JSON encoder that understands the numpy types Scarabaeus produces.

Methods

default(o)

Encode the non-native types Scarabaeus emits into JSON values.

encode(o)

Return a JSON string representation of a Python data structure.

iterencode(o[, _one_shot])

Encode the given object and yield each string representation as available.

default(o: Any)#

Encode the non-native types Scarabaeus emits into JSON values.

Converts numpy arrays/scalars, set/tuple, and pathlib.Path to JSON-native types; defers anything else to json.JSONEncoder.default().

Parameters:
oAny

Object the base encoder could not serialize.

Returns:
Any

A JSON-native representation of o.

awu_from_dict(d)#

Reconstruct an ArrayWUnits from a dict produced by awu_to_dict().

Parameters:
ddict or None

Serialized quantity ({"values", "units"}).

Returns:
ArrayWUnits or None

The reconstructed quantity, or None when d is None.

awu_to_dict(awu) → dict | None#

Serialize an ArrayWUnits to a plain dict.

Parameters:
awuArrayWUnits or None

Quantity to serialize.

Returns:
dict or None

{"values": <list>, "units": <units dict>}, or None when awu is None.

dump(obj: Any, path: str | Path, fmt: str = None, indent: int = 2) → Path#

Serialize obj to path as JSON or pickle (one entry point for both).

Parameters:
objAny

Object to serialize (typically a to_dict result).

pathstr or pathlib.Path

Destination file path.

fmt{“json”, “pickle”}, optional

Output format. When None (default), inferred from the file extension.

indentint, optional

Indentation for the JSON format. Ignored for pickle. Defaults to 2.

Returns:
pathlib.Path

The resolved destination path.

dump_json(obj: Any, path: str | Path, indent: int = 2) → Path#

Write obj to path as JSON using the numpy-aware encoder.

Parent directories are created automatically.

Parameters:
objAny

Object to serialize; numpy types are handled by SCBJSONEncoder.

pathstr or pathlib.Path

Destination file path.

indentint, optional

Indentation passed to json.dump(). Defaults to 2.

Returns:
pathlib.Path

The resolved destination path.

dump_pickle(obj: Any, path: str | Path, protocol: int = 5) → Path#

Write obj to path as a pickle. Parent directories are created.

Parameters:
objAny

Object to serialize (typically a to_dict result, but any picklable object is accepted).

pathstr or pathlib.Path

Destination file path.

protocolint, optional

Pickle protocol. Defaults to pickle.HIGHEST_PROTOCOL.

Returns:
pathlib.Path

The resolved destination path.

format_suffix(fmt: str = None) → str#

Return the file extension (".json" or ".pkl") for fmt.

fmt of None defaults to ".json". Useful for save paths that build their own file names and need the extension to follow the chosen format.

load(path: str | Path, fmt: str = None) → Any#

Read a JSON or pickle file written by dump().

Parameters:
pathstr or pathlib.Path

Source file path.

fmt{“json”, “pickle”}, optional

Input format. When None (default), inferred from the file extension.

Returns:
Any

The decoded object.

load_json(path: str | Path) → Any#

Read and return the JSON object stored at path.

Parameters:
pathstr or pathlib.Path

Path to a JSON file written by dump_json().

Returns:
Any

The decoded JSON object.

load_pickle(path: str | Path) → Any#

Read and return the object stored at path by dump_pickle().

Parameters:
pathstr or pathlib.Path

Path to a pickle file.

Returns:
Any

The unpickled object.

owner_from_dict(d)#

Reconstruct a state-component owner from owner_to_dict().

Parameters:
ddict

Serialized owner (as produced by owner_to_dict()).

Returns:
Spacecraft, GroundStation, CelestialBody or Body

The reconstructed owner. Unknown type values fall back to a generic Body.

owner_to_dict(owner) → dict#

Serialize a state-component owner to a plain dict.

Captures the type, name and SPICE id of any owner; for a Spacecraft it also records the initial mass, area, reflectivity coefficient, n-plate model and attitude configuration so the object can be rebuilt by owner_from_dict().

Parameters:
ownerSpacecraft, CelestialBody, GroundStation or Body

State-component owner to serialize.

Returns:
dict

Serialized owner (always has type, name, spice_id).

resolve_format(path: str | Path, fmt: str = None) → str#

Resolve the serialization format, returning "json" or "pickle".

Uses fmt when given (case-insensitive; accepts "json", "pickle", "pkl"); otherwise infers it from the file extension (.pkl / .pickle gives pickle, anything else json).

Raises:
UnknownSerializationFormatError

If fmt is given and is none of "json", "pickle" and "pkl".

safe_initial_mass(owner)#

Return the spacecraft’s initial mass as an ArrayWUnits.

Robust to the mass having been converted to a time-varying polynomial during a prior propagation: prefers the stored _mass_profile, then evaluates the mass at the start of the first profile span, then falls back to a plain mass() query.

The first span is the one that matters: profiles accumulate one per propagated leg, so the most recent span starts wherever the last leg did, by which point a burn may already have spent propellant.

Parameters:
ownerSpacecraft

Body whose initial mass is requested.

Returns:
ArrayWUnits or None

The initial mass, or None if it cannot be determined.

scalar_from_dict(d)#

Reconstruct a value written by scalar_to_dict().

Parameters:
ddict, float, int or None

Serialized value.

Returns:
ArrayWUnits, float, int or None

The ArrayWUnits when d carries the "__awu__" marker, else d unchanged.

scalar_to_dict(value) → Any#

Serialize a value that may be a bare number or an ArrayWUnits.

Several spacecraft properties (ref_coeff above all) are documented as plain floats but are just as often built as unitful quantities, so the on-disk form has to carry both cases. An ArrayWUnits becomes the tagged dict awu_to_dict() produces, plus a "__awu__" marker so scalar_from_dict() knows to rebuild the quantity; anything else is written through unchanged.

Parameters:
valueArrayWUnits, float, int or None

Value to serialize.

Returns:
Any

A JSON-native representation of value.

to_jsonable(obj: Any) → Any#

Return a deep, JSON-serializable copy of obj.

Round-trips obj through the numpy-aware SCBJSONEncoder so that numpy scalars/arrays, sets, tuples and Path objects are converted to native Python types.

Parameters:
objAny

Object to convert. May contain numpy types nested arbitrarily.

Returns:
Any

A new object containing only JSON-native types (dict, list, str, int, float, bool, None).

with_format_suffix(path: str | Path, fmt: str = None) → Path#

Return path with its extension switched to match fmt.

When fmt is None the path is returned unchanged (the caller’s extension already selects the format); otherwise the suffix becomes .json or .pkl so the on-disk name matches the bytes written.

exception UnknownSerializationFormatError#

Bases: ValueError