defair_data

Submodules

Attributes

Classes

Functions

Package Contents

defair_data.CF_VERSION = 'CF-1.13'
class defair_data.Dataset(dataset: xarray.Dataset | None = None, cdm: defair_data.cdm.CommonDataModel | None = None, *, _stream_plan: StreamingPlan | None = None)
property data: xarray.Dataset

Access the underlying xarray Dataset.

A streaming plan does not provide data directly. Call .to_file(path) and reload the output to inspect it.

property is_streaming: bool

True if this Dataset is a deferred streaming plan.

property cdm: defair_data.cdm.CommonDataModel | None

Runtime CDM, or None if the reader did not declare one.

with_cdm(cdm: defair_data.cdm.CommonDataModel | None) → Dataset

Return a new Dataset carrying cdm (None strips the contract).

Used by geometry-changing transformations: the handler returns a fresh xr.Dataset and a fresh CommonDataModel; callers wrap them with Dataset.with_cdm rather than mutating in place.

with_latlon(groups: collections.abc.Iterable[str] | None = None) → Dataset

Return a copy carrying the 2D lat/lon pair for the requested grids.

A plain read is projection-only: the 1D projection axes and the CF grid mapping determine every pixel, so the 2D pair is derivable rather than stored, and paying for it on every read charges callers who never use it. This is how a caller asks for it, in place of re-reading the product with include_latlon=True.

The pair is built from the grid’s own spec, so it is the same pair the reader would have attached: same values, dtype, chunking and attributes. The grid’s CF description is completed with it — the geostationary parameters gain the coordinate names, and each science variable gains the coordinates reference for its own grid.

Parameters:

groups – CDM grid ids to materialise; None means every gridded group.

Returns:

A new Dataset. Grids that already carry their pair are returned unchanged, so repeated calls are a no-op.

Raises:
  • RuntimeError – If this is a streaming plan, which has no data to attach to.

  • ValueError – If the dataset carries no CDM, a requested grid id is unknown or not a regular grid, or a grid’s projection cannot be resolved into a CRS to invert.

select_grid(grid_id: str) → Dataset

Return a view restricted to one CDM grid.

Keeps variables owned by grid_id, their temporal coordinates, the GriddedModel-declared aux refs (grid_mapping, geostationary nav coords), and the transitive closure of CF cross-refs they name (coordinates, ancillary_variables, bounds, cell_measures, grid_mapping). Curvilinear / Point groups keep their latitude/longitude only via the CF cross-ref walk; their declared names are not added to aux refs.

Any cached GeoTransform is re-aimed at the selected grid’s own axes, since a multi-grid dataset holds one affine describing one of its grids and a consumer that prefers a stored affine to recomputing one would otherwise read that grid’s pixel size out of every other grid. A single-group dataset is returned unchanged: its stored affine already describes its only grid.

Raises on missing CDM, unknown grid_id, or absent declared grid_mapping (checked even for single-group datasets so a stale CDM on a content-filtered dataset fails loudly rather than silently). Returns self when only one group exists and grid_mapping resolves.

split_grids() → dict[str, Dataset]

Return one standalone Dataset per CDM spatial group.

A reader that carries several sampling grids in one dataset must give the second grid suffixed spatial names (MSG SEVIRI HRV gets x_hrv/y_hrv/ lat_hrv/lon_hrv) because the plain names belong to the first. Once a grid is on its own that constraint is gone, so each returned dataset uses the canonical x/y/lat/lon spelling and carries a CDM, CF attributes and grid mapping rewritten to match.

The result is a plain mapping of ordinary single-grid Datasets, so every transformation and writer handles them without a product-specific case. Use to_datatree() for the same split as one xarray container.

A variable no spatial group declares still goes to the grid whose dims it sits on, so a reader that holds its ancillary rasters out of the CDM to keep them from being resampled does not lose them here. Only a variable that sits on no grid’s dims, or spans two, has no grid to go to; those are named in a warning and stay behind in the combined dataset.

Raises:
  • RuntimeError – If this is a streaming plan, which has nothing to split yet.

  • ValueError – If the dataset carries no CDM to split on.

to_datatree() → xarray.DataTree

Return split_grids() as an xarray.DataTree, one node per grid.

Node names are the CDM group ids (msg_visir, msg_hrv). Each node is a self-contained single-grid dataset, so sibling grids no longer have to share a coordinate namespace.

classmethod from_source(path: str | os.PathLike | list[str | os.PathLike], source: str = '', source_kwargs: dict[str, Any] | None = None, reader: str = '', concat_dim: str = 'time', *, streaming: bool | None = None, stream_batch_size: int | None = None, on_error: str = 'raise', **kwargs: Any) → typing_extensions.Self

Load a dataset using a registered reader plugin or auto-detection.

Supports single files, glob patterns, and explicit file lists. When multiple files are matched (via glob or list), they are read individually and concatenated along concat_dim.

Parameters:
  • path – Path to data file(s). Accepts a single path string/PathLike, a glob pattern (e.g., "s3://bucket/*.nc"), or an explicit list of paths.

  • source – Name of the data source plugin (for example, "local", "s3", or "s3boto"). If empty, auto-detects from the path. An s3:// path selects "s3" by default; use "s3boto" for boto3 listing and direct reads. xarray reads may still use s3fs with either plugin.

  • source_kwargs – Additional arguments passed to the source plugin (e.g., S3 credentials, endpoint URLs, caching options).

  • reader – Name of the reader plugin (e.g., ‘msg15nat’, ‘mtg_fci_l1c_nc’) or empty for auto-detection.

  • concat_dim – Dimension to concatenate along when reading multiple files (default: "time"). Ignored for single-file paths.

  • streaming – For a path list or glob, True processes a limited number of scene groups at a time during to_file(). False (the default) builds one dataset while keeping its arrays lazy. DEFAIR_STREAMING_MODE=on changes the list/glob default. Streaming plans currently write only to Zarr and support a limited set of transformations.

  • stream_batch_size – Maximum scene groups per streaming batch. The default is four; DEFAIR_STREAM_BATCH_SIZE supplies an environment default when this argument is omitted.

  • on_error – What to do when an input cannot be read, for a path list or glob. "raise" (the default) stops the read and reports the failure. "skip" drops the unreadable scene group, warns, and continues with the rest; the result records the dropped files in the skipped_inputs and skipped_input_count attributes. A scene group is the unit a reader assembles in one call, which is a single file for most readers but a whole set for the ones that stitch chunks or time slots (MTG FCI L1c, the MTG LI readers, Metop IASI THR). Only a missing, unreadable or truncated input is skippable: a permission failure, a decode failure such as the wrong reader for the file, and any failure that surfaces later during lazy computation all remain fatal. Ignored for a single-file path.

  • **kwargs – Options for the selected reader’s constructor and read() method. Inspect both signatures on type(load_reader(name)) and load_reader(name).read to see the supported options.

Raises:
  • ValueError – If the reader plugin is not found, no reader can handle the path, or the file list is empty

  • FileNotFoundError – If a glob pattern matches no files

Examples

>>> # Single file
>>> dataset = Dataset.from_source("/path/to/file.nat")
>>> # Glob pattern
>>> dataset = Dataset.from_source("s3://bucket/*.nc", source="s3",
...                               reader="metop_avhrr_amv")
>>> # Explicit file list
>>> dataset = Dataset.from_source(["/data/a.nc", "/data/b.nc"],
...                               reader="metop_avhrr_amv")
>>> # Process a fixed number of scene groups at a time and append to Zarr
>>> dataset = Dataset.from_source("s3://bucket/archive/*.nc",
...                               reader="mtg_fci_l1c_nc",
...                               streaming=True,
...                               stream_batch_size=4)
>>> dataset.to_file("output/archive.zarr", writer="zarrv2")
to_file(path: str | os.PathLike, writer: str = '', source: str = '', source_kwargs: dict[str, Any] | None = None, **kwargs: Any) → None

Write the dataset to a file using a registered writer plugin or auto-detection.

For streaming-plan Datasets (returned by Dataset.from_source(big_list, streaming=True) — or with DEFAIR_STREAMING_MODE=on), this drives the per-batch materialisation loop instead of writing one giant dataset. Each batch is read+transformed+appended to the Zarr in turn, then released, so peak memory stays bounded by batch_size.

Parameters:
  • path – Output path. Local filesystem path or remote URI (e.g. s3://bucket/key/).

  • writer – Name of the writer plugin or empty for auto-detection from path extension.

  • source – Name of the data source plugin used for sink IO (e.g. 'local', 's3'). If empty, auto-detects based on path prefix (s3:// → s3, otherwise local).

  • source_kwargs – Additional arguments passed to the source plugin (e.g. S3 credentials).

  • **kwargs – Additional arguments passed to the writer plugin’s __init__.

Raises:

ValueError – If the writer plugin is not found, no writer can handle the path, or the resolved source plugin does not declare SUPPORTS_WRITE.

list_variables() → dict[str, Any]

Return available data variables, coordinates and dimensions.

Returns:

  • data_vars: List of data variable names with shapes and dtypes

  • coords: List of coordinate names with shapes and dtypes

  • dims: Dictionary of dimension names to sizes

Return type:

Dictionary containing

reproject(target: str, *, resampling: str = 'bilinear', resolution: float | None = None, bounds: tuple[float, float, float, float] | None = None, dask_client_kwargs: dict[str, Any] | None = None, backend: str | None = None, **kwargs: Any) → Dataset

Reproject the dataset using a registered operation plugin.

Parameters:
  • target – Target CRS specification (e.g., “EPSG:4326”, “healpix:64”)

  • resampling – Resampling strategy requested from the operation plugin.

  • resolution – Optional output resolution in target CRS units.

  • bounds – Optional spatial bounds in target CRS.

  • dask_client_kwargs – Optional Dask client configuration.

  • backend – Optional backend for reprojection (e.g., ‘rioxarray’, ‘astropy_healpix’).

  • **kwargs – Additional keyword arguments

Raises:

ValueError – If the reprojection operation plugin cannot be loaded.

transform(name: str, *, target: str | None = None, dask_client_kwargs: dict[str, Any] | None = None, **kwargs: Any) → Dataset

Apply a transformation using a registered transformation plugin.

Searches for a transformation plugin by name in the plugin registration system and applies it to the dataset.

Parameters:
  • name – Name of the transformation plugin (e.g., ‘content_filter’, ‘reproject’)

  • target – Target specification for the transformation (optional, depends on the operation)

  • dask_client_kwargs – Optional Dask client configuration.

  • **kwargs – Additional keyword arguments passed to the transformation plugin

Returns:

Transformed dataset

Raises:

ValueError – If the transformation plugin is not found, or if name is not in BATCH_SAFE_TRANSFORMS and this Dataset is a streaming plan (which would require cross-batch state).

isel(indexers: dict[str, Any] | None = None, **indexer_kwargs: Any) → Dataset

Index-select along dimensions; works on materialised and streaming Datasets.

On a materialised Dataset, equivalent to Dataset(self.data.isel(…)). On a streaming-plan Dataset, records the isel call to be replayed per batch in to_file. This lets pure-metadata pre-crops (e.g. AOI pixel windows on a fixed geostationary grid) work in streaming pipelines without materialising the full corpus first.

Indexing the concat_dim (typically "time") in streaming mode is rejected because the call is replayed per-batch, which would select the first/Nth elements of every batch rather than once globally. Materialise (streaming=False) and re-index for that case.

validate_cf(strict: bool = False) → defair.cf_metadata.ValidationResult

Validate CF-1.13 compliance of this dataset.

Parameters:

strict – If True, treat warnings as errors

Returns:

ValidationResult with errors and warnings

Raises:

ImportError – If defair.cf_history_mixin not available

class defair_data.S3CredentialsPlugin(environ: dict[str, str])

Bases: distributed.WorkerPlugin

Dask WorkerPlugin that injects S3 credentials as environment variables on workers.

When registered on a Dask client, this plugin sets AWS/S3 environment variables on all current and future workers, enabling them to access S3-compatible storage.

Parameters:

environ – Dictionary mapping environment variable names to their values. Only non-None, non-empty values are set.

name: str = 'defair-s3-credentials'
setup(worker: Any) → None

Set environment variables on the worker, recording prior values.

A worker running inside the client’s own process is skipped. It already sees the environment the client resolved its S3 settings from, so writing there configures nothing new; it only rewrites the caller’s environment for the rest of the interpreter’s life. An anonymous read would then leave DEFAIR_S3_ANON=1 behind and silently turn the next credentialed read into an unsigned one.

teardown(worker: Any) → None

Restore the environment variables setup actually applied.

Only touches keys that still hold the value we set; restores the previous value when the key pre-existed, otherwise removes it. Walking the setup snapshot rather than the configured mapping keeps this a no-op on a worker whose setup was skipped.

defair_data.propagate_s3_credentials(client: dask.distributed.Client | None = None, storage_options: dict[str, Any] | None = None, *, aws_access_key_id: str | None = None, aws_secret_access_key: str | None = None, aws_session_token: str | None = None, endpoint_url: str | None = None, region_name: str | None = None, force: bool = False) → None

Propagate S3 credentials to all Dask distributed workers.

Registers an S3CredentialsPlugin that sets AWS/S3 environment variables on all current and future workers. A worker running inside the caller’s own process is left alone: it already shares that environment, and rewriting it would reconfigure the caller (see S3CredentialsPlugin.setup()).

Credentials are resolved from (in priority order):
  1. Explicit keyword arguments

  2. fsspec-style storage_options dict

  3. Local environment variables (DEFAIR_AWS_* then AWS_*)

Parameters:
  • client – Dask distributed Client. If None, uses the DaskClientManager singleton’s current client.

  • storage_options – fsspec-compatible storage options dict.

  • aws_access_key_id – AWS access key ID (overrides storage_options).

  • aws_secret_access_key – AWS secret access key (overrides storage_options).

  • aws_session_token – AWS session token (overrides storage_options).

  • endpoint_url – Custom S3 endpoint URL (overrides storage_options).

  • region_name – AWS region name (overrides storage_options).

  • force – Bypass the (client_id, env_vars) dedup short-circuit and re-register the plugin. Use when workers may have rotated (auto-scale, nanny restart) since the original propagation — the plugin needs to run on each new worker, but the singleton cache thinks the credentials are already in place. Each force=True call costs one synchronous register_worker_plugin scheduler round-trip, so use only on confirmed worker-rotation events; do not adopt it as a defensive default for every call.

Raises:
  • RuntimeError – If no Dask client is available.

  • ValueError – If no credentials could be resolved from any source.

class defair_data.DataReaderPlugin(dask_client_kwargs: dict[str, Any] | None = None)

Bases: abc.ABC

Base class for data reader plugins.

Subclasses must implement the read() method and should declare their capabilities via class attributes for automatic plugin selection.

Class Attributes:
SUPPORTED_EXTENSIONS: List of file extensions this plugin can handle

(e.g., [“.nc”, “.nc4”, “.netcdf”])

PRIORITY: Priority when multiple plugins match (0-100, default 50).

Higher values take precedence.

SUPPORTED_EXTENSIONS: ClassVar[list[str]] = []
PRIORITY: ClassVar[int] = 50
S3_STORAGE_OPTION_OVERRIDES: ClassVar[dict[str, Any] | None] = None
STREAMING_UNSUPPORTED_REASON: ClassVar[str | None] = None
STREAMING_POSITIONAL_DIMENSIONS: ClassVar[tuple[StreamingDimensionContract, Ellipsis]] = ()
EXPAND_CF_FLAGS: ClassVar[bool] = False
property dask_client

Return the Dask client, acquiring it lazily on first access.

Constructed-but-untouched readers do not create a Dask client. This property is the lazy-acquisition trigger for code that genuinely needs a live client (e.g. S3 credential propagation to workers). Read-only / local-file paths should prefer DaskClientManager().get_client() for a non-allocating snapshot.

property source_kwargs_for_workers: dict[str, Any]

source_kwargs enriched with worker-propagation state from the source plugin.

Recomputed on every access rather than served from a snapshot taken at source-load time, so graphs built after the source refreshed a token (e.g. following an auth failure) embed the fresh value. Graphs built before the refresh keep the kwargs they already embedded.

Returns {} before _ensure_source_loaded() has run, and the plain user source_kwargs when the source has no worker-propagation state. Call _ensure_source_loaded() first if non-empty credentials are expected.

classmethod can_handle(path: str | os.PathLike) → bool

Check if this plugin can handle the given path.

Default implementation checks if the path’s extension matches the plugin’s declared capabilities. Subclasses can override for custom logic.

Parameters:

path – Path to check

classmethod group_files_by_scene(files: list[str]) → list[list[str]]

Group files that should be spatially assembled by the reader.

When multiple files are passed to Dataset.from_source, this method determines which files belong to the same scene and should be read together.

Performs no grouping by default. Override for readers with spatial chunk assembly so that chunk files are routed to the reader’s chunk_files parameter instead of being concatenated along the time dimension.

Parameters:

files – Pre-resolved file paths

Returns:

List of file groups. Each group is read by a single reader call. Single-element groups are read normally; a multi-element group is passed via the chunk_files keyword for spatial chunk assemblers, else handed to the reader as a file list (e.g. MTG LI products).

inspect_streaming_positional_dimensions(file_group: list[str], source: str | None = None, source_kwargs: dict[str, Any] | None = None, **read_kwargs: Any) → dict[str, StreamingDimensionInspection]

Return metadata-only schemas for enabled positional dimensions.

The default is empty because most readers have fixed schemas. A reader declaring STREAMING_POSITIONAL_DIMENSIONS returns a subset when the corresponding opt-in data is enabled and must not read large arrays.

abstract read(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None) → defair_data.Dataset

Read data from the specified path.

Parameters:
  • path – Path to the data file (can be string, Path object, or S3 URI). Implementations should accept both str and PathLike objects.

  • source – Name of the data source plugin (e.g., “local”, “s3”) for accessing the file. If None, the plugin will auto-detect the appropriate source based on the path format.

  • source_kwargs – Additional arguments passed to the source plugin (e.g., S3 credentials, endpoint URLs, caching options).

Note

Subclasses may define additional parameters for reader-specific options (e.g., channels to read, resolution, etc.).

Raises:
  • FileNotFoundError – If the file does not exist

  • ValueError – If the file cannot be read

Note

Implementations should use self.open_file(path, source, source_kwargs) to obtain a file handle from the data source plugin, ensuring transparent access to data from local paths, network paths, S3, or any other source.

open_file(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None, **kwargs: Any) → defair_data._types.FileLike

Open a file-like object for the given path.

Parameters:
  • path – Path to the data file

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

  • **kwargs – Additional keyword arguments passed to source.open()

Returns:

File-like object from DataSourcePlugin conforming to FileLike protocol

Raises:
  • FileNotFoundError – If the file does not exist

  • ValueError – If no data source plugin found for the path

file_exists(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None, *, strict: bool = False) → bool

Check if a file exists using the data source plugin.

Parameters:
  • path – Path to the data file

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

  • strict – Probe through get_info instead of exists. Either way a denial or transport failure now propagates rather than reading as absence, so this is no longer about credentials. Two things still differ: a directory or prefix that happens to share a member’s name reports as absent under strict, since it is not that file; and the strict probe bypasses the source’s listing cache, which matters to a caller checking a member right after a glob populated that cache. It costs an extra request per call, so callers that only need presence should leave it False.

glob_files(pattern: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None) → list[str]

Expand a glob pattern to matching file paths using the data source plugin.

Parameters:
  • pattern – Glob pattern to expand (e.g., /data/*.nc, s3://bucket/**/*.nat)

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

Returns:

Sorted list of matching file paths/URIs

get_filename(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None) → str

Extract filename from path using the data source plugin.

Delegates to the appropriate data source plugin for protocol-specific handling. Local filesystem uses pathlib.Path for validation, S3 uses URL string operations.

Parameters:
  • path – Path to extract filename from

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

Returns:

Filename without directory components

get_parent(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None) → str

Extract parent directory from path using the data source plugin.

Delegates to the appropriate data source plugin for protocol-specific handling. Local filesystem uses pathlib.Path for validation, S3 uses URL string operations.

Parameters:
  • path – Path to extract parent from

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

Returns:

Parent directory path, or “.” for relative paths (matching pathlib behavior)

get_storage_options(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None) → tuple[str, dict[str, Any] | None]

Resolve path and get fsspec storage options via the source plugin.

For sources that cache files locally (e.g. HDA), returns the local cache path with None storage options. For S3, returns the original path with S3 credentials. For local, returns the original path with None.

Parameters:
  • path – Path to determine source for

  • source – Name of the data source plugin, empty for auto-detection

  • source_kwargs – Additional arguments passed to the source plugin

Returns:

Tuple of (resolved_path, storage_options).

defair_data.get_logger(name: str) → loguru.Logger

Get a Loguru logger bound to a specific module name.

Parameters:

name – Name of the module (typically __name__).

Returns:

Loguru logger instance bound to the module name.

class defair_data.ReaderInfo

Bases: TypedDict

A reader and every product it covers.

Variables:
  • short_name – The name accepted by reader= and returned by list_readers().

  • products – Products this reader covers, operational collection first. Empty for a reader with no catalogue entry, such as a third-party plugin.

short_name: str
products: list[ReaderProduct]
class defair_data.ReaderProduct

Bases: TypedDict

One product a reader can read.

Variables:
  • product_name – Official product name as published by the provider.

  • provider – Organisation distributing the product.

  • collection_id – Provider collection identifier, or None when the product is not distributed as a collection.

  • notes – Short qualifier when a reader covers several products, else None.

product_name: str
provider: str
collection_id: str | None
notes: str | None
defair_data.describe_readers() → list[ReaderInfo]

Describe every registered reader, sorted by short name.

Companion to list_readers(), which returns short names only. Each description carries the official product name and EUMETSAT collection ID, so a short name can be traced to the product to download from the Data Store or the DestinE HDA.

A reader with no catalogue entry, such as a third-party plugin, is still listed, with an empty products list.

Returns:

One ReaderInfo per registered reader. Plain lists and dicts, so the result passes straight to json.dumps().

Example

>>> from defair_data.readers import describe_readers
>>> {info["short_name"]: len(info["products"]) for info in describe_readers()}["msg15nat"]
3
defair_data.find_reader_for_path(path: str) → str | None

Find the best reader plugin for the given path.

Uses plugin capability declarations and priority scoring to select the most appropriate reader.

Parameters:

path – Path or URL to the data file

defair_data.get_reader(name: str, dask_client_kwargs: dict | None = None, **kwargs) → defair_data.data_reader_plugin.DataReaderPlugin

Get a reader plugin instance by name.

Parameters:
  • name – The registered name of the reader plugin (e.g., ‘msg15’)

  • dask_client_kwargs – Keyword arguments for Dask client configuration

  • **kwargs – Additional keyword arguments passed to the plugin constructor

Raises:

ValueError – If the plugin name is not found

defair_data.get_reader_info(short_name: str) → ReaderInfo

Describe a single registered reader.

Parameters:

short_name – A reader name as returned by list_readers().

Returns:

The reader’s description, with an empty products list if it has no catalogue entry.

Raises:

ValueError – If no reader is registered under short_name.

defair_data.list_readers() → list[str]

List all available reader plugin names.

Use describe_readers() for the same readers with their official product names and EUMETSAT collection IDs.

defair_data.release_read_handles() → int

Close every open read handle and return the memory behind it to the OS.

Call this between iterations of a loop that reads one product per iteration. A read returns a lazy dataset, so DEFAIR cannot tell when a caller has finished with the files behind it; the bound in this module keeps the handle count flat on its own, and this call is how a caller says the previous iteration is done with. It closes every handle in this process and on every Dask worker, flushes xarray’s own file cache, frees the HDF5 global free lists and trims the freed heap. Datasets read before the call stay usable and reopen what they need.

Returns the number of handles closed in this process.

class defair_data.MSG15NativeReaderPlugin(dask_client_kwargs: dict[str, Any] | None = None, chunks: dict[str, int] | str | None = None, calibration: str | collections.abc.Mapping[str, str] = 'radiance', use_channel_names: bool = False)

Bases: defair_data.readers.msg15._seviri_calibration_spec_mixin.SeviriCalibrationSpecMixin, defair.cf_history_mixin.CFHistoryMixin, defair_data.data_reader_plugin.DataReaderPlugin

Reader plugin for MSG 1.5 HRSEVIRI native format files.

This reader implements the DataSourcePlugin interface for reading SEVIRI channels into xarray Datasets with numpy arrays.

Channels are identified by their official EUMETSAT names – VIS006, VIS008, IR_016, IR_039, WV_062, WV_073, IR_087, IR_097, IR_108, IR_120, IR_134, HRV – for every MSG service (0 degree, Rapid Scanning, Indian Ocean Data Coverage), which all share this format and this channel set.

HRV is opt-in: it is excluded from DEFAULT_CHANNELS (it is ~9x the data of a VIS/IR channel and a separate full-disk grid), so a default read does not surface it. Request it explicitly with channels=["HRV", ...] and a calibration it supports: HRV is a broadband solar band, so counts, radiance and reflectance work, but brightness_temperature is undefined for it and raises (an explicit HRV + brightness_temperature request is rejected with a clear error rather than silently dropped).

SUPPORTED_EXTENSIONS: ClassVar[list[str]] = ['.nat', '.NAT', '_nat']
PRIORITY: ClassVar[int] = 80
CHANNEL_METADATA: ClassVar[dict[str, dict[str, Any]]]
DEFAULT_CHANNELS: ClassVar[list[str]]
ALL_CHANNELS: ClassVar[list[str]] = ['VIS006', 'VIS008', 'IR_016', 'IR_039', 'WV_062', 'WV_073', 'IR_087', 'IR_097', 'IR_108',...
UNIT_BY_FAMILY: ClassVar[dict[str, str]]
SATELLITE_NAMES: ClassVar[dict[int, str]]
VALID_CALIBRATIONS: ClassVar[tuple[str, Ellipsis]] = ('auto', 'counts', 'radiance', 'reflectance', 'brightness_temperature')
read(path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, Any] | None = None, channels: list[str] | None = None, visir_lines_num: int | None = None, lazy_coordinates: bool = True, include_latlon: bool | None = None, include_aux_metadata: bool = False, upper_right_corner: defair_data.readers._orientation.UpperRightCorner = 'NE') → defair_data.core.Dataset

Read MSG native format file and return a Dataset.

Parameters:
  • upper_right_corner – Desired array upper-right corner: NE (default, north-up and west-left), NW, SE, SW, or native for product scan ordering. Reorders coordinates and ancillary data with the pixels, lazily and without resampling.

  • path – Path or URI to the MSG native file (.nat)

  • channels – Canonical channel names to read (e.g. ["VIS006", "IR_108"]). If None, reads all standard channels. Leave this as None when a per-channel calibration mapping was passed to the constructor: that mapping’s keys are the channel selection, so also passing channels= here raises ValueError.

  • visir_lines_num – Number of lines for VISIR channels

  • lazy_coordinates – If True, generate lat/lon coordinates as lazy Dask arrays.

  • include_latlon – Whether to attach the 2D lat/lon auxiliary coordinates (lat/lon, and lat_hrv/lon_hrv for HRV). None (the default) reads projection-only and leaves the decision to whatever consumes the dataset: xarray realizes a variable’s deferred coordinates along with its data, so attaching them charges every plain read for a geolocation grid the caller may never use. True attaches them. False also reads projection-only, and additionally says that nothing downstream may add them. The 1D x/y projection axes and the CRS are always present, so the grid stays fully determined either way; Dataset.with_latlon() materialises the pair on demand.

  • source – Optional source plugin name for data source abstraction. If None, will auto-detect from path.

  • source_kwargs – Additional arguments for the source plugin (e.g., S3 credentials).

  • include_aux_metadata – If True, attach a lazy per-channel acquisition-time raster from the LineSideInfo records (datetime64, NaT outside the scanned window). One extra bulk pass only when computed; kept out of the CDM spatial groups. Default False changes nothing.

Raises:

ValueError – If invalid channels are specified or file cannot be read

classmethod get_platform_name(header_15: dict[str, Any]) → str

Extract platform name from MSG header SatelliteId.

Parameters:

header_15 – Parsed MSG 1.5 header dictionary

Returns:

Platform name string (e.g., “Meteosat-10”) or “Unknown” if not found

static parse_cds_time(cds_data: list | numpy.ndarray) → datetime.datetime | None

Parse CDS (CCSDS Day Segmented) time format.

Parameters:

cds_data – Array/list with [days, milliseconds, microseconds?, nanoseconds?] Days are since CDS epoch (1958-01-01)

Returns:

datetime object or None if parsing fails

static extract_earth_model(header_15: dict[str, Any]) → dict[str, float | int]

Extract Earth model parameters from MSG header.

Reads the ellipsoid parameters from GeometricProcessing/EarthModel. MSG uses its own Earth model (a=6378169 m) which differs from WGS84 (a=6378137 m).

Parameters:

header_15 – Parsed MSG 1.5 header dictionary

Returns:

type_of_earth_model, equatorial_radius, north_polar_radius, south_polar_radius, polar_radius (all radii in meters)

Return type:

Dictionary with keys

static extract_nominal_longitude(header_15: dict[str, Any]) → float | None

Extract nominal satellite longitude from header.

Parameters:

header_15 – Parsed MSG 1.5 header dictionary

Returns:

Nominal longitude in degrees, or None if not found

classmethod find_orbit_polynomial(header_15: dict[str, Any], eval_time: datetime.datetime | None = None) → tuple[dict, datetime.datetime, datetime.datetime, datetime.datetime] | None

Find the orbit polynomial covering the image acquisition time.

Parameters:
  • header_15 – Parsed MSG 1.5 header dictionary

  • eval_time – Time at which to evaluate the polynomial (defaults to TrueRepeatCycleStart)

Returns:

Tuple of (polynomial_dict, poly_start_time, poly_end_time, eval_time) or None

classmethod evaluate_satellite_position(poly: dict, poly_start: datetime.datetime, poly_end: datetime.datetime, eval_time: datetime.datetime, earth_model: dict[str, float] | None = None) → tuple[float, float, float] | None

Evaluate orbit polynomial at scan time and convert to geodetic coordinates.

MSG orbit polynomials use Chebyshev coefficients. The evaluation uses numpy.polynomial.chebyshev.Chebyshev with the polynomial’s time domain mapped to the Chebyshev [-1, 1] interval, and applies the standard Chebyshev T0 correction (subtract 0.5 * coefs[0]).

Parameters:
  • poly – Orbit polynomial dictionary with X, Y, Z Chebyshev coefficients

  • poly_start – Start time of the polynomial validity period

  • poly_end – End time of the polynomial validity period

  • eval_time – Time at which to evaluate the polynomial

  • earth_model – Optional Earth model dict for ECEF conversion ellipsoid

Returns:

Tuple of (longitude, latitude, altitude_meters) or None

classmethod extract_orbital_parameters(header_15: dict[str, Any], satellite_longitude: float, observation_start_time: datetime.datetime | None = None, earth_model: dict[str, float] | None = None) → dict[str, Any]

Extract orbital parameters from MSG header.

Parameters:
  • header_15 – Parsed MSG 1.5 header dictionary

  • satellite_longitude – Satellite longitude in degrees (from LLOS or nominal)

  • observation_start_time – Actual observation start time for polynomial evaluation. If None, falls back to TrueRepeatCycleStart from header.

  • earth_model – Earth model parameters for ECEF conversion ellipsoid

Returns:

  • projection_longitude: Sub-satellite point longitude

  • projection_latitude: Sub-satellite point latitude (always 0 for geostationary)

  • projection_altitude: Satellite altitude in meters

  • satellite_nominal_longitude: Nominal sub-satellite longitude

  • satellite_nominal_latitude: Nominal sub-satellite latitude (0)

  • satellite_actual_longitude: Actual longitude if available

  • satellite_actual_latitude: Actual latitude if available

  • satellite_actual_altitude: Actual altitude if available

Return type:

Dictionary with orbital parameters including

static ecef_to_geodetic(x_m: float, y_m: float, z_m: float, earth_model: dict[str, float] | None = None) → tuple[float, float, float]

Convert ECEF coordinates to geodetic (lon, lat, altitude).

Uses pyproj for accurate conversion from Earth-Centered Earth-Fixed (ECEF) coordinates to geodetic coordinates.

Parameters:
  • x_m – X coordinate in meters

  • y_m – Y coordinate in meters

  • z_m – Z coordinate in meters

  • earth_model – Optional Earth model dict with equatorial_radius and polar_radius. If provided, uses the file’s ellipsoid. If None, uses WGS84.

Returns:

Tuple of (longitude_deg, latitude_deg, altitude_m)

static round_nom_time(dt: datetime.datetime, time_delta: datetime.timedelta) → datetime.datetime

Round a datetime to the nearest multiple of a time delta.

Used to compute nominal start/end times from observation times by rounding to the nearest repeat cycle slot.

Parameters:
  • dt – Datetime to round

  • time_delta – Repeat cycle duration (e.g., 15 min for FES, 5 min for RSS)

Returns:

Rounded datetime

classmethod extract_time_parameters(header_15: dict[str, Any], filepath: str, trailer: dict[str, Any] | None = None) → dict[str, Any]

Extract time parameters from MSG header, trailer, and filename.

Observation times come from the trailer’s ActualScanningSummary (preferred) or from the header’s PlannedAcquisitionTime (fallback). Nominal times are computed by rounding the observation start to the nearest repeat cycle slot.

Parameters:
  • header_15 – Parsed 15_DATA_HEADER dictionary

  • filepath – Path to MSG file (for filename timestamp extraction)

  • trailer – Optional parsed 15_TRAILER dictionary with actual scan times

Returns:

  • nominal_start_time: Nominal scan start time rounded to repeat cycle (datetime)

  • nominal_end_time: Nominal scan end time (datetime)

  • observation_start_time: Actual observation start (datetime)

  • observation_end_time: Actual observation end (datetime)

Return type:

Dictionary with time parameters including

classmethod get_channel_info(channel: str) → dict[str, Any]

Get information about a specific channel.

Parameters:

channel – Canonical channel name (e.g., ‘VIS006’, ‘IR_108’)

Raises:

ValueError – If channel is unknown