xopr.opr_access

Core data access interface for Open Polar Radar (OPR) datasets.

This module provides the primary interface for discovering, querying, and loading polar ice-penetrating radar data from the Open Polar Radar archive. It implements a STAC (SpatioTemporal Asset Catalog) based workflow for efficient data discovery and retrieval.

Primary Class

OPRConnection : Main interface for accessing OPR data Provides methods for querying STAC catalogs, loading radar frames, and retrieving layer picks from both file-based and database sources.

Typical Workflow
  1. Create an OPRConnection object, optionally with local caching
  2. Query the STAC catalog to find radar data matching your criteria
  3. Load radar frames as xarray Datasets
  4. Optionally load associated layer picks
  5. Process and visualize the data

See this notebook for an end-to-end example:

Examples
>>> import xopr
>>> # Connect to OPR with local caching
>>> opr = xopr.OPRConnection(cache_dir='radar_cache')
>>>
>>> # Query for data in a specific collection and segment
>>> stac_items = opr.query_frames(
...     collections=['2022_Antarctica_BaslerMKB'],
...     segment_paths=['20230109_01']
... )
>>>
>>> # Load the radar frames
>>> frames = opr.load_frames(stac_items)
>>>
>>> # Get layer picks (surface/bed)
>>> layers = opr.get_layers(frames[0])
See Also

xopr.geometry: Geographic utilities for region selection and projection
xopr.radar_util: Processing functions for radar data and layers
ops_api: Interface to the OPS database API

   1"""
   2Core data access interface for Open Polar Radar (OPR) datasets.
   3
   4This module provides the primary interface for discovering, querying, and loading
   5polar ice-penetrating radar data from the Open Polar Radar archive. It implements
   6a STAC (SpatioTemporal Asset Catalog) based workflow for efficient data discovery
   7and retrieval.
   8
   9Primary Class
  10-------------
  11OPRConnection : Main interface for accessing OPR data
  12    Provides methods for querying STAC catalogs, loading radar frames,
  13    and retrieving layer picks from both file-based and database sources.
  14
  15Typical Workflow
  16----------------
  171. Create an OPRConnection object, optionally with local caching
  182. Query the STAC catalog to find radar data matching your criteria
  193. Load radar frames as xarray Datasets
  204. Optionally load associated layer picks
  215. Process and visualize the data
  22
  23See this notebook for an end-to-end example:
  24- https://docs.englacial.org/xopr/demo-notebook/
  25
  26Examples
  27--------
  28>>> import xopr
  29>>> # Connect to OPR with local caching
  30>>> opr = xopr.OPRConnection(cache_dir='radar_cache')
  31>>>
  32>>> # Query for data in a specific collection and segment
  33>>> stac_items = opr.query_frames(
  34...     collections=['2022_Antarctica_BaslerMKB'],
  35...     segment_paths=['20230109_01']
  36... )
  37>>>
  38>>> # Load the radar frames
  39>>> frames = opr.load_frames(stac_items)
  40>>>
  41>>> # Get layer picks (surface/bed)
  42>>> layers = opr.get_layers(frames[0])
  43
  44See Also
  45--------
  46xopr.geometry : Geographic utilities for region selection and projection
  47xopr.radar_util : Processing functions for radar data and layers
  48ops_api : Interface to the OPS database API
  49"""
  50
  51import getpass
  52import netrc
  53import os
  54import re
  55import sys
  56import warnings
  57from typing import Union
  58from urllib.parse import urlparse
  59
  60import aiohttp
  61import antimeridian
  62import fsspec
  63import geopandas as gpd
  64import h5py
  65import hdf5storage
  66import numpy as np
  67import pandas as pd
  68import scipy.io
  69import shapely
  70import xarray as xr
  71from rustac import DuckdbClient
  72
  73from . import opr_tools, ops_api
  74from .cf_units import apply_cf_compliant_attrs
  75from .matlab_attribute_utils import (
  76    decode_hdf5_matlab_variable,
  77    extract_legacy_mat_attributes,
  78)
  79from .stac_cache import get_opr_catalog_path, sync_opr_catalogs
  80
  81AUTH_STRATEGIES = ("environment", "netrc", "interactive")
  82
  83
  84def _is_interactive():
  85    """True if a user can answer a prompt (terminal or Jupyter kernel)."""
  86    return (sys.stdin is not None and sys.stdin.isatty()) or 'ipykernel' in sys.modules
  87
  88
  89def _resolve_auth(auth, host):
  90    """
  91    Resolve HTTP basic auth credentials for ``host``.
  92
  93    Parameters
  94    ----------
  95    auth : str, tuple, or None
  96        ``(username, password)`` tuple, ``None`` (no auth), or a strategy:
  97        ``"environment"`` (``OPR_USERNAME``/``OPR_PASSWORD``), ``"netrc"``
  98        (``~/.netrc`` or ``$NETRC``), ``"interactive"`` (prompt), or ``"all"``
  99        (try each in that order, skipping the prompt if non-interactive).
 100    host : str
 101        Hostname to look up in netrc and to show in the prompt.
 102
 103    Returns
 104    -------
 105    tuple or None
 106        ``(username, password)``, or None if ``auth="all"`` found nothing.
 107    """
 108    if auth is None or isinstance(auth, tuple):
 109        return auth
 110    if auth == "all":
 111        for strategy in AUTH_STRATEGIES:
 112            if strategy == "interactive" and not _is_interactive():
 113                continue
 114            creds = _resolve_auth_strategy(strategy, host)
 115            if creds:
 116                return creds
 117        warnings.warn(f"No credentials found for {host} (set OPR_USERNAME/OPR_PASSWORD, "
 118                      f"add a ~/.netrc entry, or pass auth=(username, password)). "
 119                      f"Continuing without authentication.", UserWarning, stacklevel=3)
 120        return None
 121    if auth not in AUTH_STRATEGIES:
 122        raise ValueError(f"Unknown auth strategy {auth!r}; expected one of "
 123                         f"{('all',) + AUTH_STRATEGIES}, a (username, password) tuple, or None")
 124    creds = _resolve_auth_strategy(auth, host)
 125    if not creds:
 126        raise ValueError(f"auth={auth!r} did not provide credentials for {host}")
 127    return creds
 128
 129
 130def _resolve_auth_strategy(strategy, host):
 131    """Return ``(username, password)`` from a single strategy, or None."""
 132    if strategy == "environment":
 133        user, password = os.environ.get("OPR_USERNAME"), os.environ.get("OPR_PASSWORD")
 134    elif strategy == "netrc":
 135        try:
 136            entry = netrc.netrc(os.environ.get("NETRC")).authenticators(host)
 137        except (FileNotFoundError, netrc.NetrcParseError):
 138            entry = None
 139        user, password = (entry[0], entry[2]) if entry else (None, None)
 140    else:
 141        try:
 142            print(f"Enter credentials for {host}")
 143            user, password = input("Username: "), getpass.getpass("Password: ")
 144        except (EOFError, NotImplementedError, OSError):  # e.g. kernel without stdin
 145            user, password = None, None
 146    return (user, password) if user and password else None
 147
 148
 149class OPRConnection:
 150    def __init__(self,
 151                 collection_url: str = "https://data.cresis.ku.edu/data/",
 152                 cache_dir: str = None,
 153                 stac_parquet_href: str = None,
 154                 sync_catalogs: bool = True,
 155                 auth: Union[str, tuple, None] = "all"):
 156        """
 157        Initialize connection to OPR data archive.
 158
 159        Parameters
 160        ----------
 161        collection_url : str, optional
 162            Base URL for OPR data collection.
 163        cache_dir : str, optional
 164            Directory to cache downloaded data for faster repeated access.
 165        stac_parquet_href : str, optional
 166            Path or URL pattern to STAC catalog parquet files.  When *None*
 167            (default), the local cache is used if available, falling back to
 168            the S3 catalog.
 169        sync_catalogs : bool, optional
 170            If True (default), sync OPR STAC catalogs to a local cache
 171            before resolving the catalog path.  Uses ETag-based change
 172            detection so repeated calls are cheap (single HTTP request).
 173        auth : str, tuple, or None, optional
 174            HTTP basic auth for the ``collection_url`` host. Either a
 175            ``(username, password)`` tuple, None to disable, or a strategy:
 176            ``"environment"`` (``OPR_USERNAME``/``OPR_PASSWORD`` env vars),
 177            ``"netrc"`` (``~/.netrc`` or ``$NETRC``), ``"interactive"``
 178            (prompt), or ``"all"`` (default; try each in that order, skipping
 179            the prompt in non-interactive sessions and warning if nothing is
 180            found). Credentials are only sent to the ``collection_url`` host.
 181        """
 182        self.collection_url = collection_url
 183        self.auth_host = urlparse(collection_url).hostname
 184        self._auth = _resolve_auth(auth, self.auth_host)
 185        self.cache_dir = cache_dir
 186        self._user_set_href = stac_parquet_href is not None
 187        if sync_catalogs and not self._user_set_href:
 188            sync_opr_catalogs()
 189        self.stac_parquet_href = stac_parquet_href or get_opr_catalog_path()
 190
 191        self.fsspec_cache_kwargs = {}
 192        self.fsspec_url_prefix = ''
 193        if cache_dir:
 194            self.fsspec_cache_kwargs['cache_storage'] = cache_dir
 195            self.fsspec_cache_kwargs['check_files'] = True
 196            self.fsspec_url_prefix = 'filecache::'
 197
 198        self.db_layers_metadata = None # Cache for OPS database layers metadata
 199
 200        # Lazy-initialized DuckDB client for STAC queries — reusing a single
 201        # session caches remote file metadata (parquet footers) across calls
 202        self._duckdb_client = None
 203
 204    @property
 205    def duckdb_client(self):
 206        """Lazy-initialized DuckDB client, recreated after pickling."""
 207        if self._duckdb_client is None:
 208            self._duckdb_client = DuckdbClient()
 209        return self._duckdb_client
 210
 211    def __getstate__(self):
 212        state = self.__dict__.copy()
 213        state['_duckdb_client'] = None  # DuckdbClient can't be pickled
 214        return state
 215
 216    def _open_file(self, url):
 217        """Helper method to open files with appropriate caching.
 218
 219        Local filesystem paths are returned as-is (no fsspec wrapping).
 220        Remote URLs (http, https, s3, gs) use filecache or simplecache.
 221        """
 222        if not url.startswith(('http://', 'https://', 's3://', 'gs://')):
 223            return url
 224        protocol = url.split('://')[0]
 225        cache = self.fsspec_url_prefix.rstrip(':') or 'simplecache'
 226        kwargs = {cache: self.fsspec_cache_kwargs}
 227        if self._auth and urlparse(url).hostname == self.auth_host:
 228            kwargs[protocol] = {'client_kwargs': {'auth': aiohttp.BasicAuth(*self._auth)}}
 229        try:
 230            return fsspec.open_local(f"{cache}::{url}", **kwargs)
 231        except aiohttp.ClientResponseError as e:
 232            if e.status not in (401, 403):
 233                raise
 234            reason = ("the provided credentials were rejected" if self._auth else
 235                      "no credentials were provided")
 236            raise PermissionError(
 237                f"HTTP {e.status} accessing {url}: {reason}. Set OPR_USERNAME/OPR_PASSWORD, "
 238                f"add a ~/.netrc entry for {urlparse(url).hostname}, or pass "
 239                f"OPRConnection(auth=(username, password)).") from e
 240
 241    def _extract_segment_info(self, segment):
 242        """Extract collection, segment_path, and frame from Dataset or dict."""
 243        if isinstance(segment, xr.Dataset):
 244            return (segment.attrs.get('collection'),
 245                    segment.attrs.get('segment_path'),
 246                    segment.attrs.get('frame'))
 247        else:
 248            return (segment['collection'],
 249                    f"{segment['properties'].get('opr:date')}_{segment['properties'].get('opr:segment'):02d}",
 250                    segment['properties'].get('opr:frame'))
 251
 252    def query_frames(self, collections: list[str] = None, segment_paths: list[str] = None,
 253                     geometry = None, date_range: tuple = None, properties: dict = {},
 254                     max_items: int = None, exclude_geometry: bool = False,
 255                     search_kwargs: dict = {}) -> gpd.GeoDataFrame:
 256        """
 257        Query STAC catalog for radar frames matching search criteria.
 258
 259        Multiple parameters are combined with AND logic. Lists of values passed to a
 260        single parameter are treated with OR logic (any value matches).
 261
 262        Parameters
 263        ----------
 264        collections : list[str] or str, optional
 265            Collection name(s) (e.g., "2022_Antarctica_BaslerMKB").
 266        segment_paths : list[str] or str, optional
 267            Segment path(s) in format "YYYYMMDD_NN" (e.g., "20230126_01").
 268        geometry : shapely geometry or dict, optional
 269            Geospatial geometry to filter by intersection.
 270        date_range : str, optional
 271            Date range in ISO format (e.g., "2021-01-01/2025-06-01").
 272        properties : dict, optional
 273            Additional STAC properties to filter by.
 274        max_items : int, optional
 275            Maximum number of items to return.
 276        exclude_geometry : bool, optional
 277            If True, exclude geometry field to reduce response size.
 278        search_kwargs : dict, optional
 279            Additional keyword arguments for STAC search.
 280
 281        Returns
 282        -------
 283        gpd.GeoDataFrame or None
 284            GeoDataFrame of matching STAC items with columns for collection,
 285            geometry, properties, and assets. Returns None if no matches found.
 286        """
 287
 288        search_params = {}
 289
 290        # Exclude geometry -- do not return the geometry field to reduce response size
 291        if exclude_geometry:
 292            search_params['exclude'] = ['geometry']
 293
 294        # Handle collections (seasons)
 295        if collections is not None:
 296            search_params['collections'] = [collections] if isinstance(collections, str) else collections
 297
 298        # Handle geometry filtering
 299        if geometry is not None:
 300            if hasattr(geometry, '__geo_interface__'):
 301                geometry = geometry.__geo_interface__
 302
 303            # Fix geometries that cross the antimeridian
 304            geometry = antimeridian.fix_geojson(geometry, reverse=True)
 305
 306            search_params['intersects'] = geometry
 307
 308        # Handle date range filtering
 309        if date_range is not None:
 310            search_params['datetime'] = date_range
 311
 312        # Handle max_items
 313        if max_items is not None:
 314            search_params['limit'] = max_items
 315
 316        # Handle segment_paths filtering using CQL2
 317        filter_conditions = []
 318
 319        if segment_paths is not None:
 320            segment_paths = [segment_paths] if isinstance(segment_paths, str) else segment_paths
 321
 322            # Create OR conditions for segment paths
 323            segment_conditions = []
 324            for segment_path in segment_paths:
 325                try:
 326                    date_str, segment_num_str = segment_path.split('_')
 327                    segment_num = int(segment_num_str)
 328
 329                    # Create AND condition for this specific segment
 330                    segment_condition = {
 331                        "op": "and",
 332                        "args": [
 333                            {
 334                                "op": "=",
 335                                "args": [{"property": "opr:date"}, date_str]
 336                            },
 337                            {
 338                                "op": "=",
 339                                "args": [{"property": "opr:segment"}, segment_num]
 340                            }
 341                        ]
 342                    }
 343                    segment_conditions.append(segment_condition)
 344                except ValueError:
 345                    print(f"Warning: Invalid segment_path format '{segment_path}'. Expected format: YYYYMMDD_NN")
 346                    continue
 347
 348            if segment_conditions:
 349                if len(segment_conditions) == 1:
 350                    filter_conditions.append(segment_conditions[0])
 351                else:
 352                    # Multiple segments - combine with OR
 353                    filter_conditions.append({
 354                        "op": "or",
 355                        "args": segment_conditions
 356                    })
 357
 358        # Add any additional property filters
 359        for key, value in properties.items():
 360            filter_conditions.append({
 361                "op": "=",
 362                "args": [{"property": key}, value]
 363            })
 364
 365        # Combine all filter conditions with AND
 366        if filter_conditions:
 367            if len(filter_conditions) == 1:
 368                filter_expr = filter_conditions[0]
 369            else:
 370                filter_expr = {
 371                    "op": "and",
 372                    "args": filter_conditions
 373                }
 374
 375            search_params['filter'] = filter_expr
 376
 377        # Add any extra kwargs to search
 378        search_params.update(search_kwargs)
 379
 380        #print(search_params) # TODO: Remove
 381
 382        # Perform the search
 383        # from rustac import DuckdbClient
 384        items = self.duckdb_client.search(self.stac_parquet_href, **search_params)
 385        if isinstance(items, dict):
 386            items = items['features']
 387
 388        if not items or len(items) == 0:
 389            warnings.warn("No items found matching the query criteria", UserWarning)
 390            return None
 391
 392        # Convert to GeoDataFrame
 393        items_df = gpd.GeoDataFrame(items)
 394        # Set index
 395        items_df = items_df.set_index(items_df['id'])
 396        items_df.index.name = 'stac_item_id'
 397        # Set the geometry column
 398        if 'geometry' in items_df.columns and not exclude_geometry:
 399            items_df = items_df.set_geometry(items_df['geometry'].apply(shapely.geometry.shape))
 400            items_df.crs = "EPSG:4326"
 401
 402        # Reorder the columns, leaving any extra columns at the end
 403        desired_order = ['collection', 'geometry', 'properties', 'assets']
 404        items_df = items_df[[col for col in desired_order if col in items_df.columns] + list(items_df.columns.difference(desired_order))]
 405
 406        return items_df
 407
 408    def load_frames(self, stac_items: gpd.GeoDataFrame,
 409                    data_product: str = "CSARP_standard",
 410                    image: Union[int, None] = None,
 411                    merge_flights: bool = False,
 412                    skip_errors: bool = False,
 413                    allow_unlisted_products: bool = False
 414                    ) -> Union[list[xr.Dataset], xr.Dataset]:
 415        """
 416        Load multiple radar frames from STAC items.
 417
 418        Parameters
 419        ----------
 420        stac_items : gpd.GeoDataFrame
 421            STAC items returned from query_frames.
 422        data_product : str, optional
 423            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
 424        image : int or None, optional
 425            The image number to load for each frame. If None (default), loads the
 426            combined image. If specified, `allow_unlisted_products` must be True.
 427        merge_flights : bool, optional
 428            If True, merge frames from the same segment into single Datasets.
 429        skip_errors : bool, optional
 430            If True, skip failed frames and continue loading others.
 431        allow_unlisted_products : bool, optional
 432            If True, attempt to load the specified data product even if it's not
 433            listed in the item's assets. See `load_frame` for details.
 434
 435        Returns
 436        -------
 437        list[xr.Dataset] or xr.Dataset
 438            List of radar frame Datasets, or list of merged Datasets if
 439            merge_flights=True.
 440        """
 441        frames = []
 442
 443        for idx, item in stac_items.iterrows():
 444            try:
 445                frame = self.load_frame(item, data_product, image=image, allow_unlisted_products=allow_unlisted_products)
 446                frames.append(frame)
 447            except Exception as e:
 448                print(f"Error loading frame for item {item.get('id', 'unknown')}: {e}")
 449                if skip_errors:
 450                    continue
 451                else:
 452                    raise e
 453
 454        if merge_flights:
 455            return opr_tools.merge_frames(frames)
 456        else:
 457            return frames
 458
 459    def load_frame(self, stac_item, data_product: str = "CSARP_standard",
 460                   image: Union[int, None] = None,
 461                   allow_unlisted_products: bool = False) -> xr.Dataset:
 462        """
 463        Load a single radar frame from a STAC item.
 464
 465        Parameters
 466        ----------
 467        stac_item : dict or pd.Series
 468            STAC item containing asset URLs.
 469        data_product : str, optional
 470            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
 471        image : int or None, optional
 472            The image number to load for this frame. If None (default), loads the
 473            combined image. If specified, `allow_unlisted_products` must be True.
 474        allow_unlisted_products : bool, optional
 475            If True, attempt to load the specified data product even if it's not
 476            listed in the item's assets.  This can be useful for loading non-standard
 477            products. If set to True and the data product is not found in the STAC
 478            item assets, the method will attempt to construct the URL based on any
 479            available CSARP_* asset. (If the frame is entirely unlisted, you can use
 480            `load_frame_url` instead.)
 481        Returns
 482        -------
 483        xr.Dataset
 484            Radar frame with coordinates slow_time and twtt, and data variables
 485            including Data, Latitude, Longitude, Elevation, Surface, etc.
 486        """
 487
 488        assets = stac_item['assets']
 489
 490        # Get the data asset
 491        data_asset = assets.get(data_product)
 492        if not data_asset:
 493            if not allow_unlisted_products:
 494                available_assets = list(assets.keys())
 495                raise ValueError(f"{data_product} asset not found in STAC item. Available assets: {available_assets}")
 496            else:
 497                # Find any available CSARP_* asset to use as a template for constructing the URL
 498                template_asset_name = None
 499                template_asset_url = None
 500                for asset_name, asset_info in assets.items():
 501                    if asset_name.startswith('CSARP_'):
 502                        template_asset_name = asset_name
 503                        template_asset_url = asset_info.get('href')
 504                        break
 505
 506                if not template_asset_url:
 507                    available_assets = list(assets.keys())
 508                    raise ValueError(f"No CSARP_* asset found in STAC item to use as a template for constructing URL for {data_product}. Available assets: {available_assets}")
 509
 510                url = template_asset_url.replace(template_asset_name, data_product)
 511        else:
 512            # The asset does exist in the STAC item, so just get the URL from the asset
 513            url = data_asset.get('href')
 514
 515            if not url:
 516                raise ValueError(f"No href found in {data_product} asset")
 517
 518        # If a specific image is requested, modify the URL to point to that image
 519        if image is not None:
 520            if not allow_unlisted_products:
 521                raise ValueError("Specifying an image number requires allow_unlisted_products=True to construct the URL")
 522            url = url.replace("Data_", f"Data_img_{image:02d}_")
 523
 524        # Load the frame using the existing method
 525        return self.load_frame_url(url)
 526
 527    def load_frame_url(self, url: str) -> xr.Dataset:
 528        """
 529        Load a radar frame directly from a URL.
 530
 531        Automatically detects and handles both HDF5 and legacy MATLAB formats.
 532
 533        Parameters
 534        ----------
 535        url : str
 536            URL to radar frame data file (.mat).
 537
 538        Returns
 539        -------
 540        xr.Dataset
 541            Radar frame with CF-compliant metadata and citation information.
 542        """
 543
 544        file = self._open_file(url)
 545
 546        filetype = None
 547        try:
 548            ds = self._load_frame_hdf5(file)
 549            filetype = 'hdf5'
 550        except OSError:
 551            ds = self._load_frame_matlab(file)
 552            filetype = 'matlab'
 553
 554        # Add the source URL as an attribute
 555        ds.attrs['source_url'] = url
 556
 557        # Apply CF-compliant attributes
 558        ds = apply_cf_compliant_attrs(ds)
 559
 560        # Get the season and segment from the URL
 561        match = re.search(r'(\d{4}_\w+_[A-Za-z0-9]+)\/([\w_]+)\/[\d_]+\/[\w]+(\d{8}_\d{2}_\d{3})', url)
 562        if match:
 563            collection, data_product, granule = match.groups()
 564            date, segment_id, frame_id = granule.split('_')
 565            ds.attrs['collection'] = collection
 566            ds.attrs['data_product'] = data_product
 567            ds.attrs['granule'] = granule
 568            ds.attrs['segment_path'] = f"{date}_{segment_id}"
 569            ds.attrs['date_str'] = date
 570            ds.attrs['segment'] = int(segment_id)
 571            ds.attrs['frame'] = int(frame_id)
 572
 573            # Load citation information
 574            result = ops_api.get_segment_metadata(segment_name=ds.attrs['segment_path'], season_name=collection)
 575            if result:
 576                if isinstance(result['data'], str):
 577                    warnings.warn(f"Warning: Unexpected result from ops_api: {result['data']}", UserWarning)
 578                else:
 579                    result_data = {}
 580                    for key, value in result['data'].items():
 581                        if len(value) == 1:
 582                            result_data[key] = value[0]
 583                        elif len(value) > 1:
 584                            result_data[key] = set(value)
 585
 586                    if 'dois' in result_data:
 587                        ds.attrs['doi'] = result_data['dois']
 588                    if 'rors' in result_data:
 589                        ds.attrs['ror'] = result_data['rors']
 590                    if 'funding_sources' in result_data:
 591                        ds.attrs['funder_text'] = result_data['funding_sources']
 592
 593        # Add the rest of the Matlab parameters
 594        if filetype == 'hdf5':
 595            ds.attrs['mimetype'] = 'application/x-hdf5'
 596            ds.attrs.update(decode_hdf5_matlab_variable(h5py.File(file, 'r'),
 597                                                        skip_variables=True,
 598                                                        skip_errors=True))
 599        elif filetype == 'matlab':
 600            ds.attrs['mimetype'] = 'application/x-matlab-data'
 601            ds.attrs.update(extract_legacy_mat_attributes(file,
 602                                                          skip_keys=ds.keys(),
 603                                                          skip_errors=True))
 604
 605        return ds
 606
 607    def _load_frame_hdf5(self, file) -> xr.Dataset:
 608        """
 609        Load a radar frame from an HDF5 file.
 610
 611        Parameters
 612        ----------
 613        file :
 614            The path to the HDF5 file containing radar frame data.
 615
 616        Returns
 617        -------
 618        xr.Dataset
 619            The loaded radar frame as an xarray Dataset.
 620        """
 621
 622        ds = xr.open_dataset(file, engine='h5netcdf', phony_dims='sort')
 623
 624        # Re-arrange variables to provide useful dimensions and coordinates
 625
 626        ds = ds.squeeze() # Drop the singleton dimensions matlab adds
 627
 628        ds = ds.rename({ # Label the dimensions with more useful names
 629            ds.Data.dims[0]: 'slow_time_idx',
 630            ds.Data.dims[1]: 'twtt_idx',
 631        })
 632
 633        # Make variables with no dimensions into scalar attributes
 634        for var in ds.data_vars:
 635            if ds[var].ndim == 0:
 636                ds.attrs[var] = ds[var].item()
 637                ds = ds.drop_vars(var)
 638
 639        # Make the file_type an attribute
 640        if 'file_type' in ds.data_vars:
 641            ds.attrs['file_type'] = ds['file_type'].to_numpy()
 642            ds = ds.drop_vars('file_type')
 643
 644        # Name the two time coordinates
 645        ds = ds.rename({'Time': 'twtt', 'GPS_time': 'slow_time'})
 646        ds = ds.set_coords(['slow_time', 'twtt'])
 647
 648        slow_time_1d = pd.to_datetime(ds['slow_time'].values, unit='s')
 649        ds = ds.assign_coords(slow_time=('slow_time_idx', slow_time_1d))
 650
 651        # Make twtt and slow_time the indexing coordinates
 652        ds = ds.swap_dims({'twtt_idx': 'twtt'})
 653        ds = ds.swap_dims({'slow_time_idx': 'slow_time'})
 654
 655        return ds
 656
 657    def _load_frame_matlab(self, file) -> xr.Dataset:
 658        """
 659        Load a radar frame from a MATLAB file.
 660
 661        Parameters
 662        ----------
 663        file :
 664            The path to the MATLAB file containing radar frame data.
 665
 666        Returns
 667        -------
 668        xr.Dataset
 669            The loaded radar frame as an xarray Dataset.
 670        """
 671
 672        m = scipy.io.loadmat(file, mat_dtype=False)
 673
 674        key_dims = {
 675            'Time': ('twtt',),
 676            'GPS_time': ('slow_time',),
 677            'Latitude': ('slow_time',),
 678            'Longitude': ('slow_time',),
 679            'Elevation': ('slow_time',),
 680            'Roll': ('slow_time',),
 681            'Pitch': ('slow_time',),
 682            'Heading': ('slow_time',),
 683            'Surface': ('slow_time',),
 684            'Data': ('twtt', 'slow_time')
 685        }
 686
 687        ds = xr.Dataset(
 688            {
 689                key: (dims, np.squeeze(m[key])) for key, dims in key_dims.items() if key in m
 690            },
 691            coords={
 692                'twtt': ('twtt', np.squeeze(m['Time'])),
 693                'slow_time': ('slow_time', pd.to_datetime(np.squeeze(m['GPS_time']), unit='s')),
 694            }
 695        )
 696
 697        return ds
 698
 699    def get_collections(self) -> list:
 700        """
 701        Get all available collections (seasons/campaigns) in STAC catalog.
 702
 703        Returns
 704        -------
 705        list[dict]
 706            List of collection dictionaries with id, description, and extent.
 707        """
 708
 709        return self.duckdb_client.get_collections(self.stac_parquet_href)
 710
 711    def get_segments(self, collection_id: str) -> list:
 712        """
 713        Get all segments (flights) within a collection.
 714
 715        Parameters
 716        ----------
 717        collection_id : str
 718            STAC collection ID (e.g., "2022_Antarctica_BaslerMKB").
 719
 720        Returns
 721        -------
 722        list[dict]
 723            List of segment dictionaries with segment_path, date, flight_number,
 724            and frame count.
 725        """
 726        # Query STAC API for all items in collection (exclude geometry for better performance)
 727        items = self.query_frames(collections=[collection_id], exclude_geometry=True)
 728
 729        if items is None or len(items) == 0:
 730            print(f"No items found in collection '{collection_id}'")
 731            return []
 732
 733        # Group items by segment (opr:date + opr:segment)
 734        segments = {}
 735        for idx, item in items.iterrows():
 736            properties = item['properties']
 737            date = properties['opr:date']
 738            flight_num = properties['opr:segment']
 739
 740            if date and flight_num is not None:
 741                segment_path = f"{date}_{flight_num:02d}"
 742
 743                if segment_path not in segments:
 744                    segments[segment_path] = {
 745                        'segment_path': segment_path,
 746                        'date': date,
 747                        'flight_number': flight_num,
 748                        'collection': collection_id,
 749                        'frames': [],
 750                        'item_count': 0
 751                    }
 752
 753                segments[segment_path]['frames'].append(properties.get('opr:frame'))
 754                segments[segment_path]['item_count'] += 1
 755
 756        # Sort segments by date and flight number
 757        segment_list = list(segments.values())
 758        segment_list.sort(key=lambda x: (x['date'], x['flight_number']))
 759
 760        return segment_list
 761
 762    def _get_layers_files(self, segment: Union[xr.Dataset, dict], raise_errors=True) -> dict:
 763        """
 764        Fetch layers from the CSARP_layers files
 765
 766        See https://gitlab.com/openpolarradar/opr/-/wikis/Layer-File-Guide for file formats
 767
 768        Parameters
 769        ----------
 770        segment : xr.Dataset or dict
 771            Radar frame Dataset or STAC item.
 772        raise_errors : bool, optional
 773            If True, raise errors when layers cannot be found.
 774
 775        Returns
 776        -------
 777        dict
 778            Dictionary mapping layer names (e.g., "standard:surface",
 779            "standard:bottom") to layer Datasets.
 780        """
 781        collection, segment_path, frame = self._extract_segment_info(segment)
 782
 783        # If we already have a STAC item, just use it. Otherwise, query to find the matching STAC items
 784        if isinstance(segment, xr.Dataset):
 785            properties = {}
 786            if frame:
 787                properties['opr:frame'] = frame
 788
 789            # Query STAC collection for CSARP_layer files matching this specific segment
 790
 791            # Get items from this specific segment
 792            stac_items = self.query_frames(collections=[collection], segment_paths=[segment_path], properties=properties)
 793
 794            # Filter for items that have CSARP_layer assets
 795            layer_items = []
 796            for idx, item in stac_items.iterrows():
 797                if 'CSARP_layer' in item['assets']:
 798                    layer_items.append(item)
 799        else:
 800            layer_items = [segment] if 'CSARP_layer' in segment.get('assets', {}) else []
 801
 802        if not layer_items:
 803            if raise_errors:
 804                raise ValueError(f"No CSARP_layer files found for segment path {segment_path} in collection {collection}")
 805            else:
 806                return {}
 807
 808        # Load each layer file and combine them
 809        layer_frames = []
 810        for item in layer_items:
 811            layer_asset = item['assets']['CSARP_layer']
 812            if layer_asset and 'href' in layer_asset:
 813                url = layer_asset['href']
 814                try:
 815                    layer_ds = self.load_layers_file(url)
 816                    layer_frames.append(layer_ds)
 817                except Exception as e:
 818                    raise e # TODO
 819                    print(f"Warning: Failed to load layer file {url}: {e}")
 820                    continue
 821
 822        if not layer_frames:
 823            if raise_errors:
 824                raise ValueError(f"No valid CSARP_layer files could be loaded for segment {segment_path} in collection {collection}")
 825            else:
 826                return {}
 827
 828        # Concatenate all layer frames along slow_time dimension
 829        layers_segment = xr.concat(layer_frames, dim='slow_time', combine_attrs='drop_conflicts', data_vars='minimal')
 830        layers_segment = layers_segment.sortby('slow_time')
 831
 832        # Trim to bounds of the original dataset
 833        layers_segment = self._trim_to_bounds(layers_segment, segment)
 834
 835        # Find the layer organization file to map layer IDs to names
 836        # Layer organization files are one per directory. For example, the layer file:
 837        # https://data.cresis.ku.edu/data/rds/2017_Antarctica_BaslerJKB/CSARP_layer/20180105_03/Data_20180105_03_003.mat
 838        # would have a layer organization file at:
 839        # https://data.cresis.ku.edu/data/rds/2017_Antarctica_BaslerJKB/CSARP_layer/20180105_03/layer_20180105_03.mat
 840
 841        layer_organization_file_url = re.sub(r'Data_(\d{8}_\d{2})_\d{3}.mat', r'layer_\1.mat', url)
 842        layer_organization_ds = self._load_layer_organization(self._open_file(layer_organization_file_url))
 843
 844        # Split into separate layers by ID
 845        layers = {}
 846
 847        layer_ids = np.unique(layers_segment['layer'])
 848
 849        for i, layer_id in enumerate(layer_ids):
 850            layer_id_int = int(layer_id)
 851            layer_name = str(layer_organization_ds['lyr_name'].sel(lyr_id=layer_id_int).values.item().squeeze())
 852            layer_group = str(layer_organization_ds['lyr_group_name'].sel(lyr_id=layer_id_int).values.item().squeeze())
 853            if layer_group == '[]':
 854                layer_group = ''
 855            layer_display_name = f"{layer_group}:{layer_name}"
 856
 857            layer_ds = layers_segment.sel(layer=layer_id).drop_vars('layer')
 858            # Only add non-empty layers with at least some non-NaN data
 859            if layer_ds.sizes.get('slow_time', 0) > 0:
 860                if not layer_ds.to_array().isnull().all():
 861                    layers[layer_display_name] = layer_ds
 862
 863        return layers
 864
 865    def _trim_to_bounds(self, ds: xr.Dataset, ref: Union[xr.Dataset, dict]) -> xr.Dataset:
 866        start_time, end_time = None, None
 867        if isinstance(ref, xr.Dataset) and 'slow_time' in ref.coords:
 868            start_time = ref['slow_time'].min()
 869            end_time = ref['slow_time'].max()
 870        else:
 871            properties = ref.get('properties', {})
 872            if 'start_datetime' in properties and 'end_datetime' in properties:
 873                start_time = pd.to_datetime(properties['start_datetime'])
 874                end_time = pd.to_datetime(properties['end_datetime'])
 875
 876        if start_time:
 877            return ds.sel(slow_time=slice(start_time, end_time))
 878        else:
 879            return ds
 880
 881    def load_layers_file(self, url: str) -> xr.Dataset:
 882        """
 883        Load layer data from CSARP_layer file.
 884
 885        Parameters
 886        ----------
 887        url : str
 888            URL or path to layer file.
 889
 890        Returns
 891        -------
 892        xr.Dataset
 893            Layer data with coordinates slow_time and layer, and data variables
 894            twtt, quality, type, lat, lon, and elev.
 895            Layer data in a standardized format with coordinates:
 896            - slow_time: GPS time converted to datetime
 897            And data variables:
 898            - twtt: Two-way travel time for each layer
 899            - quality: Quality values for each layer
 900            - type: Type values for each layer
 901            - lat, lon, elev: Geographic coordinates
 902            - id: Layer IDs
 903        """
 904
 905        file = self._open_file(url)
 906
 907        ds = self._load_layers(file)
 908
 909        # Add the source URL as an attribute
 910        ds.attrs['source_url'] = url
 911
 912        # Apply common manipulations to match the expected structure
 913        # Convert GPS time to datetime coordinate
 914        if 'gps_time' in ds.variables:
 915            slow_time_dt = pd.to_datetime(ds['gps_time'].values, unit='s')
 916            ds = ds.assign_coords(slow_time=('slow_time', slow_time_dt))
 917
 918            # Set slow_time as the main coordinate and remove gps_time from data_vars
 919            if 'slow_time' not in ds.dims:
 920                ds = ds.swap_dims({'gps_time': 'slow_time'})
 921
 922            # Remove gps_time from data_vars if it exists there to avoid conflicts
 923            if ('gps_time' in ds.data_vars) or ('gps_time' in ds.coords):
 924                ds = ds.drop_vars('gps_time')
 925
 926        # Sort by slow_time if it exists
 927        if 'slow_time' in ds.coords:
 928            ds = ds.sortby('slow_time')
 929
 930        return ds
 931
 932    def _load_layers(self, file) -> xr.Dataset:
 933        """
 934        Load layer data file using hdf5storage
 935
 936        Parameters:
 937        file : str
 938            Path to the layer file
 939        Returns: xr.Dataset
 940        """
 941
 942        d = hdf5storage.loadmat(file, appendmat=False)
 943
 944        # Ensure 'id' is at least 1D for the layer dimension
 945        id_data = np.atleast_1d(d['id'].squeeze())
 946
 947        # For 2D arrays with (layer, slow_time) dimensions, ensure they remain 2D
 948        # even when there's only one layer
 949        quality_data = np.atleast_2d(d['quality'].squeeze())
 950        if quality_data.shape[0] == 1 or quality_data.ndim == 1:
 951            quality_data = quality_data.reshape(len(id_data), -1)
 952
 953        twtt_data = np.atleast_2d(d['twtt'].squeeze())
 954        if twtt_data.shape[0] == 1 or twtt_data.ndim == 1:
 955            twtt_data = twtt_data.reshape(len(id_data), -1)
 956
 957        type_data = np.atleast_2d(d['type'].squeeze())
 958        if type_data.shape[0] == 1 or type_data.ndim == 1:
 959            type_data = type_data.reshape(len(id_data), -1)
 960
 961        ds = xr.Dataset({
 962            'file_type': ((), d['file_type'].squeeze()),
 963            'file_version': ((), d['file_version'].squeeze()),
 964            'elev': (('slow_time',), d['elev'].squeeze()),
 965            #'gps_source': ((), d['gps_source'].squeeze()),
 966            'gps_time': (('slow_time',), d['gps_time'].squeeze()),
 967            'id': (('layer',), id_data),
 968            'lat': (('slow_time',), d['lat'].squeeze()),
 969            'lon': (('slow_time',), d['lon'].squeeze()),
 970            'quality': (('layer', 'slow_time'), quality_data),
 971            'twtt': (('layer', 'slow_time'), twtt_data),
 972            'type': (('layer', 'slow_time'), type_data),
 973        })
 974
 975        ds = ds.assign_coords({'layer': ds['id'], 'slow_time': ds['gps_time']})
 976
 977        return ds
 978
 979    def _load_layer_organization(self, file) -> xr.Dataset:
 980        """
 981        Load a layer organization file
 982
 983        Parameters
 984        ----------
 985        file : str
 986            Path to the HDF5 layer organization file
 987
 988        Returns
 989        -------
 990        xr.Dataset
 991            Raw layer data from HDF5 file
 992        """
 993        d = hdf5storage.loadmat(file, appendmat=False)
 994        ds = xr.Dataset({
 995            'file_type': ((), d['file_type'].squeeze()),
 996            'file_version': ((), d['file_version'].squeeze()),
 997            'lyr_age': (('lyr_id',), np.atleast_1d(d['lyr_age'].squeeze())),
 998            'lyr_age_source': (('lyr_id',), np.atleast_1d(d['lyr_age_source'].squeeze())),
 999            'lyr_desc': (('lyr_id',), np.atleast_1d(d['lyr_desc'].squeeze())),
1000            'lyr_group_name': (('lyr_id',), np.atleast_1d(d['lyr_group_name'].squeeze())),
1001            'lyr_id': (('lyr_id',), np.atleast_1d(d['lyr_id'].squeeze())),
1002            'lyr_name': (('lyr_id',), np.atleast_1d(d['lyr_name'].squeeze())),
1003            'lyr_order': (('lyr_id',), np.atleast_1d(d['lyr_order'].squeeze())),
1004            }, attrs={'param': d['param']})
1005
1006        ds = ds.set_index(lyr_id='lyr_id')
1007
1008        return ds
1009
1010    def _get_layers_db(self, flight: Union[xr.Dataset, dict], include_geometry=True, raise_errors=True) -> dict:
1011        """
1012        Load layer picks from OPS database API.
1013
1014        Parameters
1015        ----------
1016        flight : xr.Dataset or dict
1017            Radar frame Dataset or STAC item.
1018        include_geometry : bool, optional
1019            If True, include geometry information in layers.
1020        raise_errors : bool, optional
1021            If True, raise errors when layers cannot be found.
1022
1023        Returns
1024        -------
1025        dict
1026            Dictionary mapping layer names to layer Datasets.
1027        """
1028
1029        collection, segment_path, _ = self._extract_segment_info(flight)
1030
1031        if 'Antarctica' in collection:
1032            location = 'antarctic'
1033        elif 'Greenland' in collection:
1034            location = 'arctic'
1035        else:
1036            raise ValueError("Dataset does not belong to a recognized location (Antarctica or Greenland).")
1037
1038        layer_points = ops_api.get_layer_points(
1039            segment_name=segment_path,
1040            season_name=collection,
1041            location=location,
1042            include_geometry=include_geometry
1043        )
1044
1045        if layer_points['status'] != 1:
1046            if raise_errors:
1047                raise ValueError(f"Failed to fetch layer points. Received response with status {layer_points['status']}.")
1048            else:
1049                return {}
1050
1051        layer_ds_raw = xr.Dataset(
1052            {k: (['gps_time'], v) for k, v in layer_points['data'].items() if k != 'gps_time'},
1053            coords={'gps_time': layer_points['data']['gps_time']}
1054        )
1055        # Split into a dictionary of layers based on lyr_id
1056        layer_ids = set(layer_ds_raw['lyr_id'].to_numpy())
1057        layer_ids = [int(layer_id) for layer_id in layer_ids if not np.isnan(layer_id)]
1058
1059        # Get the mapping of layer IDs to names
1060        if self.db_layers_metadata is None:
1061            layer_metadata = ops_api.get_layer_metadata()
1062            if layer_metadata['status'] == 1:
1063                df = pd.DataFrame(layer_metadata['data'])
1064                df['display_name'] = df['lyr_group_name'] + ":" + df['lyr_name']
1065                self.db_layers_metadata = df
1066            else:
1067                raise ValueError("Failed to fetch layer metadata from OPS API.")
1068
1069        layers = {}
1070        for layer_id in layer_ids:
1071            layer_name = self.db_layers_metadata.loc[self.db_layers_metadata['lyr_id'] == layer_id, 'display_name'].values[0]
1072
1073            layer_ds = layer_ds_raw.where(layer_ds_raw['lyr_id'] == layer_id, drop=True)
1074
1075            layer_ds = layer_ds.sortby('gps_time')
1076
1077            layer_ds = layer_ds.rename({'gps_time': 'slow_time'})
1078            layer_ds = layer_ds.set_coords(['slow_time'])
1079
1080            layer_ds['slow_time'] = pd.to_datetime(layer_ds['slow_time'].values, unit='s')
1081
1082            # Filter to the same time range as flight
1083            layer_ds = self._trim_to_bounds(layer_ds, flight)
1084
1085            # Only add non-empty layers with at least some non-NaN data
1086            if layer_ds.sizes.get('slow_time', 0) > 0:
1087                if not layer_ds.to_array().isnull().all():
1088                    layers[layer_name] = layer_ds
1089
1090        return layers
1091
1092    def get_layers(self, ds : Union[xr.Dataset, dict], source: str = 'auto', include_geometry=True, errors='warn') -> dict:
1093        """
1094        Load layer picks from files or database.
1095
1096        Tries files first, falls back to database if source='auto'.
1097
1098        Parameters
1099        ----------
1100        ds : Union[xr.Dataset, dict]
1101            Radar frame Dataset or STAC item.
1102        source : {'auto', 'files', 'db'}, optional
1103            Source for layers. 'auto' tries files then falls back to database.
1104        include_geometry : bool, optional
1105            If True, include geometry information when fetching from the API.
1106        errors : str, optional
1107            How to handle missing layer data: 'warn' (default) returns None with a warning,
1108            'error' raises an exception.
1109
1110        Returns
1111        -------
1112        dict or None
1113            A dictionary mapping layer IDs to their corresponding data, or None if no layers
1114            found and errors='warn'.
1115        """
1116        collection, segment_path, _ = self._extract_segment_info(ds)
1117
1118        if source == 'auto':
1119            # Try to get layers from files first
1120            try:
1121                layers = self._get_layers_files(ds, raise_errors=True)
1122                return layers
1123            except Exception:
1124                # Fallback to API if no layers found in files
1125                try:
1126                    return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1127                except Exception as e:
1128                    if errors == 'error':
1129                        raise
1130                    else:
1131                        warnings.warn(f"No layer data found for {collection}/{segment_path}: {e}")
1132                        return None
1133        elif source == 'files':
1134            try:
1135                return self._get_layers_files(ds, raise_errors=True)
1136            except Exception as e:
1137                if errors == 'error':
1138                    raise
1139                else:
1140                    warnings.warn(f"No layer files found for {collection}/{segment_path}: {e}")
1141                    return None
1142        elif source == 'db':
1143            try:
1144                return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1145            except Exception as e:
1146                if errors == 'error':
1147                    raise
1148                else:
1149                    warnings.warn(f"No layer data in DB for {collection}/{segment_path}: {e}")
1150                    return None
1151        else:
1152            raise ValueError("Invalid source specified. Must be one of: 'auto', 'files', 'db'.")
AUTH_STRATEGIES = ('environment', 'netrc', 'interactive')
class OPRConnection:
 150class OPRConnection:
 151    def __init__(self,
 152                 collection_url: str = "https://data.cresis.ku.edu/data/",
 153                 cache_dir: str = None,
 154                 stac_parquet_href: str = None,
 155                 sync_catalogs: bool = True,
 156                 auth: Union[str, tuple, None] = "all"):
 157        """
 158        Initialize connection to OPR data archive.
 159
 160        Parameters
 161        ----------
 162        collection_url : str, optional
 163            Base URL for OPR data collection.
 164        cache_dir : str, optional
 165            Directory to cache downloaded data for faster repeated access.
 166        stac_parquet_href : str, optional
 167            Path or URL pattern to STAC catalog parquet files.  When *None*
 168            (default), the local cache is used if available, falling back to
 169            the S3 catalog.
 170        sync_catalogs : bool, optional
 171            If True (default), sync OPR STAC catalogs to a local cache
 172            before resolving the catalog path.  Uses ETag-based change
 173            detection so repeated calls are cheap (single HTTP request).
 174        auth : str, tuple, or None, optional
 175            HTTP basic auth for the ``collection_url`` host. Either a
 176            ``(username, password)`` tuple, None to disable, or a strategy:
 177            ``"environment"`` (``OPR_USERNAME``/``OPR_PASSWORD`` env vars),
 178            ``"netrc"`` (``~/.netrc`` or ``$NETRC``), ``"interactive"``
 179            (prompt), or ``"all"`` (default; try each in that order, skipping
 180            the prompt in non-interactive sessions and warning if nothing is
 181            found). Credentials are only sent to the ``collection_url`` host.
 182        """
 183        self.collection_url = collection_url
 184        self.auth_host = urlparse(collection_url).hostname
 185        self._auth = _resolve_auth(auth, self.auth_host)
 186        self.cache_dir = cache_dir
 187        self._user_set_href = stac_parquet_href is not None
 188        if sync_catalogs and not self._user_set_href:
 189            sync_opr_catalogs()
 190        self.stac_parquet_href = stac_parquet_href or get_opr_catalog_path()
 191
 192        self.fsspec_cache_kwargs = {}
 193        self.fsspec_url_prefix = ''
 194        if cache_dir:
 195            self.fsspec_cache_kwargs['cache_storage'] = cache_dir
 196            self.fsspec_cache_kwargs['check_files'] = True
 197            self.fsspec_url_prefix = 'filecache::'
 198
 199        self.db_layers_metadata = None # Cache for OPS database layers metadata
 200
 201        # Lazy-initialized DuckDB client for STAC queries — reusing a single
 202        # session caches remote file metadata (parquet footers) across calls
 203        self._duckdb_client = None
 204
 205    @property
 206    def duckdb_client(self):
 207        """Lazy-initialized DuckDB client, recreated after pickling."""
 208        if self._duckdb_client is None:
 209            self._duckdb_client = DuckdbClient()
 210        return self._duckdb_client
 211
 212    def __getstate__(self):
 213        state = self.__dict__.copy()
 214        state['_duckdb_client'] = None  # DuckdbClient can't be pickled
 215        return state
 216
 217    def _open_file(self, url):
 218        """Helper method to open files with appropriate caching.
 219
 220        Local filesystem paths are returned as-is (no fsspec wrapping).
 221        Remote URLs (http, https, s3, gs) use filecache or simplecache.
 222        """
 223        if not url.startswith(('http://', 'https://', 's3://', 'gs://')):
 224            return url
 225        protocol = url.split('://')[0]
 226        cache = self.fsspec_url_prefix.rstrip(':') or 'simplecache'
 227        kwargs = {cache: self.fsspec_cache_kwargs}
 228        if self._auth and urlparse(url).hostname == self.auth_host:
 229            kwargs[protocol] = {'client_kwargs': {'auth': aiohttp.BasicAuth(*self._auth)}}
 230        try:
 231            return fsspec.open_local(f"{cache}::{url}", **kwargs)
 232        except aiohttp.ClientResponseError as e:
 233            if e.status not in (401, 403):
 234                raise
 235            reason = ("the provided credentials were rejected" if self._auth else
 236                      "no credentials were provided")
 237            raise PermissionError(
 238                f"HTTP {e.status} accessing {url}: {reason}. Set OPR_USERNAME/OPR_PASSWORD, "
 239                f"add a ~/.netrc entry for {urlparse(url).hostname}, or pass "
 240                f"OPRConnection(auth=(username, password)).") from e
 241
 242    def _extract_segment_info(self, segment):
 243        """Extract collection, segment_path, and frame from Dataset or dict."""
 244        if isinstance(segment, xr.Dataset):
 245            return (segment.attrs.get('collection'),
 246                    segment.attrs.get('segment_path'),
 247                    segment.attrs.get('frame'))
 248        else:
 249            return (segment['collection'],
 250                    f"{segment['properties'].get('opr:date')}_{segment['properties'].get('opr:segment'):02d}",
 251                    segment['properties'].get('opr:frame'))
 252
 253    def query_frames(self, collections: list[str] = None, segment_paths: list[str] = None,
 254                     geometry = None, date_range: tuple = None, properties: dict = {},
 255                     max_items: int = None, exclude_geometry: bool = False,
 256                     search_kwargs: dict = {}) -> gpd.GeoDataFrame:
 257        """
 258        Query STAC catalog for radar frames matching search criteria.
 259
 260        Multiple parameters are combined with AND logic. Lists of values passed to a
 261        single parameter are treated with OR logic (any value matches).
 262
 263        Parameters
 264        ----------
 265        collections : list[str] or str, optional
 266            Collection name(s) (e.g., "2022_Antarctica_BaslerMKB").
 267        segment_paths : list[str] or str, optional
 268            Segment path(s) in format "YYYYMMDD_NN" (e.g., "20230126_01").
 269        geometry : shapely geometry or dict, optional
 270            Geospatial geometry to filter by intersection.
 271        date_range : str, optional
 272            Date range in ISO format (e.g., "2021-01-01/2025-06-01").
 273        properties : dict, optional
 274            Additional STAC properties to filter by.
 275        max_items : int, optional
 276            Maximum number of items to return.
 277        exclude_geometry : bool, optional
 278            If True, exclude geometry field to reduce response size.
 279        search_kwargs : dict, optional
 280            Additional keyword arguments for STAC search.
 281
 282        Returns
 283        -------
 284        gpd.GeoDataFrame or None
 285            GeoDataFrame of matching STAC items with columns for collection,
 286            geometry, properties, and assets. Returns None if no matches found.
 287        """
 288
 289        search_params = {}
 290
 291        # Exclude geometry -- do not return the geometry field to reduce response size
 292        if exclude_geometry:
 293            search_params['exclude'] = ['geometry']
 294
 295        # Handle collections (seasons)
 296        if collections is not None:
 297            search_params['collections'] = [collections] if isinstance(collections, str) else collections
 298
 299        # Handle geometry filtering
 300        if geometry is not None:
 301            if hasattr(geometry, '__geo_interface__'):
 302                geometry = geometry.__geo_interface__
 303
 304            # Fix geometries that cross the antimeridian
 305            geometry = antimeridian.fix_geojson(geometry, reverse=True)
 306
 307            search_params['intersects'] = geometry
 308
 309        # Handle date range filtering
 310        if date_range is not None:
 311            search_params['datetime'] = date_range
 312
 313        # Handle max_items
 314        if max_items is not None:
 315            search_params['limit'] = max_items
 316
 317        # Handle segment_paths filtering using CQL2
 318        filter_conditions = []
 319
 320        if segment_paths is not None:
 321            segment_paths = [segment_paths] if isinstance(segment_paths, str) else segment_paths
 322
 323            # Create OR conditions for segment paths
 324            segment_conditions = []
 325            for segment_path in segment_paths:
 326                try:
 327                    date_str, segment_num_str = segment_path.split('_')
 328                    segment_num = int(segment_num_str)
 329
 330                    # Create AND condition for this specific segment
 331                    segment_condition = {
 332                        "op": "and",
 333                        "args": [
 334                            {
 335                                "op": "=",
 336                                "args": [{"property": "opr:date"}, date_str]
 337                            },
 338                            {
 339                                "op": "=",
 340                                "args": [{"property": "opr:segment"}, segment_num]
 341                            }
 342                        ]
 343                    }
 344                    segment_conditions.append(segment_condition)
 345                except ValueError:
 346                    print(f"Warning: Invalid segment_path format '{segment_path}'. Expected format: YYYYMMDD_NN")
 347                    continue
 348
 349            if segment_conditions:
 350                if len(segment_conditions) == 1:
 351                    filter_conditions.append(segment_conditions[0])
 352                else:
 353                    # Multiple segments - combine with OR
 354                    filter_conditions.append({
 355                        "op": "or",
 356                        "args": segment_conditions
 357                    })
 358
 359        # Add any additional property filters
 360        for key, value in properties.items():
 361            filter_conditions.append({
 362                "op": "=",
 363                "args": [{"property": key}, value]
 364            })
 365
 366        # Combine all filter conditions with AND
 367        if filter_conditions:
 368            if len(filter_conditions) == 1:
 369                filter_expr = filter_conditions[0]
 370            else:
 371                filter_expr = {
 372                    "op": "and",
 373                    "args": filter_conditions
 374                }
 375
 376            search_params['filter'] = filter_expr
 377
 378        # Add any extra kwargs to search
 379        search_params.update(search_kwargs)
 380
 381        #print(search_params) # TODO: Remove
 382
 383        # Perform the search
 384        # from rustac import DuckdbClient
 385        items = self.duckdb_client.search(self.stac_parquet_href, **search_params)
 386        if isinstance(items, dict):
 387            items = items['features']
 388
 389        if not items or len(items) == 0:
 390            warnings.warn("No items found matching the query criteria", UserWarning)
 391            return None
 392
 393        # Convert to GeoDataFrame
 394        items_df = gpd.GeoDataFrame(items)
 395        # Set index
 396        items_df = items_df.set_index(items_df['id'])
 397        items_df.index.name = 'stac_item_id'
 398        # Set the geometry column
 399        if 'geometry' in items_df.columns and not exclude_geometry:
 400            items_df = items_df.set_geometry(items_df['geometry'].apply(shapely.geometry.shape))
 401            items_df.crs = "EPSG:4326"
 402
 403        # Reorder the columns, leaving any extra columns at the end
 404        desired_order = ['collection', 'geometry', 'properties', 'assets']
 405        items_df = items_df[[col for col in desired_order if col in items_df.columns] + list(items_df.columns.difference(desired_order))]
 406
 407        return items_df
 408
 409    def load_frames(self, stac_items: gpd.GeoDataFrame,
 410                    data_product: str = "CSARP_standard",
 411                    image: Union[int, None] = None,
 412                    merge_flights: bool = False,
 413                    skip_errors: bool = False,
 414                    allow_unlisted_products: bool = False
 415                    ) -> Union[list[xr.Dataset], xr.Dataset]:
 416        """
 417        Load multiple radar frames from STAC items.
 418
 419        Parameters
 420        ----------
 421        stac_items : gpd.GeoDataFrame
 422            STAC items returned from query_frames.
 423        data_product : str, optional
 424            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
 425        image : int or None, optional
 426            The image number to load for each frame. If None (default), loads the
 427            combined image. If specified, `allow_unlisted_products` must be True.
 428        merge_flights : bool, optional
 429            If True, merge frames from the same segment into single Datasets.
 430        skip_errors : bool, optional
 431            If True, skip failed frames and continue loading others.
 432        allow_unlisted_products : bool, optional
 433            If True, attempt to load the specified data product even if it's not
 434            listed in the item's assets. See `load_frame` for details.
 435
 436        Returns
 437        -------
 438        list[xr.Dataset] or xr.Dataset
 439            List of radar frame Datasets, or list of merged Datasets if
 440            merge_flights=True.
 441        """
 442        frames = []
 443
 444        for idx, item in stac_items.iterrows():
 445            try:
 446                frame = self.load_frame(item, data_product, image=image, allow_unlisted_products=allow_unlisted_products)
 447                frames.append(frame)
 448            except Exception as e:
 449                print(f"Error loading frame for item {item.get('id', 'unknown')}: {e}")
 450                if skip_errors:
 451                    continue
 452                else:
 453                    raise e
 454
 455        if merge_flights:
 456            return opr_tools.merge_frames(frames)
 457        else:
 458            return frames
 459
 460    def load_frame(self, stac_item, data_product: str = "CSARP_standard",
 461                   image: Union[int, None] = None,
 462                   allow_unlisted_products: bool = False) -> xr.Dataset:
 463        """
 464        Load a single radar frame from a STAC item.
 465
 466        Parameters
 467        ----------
 468        stac_item : dict or pd.Series
 469            STAC item containing asset URLs.
 470        data_product : str, optional
 471            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
 472        image : int or None, optional
 473            The image number to load for this frame. If None (default), loads the
 474            combined image. If specified, `allow_unlisted_products` must be True.
 475        allow_unlisted_products : bool, optional
 476            If True, attempt to load the specified data product even if it's not
 477            listed in the item's assets.  This can be useful for loading non-standard
 478            products. If set to True and the data product is not found in the STAC
 479            item assets, the method will attempt to construct the URL based on any
 480            available CSARP_* asset. (If the frame is entirely unlisted, you can use
 481            `load_frame_url` instead.)
 482        Returns
 483        -------
 484        xr.Dataset
 485            Radar frame with coordinates slow_time and twtt, and data variables
 486            including Data, Latitude, Longitude, Elevation, Surface, etc.
 487        """
 488
 489        assets = stac_item['assets']
 490
 491        # Get the data asset
 492        data_asset = assets.get(data_product)
 493        if not data_asset:
 494            if not allow_unlisted_products:
 495                available_assets = list(assets.keys())
 496                raise ValueError(f"{data_product} asset not found in STAC item. Available assets: {available_assets}")
 497            else:
 498                # Find any available CSARP_* asset to use as a template for constructing the URL
 499                template_asset_name = None
 500                template_asset_url = None
 501                for asset_name, asset_info in assets.items():
 502                    if asset_name.startswith('CSARP_'):
 503                        template_asset_name = asset_name
 504                        template_asset_url = asset_info.get('href')
 505                        break
 506
 507                if not template_asset_url:
 508                    available_assets = list(assets.keys())
 509                    raise ValueError(f"No CSARP_* asset found in STAC item to use as a template for constructing URL for {data_product}. Available assets: {available_assets}")
 510
 511                url = template_asset_url.replace(template_asset_name, data_product)
 512        else:
 513            # The asset does exist in the STAC item, so just get the URL from the asset
 514            url = data_asset.get('href')
 515
 516            if not url:
 517                raise ValueError(f"No href found in {data_product} asset")
 518
 519        # If a specific image is requested, modify the URL to point to that image
 520        if image is not None:
 521            if not allow_unlisted_products:
 522                raise ValueError("Specifying an image number requires allow_unlisted_products=True to construct the URL")
 523            url = url.replace("Data_", f"Data_img_{image:02d}_")
 524
 525        # Load the frame using the existing method
 526        return self.load_frame_url(url)
 527
 528    def load_frame_url(self, url: str) -> xr.Dataset:
 529        """
 530        Load a radar frame directly from a URL.
 531
 532        Automatically detects and handles both HDF5 and legacy MATLAB formats.
 533
 534        Parameters
 535        ----------
 536        url : str
 537            URL to radar frame data file (.mat).
 538
 539        Returns
 540        -------
 541        xr.Dataset
 542            Radar frame with CF-compliant metadata and citation information.
 543        """
 544
 545        file = self._open_file(url)
 546
 547        filetype = None
 548        try:
 549            ds = self._load_frame_hdf5(file)
 550            filetype = 'hdf5'
 551        except OSError:
 552            ds = self._load_frame_matlab(file)
 553            filetype = 'matlab'
 554
 555        # Add the source URL as an attribute
 556        ds.attrs['source_url'] = url
 557
 558        # Apply CF-compliant attributes
 559        ds = apply_cf_compliant_attrs(ds)
 560
 561        # Get the season and segment from the URL
 562        match = re.search(r'(\d{4}_\w+_[A-Za-z0-9]+)\/([\w_]+)\/[\d_]+\/[\w]+(\d{8}_\d{2}_\d{3})', url)
 563        if match:
 564            collection, data_product, granule = match.groups()
 565            date, segment_id, frame_id = granule.split('_')
 566            ds.attrs['collection'] = collection
 567            ds.attrs['data_product'] = data_product
 568            ds.attrs['granule'] = granule
 569            ds.attrs['segment_path'] = f"{date}_{segment_id}"
 570            ds.attrs['date_str'] = date
 571            ds.attrs['segment'] = int(segment_id)
 572            ds.attrs['frame'] = int(frame_id)
 573
 574            # Load citation information
 575            result = ops_api.get_segment_metadata(segment_name=ds.attrs['segment_path'], season_name=collection)
 576            if result:
 577                if isinstance(result['data'], str):
 578                    warnings.warn(f"Warning: Unexpected result from ops_api: {result['data']}", UserWarning)
 579                else:
 580                    result_data = {}
 581                    for key, value in result['data'].items():
 582                        if len(value) == 1:
 583                            result_data[key] = value[0]
 584                        elif len(value) > 1:
 585                            result_data[key] = set(value)
 586
 587                    if 'dois' in result_data:
 588                        ds.attrs['doi'] = result_data['dois']
 589                    if 'rors' in result_data:
 590                        ds.attrs['ror'] = result_data['rors']
 591                    if 'funding_sources' in result_data:
 592                        ds.attrs['funder_text'] = result_data['funding_sources']
 593
 594        # Add the rest of the Matlab parameters
 595        if filetype == 'hdf5':
 596            ds.attrs['mimetype'] = 'application/x-hdf5'
 597            ds.attrs.update(decode_hdf5_matlab_variable(h5py.File(file, 'r'),
 598                                                        skip_variables=True,
 599                                                        skip_errors=True))
 600        elif filetype == 'matlab':
 601            ds.attrs['mimetype'] = 'application/x-matlab-data'
 602            ds.attrs.update(extract_legacy_mat_attributes(file,
 603                                                          skip_keys=ds.keys(),
 604                                                          skip_errors=True))
 605
 606        return ds
 607
 608    def _load_frame_hdf5(self, file) -> xr.Dataset:
 609        """
 610        Load a radar frame from an HDF5 file.
 611
 612        Parameters
 613        ----------
 614        file :
 615            The path to the HDF5 file containing radar frame data.
 616
 617        Returns
 618        -------
 619        xr.Dataset
 620            The loaded radar frame as an xarray Dataset.
 621        """
 622
 623        ds = xr.open_dataset(file, engine='h5netcdf', phony_dims='sort')
 624
 625        # Re-arrange variables to provide useful dimensions and coordinates
 626
 627        ds = ds.squeeze() # Drop the singleton dimensions matlab adds
 628
 629        ds = ds.rename({ # Label the dimensions with more useful names
 630            ds.Data.dims[0]: 'slow_time_idx',
 631            ds.Data.dims[1]: 'twtt_idx',
 632        })
 633
 634        # Make variables with no dimensions into scalar attributes
 635        for var in ds.data_vars:
 636            if ds[var].ndim == 0:
 637                ds.attrs[var] = ds[var].item()
 638                ds = ds.drop_vars(var)
 639
 640        # Make the file_type an attribute
 641        if 'file_type' in ds.data_vars:
 642            ds.attrs['file_type'] = ds['file_type'].to_numpy()
 643            ds = ds.drop_vars('file_type')
 644
 645        # Name the two time coordinates
 646        ds = ds.rename({'Time': 'twtt', 'GPS_time': 'slow_time'})
 647        ds = ds.set_coords(['slow_time', 'twtt'])
 648
 649        slow_time_1d = pd.to_datetime(ds['slow_time'].values, unit='s')
 650        ds = ds.assign_coords(slow_time=('slow_time_idx', slow_time_1d))
 651
 652        # Make twtt and slow_time the indexing coordinates
 653        ds = ds.swap_dims({'twtt_idx': 'twtt'})
 654        ds = ds.swap_dims({'slow_time_idx': 'slow_time'})
 655
 656        return ds
 657
 658    def _load_frame_matlab(self, file) -> xr.Dataset:
 659        """
 660        Load a radar frame from a MATLAB file.
 661
 662        Parameters
 663        ----------
 664        file :
 665            The path to the MATLAB file containing radar frame data.
 666
 667        Returns
 668        -------
 669        xr.Dataset
 670            The loaded radar frame as an xarray Dataset.
 671        """
 672
 673        m = scipy.io.loadmat(file, mat_dtype=False)
 674
 675        key_dims = {
 676            'Time': ('twtt',),
 677            'GPS_time': ('slow_time',),
 678            'Latitude': ('slow_time',),
 679            'Longitude': ('slow_time',),
 680            'Elevation': ('slow_time',),
 681            'Roll': ('slow_time',),
 682            'Pitch': ('slow_time',),
 683            'Heading': ('slow_time',),
 684            'Surface': ('slow_time',),
 685            'Data': ('twtt', 'slow_time')
 686        }
 687
 688        ds = xr.Dataset(
 689            {
 690                key: (dims, np.squeeze(m[key])) for key, dims in key_dims.items() if key in m
 691            },
 692            coords={
 693                'twtt': ('twtt', np.squeeze(m['Time'])),
 694                'slow_time': ('slow_time', pd.to_datetime(np.squeeze(m['GPS_time']), unit='s')),
 695            }
 696        )
 697
 698        return ds
 699
 700    def get_collections(self) -> list:
 701        """
 702        Get all available collections (seasons/campaigns) in STAC catalog.
 703
 704        Returns
 705        -------
 706        list[dict]
 707            List of collection dictionaries with id, description, and extent.
 708        """
 709
 710        return self.duckdb_client.get_collections(self.stac_parquet_href)
 711
 712    def get_segments(self, collection_id: str) -> list:
 713        """
 714        Get all segments (flights) within a collection.
 715
 716        Parameters
 717        ----------
 718        collection_id : str
 719            STAC collection ID (e.g., "2022_Antarctica_BaslerMKB").
 720
 721        Returns
 722        -------
 723        list[dict]
 724            List of segment dictionaries with segment_path, date, flight_number,
 725            and frame count.
 726        """
 727        # Query STAC API for all items in collection (exclude geometry for better performance)
 728        items = self.query_frames(collections=[collection_id], exclude_geometry=True)
 729
 730        if items is None or len(items) == 0:
 731            print(f"No items found in collection '{collection_id}'")
 732            return []
 733
 734        # Group items by segment (opr:date + opr:segment)
 735        segments = {}
 736        for idx, item in items.iterrows():
 737            properties = item['properties']
 738            date = properties['opr:date']
 739            flight_num = properties['opr:segment']
 740
 741            if date and flight_num is not None:
 742                segment_path = f"{date}_{flight_num:02d}"
 743
 744                if segment_path not in segments:
 745                    segments[segment_path] = {
 746                        'segment_path': segment_path,
 747                        'date': date,
 748                        'flight_number': flight_num,
 749                        'collection': collection_id,
 750                        'frames': [],
 751                        'item_count': 0
 752                    }
 753
 754                segments[segment_path]['frames'].append(properties.get('opr:frame'))
 755                segments[segment_path]['item_count'] += 1
 756
 757        # Sort segments by date and flight number
 758        segment_list = list(segments.values())
 759        segment_list.sort(key=lambda x: (x['date'], x['flight_number']))
 760
 761        return segment_list
 762
 763    def _get_layers_files(self, segment: Union[xr.Dataset, dict], raise_errors=True) -> dict:
 764        """
 765        Fetch layers from the CSARP_layers files
 766
 767        See https://gitlab.com/openpolarradar/opr/-/wikis/Layer-File-Guide for file formats
 768
 769        Parameters
 770        ----------
 771        segment : xr.Dataset or dict
 772            Radar frame Dataset or STAC item.
 773        raise_errors : bool, optional
 774            If True, raise errors when layers cannot be found.
 775
 776        Returns
 777        -------
 778        dict
 779            Dictionary mapping layer names (e.g., "standard:surface",
 780            "standard:bottom") to layer Datasets.
 781        """
 782        collection, segment_path, frame = self._extract_segment_info(segment)
 783
 784        # If we already have a STAC item, just use it. Otherwise, query to find the matching STAC items
 785        if isinstance(segment, xr.Dataset):
 786            properties = {}
 787            if frame:
 788                properties['opr:frame'] = frame
 789
 790            # Query STAC collection for CSARP_layer files matching this specific segment
 791
 792            # Get items from this specific segment
 793            stac_items = self.query_frames(collections=[collection], segment_paths=[segment_path], properties=properties)
 794
 795            # Filter for items that have CSARP_layer assets
 796            layer_items = []
 797            for idx, item in stac_items.iterrows():
 798                if 'CSARP_layer' in item['assets']:
 799                    layer_items.append(item)
 800        else:
 801            layer_items = [segment] if 'CSARP_layer' in segment.get('assets', {}) else []
 802
 803        if not layer_items:
 804            if raise_errors:
 805                raise ValueError(f"No CSARP_layer files found for segment path {segment_path} in collection {collection}")
 806            else:
 807                return {}
 808
 809        # Load each layer file and combine them
 810        layer_frames = []
 811        for item in layer_items:
 812            layer_asset = item['assets']['CSARP_layer']
 813            if layer_asset and 'href' in layer_asset:
 814                url = layer_asset['href']
 815                try:
 816                    layer_ds = self.load_layers_file(url)
 817                    layer_frames.append(layer_ds)
 818                except Exception as e:
 819                    raise e # TODO
 820                    print(f"Warning: Failed to load layer file {url}: {e}")
 821                    continue
 822
 823        if not layer_frames:
 824            if raise_errors:
 825                raise ValueError(f"No valid CSARP_layer files could be loaded for segment {segment_path} in collection {collection}")
 826            else:
 827                return {}
 828
 829        # Concatenate all layer frames along slow_time dimension
 830        layers_segment = xr.concat(layer_frames, dim='slow_time', combine_attrs='drop_conflicts', data_vars='minimal')
 831        layers_segment = layers_segment.sortby('slow_time')
 832
 833        # Trim to bounds of the original dataset
 834        layers_segment = self._trim_to_bounds(layers_segment, segment)
 835
 836        # Find the layer organization file to map layer IDs to names
 837        # Layer organization files are one per directory. For example, the layer file:
 838        # https://data.cresis.ku.edu/data/rds/2017_Antarctica_BaslerJKB/CSARP_layer/20180105_03/Data_20180105_03_003.mat
 839        # would have a layer organization file at:
 840        # https://data.cresis.ku.edu/data/rds/2017_Antarctica_BaslerJKB/CSARP_layer/20180105_03/layer_20180105_03.mat
 841
 842        layer_organization_file_url = re.sub(r'Data_(\d{8}_\d{2})_\d{3}.mat', r'layer_\1.mat', url)
 843        layer_organization_ds = self._load_layer_organization(self._open_file(layer_organization_file_url))
 844
 845        # Split into separate layers by ID
 846        layers = {}
 847
 848        layer_ids = np.unique(layers_segment['layer'])
 849
 850        for i, layer_id in enumerate(layer_ids):
 851            layer_id_int = int(layer_id)
 852            layer_name = str(layer_organization_ds['lyr_name'].sel(lyr_id=layer_id_int).values.item().squeeze())
 853            layer_group = str(layer_organization_ds['lyr_group_name'].sel(lyr_id=layer_id_int).values.item().squeeze())
 854            if layer_group == '[]':
 855                layer_group = ''
 856            layer_display_name = f"{layer_group}:{layer_name}"
 857
 858            layer_ds = layers_segment.sel(layer=layer_id).drop_vars('layer')
 859            # Only add non-empty layers with at least some non-NaN data
 860            if layer_ds.sizes.get('slow_time', 0) > 0:
 861                if not layer_ds.to_array().isnull().all():
 862                    layers[layer_display_name] = layer_ds
 863
 864        return layers
 865
 866    def _trim_to_bounds(self, ds: xr.Dataset, ref: Union[xr.Dataset, dict]) -> xr.Dataset:
 867        start_time, end_time = None, None
 868        if isinstance(ref, xr.Dataset) and 'slow_time' in ref.coords:
 869            start_time = ref['slow_time'].min()
 870            end_time = ref['slow_time'].max()
 871        else:
 872            properties = ref.get('properties', {})
 873            if 'start_datetime' in properties and 'end_datetime' in properties:
 874                start_time = pd.to_datetime(properties['start_datetime'])
 875                end_time = pd.to_datetime(properties['end_datetime'])
 876
 877        if start_time:
 878            return ds.sel(slow_time=slice(start_time, end_time))
 879        else:
 880            return ds
 881
 882    def load_layers_file(self, url: str) -> xr.Dataset:
 883        """
 884        Load layer data from CSARP_layer file.
 885
 886        Parameters
 887        ----------
 888        url : str
 889            URL or path to layer file.
 890
 891        Returns
 892        -------
 893        xr.Dataset
 894            Layer data with coordinates slow_time and layer, and data variables
 895            twtt, quality, type, lat, lon, and elev.
 896            Layer data in a standardized format with coordinates:
 897            - slow_time: GPS time converted to datetime
 898            And data variables:
 899            - twtt: Two-way travel time for each layer
 900            - quality: Quality values for each layer
 901            - type: Type values for each layer
 902            - lat, lon, elev: Geographic coordinates
 903            - id: Layer IDs
 904        """
 905
 906        file = self._open_file(url)
 907
 908        ds = self._load_layers(file)
 909
 910        # Add the source URL as an attribute
 911        ds.attrs['source_url'] = url
 912
 913        # Apply common manipulations to match the expected structure
 914        # Convert GPS time to datetime coordinate
 915        if 'gps_time' in ds.variables:
 916            slow_time_dt = pd.to_datetime(ds['gps_time'].values, unit='s')
 917            ds = ds.assign_coords(slow_time=('slow_time', slow_time_dt))
 918
 919            # Set slow_time as the main coordinate and remove gps_time from data_vars
 920            if 'slow_time' not in ds.dims:
 921                ds = ds.swap_dims({'gps_time': 'slow_time'})
 922
 923            # Remove gps_time from data_vars if it exists there to avoid conflicts
 924            if ('gps_time' in ds.data_vars) or ('gps_time' in ds.coords):
 925                ds = ds.drop_vars('gps_time')
 926
 927        # Sort by slow_time if it exists
 928        if 'slow_time' in ds.coords:
 929            ds = ds.sortby('slow_time')
 930
 931        return ds
 932
 933    def _load_layers(self, file) -> xr.Dataset:
 934        """
 935        Load layer data file using hdf5storage
 936
 937        Parameters:
 938        file : str
 939            Path to the layer file
 940        Returns: xr.Dataset
 941        """
 942
 943        d = hdf5storage.loadmat(file, appendmat=False)
 944
 945        # Ensure 'id' is at least 1D for the layer dimension
 946        id_data = np.atleast_1d(d['id'].squeeze())
 947
 948        # For 2D arrays with (layer, slow_time) dimensions, ensure they remain 2D
 949        # even when there's only one layer
 950        quality_data = np.atleast_2d(d['quality'].squeeze())
 951        if quality_data.shape[0] == 1 or quality_data.ndim == 1:
 952            quality_data = quality_data.reshape(len(id_data), -1)
 953
 954        twtt_data = np.atleast_2d(d['twtt'].squeeze())
 955        if twtt_data.shape[0] == 1 or twtt_data.ndim == 1:
 956            twtt_data = twtt_data.reshape(len(id_data), -1)
 957
 958        type_data = np.atleast_2d(d['type'].squeeze())
 959        if type_data.shape[0] == 1 or type_data.ndim == 1:
 960            type_data = type_data.reshape(len(id_data), -1)
 961
 962        ds = xr.Dataset({
 963            'file_type': ((), d['file_type'].squeeze()),
 964            'file_version': ((), d['file_version'].squeeze()),
 965            'elev': (('slow_time',), d['elev'].squeeze()),
 966            #'gps_source': ((), d['gps_source'].squeeze()),
 967            'gps_time': (('slow_time',), d['gps_time'].squeeze()),
 968            'id': (('layer',), id_data),
 969            'lat': (('slow_time',), d['lat'].squeeze()),
 970            'lon': (('slow_time',), d['lon'].squeeze()),
 971            'quality': (('layer', 'slow_time'), quality_data),
 972            'twtt': (('layer', 'slow_time'), twtt_data),
 973            'type': (('layer', 'slow_time'), type_data),
 974        })
 975
 976        ds = ds.assign_coords({'layer': ds['id'], 'slow_time': ds['gps_time']})
 977
 978        return ds
 979
 980    def _load_layer_organization(self, file) -> xr.Dataset:
 981        """
 982        Load a layer organization file
 983
 984        Parameters
 985        ----------
 986        file : str
 987            Path to the HDF5 layer organization file
 988
 989        Returns
 990        -------
 991        xr.Dataset
 992            Raw layer data from HDF5 file
 993        """
 994        d = hdf5storage.loadmat(file, appendmat=False)
 995        ds = xr.Dataset({
 996            'file_type': ((), d['file_type'].squeeze()),
 997            'file_version': ((), d['file_version'].squeeze()),
 998            'lyr_age': (('lyr_id',), np.atleast_1d(d['lyr_age'].squeeze())),
 999            'lyr_age_source': (('lyr_id',), np.atleast_1d(d['lyr_age_source'].squeeze())),
1000            'lyr_desc': (('lyr_id',), np.atleast_1d(d['lyr_desc'].squeeze())),
1001            'lyr_group_name': (('lyr_id',), np.atleast_1d(d['lyr_group_name'].squeeze())),
1002            'lyr_id': (('lyr_id',), np.atleast_1d(d['lyr_id'].squeeze())),
1003            'lyr_name': (('lyr_id',), np.atleast_1d(d['lyr_name'].squeeze())),
1004            'lyr_order': (('lyr_id',), np.atleast_1d(d['lyr_order'].squeeze())),
1005            }, attrs={'param': d['param']})
1006
1007        ds = ds.set_index(lyr_id='lyr_id')
1008
1009        return ds
1010
1011    def _get_layers_db(self, flight: Union[xr.Dataset, dict], include_geometry=True, raise_errors=True) -> dict:
1012        """
1013        Load layer picks from OPS database API.
1014
1015        Parameters
1016        ----------
1017        flight : xr.Dataset or dict
1018            Radar frame Dataset or STAC item.
1019        include_geometry : bool, optional
1020            If True, include geometry information in layers.
1021        raise_errors : bool, optional
1022            If True, raise errors when layers cannot be found.
1023
1024        Returns
1025        -------
1026        dict
1027            Dictionary mapping layer names to layer Datasets.
1028        """
1029
1030        collection, segment_path, _ = self._extract_segment_info(flight)
1031
1032        if 'Antarctica' in collection:
1033            location = 'antarctic'
1034        elif 'Greenland' in collection:
1035            location = 'arctic'
1036        else:
1037            raise ValueError("Dataset does not belong to a recognized location (Antarctica or Greenland).")
1038
1039        layer_points = ops_api.get_layer_points(
1040            segment_name=segment_path,
1041            season_name=collection,
1042            location=location,
1043            include_geometry=include_geometry
1044        )
1045
1046        if layer_points['status'] != 1:
1047            if raise_errors:
1048                raise ValueError(f"Failed to fetch layer points. Received response with status {layer_points['status']}.")
1049            else:
1050                return {}
1051
1052        layer_ds_raw = xr.Dataset(
1053            {k: (['gps_time'], v) for k, v in layer_points['data'].items() if k != 'gps_time'},
1054            coords={'gps_time': layer_points['data']['gps_time']}
1055        )
1056        # Split into a dictionary of layers based on lyr_id
1057        layer_ids = set(layer_ds_raw['lyr_id'].to_numpy())
1058        layer_ids = [int(layer_id) for layer_id in layer_ids if not np.isnan(layer_id)]
1059
1060        # Get the mapping of layer IDs to names
1061        if self.db_layers_metadata is None:
1062            layer_metadata = ops_api.get_layer_metadata()
1063            if layer_metadata['status'] == 1:
1064                df = pd.DataFrame(layer_metadata['data'])
1065                df['display_name'] = df['lyr_group_name'] + ":" + df['lyr_name']
1066                self.db_layers_metadata = df
1067            else:
1068                raise ValueError("Failed to fetch layer metadata from OPS API.")
1069
1070        layers = {}
1071        for layer_id in layer_ids:
1072            layer_name = self.db_layers_metadata.loc[self.db_layers_metadata['lyr_id'] == layer_id, 'display_name'].values[0]
1073
1074            layer_ds = layer_ds_raw.where(layer_ds_raw['lyr_id'] == layer_id, drop=True)
1075
1076            layer_ds = layer_ds.sortby('gps_time')
1077
1078            layer_ds = layer_ds.rename({'gps_time': 'slow_time'})
1079            layer_ds = layer_ds.set_coords(['slow_time'])
1080
1081            layer_ds['slow_time'] = pd.to_datetime(layer_ds['slow_time'].values, unit='s')
1082
1083            # Filter to the same time range as flight
1084            layer_ds = self._trim_to_bounds(layer_ds, flight)
1085
1086            # Only add non-empty layers with at least some non-NaN data
1087            if layer_ds.sizes.get('slow_time', 0) > 0:
1088                if not layer_ds.to_array().isnull().all():
1089                    layers[layer_name] = layer_ds
1090
1091        return layers
1092
1093    def get_layers(self, ds : Union[xr.Dataset, dict], source: str = 'auto', include_geometry=True, errors='warn') -> dict:
1094        """
1095        Load layer picks from files or database.
1096
1097        Tries files first, falls back to database if source='auto'.
1098
1099        Parameters
1100        ----------
1101        ds : Union[xr.Dataset, dict]
1102            Radar frame Dataset or STAC item.
1103        source : {'auto', 'files', 'db'}, optional
1104            Source for layers. 'auto' tries files then falls back to database.
1105        include_geometry : bool, optional
1106            If True, include geometry information when fetching from the API.
1107        errors : str, optional
1108            How to handle missing layer data: 'warn' (default) returns None with a warning,
1109            'error' raises an exception.
1110
1111        Returns
1112        -------
1113        dict or None
1114            A dictionary mapping layer IDs to their corresponding data, or None if no layers
1115            found and errors='warn'.
1116        """
1117        collection, segment_path, _ = self._extract_segment_info(ds)
1118
1119        if source == 'auto':
1120            # Try to get layers from files first
1121            try:
1122                layers = self._get_layers_files(ds, raise_errors=True)
1123                return layers
1124            except Exception:
1125                # Fallback to API if no layers found in files
1126                try:
1127                    return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1128                except Exception as e:
1129                    if errors == 'error':
1130                        raise
1131                    else:
1132                        warnings.warn(f"No layer data found for {collection}/{segment_path}: {e}")
1133                        return None
1134        elif source == 'files':
1135            try:
1136                return self._get_layers_files(ds, raise_errors=True)
1137            except Exception as e:
1138                if errors == 'error':
1139                    raise
1140                else:
1141                    warnings.warn(f"No layer files found for {collection}/{segment_path}: {e}")
1142                    return None
1143        elif source == 'db':
1144            try:
1145                return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1146            except Exception as e:
1147                if errors == 'error':
1148                    raise
1149                else:
1150                    warnings.warn(f"No layer data in DB for {collection}/{segment_path}: {e}")
1151                    return None
1152        else:
1153            raise ValueError("Invalid source specified. Must be one of: 'auto', 'files', 'db'.")
OPRConnection( collection_url: str = 'https://data.cresis.ku.edu/data/', cache_dir: str = None, stac_parquet_href: str = None, sync_catalogs: bool = True, auth: Union[str, tuple, NoneType] = 'all')
151    def __init__(self,
152                 collection_url: str = "https://data.cresis.ku.edu/data/",
153                 cache_dir: str = None,
154                 stac_parquet_href: str = None,
155                 sync_catalogs: bool = True,
156                 auth: Union[str, tuple, None] = "all"):
157        """
158        Initialize connection to OPR data archive.
159
160        Parameters
161        ----------
162        collection_url : str, optional
163            Base URL for OPR data collection.
164        cache_dir : str, optional
165            Directory to cache downloaded data for faster repeated access.
166        stac_parquet_href : str, optional
167            Path or URL pattern to STAC catalog parquet files.  When *None*
168            (default), the local cache is used if available, falling back to
169            the S3 catalog.
170        sync_catalogs : bool, optional
171            If True (default), sync OPR STAC catalogs to a local cache
172            before resolving the catalog path.  Uses ETag-based change
173            detection so repeated calls are cheap (single HTTP request).
174        auth : str, tuple, or None, optional
175            HTTP basic auth for the ``collection_url`` host. Either a
176            ``(username, password)`` tuple, None to disable, or a strategy:
177            ``"environment"`` (``OPR_USERNAME``/``OPR_PASSWORD`` env vars),
178            ``"netrc"`` (``~/.netrc`` or ``$NETRC``), ``"interactive"``
179            (prompt), or ``"all"`` (default; try each in that order, skipping
180            the prompt in non-interactive sessions and warning if nothing is
181            found). Credentials are only sent to the ``collection_url`` host.
182        """
183        self.collection_url = collection_url
184        self.auth_host = urlparse(collection_url).hostname
185        self._auth = _resolve_auth(auth, self.auth_host)
186        self.cache_dir = cache_dir
187        self._user_set_href = stac_parquet_href is not None
188        if sync_catalogs and not self._user_set_href:
189            sync_opr_catalogs()
190        self.stac_parquet_href = stac_parquet_href or get_opr_catalog_path()
191
192        self.fsspec_cache_kwargs = {}
193        self.fsspec_url_prefix = ''
194        if cache_dir:
195            self.fsspec_cache_kwargs['cache_storage'] = cache_dir
196            self.fsspec_cache_kwargs['check_files'] = True
197            self.fsspec_url_prefix = 'filecache::'
198
199        self.db_layers_metadata = None # Cache for OPS database layers metadata
200
201        # Lazy-initialized DuckDB client for STAC queries — reusing a single
202        # session caches remote file metadata (parquet footers) across calls
203        self._duckdb_client = None

Initialize connection to OPR data archive.

Parameters
  • collection_url (str, optional): Base URL for OPR data collection.
  • cache_dir (str, optional): Directory to cache downloaded data for faster repeated access.
  • stac_parquet_href (str, optional): Path or URL pattern to STAC catalog parquet files. When None (default), the local cache is used if available, falling back to the S3 catalog.
  • sync_catalogs (bool, optional): If True (default), sync OPR STAC catalogs to a local cache before resolving the catalog path. Uses ETag-based change detection so repeated calls are cheap (single HTTP request).
  • auth (str, tuple, or None, optional): HTTP basic auth for the collection_url host. Either a (username, password) tuple, None to disable, or a strategy: "environment" (OPR_USERNAME/OPR_PASSWORD env vars), "netrc" (~/.netrc or $NETRC), "interactive" (prompt), or "all" (default; try each in that order, skipping the prompt in non-interactive sessions and warning if nothing is found). Credentials are only sent to the collection_url host.
collection_url
auth_host
cache_dir
stac_parquet_href
fsspec_cache_kwargs
fsspec_url_prefix
db_layers_metadata
duckdb_client
205    @property
206    def duckdb_client(self):
207        """Lazy-initialized DuckDB client, recreated after pickling."""
208        if self._duckdb_client is None:
209            self._duckdb_client = DuckdbClient()
210        return self._duckdb_client

Lazy-initialized DuckDB client, recreated after pickling.

def query_frames( self, collections: list[str] = None, segment_paths: list[str] = None, geometry=None, date_range: tuple = None, properties: dict = {}, max_items: int = None, exclude_geometry: bool = False, search_kwargs: dict = {}) -> geopandas.geodataframe.GeoDataFrame:
253    def query_frames(self, collections: list[str] = None, segment_paths: list[str] = None,
254                     geometry = None, date_range: tuple = None, properties: dict = {},
255                     max_items: int = None, exclude_geometry: bool = False,
256                     search_kwargs: dict = {}) -> gpd.GeoDataFrame:
257        """
258        Query STAC catalog for radar frames matching search criteria.
259
260        Multiple parameters are combined with AND logic. Lists of values passed to a
261        single parameter are treated with OR logic (any value matches).
262
263        Parameters
264        ----------
265        collections : list[str] or str, optional
266            Collection name(s) (e.g., "2022_Antarctica_BaslerMKB").
267        segment_paths : list[str] or str, optional
268            Segment path(s) in format "YYYYMMDD_NN" (e.g., "20230126_01").
269        geometry : shapely geometry or dict, optional
270            Geospatial geometry to filter by intersection.
271        date_range : str, optional
272            Date range in ISO format (e.g., "2021-01-01/2025-06-01").
273        properties : dict, optional
274            Additional STAC properties to filter by.
275        max_items : int, optional
276            Maximum number of items to return.
277        exclude_geometry : bool, optional
278            If True, exclude geometry field to reduce response size.
279        search_kwargs : dict, optional
280            Additional keyword arguments for STAC search.
281
282        Returns
283        -------
284        gpd.GeoDataFrame or None
285            GeoDataFrame of matching STAC items with columns for collection,
286            geometry, properties, and assets. Returns None if no matches found.
287        """
288
289        search_params = {}
290
291        # Exclude geometry -- do not return the geometry field to reduce response size
292        if exclude_geometry:
293            search_params['exclude'] = ['geometry']
294
295        # Handle collections (seasons)
296        if collections is not None:
297            search_params['collections'] = [collections] if isinstance(collections, str) else collections
298
299        # Handle geometry filtering
300        if geometry is not None:
301            if hasattr(geometry, '__geo_interface__'):
302                geometry = geometry.__geo_interface__
303
304            # Fix geometries that cross the antimeridian
305            geometry = antimeridian.fix_geojson(geometry, reverse=True)
306
307            search_params['intersects'] = geometry
308
309        # Handle date range filtering
310        if date_range is not None:
311            search_params['datetime'] = date_range
312
313        # Handle max_items
314        if max_items is not None:
315            search_params['limit'] = max_items
316
317        # Handle segment_paths filtering using CQL2
318        filter_conditions = []
319
320        if segment_paths is not None:
321            segment_paths = [segment_paths] if isinstance(segment_paths, str) else segment_paths
322
323            # Create OR conditions for segment paths
324            segment_conditions = []
325            for segment_path in segment_paths:
326                try:
327                    date_str, segment_num_str = segment_path.split('_')
328                    segment_num = int(segment_num_str)
329
330                    # Create AND condition for this specific segment
331                    segment_condition = {
332                        "op": "and",
333                        "args": [
334                            {
335                                "op": "=",
336                                "args": [{"property": "opr:date"}, date_str]
337                            },
338                            {
339                                "op": "=",
340                                "args": [{"property": "opr:segment"}, segment_num]
341                            }
342                        ]
343                    }
344                    segment_conditions.append(segment_condition)
345                except ValueError:
346                    print(f"Warning: Invalid segment_path format '{segment_path}'. Expected format: YYYYMMDD_NN")
347                    continue
348
349            if segment_conditions:
350                if len(segment_conditions) == 1:
351                    filter_conditions.append(segment_conditions[0])
352                else:
353                    # Multiple segments - combine with OR
354                    filter_conditions.append({
355                        "op": "or",
356                        "args": segment_conditions
357                    })
358
359        # Add any additional property filters
360        for key, value in properties.items():
361            filter_conditions.append({
362                "op": "=",
363                "args": [{"property": key}, value]
364            })
365
366        # Combine all filter conditions with AND
367        if filter_conditions:
368            if len(filter_conditions) == 1:
369                filter_expr = filter_conditions[0]
370            else:
371                filter_expr = {
372                    "op": "and",
373                    "args": filter_conditions
374                }
375
376            search_params['filter'] = filter_expr
377
378        # Add any extra kwargs to search
379        search_params.update(search_kwargs)
380
381        #print(search_params) # TODO: Remove
382
383        # Perform the search
384        # from rustac import DuckdbClient
385        items = self.duckdb_client.search(self.stac_parquet_href, **search_params)
386        if isinstance(items, dict):
387            items = items['features']
388
389        if not items or len(items) == 0:
390            warnings.warn("No items found matching the query criteria", UserWarning)
391            return None
392
393        # Convert to GeoDataFrame
394        items_df = gpd.GeoDataFrame(items)
395        # Set index
396        items_df = items_df.set_index(items_df['id'])
397        items_df.index.name = 'stac_item_id'
398        # Set the geometry column
399        if 'geometry' in items_df.columns and not exclude_geometry:
400            items_df = items_df.set_geometry(items_df['geometry'].apply(shapely.geometry.shape))
401            items_df.crs = "EPSG:4326"
402
403        # Reorder the columns, leaving any extra columns at the end
404        desired_order = ['collection', 'geometry', 'properties', 'assets']
405        items_df = items_df[[col for col in desired_order if col in items_df.columns] + list(items_df.columns.difference(desired_order))]
406
407        return items_df

Query STAC catalog for radar frames matching search criteria.

Multiple parameters are combined with AND logic. Lists of values passed to a single parameter are treated with OR logic (any value matches).

Parameters
  • collections (list[str] or str, optional): Collection name(s) (e.g., "2022_Antarctica_BaslerMKB").
  • segment_paths (list[str] or str, optional): Segment path(s) in format "YYYYMMDD_NN" (e.g., "20230126_01").
  • geometry (shapely geometry or dict, optional): Geospatial geometry to filter by intersection.
  • date_range (str, optional): Date range in ISO format (e.g., "2021-01-01/2025-06-01").
  • properties (dict, optional): Additional STAC properties to filter by.
  • max_items (int, optional): Maximum number of items to return.
  • exclude_geometry (bool, optional): If True, exclude geometry field to reduce response size.
  • search_kwargs (dict, optional): Additional keyword arguments for STAC search.
Returns
  • gpd.GeoDataFrame or None: GeoDataFrame of matching STAC items with columns for collection, geometry, properties, and assets. Returns None if no matches found.
def load_frames( self, stac_items: geopandas.geodataframe.GeoDataFrame, data_product: str = 'CSARP_standard', image: Optional[int] = None, merge_flights: bool = False, skip_errors: bool = False, allow_unlisted_products: bool = False) -> Union[list[xarray.core.dataset.Dataset], xarray.core.dataset.Dataset]:
409    def load_frames(self, stac_items: gpd.GeoDataFrame,
410                    data_product: str = "CSARP_standard",
411                    image: Union[int, None] = None,
412                    merge_flights: bool = False,
413                    skip_errors: bool = False,
414                    allow_unlisted_products: bool = False
415                    ) -> Union[list[xr.Dataset], xr.Dataset]:
416        """
417        Load multiple radar frames from STAC items.
418
419        Parameters
420        ----------
421        stac_items : gpd.GeoDataFrame
422            STAC items returned from query_frames.
423        data_product : str, optional
424            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
425        image : int or None, optional
426            The image number to load for each frame. If None (default), loads the
427            combined image. If specified, `allow_unlisted_products` must be True.
428        merge_flights : bool, optional
429            If True, merge frames from the same segment into single Datasets.
430        skip_errors : bool, optional
431            If True, skip failed frames and continue loading others.
432        allow_unlisted_products : bool, optional
433            If True, attempt to load the specified data product even if it's not
434            listed in the item's assets. See `load_frame` for details.
435
436        Returns
437        -------
438        list[xr.Dataset] or xr.Dataset
439            List of radar frame Datasets, or list of merged Datasets if
440            merge_flights=True.
441        """
442        frames = []
443
444        for idx, item in stac_items.iterrows():
445            try:
446                frame = self.load_frame(item, data_product, image=image, allow_unlisted_products=allow_unlisted_products)
447                frames.append(frame)
448            except Exception as e:
449                print(f"Error loading frame for item {item.get('id', 'unknown')}: {e}")
450                if skip_errors:
451                    continue
452                else:
453                    raise e
454
455        if merge_flights:
456            return opr_tools.merge_frames(frames)
457        else:
458            return frames

Load multiple radar frames from STAC items.

Parameters
  • stac_items (gpd.GeoDataFrame): STAC items returned from query_frames.
  • data_product (str, optional): Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
  • image (int or None, optional): The image number to load for each frame. If None (default), loads the combined image. If specified, allow_unlisted_products must be True.
  • merge_flights (bool, optional): If True, merge frames from the same segment into single Datasets.
  • skip_errors (bool, optional): If True, skip failed frames and continue loading others.
  • allow_unlisted_products (bool, optional): If True, attempt to load the specified data product even if it's not listed in the item's assets. See load_frame for details.
Returns
  • list[xr.Dataset] or xr.Dataset: List of radar frame Datasets, or list of merged Datasets if merge_flights=True.
def load_frame( self, stac_item, data_product: str = 'CSARP_standard', image: Optional[int] = None, allow_unlisted_products: bool = False) -> xarray.core.dataset.Dataset:
460    def load_frame(self, stac_item, data_product: str = "CSARP_standard",
461                   image: Union[int, None] = None,
462                   allow_unlisted_products: bool = False) -> xr.Dataset:
463        """
464        Load a single radar frame from a STAC item.
465
466        Parameters
467        ----------
468        stac_item : dict or pd.Series
469            STAC item containing asset URLs.
470        data_product : str, optional
471            Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
472        image : int or None, optional
473            The image number to load for this frame. If None (default), loads the
474            combined image. If specified, `allow_unlisted_products` must be True.
475        allow_unlisted_products : bool, optional
476            If True, attempt to load the specified data product even if it's not
477            listed in the item's assets.  This can be useful for loading non-standard
478            products. If set to True and the data product is not found in the STAC
479            item assets, the method will attempt to construct the URL based on any
480            available CSARP_* asset. (If the frame is entirely unlisted, you can use
481            `load_frame_url` instead.)
482        Returns
483        -------
484        xr.Dataset
485            Radar frame with coordinates slow_time and twtt, and data variables
486            including Data, Latitude, Longitude, Elevation, Surface, etc.
487        """
488
489        assets = stac_item['assets']
490
491        # Get the data asset
492        data_asset = assets.get(data_product)
493        if not data_asset:
494            if not allow_unlisted_products:
495                available_assets = list(assets.keys())
496                raise ValueError(f"{data_product} asset not found in STAC item. Available assets: {available_assets}")
497            else:
498                # Find any available CSARP_* asset to use as a template for constructing the URL
499                template_asset_name = None
500                template_asset_url = None
501                for asset_name, asset_info in assets.items():
502                    if asset_name.startswith('CSARP_'):
503                        template_asset_name = asset_name
504                        template_asset_url = asset_info.get('href')
505                        break
506
507                if not template_asset_url:
508                    available_assets = list(assets.keys())
509                    raise ValueError(f"No CSARP_* asset found in STAC item to use as a template for constructing URL for {data_product}. Available assets: {available_assets}")
510
511                url = template_asset_url.replace(template_asset_name, data_product)
512        else:
513            # The asset does exist in the STAC item, so just get the URL from the asset
514            url = data_asset.get('href')
515
516            if not url:
517                raise ValueError(f"No href found in {data_product} asset")
518
519        # If a specific image is requested, modify the URL to point to that image
520        if image is not None:
521            if not allow_unlisted_products:
522                raise ValueError("Specifying an image number requires allow_unlisted_products=True to construct the URL")
523            url = url.replace("Data_", f"Data_img_{image:02d}_")
524
525        # Load the frame using the existing method
526        return self.load_frame_url(url)

Load a single radar frame from a STAC item.

Parameters
  • stac_item (dict or pd.Series): STAC item containing asset URLs.
  • data_product (str, optional): Data product to load (e.g., "CSARP_standard", "CSARP_qlook").
  • image (int or None, optional): The image number to load for this frame. If None (default), loads the combined image. If specified, allow_unlisted_products must be True.
  • allow_unlisted_products (bool, optional): If True, attempt to load the specified data product even if it's not listed in the item's assets. This can be useful for loading non-standard products. If set to True and the data product is not found in the STAC item assets, the method will attempt to construct the URL based on any available CSARP_* asset. (If the frame is entirely unlisted, you can use load_frame_url instead.)
Returns
  • xr.Dataset: Radar frame with coordinates slow_time and twtt, and data variables including Data, Latitude, Longitude, Elevation, Surface, etc.
def load_frame_url(self, url: str) -> xarray.core.dataset.Dataset:
528    def load_frame_url(self, url: str) -> xr.Dataset:
529        """
530        Load a radar frame directly from a URL.
531
532        Automatically detects and handles both HDF5 and legacy MATLAB formats.
533
534        Parameters
535        ----------
536        url : str
537            URL to radar frame data file (.mat).
538
539        Returns
540        -------
541        xr.Dataset
542            Radar frame with CF-compliant metadata and citation information.
543        """
544
545        file = self._open_file(url)
546
547        filetype = None
548        try:
549            ds = self._load_frame_hdf5(file)
550            filetype = 'hdf5'
551        except OSError:
552            ds = self._load_frame_matlab(file)
553            filetype = 'matlab'
554
555        # Add the source URL as an attribute
556        ds.attrs['source_url'] = url
557
558        # Apply CF-compliant attributes
559        ds = apply_cf_compliant_attrs(ds)
560
561        # Get the season and segment from the URL
562        match = re.search(r'(\d{4}_\w+_[A-Za-z0-9]+)\/([\w_]+)\/[\d_]+\/[\w]+(\d{8}_\d{2}_\d{3})', url)
563        if match:
564            collection, data_product, granule = match.groups()
565            date, segment_id, frame_id = granule.split('_')
566            ds.attrs['collection'] = collection
567            ds.attrs['data_product'] = data_product
568            ds.attrs['granule'] = granule
569            ds.attrs['segment_path'] = f"{date}_{segment_id}"
570            ds.attrs['date_str'] = date
571            ds.attrs['segment'] = int(segment_id)
572            ds.attrs['frame'] = int(frame_id)
573
574            # Load citation information
575            result = ops_api.get_segment_metadata(segment_name=ds.attrs['segment_path'], season_name=collection)
576            if result:
577                if isinstance(result['data'], str):
578                    warnings.warn(f"Warning: Unexpected result from ops_api: {result['data']}", UserWarning)
579                else:
580                    result_data = {}
581                    for key, value in result['data'].items():
582                        if len(value) == 1:
583                            result_data[key] = value[0]
584                        elif len(value) > 1:
585                            result_data[key] = set(value)
586
587                    if 'dois' in result_data:
588                        ds.attrs['doi'] = result_data['dois']
589                    if 'rors' in result_data:
590                        ds.attrs['ror'] = result_data['rors']
591                    if 'funding_sources' in result_data:
592                        ds.attrs['funder_text'] = result_data['funding_sources']
593
594        # Add the rest of the Matlab parameters
595        if filetype == 'hdf5':
596            ds.attrs['mimetype'] = 'application/x-hdf5'
597            ds.attrs.update(decode_hdf5_matlab_variable(h5py.File(file, 'r'),
598                                                        skip_variables=True,
599                                                        skip_errors=True))
600        elif filetype == 'matlab':
601            ds.attrs['mimetype'] = 'application/x-matlab-data'
602            ds.attrs.update(extract_legacy_mat_attributes(file,
603                                                          skip_keys=ds.keys(),
604                                                          skip_errors=True))
605
606        return ds

Load a radar frame directly from a URL.

Automatically detects and handles both HDF5 and legacy MATLAB formats.

Parameters
  • url (str): URL to radar frame data file (.mat).
Returns
  • xr.Dataset: Radar frame with CF-compliant metadata and citation information.
def get_collections(self) -> list:
700    def get_collections(self) -> list:
701        """
702        Get all available collections (seasons/campaigns) in STAC catalog.
703
704        Returns
705        -------
706        list[dict]
707            List of collection dictionaries with id, description, and extent.
708        """
709
710        return self.duckdb_client.get_collections(self.stac_parquet_href)

Get all available collections (seasons/campaigns) in STAC catalog.

Returns
  • list[dict]: List of collection dictionaries with id, description, and extent.
def get_segments(self, collection_id: str) -> list:
712    def get_segments(self, collection_id: str) -> list:
713        """
714        Get all segments (flights) within a collection.
715
716        Parameters
717        ----------
718        collection_id : str
719            STAC collection ID (e.g., "2022_Antarctica_BaslerMKB").
720
721        Returns
722        -------
723        list[dict]
724            List of segment dictionaries with segment_path, date, flight_number,
725            and frame count.
726        """
727        # Query STAC API for all items in collection (exclude geometry for better performance)
728        items = self.query_frames(collections=[collection_id], exclude_geometry=True)
729
730        if items is None or len(items) == 0:
731            print(f"No items found in collection '{collection_id}'")
732            return []
733
734        # Group items by segment (opr:date + opr:segment)
735        segments = {}
736        for idx, item in items.iterrows():
737            properties = item['properties']
738            date = properties['opr:date']
739            flight_num = properties['opr:segment']
740
741            if date and flight_num is not None:
742                segment_path = f"{date}_{flight_num:02d}"
743
744                if segment_path not in segments:
745                    segments[segment_path] = {
746                        'segment_path': segment_path,
747                        'date': date,
748                        'flight_number': flight_num,
749                        'collection': collection_id,
750                        'frames': [],
751                        'item_count': 0
752                    }
753
754                segments[segment_path]['frames'].append(properties.get('opr:frame'))
755                segments[segment_path]['item_count'] += 1
756
757        # Sort segments by date and flight number
758        segment_list = list(segments.values())
759        segment_list.sort(key=lambda x: (x['date'], x['flight_number']))
760
761        return segment_list

Get all segments (flights) within a collection.

Parameters
  • collection_id (str): STAC collection ID (e.g., "2022_Antarctica_BaslerMKB").
Returns
  • list[dict]: List of segment dictionaries with segment_path, date, flight_number, and frame count.
def load_layers_file(self, url: str) -> xarray.core.dataset.Dataset:
882    def load_layers_file(self, url: str) -> xr.Dataset:
883        """
884        Load layer data from CSARP_layer file.
885
886        Parameters
887        ----------
888        url : str
889            URL or path to layer file.
890
891        Returns
892        -------
893        xr.Dataset
894            Layer data with coordinates slow_time and layer, and data variables
895            twtt, quality, type, lat, lon, and elev.
896            Layer data in a standardized format with coordinates:
897            - slow_time: GPS time converted to datetime
898            And data variables:
899            - twtt: Two-way travel time for each layer
900            - quality: Quality values for each layer
901            - type: Type values for each layer
902            - lat, lon, elev: Geographic coordinates
903            - id: Layer IDs
904        """
905
906        file = self._open_file(url)
907
908        ds = self._load_layers(file)
909
910        # Add the source URL as an attribute
911        ds.attrs['source_url'] = url
912
913        # Apply common manipulations to match the expected structure
914        # Convert GPS time to datetime coordinate
915        if 'gps_time' in ds.variables:
916            slow_time_dt = pd.to_datetime(ds['gps_time'].values, unit='s')
917            ds = ds.assign_coords(slow_time=('slow_time', slow_time_dt))
918
919            # Set slow_time as the main coordinate and remove gps_time from data_vars
920            if 'slow_time' not in ds.dims:
921                ds = ds.swap_dims({'gps_time': 'slow_time'})
922
923            # Remove gps_time from data_vars if it exists there to avoid conflicts
924            if ('gps_time' in ds.data_vars) or ('gps_time' in ds.coords):
925                ds = ds.drop_vars('gps_time')
926
927        # Sort by slow_time if it exists
928        if 'slow_time' in ds.coords:
929            ds = ds.sortby('slow_time')
930
931        return ds

Load layer data from CSARP_layer file.

Parameters
  • url (str): URL or path to layer file.
Returns
  • xr.Dataset: Layer data with coordinates slow_time and layer, and data variables twtt, quality, type, lat, lon, and elev. Layer data in a standardized format with coordinates:
    • slow_time: GPS time converted to datetime And data variables:
    • twtt: Two-way travel time for each layer
    • quality: Quality values for each layer
    • type: Type values for each layer
    • lat, lon, elev: Geographic coordinates
    • id: Layer IDs
def get_layers( self, ds: Union[xarray.core.dataset.Dataset, dict], source: str = 'auto', include_geometry=True, errors='warn') -> dict:
1093    def get_layers(self, ds : Union[xr.Dataset, dict], source: str = 'auto', include_geometry=True, errors='warn') -> dict:
1094        """
1095        Load layer picks from files or database.
1096
1097        Tries files first, falls back to database if source='auto'.
1098
1099        Parameters
1100        ----------
1101        ds : Union[xr.Dataset, dict]
1102            Radar frame Dataset or STAC item.
1103        source : {'auto', 'files', 'db'}, optional
1104            Source for layers. 'auto' tries files then falls back to database.
1105        include_geometry : bool, optional
1106            If True, include geometry information when fetching from the API.
1107        errors : str, optional
1108            How to handle missing layer data: 'warn' (default) returns None with a warning,
1109            'error' raises an exception.
1110
1111        Returns
1112        -------
1113        dict or None
1114            A dictionary mapping layer IDs to their corresponding data, or None if no layers
1115            found and errors='warn'.
1116        """
1117        collection, segment_path, _ = self._extract_segment_info(ds)
1118
1119        if source == 'auto':
1120            # Try to get layers from files first
1121            try:
1122                layers = self._get_layers_files(ds, raise_errors=True)
1123                return layers
1124            except Exception:
1125                # Fallback to API if no layers found in files
1126                try:
1127                    return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1128                except Exception as e:
1129                    if errors == 'error':
1130                        raise
1131                    else:
1132                        warnings.warn(f"No layer data found for {collection}/{segment_path}: {e}")
1133                        return None
1134        elif source == 'files':
1135            try:
1136                return self._get_layers_files(ds, raise_errors=True)
1137            except Exception as e:
1138                if errors == 'error':
1139                    raise
1140                else:
1141                    warnings.warn(f"No layer files found for {collection}/{segment_path}: {e}")
1142                    return None
1143        elif source == 'db':
1144            try:
1145                return self._get_layers_db(ds, include_geometry=include_geometry, raise_errors=True)
1146            except Exception as e:
1147                if errors == 'error':
1148                    raise
1149                else:
1150                    warnings.warn(f"No layer data in DB for {collection}/{segment_path}: {e}")
1151                    return None
1152        else:
1153            raise ValueError("Invalid source specified. Must be one of: 'auto', 'files', 'db'.")

Load layer picks from files or database.

Tries files first, falls back to database if source='auto'.

Parameters
  • ds (Union[xr.Dataset, dict]): Radar frame Dataset or STAC item.
  • source ({'auto', 'files', 'db'}, optional): Source for layers. 'auto' tries files then falls back to database.
  • include_geometry (bool, optional): If True, include geometry information when fetching from the API.
  • errors (str, optional): How to handle missing layer data: 'warn' (default) returns None with a warning, 'error' raises an exception.
Returns
  • dict or None: A dictionary mapping layer IDs to their corresponding data, or None if no layers found and errors='warn'.