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:
JSONEncoderJSON 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, andpathlib.Pathto JSON-native types; defers anything else tojson.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
ArrayWUnitsfrom a dict produced byawu_to_dict().- Parameters:
- ddict or None
Serialized quantity (
{"values", "units"}).
- Returns:
- ArrayWUnits or None
The reconstructed quantity, or
Nonewhen d isNone.
- awu_to_dict(awu) dict | None#
Serialize an
ArrayWUnitsto a plain dict.- Parameters:
- awuArrayWUnits or None
Quantity to serialize.
- Returns:
- dict or None
{"values": <list>, "units": <units dict>}, orNonewhen awu isNone.
- dump(obj: Any, path: str | Path, fmt: str = None, indent: int = 2) Path#
Serialize
objtopathas JSON or pickle (one entry point for both).- Parameters:
- objAny
Object to serialize (typically a
to_dictresult).- 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
objtopathas 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 to2.
- Returns:
- pathlib.Path
The resolved destination path.
- dump_pickle(obj: Any, path: str | Path, protocol: int = 5) Path#
Write
objtopathas a pickle. Parent directories are created.- Parameters:
- objAny
Object to serialize (typically a
to_dictresult, 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") forfmt.fmtofNonedefaults 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
pathbydump_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
typevalues fall back to a genericBody.
- 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
Spacecraftit also records the initial mass, area, reflectivity coefficient, n-plate model and attitude configuration so the object can be rebuilt byowner_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
fmtwhen given (case-insensitive; accepts"json","pickle","pkl"); otherwise infers it from the file extension (.pkl/.picklegives pickle, anything else json).- Raises:
- UnknownSerializationFormatError
If
fmtis 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 plainmass()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
Noneif 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
ArrayWUnitswhen 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_coeffabove 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. AnArrayWUnitsbecomes the tagged dictawu_to_dict()produces, plus a"__awu__"marker soscalar_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
objthrough the numpy-awareSCBJSONEncoderso that numpy scalars/arrays, sets, tuples andPathobjects 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
pathwith its extension switched to matchfmt.When
fmtisNonethe path is returned unchanged (the caller’s extension already selects the format); otherwise the suffix becomes.jsonor.pklso the on-disk name matches the bytes written.
- exception UnknownSerializationFormatError#
Bases:
ValueError