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:
BaseModelStandardized representation of an instrument header for a single exposure observation.
- Parameters:
header (
dict-like) – Representation of an instrument header accessible as adict. 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 notNone, 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 aheaderis specified.search_path (
Iterable, optional) – Override search paths to use during header fix up. Only used if aheaderis 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 wherepedanticisTruethis will still check that the resulting value is notNone. Only used if aheaderis specified.subset (
set, optional) – If notNone, 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 aheaderis specified.quiet (
bool, optional) – IfTrue, 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 anObservationInfodirectly from supplied properties rather than by translating a header. Ifheaderis provided it is an error to also providekwargs.
- 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
makeObservationInfofactory function by providing theextensionsdefinitions, or through the regularObservationInfoconstructor when the extensions have been defined in theMetadataTranslatorfor the instrument of interest (or in the providedtranslator_class).There are two forms of the constructor. If the
headeris 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
filenameandtranslator_classparameters will be used. The latter is used to determine any extensions that are being provided, although when using standard serializations the special_translatorkey 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
Definitions of all known properties (core plus extensions).
Header cards used for the translation.
Definitions of the translator-specific extension properties.
Name of the file whose header was translated, if any.
Configuration for the model, should be a dictionary conforming to [
ConfigDict][pydantic.config.ConfigDict].Name of the metadata translator class used for these data.
Methods Summary
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
ObservationInfofrom the output ofto_flat_dict.from_header(header, *[, filename, ...])Create an
ObservationInfoby translating a metadata header.from_json(json_str)Create
ObservationInfofrom JSON string.from_simple(simple)Convert the entity returned by
to_simpleback into anObservationInfo.has_flat_dict(flat, *[, prefix, sep])Report whether a mapping contains keys written by
to_flat_dict.makeObservationInfo(*[, extensions, ...])Construct an
ObservationInfofrom 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_dictfrom a mapping in place.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.
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.
- 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:
- classmethod from_flat_dict(flat, *, prefix=None, sep='.')#
Create an
ObservationInfofrom the output ofto_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 (
strorNone, optional) – Prefix given toto_flat_dict.Nonedetects the prefix and separator automatically, in which casesepis ignored.sep (
str, optional) – Separator given toto_flat_dict.
- Returns:
obsinfo – New object constructed from the mapping.
- Return type:
- 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 theNAN,+INFINITY, and-INFINITYstrings written byto_flat_dictwithencode_non_finite, and by cfitsio and afw for non-finite floats, as well as theNaNandInfinityspellings 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
ObservationInfoby 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. IfNone, translator will be auto-determined.pedantic (
bool, optional) – IfTrue, 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) – IfTrue, warning level log messages that would be issued in non pedantic mode are converted to debug messages.
- Returns:
obsinfo – Translated observation metadata.
- Return type:
- classmethod from_json(json_str)#
Create
ObservationInfofrom JSON string.- Parameters:
json_str (
str) – The JSON representation.- Returns:
obsinfo – Reconstructed object.
- Return type:
Notes
Round-tripping of extension properties requires that the
ObservationInfowas created with the help of a registeredMetadataTranslator(which contains the extension property definitions).
- classmethod from_simple(simple)#
Convert the entity returned by
to_simpleback into anObservationInfo.- Parameters:
- Returns:
obsinfo – New object constructed from the dict.
- Return type:
Notes
Round-tripping of extension properties requires that the
ObservationInfowas created with the help of a registeredMetadataTranslator(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 (
strorNone, optional) – Prefix given toto_flat_dict.Nonedetects the prefix and separator automatically, in which casesepis ignored.sep (
str, optional) – Separator given toto_flat_dict.
- Returns:
present –
Trueif at least one key was found.- Return type:
- Raises:
ValueError – Raised if automatic detection finds two prefixes that match equally well.
Notes
Use this before
from_flat_dictto tell the absence of content from content that fails validation. Automatic detection requires an indexed tuple-valued property such asdatetime_begin_0to be present. Keys that differ only in case count as present even thoughfrom_flat_dictwill reject them.
- classmethod makeObservationInfo(*, extensions=None, translator_class=None, **kwargs)#
Construct an
ObservationInfofrom the supplied parameters.- Parameters:
extensions (
dict[str:PropertyDefinition], optional) – Optional extension definitions, indexed by extension name (without theext_prefix, which will be added byObservationInfo).translator_class (
MetadataTranslator-class, optional) – Optional translator class defining the extension properties. If provided, this can be used instead ofextensionsand 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 theext_prefix.
- Return type:
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.
- 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.
- classmethod strip_from_flat_dict(flat, *, prefix=None, sep='.')#
Remove keys written by
to_flat_dictfrom a mapping in place.- Parameters:
flat (
MutableMapping[str,Any]) – Mapping to modify, for example a FITS header. Keys are matched case-insensitively.prefix (
strorNone, optional) – Prefix given toto_flat_dict.Nonedetects the prefix and separator automatically, in which casesepis ignored.sep (
str, optional) – Separator given toto_flat_dict.
- Raises:
ValueError – Raised if
sepis invalid or detection is ambiguous.- Return type:
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. UseFITS_FLAT_DICT_PREFIXfor 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 whenprefixis empty. UseFITS_FLAT_DICT_SEPfor FITS headers.use_upper (
boolorNone, optional) – IfNonethe property names are upper-cased when the first character ofprefixis upper case and left lower case otherwise.TrueorFalseforce the case.encode_non_finite (
bool, optional) – IfTrue,NaNand infinite floats are written as the stringsNAN,+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:
- Raises:
ValueError – Raised if
sepis 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 asdatetime_begin, is written as one key per element with an index suffix:datetime_begin_0anddatetime_begin_1. The_translatorentry is written astranslator. Withprefix="OBS_INFO"andsep=" "the keys are suitable for FITSHIERARCHcards, for exampleOBS_INFO DATETIME_BEGIN_0.Values are passed through unchanged unless
encode_non_finiteis set. The strings it writes are the ones cfitsio and afw use for non-finite floats, andfrom_flat_dictconverts 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:
Notes
Round-tripping of extension properties requires that the
ObservationInfowas created with the help of a registeredMetadataTranslator(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
Nonevalue will be skipped.Can be converted back to an
ObservationInfousingfrom_simple.Notes
Round-tripping of extension properties requires that the
ObservationInfowas created with the help of a registeredMetadataTranslator(which contains the extension property definitions).