ObservationInfo#

class astro_metadata_translator.ObservationInfo(header=None, filename=None, translator_class=None, pedantic=False, search_path=None, required=None, subset=None, quiet=False, **kwargs)#

Bases: BaseModel

Standardized representation of an instrument header for a single exposure observation.

Parameters:
  • header (dict-like) – Representation of an instrument header accessible as a dict. May be updated with header corrections if corrections are found.

  • filename (str, optional) – Name of the file whose header is being translated. For some datasets with missing header information this can sometimes allow for some fixups in translations.

  • translator_class (MetadataTranslator-class, optional) – If not None, the class to use to translate the supplied headers into standard form. Otherwise each registered translator class will be asked in turn if it knows how to translate the supplied header.

  • pedantic (bool, optional) – If True the translation must succeed for all properties. If False individual property translations must all be implemented but can fail and a warning will be issued. Only used if a header is specified.

  • search_path (Iterable, optional) – Override search paths to use during header fix up. Only used if a header is specified.

  • required (set, optional) – This parameter can be used to confirm that all properties contained in the set must translate correctly and also be non-None. For the case where pedantic is True this will still check that the resulting value is not None. Only used if a header is specified.

  • subset (set, optional) – If not None, controls the translations that will be performed during construction. This can be useful if the caller is only interested in a subset of the properties and knows that some of the others might be slow to compute (for example the airmass if it has to be derived). Only used if a header is specified.

  • quiet (bool, optional) – If True, warning level log messages that would be issued in non pedantic mode are converted to debug messages.

  • **kwargs (typing.Any) – Property name/value pairs for kwargs-based construction mode. This mode creates an ObservationInfo directly from supplied properties rather than by translating a header. If header is provided it is an error to also provide kwargs.

Raises:
  • ValueError – Raised if the supplied header was not recognized by any of the registered translators. Also raised if the request property subset is not a subset of the known properties or if a header is given along with kwargs.

  • TypeError – Raised if the supplied translator class was not a MetadataTranslator.

  • KeyError – Raised if a required property cannot be calculated, or if pedantic mode is enabled and any translations fails.

  • NotImplementedError – Raised if the selected translator does not support a required property.

Notes

There is a core set of instrumental properties that are pre-defined. Additional properties may be defined, either through the makeObservationInfo factory function by providing the extensions definitions, or through the regular ObservationInfo constructor when the extensions have been defined in the MetadataTranslator for the instrument of interest (or in the provided translator_class).

There are two forms of the constructor. If the header is given then a translator will be determined and the properties will be populated accordingly. No generic keyword arguments will be expected and the remaining parameters control the behavior of the translator.

If the header is not given it is assumed that the keyword arguments are direct specifications of observation properties. In this mode only the filename and translator_class parameters will be used. The latter is used to determine any extensions that are being provided, although when using standard serializations the special _translator key will be used instead to specify the name of the registered translator from which to extract extension definitions.

Headers will be corrected if correction files are located and this will modify the header provided to the constructor. Modifying the supplied header after construction will modify the internal cached header.

Values of the properties are read-only.

Attributes Summary

all_properties

Definitions of all known properties (core plus extensions).

cards_used

Header cards used for the translation.

extensions

Definitions of the translator-specific extension properties.

filename

Name of the file whose header was translated, if any.

model_config

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

translator_class_name

Name of the metadata translator class used for these data.

Methods Summary

edit_copy()

Edit a copy of this struct, via a context manager that marks it as read-only when it exits.

from_flat_dict(flat, *[, prefix, sep])

Create an ObservationInfo from the output of to_flat_dict.

from_header(header, *[, filename, ...])

Create an ObservationInfo by translating a metadata header.

from_json(json_str)

Create ObservationInfo from JSON string.

from_simple(simple)

Convert the entity returned by to_simple back into an ObservationInfo.

has_flat_dict(flat, *[, prefix, sep])

Report whether a mapping contains keys written by to_flat_dict.

makeObservationInfo(*[, extensions, ...])

Construct an ObservationInfo from the supplied parameters.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialize private attributes.

strip_from_flat_dict(flat, *[, prefix, sep])

Remove keys written by to_flat_dict from a mapping in place.

stripped_header()

Return a copy of the supplied header with used keywords removed.

to_flat_dict(*[, prefix, sep, use_upper, ...])

Convert the contents of this object to a flat dict of scalars.

to_json()

Serialize the object to JSON string.

to_simple()

Convert the contents of this object to simple dict form.

Attributes Documentation

all_properties#

Definitions of all known properties (core plus extensions).

cards_used#

Header cards used for the translation.

Returns:

used – Set of card used.

Return type:

frozenset of str

extensions#

Definitions of the translator-specific extension properties.

filename#

Name of the file whose header was translated, if any.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'populate_by_name': True, 'ser_json_inf_nan': 'constants', 'serialize_by_alias': True, 'validate_assignment': False}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

translator_class_name#

Name of the metadata translator class used for these data.

Methods Documentation

edit_copy()#

Edit a copy of this struct, via a context manager that marks it as read-only when it exits.

Return type:

Generator[ObservationInfo]

classmethod from_flat_dict(flat, *, prefix=None, sep='.')#

Create an ObservationInfo from the output of to_flat_dict.

Parameters:
  • flat (Mapping [str, Any]) – Mapping containing the flat keys, for example a FITS header. Keys are matched case-insensitively and unrelated keys are ignored.

  • prefix (str or None, optional) – Prefix given to to_flat_dict. None detects the prefix and separator automatically, in which case sep is ignored.

  • sep (str, optional) – Separator given to to_flat_dict.

Returns:

obsinfo – New object constructed from the mapping.

Return type:

ObservationInfo

Raises:
  • ValueError – Raised if no keys are found, if automatic detection is ambiguous, if two keys differ only in case, if the indexed values of a property are incomplete, or if a float property holds a string that is not a number. Also raised, as pydantic.ValidationError, if a value fails validation.

  • KeyError – Raised if extension properties are present but the named translator is not registered, so their definitions are unknown.

Notes

A string found for a float property is converted with float. This restores the NAN, +INFINITY, and -INFINITY strings written by to_flat_dict with encode_non_finite, and by cfitsio and afw for non-finite floats, as well as the NaN and Infinity spellings used in JSON.

Round-tripping of extension properties requires that the translator named in the mapping is registered, because its extension definitions are needed to interpret ext_ keys.

classmethod from_header(header, *, filename=None, translator_class=None, pedantic=False, search_path=None, required=None, subset=None, quiet=False)#

Create an ObservationInfo by translating a metadata header.

Parameters:
  • header (dict-like) – Header mapping to translate.

  • filename (str, optional) – Name of file associated with this header.

  • translator_class (MetadataTranslator-class, optional) – Translator class to use. If None, translator will be auto-determined.

  • pedantic (bool, optional) – If True, translation failures are fatal.

  • search_path (Sequence [str], optional) – Search paths for header corrections.

  • required (set [str], optional) – Properties that must be translated and non-None.

  • subset (set [str], optional) – Restrict translation to this subset of properties.

  • quiet (bool, optional) – If True, warning level log messages that would be issued in non pedantic mode are converted to debug messages.

Returns:

obsinfo – Translated observation metadata.

Return type:

ObservationInfo

classmethod from_json(json_str)#

Create ObservationInfo from JSON string.

Parameters:

json_str (str) – The JSON representation.

Returns:

obsinfo – Reconstructed object.

Return type:

ObservationInfo

Notes

Round-tripping of extension properties requires that the ObservationInfo was created with the help of a registered MetadataTranslator (which contains the extension property definitions).

classmethod from_simple(simple)#

Convert the entity returned by to_simple back into an ObservationInfo.

Parameters:

simple (dict [str, Any]) – The dict returned by to_simple.

Returns:

obsinfo – New object constructed from the dict.

Return type:

ObservationInfo

Notes

Round-tripping of extension properties requires that the ObservationInfo was created with the help of a registered MetadataTranslator (which contains the extension property definitions).

classmethod has_flat_dict(flat, *, prefix=None, sep='.')#

Report whether a mapping contains keys written by to_flat_dict.

Parameters:
  • flat (Mapping [str, Any]) – Mapping to inspect, for example a FITS header. Keys are matched case-insensitively.

  • prefix (str or None, optional) – Prefix given to to_flat_dict. None detects the prefix and separator automatically, in which case sep is ignored.

  • sep (str, optional) – Separator given to to_flat_dict.

Returns:

present – True if at least one key was found.

Return type:

bool

Raises:

ValueError – Raised if automatic detection finds two prefixes that match equally well.

Notes

Use this before from_flat_dict to tell the absence of content from content that fails validation. Automatic detection requires an indexed tuple-valued property such as datetime_begin_0 to be present. Keys that differ only in case count as present even though from_flat_dict will reject them.

classmethod makeObservationInfo(*, extensions=None, translator_class=None, **kwargs)#

Construct an ObservationInfo from the supplied parameters.

Parameters:
  • extensions (dict [str: PropertyDefinition], optional) – Optional extension definitions, indexed by extension name (without the ext_ prefix, which will be added by ObservationInfo).

  • translator_class (MetadataTranslator-class, optional) – Optional translator class defining the extension properties. If provided, this can be used instead of extensions and will be stored in the instance for JSON round-tripping.

  • **kwargs (Any) – Name-value pairs for any properties to be set. In the case of extension properties, the names should include the ext_ prefix.

Return type:

ObservationInfo

Notes

The supplied parameters should use names matching the property. The type of the supplied value will be checked against the property. Any properties not supplied will be assigned a value of None.

Raises:
  • KeyError – Raised if a supplied parameter key is not a known property.

  • TypeError – Raised if a supplied value does not match the expected type of the property.

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
Return type:

None

classmethod strip_from_flat_dict(flat, *, prefix=None, sep='.')#

Remove keys written by to_flat_dict from a mapping in place.

Parameters:
  • flat (MutableMapping [str, Any]) – Mapping to modify, for example a FITS header. Keys are matched case-insensitively.

  • prefix (str or None, optional) – Prefix given to to_flat_dict. None detects the prefix and separator automatically, in which case sep is ignored.

  • sep (str, optional) – Separator given to to_flat_dict.

Raises:

ValueError – Raised if sep is invalid or detection is ambiguous.

Return type:

None

Notes

Nothing is removed if no keys are found. Other keys in the mapping are left untouched. Keys that differ only in case are all removed.

stripped_header()#

Return a copy of the supplied header with used keywords removed.

Returns:

stripped – Same class as header supplied to constructor, but with the headers used to calculate the generic information removed.

Return type:

dict-like

to_flat_dict(*, prefix='', sep='.', use_upper=None, encode_non_finite=False)#

Convert the contents of this object to a flat dict of scalars.

Parameters:
  • prefix (str, optional) – Prefix placed before every key. Emitted exactly as given. Use FITS_FLAT_DICT_PREFIX for FITS headers.

  • sep (str, optional) – Separator between the prefix and the property name. Must be one character that is not a letter, digit, or underscore. Unused when prefix is empty. Use FITS_FLAT_DICT_SEP for FITS headers.

  • use_upper (bool or None, optional) – If None the property names are upper-cased when the first character of prefix is upper case and left lower case otherwise. True or False force the case.

  • encode_non_finite (bool, optional) – If True, NaN and infinite floats are written as the strings NAN, +INFINITY, and -INFINITY. FITS can not hold such floats, so set this when the result is going into a FITS header. By default they are left as floats.

Returns:

flat – Flat mapping of all properties that are not None.

Return type:

dict [str, str | int | float | bool]

Raises:
  • ValueError – Raised if sep is not valid.

  • TypeError – Raised if a property value can not be represented as a scalar or a flat sequence of scalars.

Notes

Each key is the property name as used by to_simple, optionally preceded by the prefix and separator. A property whose simple form is a tuple, such as datetime_begin, is written as one key per element with an index suffix: datetime_begin_0 and datetime_begin_1. The _translator entry is written as translator. With prefix="OBS_INFO" and sep=" " the keys are suitable for FITS HIERARCH cards, for example OBS_INFO DATETIME_BEGIN_0.

Values are passed through unchanged unless encode_non_finite is set. The strings it writes are the ones cfitsio and afw use for non-finite floats, and from_flat_dict converts them back to floats. FITS does not preserve trailing spaces in string values.

The result can be converted back with from_flat_dict. Round-tripping of extension properties requires that the translator is registered, and an extension name must not end in an underscore followed by digits if a tuple-valued extension with the shorter name also exists.

to_json()#

Serialize the object to JSON string.

Returns:

j – The properties of the ObservationInfo in JSON string form.

Return type:

str

Notes

Round-tripping of extension properties requires that the ObservationInfo was created with the help of a registered MetadataTranslator (which contains the extension property definitions).

to_simple()#

Convert the contents of this object to simple dict form.

The keys of the dict are the standard properties but the values can be simplified to support JSON serialization. For example a SkyCoord might be represented as an ICRS RA/Dec tuple rather than a full SkyCoord representation.

Any properties with None value will be skipped.

Can be converted back to an ObservationInfo using from_simple.

Returns:

simple – Simple dict of all properties.

Return type:

dict of [str, Any]

Notes

Round-tripping of extension properties requires that the ObservationInfo was created with the help of a registered MetadataTranslator (which contains the extension property definitions).