MeasurementSpec#

class MeasurementSpec(model: Any = None, observed_meas: Any = None, epochs: Any = None, dataset_name: str | None = None, file_label: str | None = None, dataset: Any = None, provenance: dict | None = None, _items: tuple | None = None)#

Bases: object

Specification of one or more measurement datasets for filtering.

This class can represent either a single measurement specification (leaf mode) or a container of multiple MeasurementSpec objects (container mode). In both cases, the object is iterable and yields dictionaries compatible with the Scarabaeus filtering API.

Attributes:
modelAny

Measurement model instance (e.g., RangeIdeal, RangeRateIdeal, AngularIdeal).

observed_measAny

Observed measurement quantities as returned by the measurement model.

epochsAny

Epochs corresponding to the observed measurements (used in covariance analysis where actual observations are not required).

dataset_namestr

Human-readable name of the dataset (used for labeling and plotting).

file_labelstr, optional

Path or label of the file the observations were read from.

_itemstuple of MeasurementSpec, optional

Internal container holding multiple MeasurementSpec objects. If set, this instance acts as a container and yields each contained spec when iterated.

Methods

build(streams[, config, target])

Build a filter-ready spec from a list of measurement streams.

compute(target[, frame, reference_state])

Compute measurements and residuals for every stream, and keep the resulting MeasurementDataSet on the spec.

dataset_names()

Return the dataset names.

edit(method[, sigma_units, dataset_name])

Run a MeasurementEditing method over this spec's computed datasets and keep the resulting flags.

epoch_span([pad, n])

Epoch coverage of every stream, optionally padded and resampled.

flag(indices_by_name[, sigma])

Mark the given measurement indices as outliers.

flag_outliers([mean_outlier, sigma_outlier, ...])

Flag outliers on each stream from its residuals, and write the flags back to the source observations.

from_dict(d)

Create a MeasurementSpec from a dictionary or list of dictionaries.

from_dicts(dicts)

Construct a container spec from an iterable of measurement dictionaries.

from_models(models, observed[, names])

Build a container MeasurementSpec from measurement models and their observed quantities.

many(*specs)

Create a container spec holding multiple MeasurementSpec objects.

outlier_flags()

Return the current outlier flags of each dataset.

residuals()

Return the residuals of each dataset, as computed by compute().

sigmas()

Return the current sigma of each dataset.

summary()

Return a one-line summary per stream.

to_dict()

Convert the MeasurementSpec instance to a dictionary representation.

to_list()

Convert the MeasurementSpec object to a list of measurement dictionaries.

Notes

A MeasurementSpec operates in two modes:

Leaf mode — represents one dataset; iteration yields a single dictionary {"model": ..., "observed_meas": ..., "dataset_name": ...}.

Container mode — wraps multiple leaf specs; iteration yields one dictionary per contained spec.

Both modes are accepted wherever the filtering pipeline expects a list of measurement dictionaries, providing backward compatibility with the legacy list[dict] interface.

Examples

Single measurement dataset:

spec = MeasurementSpec(
    model=RangeIdeal(...),
    observed_meas=y_range,
    dataset_name="DSN Range",
)

Multiple datasets (container mode):

spec = MeasurementSpec.many(
    MeasurementSpec(model=range_model, ...),
    MeasurementSpec(model=rangerate_model, ...),
)

Legacy dict interface:

spec = MeasurementSpec.from_dict(meas_dict)
spec = MeasurementSpec.from_dicts(list_of_dicts)
classmethod build(streams, config=None, target=None) → MeasurementSpec#

Build a filter-ready spec from a list of measurement streams.

Each stream is normally a (file, meas_type, station) tuple. The measurement type supplies the model class, the data block to read and the units; the config supplies what is shared across streams. Anything needing more control can be given as a MeasurementStream instead.

No trajectory is needed here: the observations are read, the models built and the media corrections attached. Computing measurements and residuals is a separate step, so the spec is usable straight away for a run with no outlier rejection.

Parameters:
streamssequence

(file, meas_type, station) tuples, or MeasurementStream objects.

configMeasurementConfig, optional

Settings shared across streams.

targetBody, optional

Not used, and deliberately kept. build reads observations and assembles models, none of which needs a target; computing the measurements does, and that is compute(). Accepting it here lets a caller hand the same arguments to both steps rather than remembering which one takes what.

Returns:
MeasurementSpec

Container spec holding one entry per stream.

Examples

>>> spec = MeasurementSpec.build(
...     [(file1, "SeqRange", DSS_25),
...      (file2, "Doppler",  DSS_25)],
...     config=cfg,
... )
classmethod from_dict(d)#

Create a MeasurementSpec from a dictionary or list of dictionaries.

Parameters:
ddict or list or tuple

A dictionary with measurement specification data, or a list/tuple of such dictionaries to create a container spec.

Returns:
MeasurementSpec

A single spec if d is a dict; a container spec if d is a list or tuple.

Raises:
KeyError

If required keys "model" or "dataset_name" are missing.

Examples

>>> spec = MeasurementSpec.from_dict({
...     "model": range_model,
...     "observed_meas": y_range,
...     "dataset_name": "DSN Range",
...     "file_label": "dsn_range.json",
... })
classmethod from_dicts(dicts: Iterable[Dict[str, Any]]) → MeasurementSpec#

Construct a container spec from an iterable of measurement dictionaries.

Parameters:
dictsiterable of dict

Each dict must satisfy the same requirements as the argument to from_dict().

Returns:
MeasurementSpec

A container spec equivalent to MeasurementSpec.many(*specs).

classmethod from_models(models, observed, names=None) → MeasurementSpec#

Build a container MeasurementSpec from measurement models and their observed quantities.

Parameters:
modelsSequence

Measurement model instances (e.g. SequentialRangingReal, DopplerReal). Each model already carries its instrument, sigma, bias, media corrections and measurement type.

observedSequence

Observed quantities for each model, as returned by model.observed_measurements(...) (an ObsData).

namesSequence[str], optional

Dataset name for each model. Defaults to each model’s name.

Returns:
MeasurementSpec

Container spec, ready to hand to a filter.

classmethod many(*specs: MeasurementSpec) → MeasurementSpec#

Create a container spec holding multiple MeasurementSpec objects.

Parameters:
*specsMeasurementSpec

One or more individual MeasurementSpec instances to group.

Returns:
MeasurementSpec

A container instance whose iteration yields one dict per spec.

compute(target, frame=None, reference_state=None, **kwargs)#

Compute measurements and residuals for every stream, and keep the resulting MeasurementDataSet on the spec.

This is for inspecting residuals (and rejecting outliers) before the spec is handed to a filter. It does NOT pre-empt the filter’s own computation: a filter computes against its own reference trajectory, which is generally not the one used here and which changes on every iteration. See the note in FilterOD._initialize.

Parameters:
targetBody

The target whose trajectory the measurements are computed against.

frameFrame, optional

Frame for the computation. Defaults to the model’s own default.

reference_stateStateArray, optional

Reference state to push into each model before computing.

**kwargs

Passed through to Measurement.generate_measurement_dataset.

Returns:
MeasurementSpec

self, so this can be chained.

dataset_names() → list#

Return the dataset names.

Returns:
list of str

One name per stream, in stream order.

edit(method: str, sigma_units=None, dataset_name=None, **kwargs) → Dict[str, Any]#

Run a MeasurementEditing method over this spec’s computed datasets and keep the resulting flags.

MeasurementEditing owns the editing algorithms but works on datasets, which a filter rebuilds on every iteration. Routing through here writes the flags onto the source observations as well, so they survive that rebuild, and applies any refitted sigma to the measurement models, which the editor does not own.

Parameters:
methodstr

Name of the MeasurementEditing method, e.g. "huber_mad_filter", "chi_squared_filter", "lasso_editor".

dataset_namestr or sequence of str, optional

Restrict the edit, and the returned flags, to these datasets. When omitted the edit covers every dataset in the spec. Passed through to the editor method as well, so the algorithm and the reported result agree on scope. The name of a two-component stream selects both of its component datasets, "<dataset_name>_<label>", which can also be named one at a time.

sigma_unitsUnits or dict, optional

Units for any refitted sigma, shared or keyed by dataset name. The refit is in the units of the residuals and is converted to these. Defaults to the units of each model’s current sigma, else to the residuals’ own.

**kwargs

Passed straight to the MeasurementEditing method.

Returns:
dict

Newly flagged indices per dataset name, for the datasets the edit covered. A two-component stream reports once, under its own name, since its components share their observations.

Raises:
RefitSigmaUnitsError

If a refitted sigma cannot be converted to the units asked for. Nothing is flagged then.

Examples

>>> spec.compute(target=orbiter, frame=frame)
>>> spec.edit("huber_mad_filter", dataset_name="GS1 Real Range", n_sigma=5.0)
epoch_span(pad=0.0, n: int = None)#

Epoch coverage of every stream, optionally padded and resampled.

Replaces the min/max loop each analysis script wrote by hand to work out what span to propagate over.

Parameters:
padArrayWUnits or float, optional

Time to extend before the first and after the last observation. An ArrayWUnits must have dimensions of time; a bare number is taken as seconds.

nint, optional

If given, return this many evenly spaced epochs across the span. Otherwise return the sorted unique observation epochs, or just the padded end points when pad is non-zero.

Returns:
EpochArray

Expressed in the time system the observations share, or in TDB when the streams use different systems.

flag(indices_by_name: Dict[str, Any], sigma=None) → Dict[str, Any]#

Mark the given measurement indices as outliers.

This is the write path every outlier rejection method goes through. Flags land on the source observations (ObsData.meas_outliers), so they survive the dataset rebuilds a filter performs on each iteration, and are mirrored onto the current dataset when one is present.

Parameters:
indices_by_namedict

Indices to flag, keyed by dataset name. Indices address the full measurement arrays, which never shrink, so they stay valid across repeated rejection passes. A two-component stream can be addressed by its own name or by its components’ dataset names; either flags the observation, and so both components.

sigmadict or ArrayWUnits, optional

Revised measurement sigma, shared or keyed by dataset name, in the form the model’s sigma takes.

Returns:
dict

Newly flagged indices per dataset name, excluding any that were already flagged, for the streams indices_by_name addresses.

flag_outliers(mean_outlier=None, sigma_outlier=None, sigma=None)#

Flag outliers on each stream from its residuals, and write the flags back to the source observations.

The write-back matters: a filter rebuilds its datasets on every iteration from the observations, so a flag left only on the dataset would be discarded on the next pass. Writing to ObsData.meas_outliers means each regenerated dataset inherits it.

Parameters:
mean_outlier, sigma_outlierfloat, optional

Passed to MeasurementEditing.residual_filter. Defaults to 5 sigma about the mean of the unflagged residuals.

Plain numbers in residual units, i.e. the units of each stream’s measurements (km for range, Hz for Doppler, RU for sequential ranging, …), which is what the residuals column holds. The same numbers are applied to every stream, so explicit bounds only make sense when the streams share a measurement type; the defaults are taken from each stream’s own residuals.

sigmadict or ArrayWUnits, optional

Revised measurement sigma, either shared or keyed by dataset name.

Returns:
dict

Newly flagged indices per dataset name.

outlier_flags() → Dict[str, Any]#

Return the current outlier flags of each dataset.

Returns:
dict

{dataset_name: numpy.ndarray} of the flags of the source observations, including those read from the file.

residuals() → Dict[str, Any]#

Return the residuals of each dataset, as computed by compute().

Returns:
dict

{dataset_name: numpy.ndarray} of the residuals. A two-component stream contributes one entry per component, keyed by the component’s dataset name ("<dataset_name>_<label>").

Raises:
RuntimeError

If compute() has not been called for one or more streams.

sigmas() → Dict[str, Any]#

Return the current sigma of each dataset.

Returns:
dict

{dataset_name: sigma} with the sigma of each model.

summary() → str#

Return a one-line summary per stream.

Returns:
str

Per stream, the number of observations and of flagged ones; for a computed stream also the RMS of the kept residuals and the target and trajectory it was computed against. A computed two-component stream has one line per component.

to_dict() → Dict[str, Any]#

Convert the MeasurementSpec instance to a dictionary representation.

Returns a dictionary containing the model, dataset_name, and either observed_meas or epochs (but not both).

Returns:
dict

A dictionary with keys "model", "dataset_name", either "observed_meas" or "epochs", and optionally "file_label".

Raises:
TypeError

If _items is not None (container mode cannot be converted to a single dict).

ValueError

If both observed_meas and epochs are None, or if both are set.

to_list() → list#

Convert the MeasurementSpec object to a list of measurement dictionaries.

Returns:
list

A list of dictionaries, one per contained spec.

dataset: Any = None#
property leaves: tuple#

The individual specs, whether this is a leaf or a container.

provenance: dict | None = None#
exception RefitSigmaUnitsError#

Bases: ValueError

A refitted sigma cannot be expressed in the units asked for.

The refit is in the units of the dataset’s residuals, and the units asked for (sigma_units, else those of the model’s current sigma) are of another dimension.