Utils#

class Utils#

Bases: object

Collection of general-purpose utility methods used throughout Scarabaeus.

Provides static helpers for array manipulation and file I/O.

Methods

VandV_compare(positions, velocities, times, ...)

Compare a Scarabaeus-generated trajectory against a SPICE ground truth.

VandV_plot_errors(errorPosition, ...)

Plot position and velocity errors in a standardised V&V layout.

build_reorder_operator(old_list, new_list)

Build the Q selection/reorder operator mapping the old state to the new.

check_slices_equal(arr)

Checks if all slices are equal across an array.

cross3D(a, b)

3D vector cross product operation.

enumerate_state_blocks(state_list)

Enumerate the scalar blocks of a state definition with a rich key.

equal_along_rows(arr)

Check equality along rows of the given array.

find_date_indices_in_epochs(epochsTDB, ...)

Find the index or indices of target date(s) in a numpy array of epochs, accounting for floating-point precision.

load_json(dir[, print_flag])

Load and parse a JSON file from disk.

make_dir(dir)

Generate a folder in the given directory.

max_of_last_slice(arr)

Finds the maximum value of the last slice of an array.

open_pickle(dir)

Return a pickle object handle from dir.

reorder_covariance(Q, P[, new_block_variances])

Reorder a covariance: P' = Q P Q^T, with a-priori variances for new states.

reorder_stm(Q, STM[, new_blocks])

Reorder a State Transition Matrix: Phi' = Q Phi Q^T.

reorder_vector(Q, x)

Apply the reorder operator to a state / deviation vector: X' = Q X.

skew(vector)

Skew-symmetric cross-product matrix of a 3D vector.

tile_array(arr, desired_shape)

Construct an array by repeating A the number of times given by reps.

norm3D

See also

scarabaeus.EpochArray

Time-tag array type accepted by several helpers.

static VandV_compare(positions: ndarray, velocities: ndarray, times: EpochArray, caseId: str, integratorName: str, flag_SUN: bool = False, leg1_period=None, leg2_period=None)#

Compare a Scarabaeus-generated trajectory against a SPICE ground truth.

Loads the SPICE BSP kernel for caseId, queries the reference state at each epoch in times, computes the component-wise and norm errors, prints a summary to stdout, and delegates plotting to VandV_plot_errors().

Parameters:
positionsnumpy.ndarray

Spacecraft positions from Scarabaeus, shape (N, 3) in km.

velocitiesnumpy.ndarray

Spacecraft velocities from Scarabaeus, shape (N, 3) in km/s.

timesEpochArray

Epoch array of length N corresponding to each state sample.

caseIdstr

Scenario identifier; used to locate the BSP kernel at <cwd>/data/kernels/validation/<caseId>.bsp.

integratorNamestr

Integration scheme label, printed in the summary and plot titles.

flag_SUNbool, optional

When True uses the Sun as the inertial origin; otherwise uses Earth. Defaults to False.

leg1_periodArrayWUnits or None, optional

Duration of the first trajectory leg in seconds. Required for multi-leg cases (MONTE_case17a/b/c); None otherwise.

leg2_periodArrayWUnits or None, optional

Duration of the second trajectory leg in seconds. Required for multi-leg cases; None otherwise.

Returns:
figHandlematplotlib.figure.Figure

Handle to the V&V error plot.

max_state_error_norm_posfloat

Maximum position error norm over the trajectory in km.

max_state_error_norm_velfloat

Maximum velocity error norm over the trajectory in km/s.

static VandV_plot_errors(errorPosition: ndarray, errorVelocity: ndarray, times: EpochArray, caseId: str, integratorName: str)#

Plot position and velocity errors in a standardised V&V layout.

Produces a two-panel figure with position error (top) and velocity error (bottom) as functions of elapsed time in days.

Parameters:
errorPositionnumpy.ndarray

Position error array of shape (N, 3) in km, computed as positions_scb - positions_truth.

errorVelocitynumpy.ndarray

Velocity error array of shape (N, 3) in km/s, computed as velocities_scb - velocities_truth.

timesEpochArray

Epoch array of length N corresponding to each error sample.

caseIdstr

Scenario identifier used as the plot title prefix.

integratorNamestr

Integration scheme label appended to each subplot title.

Returns:
figHandlematplotlib.figure.Figure

Handle to the generated figure.

static build_reorder_operator(old_list, new_list)#

Build the Q selection/reorder operator mapping the old state to the new.

Blocks are matched on (name, spice_id, occurrence). A new block with no old counterpart yields an all-zero row in Q (an expansion target).

Parameters:
old_listlist

State definition before the node transition.

new_listlist

State definition after the node transition.

Returns:
Qnumpy.ndarray

(new_n, old_n) operator with Q[i, j] = 1 when old scalar j maps to new scalar i.

new_nint

Dimension of the new state.

new_blockslist of (str, int, int)

(name, start, size) of blocks present in new_list but absent from old_list (expansion targets — zero rows of Q).

static check_slices_equal(arr: ndarray)#

Checks if all slices are equal across an array.

Parameters:
arrnumpy.ndarray

The array to examine.

Returns:
are_equalbool

Indicates if all slices are equal or not.

static cross3D(a, b)#

3D vector cross product operation.

Removes the overhead of numpy.cross for purely 3D vectors.

Parameters:
aarray_like

First 3D vector, indexable at positions 0, 1 and 2.

barray_like

Second 3D vector, indexable at positions 0, 1 and 2.

Returns:
cross_productnumpy.ndarray

The 3D vector cross product a x b.

static enumerate_state_blocks(state_list)#

Enumerate the scalar blocks of a state definition with a rich key.

The key (name, size, spice_id, frame_name, occurrence) fully disambiguates repeated parameters across bodies and occurrences, so it can project values between a global state and per-leg definitions with one consistent keying convention.

Parameters:
state_listlist

State-definition entries (6-tuples (name, size, est, dyn, body, awf)).

Yields:
keytuple

(name, size, spice_id, frame_name, occurrence).

startint

Scalar offset of the block in the stacked state vector.

sizeint

Number of scalars in the block.

entrytuple

The original state-definition entry.

static equal_along_rows(arr: ndarray) → bool#

Check equality along rows of the given array.

Parameters:
arrnumpy.ndarray

The array to examine.

Returns:
are_equalbool

Returns True if all values are equal along rows. Returns False if they are not.

static find_date_indices_in_epochs(epochsTDB, target_dates, rtol=1e-06)#

Find the index or indices of target date(s) in a numpy array of epochs, accounting for floating-point precision.

Parameters:
epochsTDBEpochArray

Reference epoch array to search within.

target_datesEpochArray or list of EpochArray

Target epoch(s) to locate inside epochsTDB.

rtolfloat, optional

Relative tolerance for comparing the dates. Defaults to 1e-6.

Returns:
indint or list of ints

The index or indices of the target date(s), or None if not found.

static load_json(dir: str, print_flag: bool = False) → dict#

Load and parse a JSON file from disk.

Parameters:
dirstr

Path to the .json file to load.

print_flagbool, optional

When True, prints a confirmation message after a successful read. Defaults to False.

Returns:
datadict or list

Parsed JSON content.

Raises:
OSError

The file could not be read: missing, unreadable, or, for cloud-backed storage, not materialised locally.

json.JSONDecodeError

The file was read but does not contain valid JSON.

static make_dir(dir: str) → None#

Generate a folder in the given directory.

Parameters:
dirstr

The directory path to a generate a folder in.

Returns:
None
static max_of_last_slice(arr: ndarray)#

Finds the maximum value of the last slice of an array.

Parameters:
arrnumpy.ndarray

The array to examine.

Returns:
max_valsAny

The max value of the last slice.

static norm3D(a)#
static open_pickle(dir: str)#

Return a pickle object handle from dir.

Parameters:
dirstr

Directory + name of the pickle object.

Returns:
pickle_handleobject

The Python object deserialised from the pickle file.

static reorder_covariance(Q, P, new_block_variances=None)#

Reorder a covariance: P' = Q P Q^T, with a-priori variances for new states.

Parameters:
Qnumpy.ndarray

Reorder operator from build_reorder_operator().

Parray_like

Old (old_n, old_n) covariance.

new_block_varianceslist of (int, array_like), optional

(start, variances) for each expansion block; variances is the 1-D array of a-priori variances (\(\sigma^2\)) placed on that block’s diagonal. Off-diagonal (cross) terms stay zero (P_yz = 0).

Returns:
numpy.ndarray

The (new_n, new_n) reordered covariance.

static reorder_stm(Q, STM, new_blocks=None)#

Reorder a State Transition Matrix: Phi' = Q Phi Q^T.

Newly augmented states (zero rows of Q) receive a decoupled identity block, matching the convention that a fresh parameter starts uncorrelated with unit STM.

Parameters:
Qnumpy.ndarray

Reorder operator from build_reorder_operator().

STMarray_like

Old (old_n, old_n) State Transition Matrix.

new_blockslist of (str, int, int), optional

(name, start, size) expansion blocks (as returned by build_reorder_operator()) to set to identity.

Returns:
numpy.ndarray

The (new_n, new_n) reordered STM.

static reorder_vector(Q, x)#

Apply the reorder operator to a state / deviation vector: X' = Q X.

Parameters:
Qnumpy.ndarray

Reorder operator from build_reorder_operator().

xarray_like

Old state or deviation vector (old_n elements, any shape).

Returns:
numpy.ndarray

The reordered vector as an (new_n, 1) column. Newly augmented states map to zero.

static skew(vector) → ndarray#

Skew-symmetric cross-product matrix of a 3D vector.

Parameters:
vectorarray_like

3D vector a, holding exactly three elements in any shape.

Returns:
skew_matrixnumpy.ndarray

The (3, 3) matrix [a x], such that skew(a) @ b equals the cross product a x b for any 3D vector b.

Raises:
ValueError

If vector does not hold exactly three elements.

static tile_array(arr, desired_shape)#

Construct an array by repeating A the number of times given by reps.

Parameters:
arrnumpy.ndarray

The array to examine.

desired_shapetuple of int

Target shape of the output array. The last dimension must equal len(arr); all preceding dimensions specify how many times to repeat the array along each axis.

Returns:
tilednumpy.ndarray

The new tiled array.