# GeoXplain core and backend API reference

Generated from public Python exports. The `geoxplain` package is model-agnostic; backend-specific APIs are listed in separate package sections. Do not edit this file manually.

## Core package `geoxplain`

### `GeoXplain(out_path: str | os.PathLike[str] | None = None, *, title: str = 'GeoXplain', subtitle: str | None = 'Interactive geospatial attribution viewer', target_color: str = '#06b6d4', colormap: Any = 'default', contours: Optional[bool] = None, absolute: Optional[bool] = None, result: Any = None) -> None`

Qualified name: `geoxplain.viewer.GeoXplain`. Kind: class.

Build, export, and serve a standalone GeoXplain viewer.

By default the viewer keeps everything in memory: nothing is written to
disk until you call :meth:`open` (temporary browser preview),
:meth:`export` (an explicit ``viewer_data.json``), or
:meth:`export_browser` (a self-contained browser bundle). Pass
``out_path`` to opt into the legacy behavior where every data mutation
re-writes that JSON file.

Multiple methods and timestamps can be accumulated before opening the
packaged browser application or capturing a screenshot.

Parameters
----------
out_path:
    Optional ``viewer_data.json`` path that each mutation keeps in sync.
    When ``None`` (the default) the viewer never touches the filesystem on
    its own; use :meth:`open`, :meth:`export`, or :meth:`export_browser`
    instead.
title:
    Non-empty application title.
subtitle:
    Optional subtitle; ``None`` or an empty string hides it.
target_color:
    CSS color used for target points and boxes.
colormap:
    Default attribution preset or custom color stops.
contours:
    Whether attribution starts in contour mode.
absolute:
    Whether attribution starts showing absolute magnitude instead of
    signed/diverging values.
result:
    Optional ``XiaResult``-compatible object to add immediately.

Examples
--------
>>> from geoxplain import GeoXplain
>>> viewer = GeoXplain()
>>> viewer.add_attribution(
...     "saliency_700hPa.npy",
...     pressure_level=700,
...     method="Saliency",
... )

#### `GeoXplain.export_path`

Kind: property.

Configured ``viewer_data.json`` path, or ``None`` when in-memory only.

#### `GeoXplain.export(self, out_path: str | os.PathLike[str] | None = None) -> pathlib._local.Path`

Kind: method.

Write the current state as ``viewer_data.json``.

Parameters
----------
out_path:
    Destination path. When omitted, the ``out_path`` supplied to the
    constructor is used. A path is required: if neither is set, call
    :meth:`open` to preview in a browser or :meth:`export_browser` to
    write a self-contained bundle instead.

Returns
-------
pathlib.Path
    The written JSON path.

Raises
------
ValueError
    If no ``out_path`` is given and none was supplied to the
    constructor.

#### `GeoXplain.export_browser(self, out_dir: str | os.PathLike[str]) -> pathlib._local.Path`

Kind: method.

Write a self-contained static browser bundle to *out_dir*.

Copies the packaged browser application into *out_dir* and writes the
current state next to it as ``viewer_data.json``. The result can be
served by any static file host (``out_dir`` and everything under it).

Parameters
----------
out_dir:
    Destination directory. Created if it does not exist.

Returns
-------
pathlib.Path
    Path to the bundle's ``index.html``.

#### `GeoXplain.remove_export(self) -> 'GeoXplain'`

Kind: method.

Delete the configured JSON export and return this viewer.

A no-op when no ``out_path`` was configured. In-memory attributions and
overlays are never cleared.

#### `GeoXplain.screenshot(self, out_path: str | os.PathLike[str] | None = None, *, width: int | None = None, height: int | None = None, output_dir: str | os.PathLike[str] = 'screenshots', timeout: float = 30.0, launch_state: dict[str, typing.Any] | None = None) -> pathlib._local.Path`

Kind: method.

Capture the current exported viewer data as a PNG screenshot.

The screenshot contains only the map/globe visualization, attribution,
targets, and overlays. UI controls are hidden for the capture.

``out_path`` may be a file or directory. When omitted, a generated
filename is placed under ``output_dir``. The optional ``launch_state``
restores an explicit camera and viewer configuration for the capture.

Returns
-------
pathlib.Path
    The written PNG path.

#### `GeoXplain.open(self, *, open_browser: bool = True) -> geoxplain.viewer.GeoXplainOpenHandle`

Kind: method.

Serve the current viewer export from a temporary local browser build.

The returned handle owns a temporary directory and a local HTTP server.
Call ``handle.close()`` when the browser session is no longer needed.

Parameters
----------
open_browser:
    Open the generated local URL with Python's default browser handler.

Returns
-------
GeoXplainOpenHandle
    Context-manager-compatible owner of the server and temporary files.

### `GeoXplainWidget(height: 'int' = 620, initial_view_mode: 'str' = 'map', initial_map_type: 'str' = 'topo', contours: 'bool' = False, absolute: 'bool' = False, smooth: 'bool' = True, title: 'str' = 'GeoXplain', subtitle: 'str | None' = 'Interactive geospatial attribution viewer', target_color: 'str' = '#06b6d4', colormap: 'Any' = 'default', config_dir: 'str | os.PathLike[str] | None' = None, live_browser_export: 'bool | None' = None, result: 'Any' = None, **kwargs) -> 'None'`

Qualified name: `geoxplain.widget.GeoXplainWidget`. Kind: class.

Interactive Jupyter widget for GeoXplain attribution visualization.

The widget renders the same globe / map viewer used by the
standalone browser app, but embedded directly in a notebook cell.

Parameters
----------
height:
    Cell height in pixels (default 620).
initial_view_mode:
    Starting render mode — ``'globe'`` or ``'map'``.
initial_map_type:
    Starting basemap — ``'topo'`` or ``'satellite'``.
contours:
    Start with the contour-line depiction instead of the filled heatmap
    (default ``False``).  Users can switch styles at any time with the
    contour toggle in the viewer's view controls.
absolute:
    Start showing absolute magnitude instead of signed/diverging values
    (default ``False``).  Users can switch with the "Signed values" toggle
    in the viewer's Appearance menu.
smooth:
    Start with imported-grid smoothing enabled (default ``True``).
config_dir:
    Optional browser-export directory. Relative paths are resolved from the
    kernel working directory; absolute paths are treated as Jupyter
    server-relative paths (for example ``'/exports/my-widget'``).
live_browser_export:
    How the "Open in browser" button serves the standalone viewer.

    - ``None`` (default): auto-detect. When the notebook page is reached
      through an SSH port-forward — a loopback browser origin while the
      Jupyter server is bound to a remote host — the button is served from
      the Jupyter server's ``/files`` endpoint, reusing the port you
      already forward for the notebook (no extra tunnel). On a genuinely
      local session it instead uses a short-lived local preview server,
      which can also push imported-data updates into an already-open tab.
    - ``True``: always use the live preview server. Choose this on a remote
      session only if you have forwarded the preview server's port yourself
      and want live imported-data syncing.
    - ``False``: always use the static ``/files`` URL. No extra port to
      forward, but an already-open tab is not auto-updated; re-open it to
      refresh.
title:
    Application title shown in the widget and browser-viewer headers.
subtitle:
    Optional application subtitle shown under the title. Pass ``None`` or
    an empty string to hide it.
target_color:
    CSS color used for target points and boxes.
colormap:
    Default attribution preset or custom color stops.
result:
    Optional ``XiaResult``-compatible object to add immediately.
**kwargs:
    Additional keyword arguments forwarded to ``anywidget.AnyWidget``.

#### `GeoXplainWidget.screenshot(self, out_path: 'str | os.PathLike[str] | None' = None, *, width: 'int | None' = None, height: 'int | None' = None, output_dir: 'str | os.PathLike[str]' = 'screenshots', timeout: 'float' = 30.0, launch_state: 'dict[str, Any] | None' = None) -> 'pathlib.Path'`

Kind: method.

Capture the widget's current viewer state as a PNG screenshot.

The screenshot contains only the map/globe visualization, attribution,
targets, and overlays. UI controls are hidden for the capture.

When ``width`` or ``height`` is omitted, the latest dimensions reported
by the rendered widget are used, falling back to 1100 pixels by the
configured widget height. ``launch_state`` overrides the latest camera
and viewer state reported by the frontend.

Returns
-------
pathlib.Path
    The written PNG path.

#### `GeoXplainWidget.close(self) -> 'None'`

Kind: method.

Stop the browser preview server and release widget resources.

### `GeoXplainBase()`

Qualified name: `geoxplain._base.GeoXplainBase`. Kind: class.

Shared API for standalone and widget GeoXplain viewers.

#### `GeoXplainBase.add_attribution(self: '_BaseT', source: 'AttributionSource', *, level: 'str | None' = None, pressure_level: 'int | None' = None, method: 'str | _DefaultMethod' = 'saliency', timestamp: 'str | None' = None, target: 'Any' = <object object>, norm: 'str' = 'global', label: 'str | None' = None, layer_labels: 'Mapping[str, str] | None' = None, colormap: 'Any' = None) -> '_BaseT'`

Kind: method.

Add attribution data to the viewer.

Parameters
----------
source:
    A two-dimensional NumPy array, a path to a ``.npy`` grid, a mapping
    from ``"sfc"`` or ``"z-<int>"`` level IDs to grids, or an object
    satisfying :class:`geoxplain.xia_result.XiaResultProtocol`.
level:
    Level ID for one raw grid. Exactly one of ``level`` and
    ``pressure_level`` is required for a single array or path.
pressure_level:
    Pressure level in hPa for one raw grid. Supported values are
    1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, and 50.
method:
    Human-readable method name. Defaults to ``"saliency"`` for raw
    inputs and must not be supplied for a result bundle.
timestamp:
    Optional frame timestamp for a raw grid or level mapping.
target:
    Optional point or box accepted by the viewer target serializer.
    Result bundles provide their own targets.
norm:
    ``"global"``, ``"per-frame"``, or ``"per-level"``.
label:
    Display label for the single level supplied by an array or path.
layer_labels:
    Display labels keyed by level ID for a level mapping.
colormap:
    Attribution preset name or custom color stops. This may override a
    result bundle's display colormap.

Returns
-------
GeoXplainBase
    This viewer instance, for method chaining.

Raises
------
TypeError
    If the source form conflicts with supplied metadata.
ValueError
    If a level, pressure level, normalization, target, method, or
    colormap is invalid.

Notes
-----
Mutating methods return the viewer so calls can be chained. In a
Jupyter notebook this means ending a cell with a bare mutating call
re-renders an already-displayed widget as a second copy. Append a
semicolon to suppress that extra output::

    widget.add_attribution(result);

#### `GeoXplainBase.clear_attributions(self: '_BaseT') -> '_BaseT'`

Kind: method.

Remove attribution methods, frames, targets, and level data.

#### `GeoXplainBase.add_overlay(self: '_BaseT', source: 'OverlaySource', *, variable: 'str | None' = None, name: 'str | None' = None, unit: 'str | None' = None, colormap: 'Any' = None, timestamps: 'Sequence[str | None] | None' = None, visible: 'bool | None' = None, opacity: 'float | None' = None, stretch: 'tuple[float, float] | Sequence[float] | None' = None, offset_hours: 'int | None' = None, time_label: 'str | None' = None) -> '_BaseT'`

Kind: method.

Add a weather overlay to the viewer.

Parameters
----------
source:
    A two- or three-dimensional NumPy array, a NetCDF path, or an
    object satisfying
    :class:`geoxplain.overlay_result.OverlayResultProtocol`.
variable:
    NetCDF variable to load. Required for a path and rejected for an
    array or result bundle.
name:
    Display name. Defaults to the NetCDF variable, ``"Overlay"`` for
    an array, or metadata from a result bundle.
unit:
    Unit displayed by the viewer.
colormap:
    ``"viridis"``, ``"plasma"``, ``"thermal"``, ``"sequential"``,
    or custom ``(position, color)`` gradient stops.
timestamps:
    Optional sequence aligned with the first dimension of a 3-D array.
visible:
    Whether the overlay starts visible.
opacity:
    Optional default layer opacity in ``[0, 1]``. When omitted the
    viewer uses its own default (0.7).
stretch:
    Optional ``(low, high)`` contrast-stretch fractions in ``[0, 1]``
    (the draggable colormap-legend handles). When omitted the viewer
    uses the full range ``(0, 1)``.
offset_hours:
    Optional integer hours the field data is shifted relative to each
    frame's displayed time (negative = earlier, positive = later). The
    displayed frame is Aurora's most-recent input step t1, so ``-6``
    pulls the prior input step t0 and ``+6`` the forecast valid time t2.
    The viewer annotates it as "… h before/after this frame". For an
    ``OverlayResult`` source it defaults to the bundle's recorded offset.
time_label:
    Optional free-text annotation the viewer shows next to the offset
    (e.g. ``"Aurora input step t0"`` for ``-6`` or ``"Forecast valid
    time t2"`` for ``+6``). For an ``OverlayResult`` source it defaults
    to the bundle's recorded label.

Returns
-------
GeoXplainBase
    This viewer instance, for method chaining.

Raises
------
TypeError
    If the source form conflicts with ``variable``.
ValueError
    If required metadata, dimensions, or the colormap is invalid.

Notes
-----
Mutating methods return the viewer so calls can be chained. In a
Jupyter notebook this means ending a cell with a bare mutating call
re-renders an already-displayed widget as a second copy. Append a
semicolon to suppress that extra output::

    widget.add_overlay(overlay);

#### `GeoXplainBase.clear_overlays(self: '_BaseT') -> '_BaseT'`

Kind: method.

Remove overlays only.

#### `GeoXplainBase.set_title(self: '_BaseT', title: 'str') -> '_BaseT'`

Kind: method.

Set the application title shown in the viewer header.

#### `GeoXplainBase.set_subtitle(self: '_BaseT', subtitle: 'str | None') -> '_BaseT'`

Kind: method.

Set the optional application subtitle shown below the title.

#### `GeoXplainBase.set_options(self: '_BaseT', *, view_mode: 'str | None' = None, map_type: 'str | None' = None, **options: 'Any') -> '_BaseT'`

Kind: method.

Update viewer options using Python-style names.

Parameters
----------
view_mode:
    ``"heatmap"`` or ``"contours"`` for attribution depiction. For
    backward compatibility, ``"map"`` and ``"globe"`` also select
    the renderer.
map_type:
    ``"map"`` or ``"globe"`` for the renderer. ``"topo"`` and
    ``"satellite"`` are also accepted as basemap aliases.
**options:
    Additional frontend options. Common Python names are ``basemap``,
    ``contours``, ``absolute`` (or ``signed`` for the inverse),
    ``smooth`` (or ``smooth_imported_grids``), and
    ``smooth_imported_grid_sigma``. Other snake-case names are
    converted to camel case before being sent to the frontend.

Returns
-------
GeoXplainBase
    This viewer instance, for method chaining.

#### `GeoXplainBase.clear(self: '_BaseT') -> '_BaseT'`

Kind: method.

Remove attribution and overlay data while keeping configuration.

### `GeoXplainOpenHandle(*, url: str, server: geoxplain.viewer._OpenHTTPServer, thread: threading.Thread, temporary_directory: tempfile.TemporaryDirectory) -> None`

Qualified name: `geoxplain.viewer.GeoXplainOpenHandle`. Kind: class.

Handle returned by :meth:`GeoXplain.open`.

#### `GeoXplainOpenHandle.close(self) -> None`

Kind: method.

Stop the local static server and remove its temporary files.

### `XiaFrameProtocol(*args, **kwargs)`

Qualified name: `geoxplain.xia_result.XiaFrameProtocol`. Kind: class.

Duck-typed interface for one time step of a :class:`XiaResultProtocol`.

#### `XiaFrameProtocol.as_widget_dict(self) -> 'dict'`

Kind: method.

Return this frame's target info as a dict accepted by the widget.

### `XiaFrameFile(timestamp: 'str', attributions: 'dict[str, dict[str, np.ndarray]]', diverging: 'bool', meta: 'dict' = <factory>, _target_dict: 'dict' = <factory>) -> None`

Qualified name: `geoxplain.xia_result.XiaFrameFile`. Kind: class.

Concrete ``XiaFrameProtocol`` implementation loaded from a ``.xia.npz``.

#### `XiaFrameFile.as_widget_dict(self) -> 'dict'`

Kind: method.

Return the frame's target info in the format accepted by the widget.

``mode="box"`` targets store ``(lat, lon)`` as the box *center* and
``size=(dlat, dlon)`` as the full extent in degrees; we derive
south / north / west / east from those here.

### `XiaResultProtocol(*args, **kwargs)`

Qualified name: `geoxplain.xia_result.XiaResultProtocol`. Kind: class.

Duck-typed interface accepted by ``add_attribution()``.

Any object providing these attributes can be used, regardless of which
model or explanation library produced it.

### `XiaResultFile(method: 'str', frames: 'list[XiaFrameFile]', layer_labels: 'dict[str, str]' = <factory>, meta: 'dict' = <factory>, method_label: 'str' = '') -> None`

Qualified name: `geoxplain.xia_result.XiaResultFile`. Kind: class.

Concrete ``XiaResultProtocol`` implementation loaded from a ``.xia.npz``.

### `load_xia_result(path: 'str | os.PathLike') -> 'XiaResultFile'`

Qualified name: `geoxplain.xia_result.load_xia_result`. Kind: function.

Load a backend-independent ``.xia.npz`` attribution bundle.

Parameters
----------
path:
    Path to the ``.xia.npz`` archive (``format_version == 2``).

Returns
-------
An ``XiaResultFile`` instance that satisfies ``XiaResultProtocol``
and can be passed to ``GeoXplain.add_attribution()`` or
``GeoXplainWidget.add_attribution()``.

### `OverlayFrameProtocol(*args, **kwargs)`

Qualified name: `geoxplain.overlay_result.OverlayFrameProtocol`. Kind: class.

Base class for protocol classes.

Protocol classes are defined as::

    class Proto(Protocol):
        def meth(self) -> int:
            ...

Such classes are primarily used with static type checkers that recognize
structural subtyping (static duck-typing).

For example::

    class C:
        def meth(self) -> int:
            return 0

    def func(x: Proto) -> int:
        return x.meth()

    func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with
@typing.runtime_checkable act as simple-minded runtime protocols that check
only the presence of given attributes, ignoring their type signatures.
Protocol classes can be generic, they are defined as::

    class GenProto[T](Protocol):
        def meth(self) -> T:
            ...

### `OverlayFrameFile(timestamp: 'str', data: 'np.ndarray') -> None`

Qualified name: `geoxplain.overlay_result.OverlayFrameFile`. Kind: class.

Concrete ``OverlayFrameProtocol`` implementation loaded from a ``.overlay.npz``.

### `OverlayResultProtocol(*args, **kwargs)`

Qualified name: `geoxplain.overlay_result.OverlayResultProtocol`. Kind: class.

Base class for protocol classes.

Protocol classes are defined as::

    class Proto(Protocol):
        def meth(self) -> int:
            ...

Such classes are primarily used with static type checkers that recognize
structural subtyping (static duck-typing).

For example::

    class C:
        def meth(self) -> int:
            return 0

    def func(x: Proto) -> int:
        return x.meth()

    func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with
@typing.runtime_checkable act as simple-minded runtime protocols that check
only the presence of given attributes, ignoring their type signatures.
Protocol classes can be generic, they are defined as::

    class GenProto[T](Protocol):
        def meth(self) -> T:
            ...

### `OverlayResultFile(variable: 'str', level: 'int | None', frames: 'list[OverlayFrameFile]', label: 'str', unit: 'str', colormap: 'Any', visible: 'bool', overlay_offset_hours: 'int' = 0, time_label: 'str | None' = None, meta: 'dict' = <factory>) -> None`

Qualified name: `geoxplain.overlay_result.OverlayResultFile`. Kind: class.

Concrete ``OverlayResultProtocol`` implementation loaded from a ``.overlay.npz``.

### `load_overlay_result(path: 'str | os.PathLike') -> 'OverlayResultFile'`

Qualified name: `geoxplain.overlay_result.load_overlay_result`. Kind: function.

Load a ``.overlay.npz`` file produced by ``OverlayResult.save()``.

Parameters
----------
path:
    Path to the ``.overlay.npz`` archive (``format_version == 3``; older
    version-1/2 bundles load too, with ``overlay_offset_hours`` defaulting
    to 0 and ``time_label`` to ``None``).

Returns
-------
An ``OverlayResultFile`` instance that satisfies ``OverlayResultProtocol``
and can be passed to ``GeoXplainWidget.add_overlay()``.

## Backend package `geoxplain_aurora_adapter`

### `Target()`

Qualified name: `geoxplain_aurora_adapter.schema.spec.Target`. Kind: class.

Namespace for TargetSpec factory methods.

Usage::

    import geoxplain_aurora_adapter as ax

    # Single grid point
    target = ax.Target.point(var="q", level=850, lat=46.2, lon=8.8,
                             timestamp="2024-03-20T00:00:00Z")

    # Box of default size (2.0° lat × 3.0° lon) centered at (lat, lon)
    target = ax.Target.box(var="q", level=850, lat=46.25, lon=8.75,
                           timestamp="2024-03-20T00:00:00Z")

    # Box of custom size
    target = ax.Target.box(var="q", level=850, lat=46.25, lon=8.75,
                           size=(1.5, 2.5),
                           timestamp="2024-03-20T00:00:00Z")

#### `Target.point(*, var: 'str', level: 'Optional[int]', lat: 'float', lon: 'float', timestamp: 'str') -> "'TargetSpec'"`

Kind: static method.

Single-grid-point target.

#### `Target.box(*, var: 'str', level: 'Optional[int]', lat: 'float', lon: 'float', timestamp: 'str', size: 'tuple[float, float]' = (2.0, 3.0)) -> "'TargetSpec'"`

Kind: static method.

Box-mean target centered at ``(lat, lon)`` with extent ``size``.

### `TargetSpec(var: 'str', level: 'Optional[int]', mode: 'str', timestamp: 'str', lat: 'Optional[float]' = None, lon: 'Optional[float]' = None, size: 'Optional[tuple[float, float]]' = None) -> None`

Qualified name: `geoxplain_aurora_adapter.schema.spec.TargetSpec`. Kind: class.

Fully-resolved specification of the XIA attribution target.

Fields
------
var:        Variable name in the model output (e.g. ``"q"``, ``"t"``, ``"zwd"``).
level:      Pressure level in hPa (e.g. ``850``).  ``None`` for surface-only vars.
mode:       Spatial selection mode: ``"point"`` or ``"box"``.
timestamp:  ISO-8601 string for the second (t1) input timestep, e.g.
            ``"2024-03-20T00:00:00Z"``.  This is what you pass when
            *constructing* a target, and it is preserved unchanged as the
            frame's displayed timestamp (``frame.target.timestamp`` ==
            ``frame.timestamp`` == t1).  The explained prediction is the
            6 h-ahead step t2 = t1 + lead, recorded in the frame's
            ``lead_hours`` metadata rather than by shifting the timestamp.
lat/lon:    Point coordinates (``mode="point"``) or *box center*
            (``mode="box"``).  Longitudes accepted in either
            ``-180..180`` or ``0..360`` convention.
size:       Box full extent in degrees ``(dlat, dlon)`` (``mode="box"``
            only).  The actual bounds are
            ``[lat-dlat/2, lat+dlat/2] × [lon-dlon/2, lon+dlon/2]``.

#### `TargetSpec.point(*, var: 'str', level: 'Optional[int]', lat: 'float', lon: 'float', timestamp: 'str') -> "'TargetSpec'"`

Kind: class method.

Single-grid-point target.

#### `TargetSpec.box(*, var: 'str', level: 'Optional[int]', lat: 'float', lon: 'float', timestamp: 'str', size: 'tuple[float, float]' = (2.0, 3.0)) -> "'TargetSpec'"`

Kind: class method.

Box-mean target centered at ``(lat, lon)`` with extent ``size``.

#### `TargetSpec.box_bounds(self) -> 'tuple[float, float, float, float]'`

Kind: method.

Return ``(south, north, west, east)`` for ``mode="box"``.

#### `TargetSpec.to_dict(self) -> 'dict'`

Kind: method.

#### `TargetSpec.from_dict(d: 'dict') -> "'TargetSpec'"`

Kind: class method.

#### `TargetSpec.as_widget_dict(self) -> 'dict'`

Kind: method.

Return the target in the model-agnostic GeoXplain viewer format.

### `XiaResult(method: 'str', frames: 'list[XiaFrame]', layer_labels: 'dict[str, str]' = <factory>, meta: 'dict' = <factory>, method_label: 'str' = '') -> None`

Qualified name: `geoxplain_aurora_adapter.schema.result.XiaResult`. Kind: class.

Self-describing XIA attribution bundle (one method, one or more frames).

Attributes
----------
method:
    XIA method id: ``"saliency"``, ``"ig"``, ``"rise"``, or ``"vit_cx"``.
    A stable machine identifier (the compute/dispatch layers branch on it).
method_label:
    Human-readable method name for display, e.g. ``"Integrated Gradients"``.
    Empty when unknown; consumers fall back to ``method`` in that case.
frames:
    One :class:`XiaFrame` per time step.  Single-frame results are the
    common case; use :meth:`single` to build one ergonomically.
layer_labels:
    Optional ``{level_key: display_name}`` map shared across frames, e.g.
    ``{"z-2": "850 hPa", "sfc": "Surface"}``.  Absent keys fall back to the
    bare number (``"z-2"`` → ``"2"``) or ``"Surface"`` for ``"sfc"``.
meta:
    Bundle-level diagnostic metadata: ``"checkpoint_hash"``, ``"host"``,
    ``"slurm_job_id"``, etc.

#### `XiaResult.single(method: 'str', target: 'TargetSpec', timestamp: 'str', attributions: 'dict[str, dict[str, np.ndarray]]', diverging: 'bool', meta: 'dict | None' = None, *, layer_labels: 'dict[str, str] | None' = None, frame_meta: 'dict | None' = None, method_label: 'str' = '') -> "'XiaResult'"`

Kind: class method.

Build a one-frame bundle.

``meta`` becomes the bundle-level metadata; ``frame_meta`` (if given)
is attached to the single frame.  For the common case where there is
only one frame, passing diagnostics via ``meta`` is fine.

#### `XiaResult.save(self, path: 'str | os.PathLike') -> 'None'`

Kind: method.

Save to a ``.xia.npz`` archive.

If *path* does not end with ``".xia.npz"``, the suffix is appended
automatically.

#### `XiaResult.load(path: 'str | os.PathLike') -> "'XiaResult'"`

Kind: class method.

Load from a ``.xia.npz`` archive (``format_version == 2``).

#### `XiaResult.to_msgpack(self) -> 'bytes'`

Kind: method.

Serialize to msgpack bytes for HTTP transport.

Arrays are embedded as raw float32 LE bytes + shape info.  The
result is designed to be deserialised by ``XiaResult.from_msgpack``.

#### `XiaResult.from_msgpack(data: 'bytes') -> "'XiaResult'"`

Kind: class method.

Deserialize from msgpack bytes produced by ``XiaResult.to_msgpack``.

#### `XiaResult.summary(self) -> 'str'`

Kind: method.

One-line human-readable summary.

### `XiaFrame(target: 'TargetSpec', timestamp: 'str', attributions: 'dict[str, dict[str, np.ndarray]]', diverging: 'bool', meta: 'dict' = <factory>) -> None`

Qualified name: `geoxplain_aurora_adapter.schema.result.XiaFrame`. Kind: class.

A single time step of an :class:`XiaResult` bundle.

Attributes
----------
target:
    The scalar that was explained (what variable, where, when).
timestamp:
    ISO-8601 string of the **requested time** — Aurora's most-recent input
    step t1 — which is what the viewer displays and equals
    ``target.timestamp``. The explained prediction is the 6 h-ahead step
    t2 = t1 + lead; ``meta["lead_hours"]`` records the lead, and
    ``meta["input_timestamp"]`` echoes t1 for convenience.
attributions:
    ``attributions[wrt_var][level_key]`` is a ``(721, 1440)`` float32
    array recording the sensitivity of the target to the input field
    ``wrt_var`` at ``level_key``.  Atmospheric level keys have the form
    ``"z-{N}"`` (higher ``N`` = higher in the tool); surface variables
    use ``"sfc"``.
diverging:
    Whether the attribution maps contain significant negative values.
    Auto-detected from the sign distribution; controls whether the
    visualization widget uses a diverging colormap.
meta:
    Optional per-frame diagnostic metadata: ``"target_score"`` (scalar
    value being explained, saliency/IG only), ``"runtime_s"``, etc.

#### `XiaFrame.as_widget_dict(self) -> 'dict'`

Kind: method.

Return this frame's target as a geoxplain-compatible dict.

The visualization side's importer calls ``as_widget_dict()`` on each
*frame* (not on ``frame.target``) to place the target point/box.  When
an in-memory :class:`XiaResult` is handed straight to the widget — the
live/remote path, with no ``.xia.npz`` round-trip — the frame object is
this class, so it must expose the method itself; otherwise the target
is silently dropped.  Delegates to :meth:`TargetSpec.as_widget_dict`.

### `OverlayResult(variable: 'str', level: 'Optional[int]', frames: 'list[OverlayFrame]', label: 'str', unit: 'str' = '', colormap: 'str' = 'viridis', visible: 'bool' = True, overlay_offset_hours: 'int' = 0, time_label: 'Optional[str]' = None, lat: 'Optional[np.ndarray]' = None, lon: 'Optional[np.ndarray]' = None, meta: 'dict' = <factory>) -> None`

Qualified name: `geoxplain_aurora_adapter.schema.overlay.OverlayResult`. Kind: class.

Self-contained weather-field overlay bundle.

``frames`` are raw ERA5/Aurora-grid arrays. The visualization package applies
its existing preprocessing pipeline when the overlay is added to a widget.

#### `OverlayResult.timestamps`

Kind: property.

#### `OverlayResult.arrays(self) -> 'np.ndarray'`

Kind: method.

#### `OverlayResult.save(self, path: 'str | os.PathLike') -> 'None'`

Kind: method.

Save to a ``.overlay.npz`` archive.

#### `OverlayResult.load(path: 'str | os.PathLike') -> "'OverlayResult'"`

Kind: class method.

Load from a ``.overlay.npz`` archive.

#### `OverlayResult.to_msgpack(self) -> 'bytes'`

Kind: method.

Serialize to msgpack bytes for HTTP transport.

#### `OverlayResult.from_msgpack(data: 'bytes') -> "'OverlayResult'"`

Kind: class method.

Deserialize bytes produced by :meth:`to_msgpack`.

#### `OverlayResult.summary(self) -> 'str'`

Kind: method.

### `OverlayFrame(timestamp: 'str', data: 'np.ndarray') -> None`

Qualified name: `geoxplain_aurora_adapter.schema.overlay.OverlayFrame`. Kind: class.

One timestamped raw weather-field overlay frame.

### `pull_overlay(variable: 'str', dates: 'str | list[str] | tuple[str, ...] | None' = None, *, level: 'Optional[int]' = None, remote: 'Optional[str]' = None, name: 'Optional[str]' = None, unit: 'Optional[str]' = None, colormap: 'Optional[str]' = None, visible: 'bool' = True, overlay_time: 'str' = 'input', step_hours: 'int' = 6, timeout_s: 'float' = 1800.0, poll_interval_s: 'float' = 2.0, poll_max_s: 'float' = 30.0) -> 'OverlayResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.pull_overlay`. Kind: function.

Pull ERA5 fields as timestamped viewer overlays.

``dates`` accepts ISO timestamps, dates, ranges, or ``None`` to reuse the
XIA frame timestamps recorded this session. The displayed frame keeps its
requested timestamp (Aurora's most-recent input step t1), so ``overlay_time``
chooses the field time relative to it: ``"input"`` (0 h, the default — the
frame's own time t1), ``"prior"`` (-6 h, the earlier input step t0), or
``"predicted"`` (+6 h, the forecast valid time t2). It also sets a
``time_label`` annotation on the result for the non-default choices
(``"prior"`` → ``"Aurora input step t0"``, ``"predicted"`` → ``"Forecast
valid time t2"``), which the viewer shows next to the offset. Remote calls
use the listener at ``remote``; local calls read from the configured
dataset.

### `session_timestamps() -> 'list[str]'`

Qualified name: `geoxplain_aurora_adapter.api.dispatch.session_timestamps`. Kind: function.

Return the XIA target timestamps recorded this session (first-seen order).

### `run_saliency(target: 'TargetSpec', input: 'list[str]', *, remote: 'Optional[str]' = None, checkpoint_path: 'Optional[str]' = None, timeframes: 'int' = 1, step_hours: 'int' = 6, levels: 'Optional[int | list[int]]' = None, **options) -> 'XiaResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.run_saliency`. Kind: function.

Compute vanilla gradient saliency attribution.

Parameters
----------
target:         What scalar to explain.
input:          Input variable names to attribute (e.g. ``["t", "q", "z"]``).
remote:         If set, delegates computation to the listener at this URL
                (e.g. ``"http://gpu01:8765"`` or
                ``"http://localhost:8765"`` for an SSH-tunnelled cluster).
                If ``None``, runs in-process on the local GPU.
checkpoint_path:Override the default checkpoint path (local mode only).
timeframes:     Number of consecutive timeframes to compute.  Values
                greater than 1 return one multi-frame XiaResult.
step_hours:     Hours between consecutive timeframes when timeframes > 1.
levels:         Pressure levels (hPa) to return attribution for, e.g.
                ``[925, 850, 700]``.  ``None`` (the default) returns every
                level in :data:`AURORA_LEVELS`.  Only affects atmospheric
                input variables; surface variables are unaffected.  The
                single backward pass computes gradients for all levels
                regardless, so this filters the output rather than reducing
                GPU cost.
**options:      No other method-specific options for saliency.

Returns
-------
XiaResult
    One frame, or a multi-frame bundle when ``timeframes > 1``.

### `run_ig(target: 'TargetSpec', input: 'list[str]', *, remote: 'Optional[str]' = None, checkpoint_path: 'Optional[str]' = None, timeframes: 'int' = 1, step_hours: 'int' = 6, n_steps: 'int' = 32, baseline_sigma_deg: 'float' = 2.5, levels: 'Optional[int | list[int]]' = None, **options) -> 'XiaResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.run_ig`. Kind: function.

Compute Integrated Gradients attribution.

Parameters
----------
target:             What scalar to explain.
input:              Input variable names to attribute.
remote:             Listener URL, or ``None`` for in-process.
checkpoint_path:    Override checkpoint path (local mode only).
timeframes:         Number of consecutive timeframes to compute.
step_hours:         Hours between consecutive timeframes when timeframes > 1.
n_steps:            Number of integration steps (midpoint Riemann rule).
baseline_sigma_deg: Gaussian sigma (degrees latitude) for the smoothed baseline.
levels:             Pressure levels (hPa) to return attribution for, e.g.
                    ``[925, 850, 700]``.  ``None`` (the default) returns
                    every level in :data:`AURORA_LEVELS`.  Only affects
                    atmospheric input variables; surface variables are
                    unaffected.  Each integration step's backward pass
                    computes gradients for all levels regardless, so this
                    filters the output rather than reducing GPU cost.

Returns
-------
XiaResult
    One frame, or a multi-frame bundle when ``timeframes > 1``.

### `run_rise(target: 'TargetSpec', input: 'list[str]', *, remote: 'Optional[str]' = None, checkpoint_path: 'Optional[str]' = None, timeframes: 'int' = 1, step_hours: 'int' = 6, n_masks: 'int' = 1200, cells_h: 'int' = 400, cells_w: 'int' = 800, seed: 'int' = 42, baseline_sigma_deg: 'float' = 2.5, **options) -> 'XiaResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.run_rise`. Kind: function.

Compute RISE (Randomized Input Sampling for Explanation) attribution.

Parameters
----------
target:             What scalar to explain.
input:              Input variable names to attribute.
remote:             Listener URL, or ``None`` for in-process.
checkpoint_path:    Override checkpoint path (local mode only).
timeframes:         Number of consecutive timeframes to compute.
step_hours:         Hours between consecutive timeframes when timeframes > 1.
n_masks:            Number of random masks.
cells_h/cells_w:    Low-resolution grid dimensions for mask upsampling.
seed:               Random seed for mask generation.
baseline_sigma_deg: Gaussian sigma for the smoothed baseline field.

Returns
-------
XiaResult
    One frame, or a multi-frame bundle when ``timeframes > 1``.

### `run_vit_cx(target: 'TargetSpec', input: 'list[str]', *, remote: 'Optional[str]' = None, checkpoint_path: 'Optional[str]' = None, timeframes: 'int' = 1, step_hours: 'int' = 6, hook_stage: 'int' = 1, n_clusters: 'int' = 4096, smooth_sigma: 'float | tuple | None' = 0, baseline_sigma_deg: 'float' = 2.5, **options) -> 'XiaResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.run_vit_cx`. Kind: function.

Compute ViT-CX (cluster-based causal attribution) attribution.

Parameters
----------
target:             What scalar to explain.
input:              Input variable names to attribute.
remote:             Listener URL, or ``None`` for in-process.
checkpoint_path:    Override checkpoint path (local mode only).
timeframes:         Number of consecutive timeframes to compute.
step_hours:         Hours between consecutive timeframes when timeframes > 1.
hook_stage:         Aurora encoder stage to hook (0-2; default 1).
n_clusters:         Fixed cluster budget = number of occlusion forward passes
                    per variable.  Bounds run cost regardless of input.
smooth_sigma:       Gaussian post-smoothing of the upsampled attribution map.
                    Default ``0`` disables smoothing and keeps the raw
                    cluster map.  A non-zero scalar applies the same sigma
                    to both axes; a ``(lat, lon)`` pair sets them
                    independently.
baseline_sigma_deg: Gaussian sigma for the smoothed baseline field.

Returns
-------
XiaResult
    One frame, or a multi-frame bundle when ``timeframes > 1``.

### `run_rollout(target: 'TargetSpec', input: 'list[str]', *, method: 'str' = 'saliency', timeframes: 'int', remote: 'Optional[str]' = None, checkpoint_path: 'Optional[str]' = None, n_steps: 'int' = 32, baseline_sigma_deg: 'float' = 2.5, timeout_s: 'float' = 1800.0, poll_interval_s: 'float' = 2.0, poll_max_s: 'float' = 30.0) -> 'XiaResult'`

Qualified name: `geoxplain_aurora_adapter.api.methods.run_rollout`. Kind: function.

Compute autoregressive rollout XIA in fixed six-hour Aurora frames.

Parameters
----------
target:
    Scalar output target for the first frame.
input:
    Input variable names to attribute.
method:
    ``"saliency"`` or ``"ig"``. RISE and ViT-CX are recognized method
    identifiers but are not implemented for rollout.
timeframes:
    Required positive number of autoregressive frames.
remote:
    Listener URL, or ``None`` for in-process execution.
checkpoint_path:
    Override the default checkpoint in local mode only.
n_steps, baseline_sigma_deg:
    Integrated Gradients options, ignored for Saliency.
timeout_s, poll_interval_s, poll_max_s:
    Remote-client timeout and polling controls.

Returns
-------
XiaResult
    One bundle containing all rollout frames.

Raises
------
ValueError
    If ``method`` is unknown or ``timeframes`` is not positive.
NotImplementedError
    If rollout is requested with RISE or ViT-CX.

### `listen_for_request(port: 'int' = 8765, host: 'str' = '127.0.0.1', persistent: 'bool' = False, prewarm: 'bool' = False, memory_retention: 'Optional[str]' = None, result_retention: 'Optional[str]' = None, **sbatch_kwargs) -> 'None'`

Qualified name: `geoxplain_aurora_adapter.api.listener.listen_for_request`. Kind: function.

Start the geoxplain_aurora_adapter HTTP listener server.

Mode is auto-detected:

+------------------+------------------+---------------------------------+
| GPU visible?     | sbatch on PATH?  | Resolved mode                   |
+==================+==================+=================================+
| yes              | yes              | sbatch-oneshot (or sbatch-persistent if persistent) |
| no               | yes              | sbatch-oneshot (or sbatch-persistent if persistent) |
| yes              | no               | gpu-listener                    |
| no               | no               | Error                           |
+------------------+------------------+---------------------------------+

Parameters
----------
port:           TCP port to listen on (default 8765).
host:           Bind address (default ``"127.0.0.1"`` — loopback only; the
                HTTP API is unauthenticated, so reach it via an SSH tunnel.
                Pass ``"0.0.0.0"`` only on a trusted/firewalled network).
persistent:     Opt into sbatch-persistent (persistent GPU worker) instead of the
                default sbatch-oneshot (one sbatch per request).
prewarm:        sbatch-persistent only — submit the GPU worker job immediately
                rather than waiting for the first request.
memory_retention: How long completed jobs and cached result bytes live in the
                listener's memory (default ``"1h"``; ``"never"`` disables).
result_retention: sbatch-oneshot only — how long on-disk result directories
                are kept (default ``"never"``).
**sbatch_kwargs: Forwarded to ``SbatchConfig`` (account, partition, etc.).
                Also accepted as CLI flags by ``geoxplain-aurora-adapter listen``.
