asp_plot.icesat2_source
=======================

.. py:module:: asp_plot.icesat2_source

.. autoapi-nested-parse::

   ICESat-2 ATL06-SR altimetry source.

   Owns the Earth/ICESat-2 side of :class:`asp_plot.altimetry.Altimetry`:
   requesting ATL06-SR points from SlideRule (with parquet caching), sampling
   ESA WorldCover, temporal and outlier filtering, differencing against the ASP
   DEM, and selecting the best track / best-worst 1 km segments used by the
   profile plots and reproducibility (#121).

   The class holds its own data (``atl06sr_processing_levels`` /
   ``atl06sr_processing_levels_filtered`` and the resolved request time range)
   and reads the cross-cutting ``dem_fn`` / ``directory`` / ``aligned_dem_fn``
   from the coordinating :class:`Altimetry` instance passed at construction.



Attributes
----------

.. autoapisummary::

   asp_plot.icesat2_source.ICESAT2_MISSION_START
   asp_plot.icesat2_source.logger


Classes
-------

.. autoapisummary::

   asp_plot.icesat2_source.Icesat2Source


Module Contents
---------------

.. py:class:: Icesat2Source(alt, atl06sr_processing_levels=None, atl06sr_processing_levels_filtered=None)

   Request, cache, filter and difference ICESat-2 ATL06-SR points.

   :param alt: The coordinating :class:`asp_plot.altimetry.Altimetry` instance.
               Cross-cutting paths (``dem_fn``, ``directory``, ``aligned_dem_fn``)
               are read from it so a single source of truth describes the DEM
               under analysis.
   :type alt: Altimetry
   :param atl06sr_processing_levels: Pre-loaded ATL06-SR data for different processing levels.
   :type atl06sr_processing_levels: dict, optional
   :param atl06sr_processing_levels_filtered: Pre-loaded filtered ATL06-SR data.
   :type atl06sr_processing_levels_filtered: dict, optional


   .. py:method:: atl06sr_to_dem_dh(n_sigma=3)

      Calculate height differences between ATL06-SR data and DEMs.

      Interpolates DEM heights at ATL06-SR point locations and calculates
      the difference between ICESat-2 heights and DEM heights. If an aligned
      DEM is available, also calculates differences against it. Outliers
      beyond ``n_sigma`` × NMAD from the median are removed by default.

      :param n_sigma: Remove dh outliers beyond this many NMAD from the median.
                      Default 3. Pass None to skip outlier filtering.
      :type n_sigma: float or None, optional

      :returns: Adds columns to the filtered ATL06-SR data:
                - dem_height: Interpolated height from the original DEM
                - icesat_minus_dem: Height difference (ICESat-2 - DEM)
                - aligned_dem_height: Interpolated height from aligned DEM (if available)
                - icesat_minus_aligned_dem: Height difference with aligned DEM (if available)
      :rtype: None

      .. rubric:: Notes

      This method performs bilinear interpolation of DEM values at
      ATL06-SR point locations using xarray and rioxarray. It handles
      coordinate system conversions automatically.



   .. py:method:: filter_esa_worldcover(filter_out='water', retain_only=None)

      Filter ATL06-SR data based on ESA WorldCover land cover classes.

      Filters the data points based on ESA WorldCover classification,
      either by removing specific land cover types or retaining only
      specific types.

      :param filter_out: Land cover group to filter out, default is "water".
                         Options: "water", "snow_ice", "trees", "low_vegetation", "built_up"
      :type filter_out: str, optional
      :param retain_only: If specified, retain only points matching this land cover group,
                          default is None. Same options as ``filter_out``.
      :type retain_only: str or None, optional

      :returns: Results are stored in the class attributes
      :rtype: None

      .. rubric:: Notes

      This method uses the ESA WorldCover land cover classification
      (see ``WORLDCOVER_NAMES``), which was sampled when requesting the
      ATL06-SR data.



   .. py:method:: filter_outliers(column='icesat_minus_dem', n_sigma=3)

      Remove dh outliers beyond *n_sigma* × standard deviation from the mean.

      :param column: Column to filter on, default ``"icesat_minus_dem"``.
      :type column: str, optional
      :param n_sigma: Number of standard deviations to allow, default 3.
      :type n_sigma: float, optional



   .. py:method:: generic_temporal_filter_atl06sr(select_years=None, select_months=None, select_days=None)

      Apply custom temporal filters to ATL06-SR data.

      Filters the data based on specific years, months, or days,
      allowing for custom temporal filtering not covered by the
      predefined filters.

      :param select_years: Years to keep (e.g., [2019, 2020]), default is None
      :type select_years: list or None, optional
      :param select_months: Months to keep (1-12), default is None
      :type select_months: list or None, optional
      :param select_days: Days of month to keep (1-31), default is None
      :type select_days: list or None, optional

      :returns: Results are filtered in-place in the class attributes
      :rtype: None

      .. rubric:: Notes

      This method modifies the existing filtered data rather than
      creating new entries with different keys. At least one of
      the filter parameters should be provided for the method
      to have any effect.



   .. py:method:: get_altimetry_selections(key='all')

      Report the ICESat-2 selections a run made, for reproducibility (#121).

      Bundles the request settings, the parquet cache locations (the exact
      points used), the auto-selected profile track, and the best/worst
      segment extents so they can be written to a figure-selections file and
      replayed on a later run.

      :param key: Processing level key, default is "all".
      :type key: str, optional

      :returns: ``{"request": {..}, "parquet_cache": {key: path},
                "profile_track": {"rgt", "cycle", "spot"},
                "segments": {"best": {..}, "worst": {..}}}``. Keys are omitted when
                the corresponding selection is unavailable.
      :rtype: dict



   .. py:method:: load_atl06sr_from_parquet(parquet_paths, h_sigma_quantile=1.0)

      Load ATL06-SR points directly from saved parquet caches.

      Replays the *exact* points a prior run used (issue #121), bypassing the
      SlideRule request entirely so a re-processed scene compares against an
      identical ICESat-2 sample. Runs the same normalization + quality filter
      as a fresh request via ``_ingest_atl06sr``.

      :param parquet_paths: Mapping of processing-level key -> parquet path
                            (e.g. ``{"all": ".../atl06sr_all.parquet"}``).
      :type parquet_paths: dict
      :param h_sigma_quantile: Quantile of ``h_sigma`` above which fits are discarded, default 1.0.
      :type h_sigma_quantile: float, optional

      :returns: True if at least one parquet was loaded, False otherwise.
      :rtype: bool



   .. py:method:: predefined_temporal_filter_atl06sr(date=None)

      Apply predefined temporal filters to ATL06-SR data.

      Creates multiple temporally filtered versions of the ATL06-SR data
      based on a reference date, including:
      - 15-day window around the date
      - 45-day window around the date
      - 91-day window around the date
      - Seasonal filter (same season as the reference date)

      :param date: Reference date for filtering. If None, extracts date from
                   stereopair metadata, default is None
      :type date: datetime or None, optional

      :returns: Results are stored in the class attributes with new keys
                indicating the temporal filter applied
      :rtype: None

      .. rubric:: Notes

      This method is particularly useful for DEM validation and alignment,
      as it provides multiple temporal windows to analyze the stability
      of the terrain and to identify optimal temporal windows for alignment.



   .. py:method:: request_atl06sr_multi_processing(processing_levels=['all', 'ground', 'canopy', 'top_of_canopy'], res=20, len=40, ats=20, cnt=10, maxi=6, h_sigma_quantile=1.0, save_to_parquet=False, filename='atl06sr', region=None, time_range='all', scene_date=None, time_buffer_days=365, t0=None, t1=None)

      Request ICESat-2 ATL06-SR data for multiple processing levels.

      Downloads ATL06-SR data from the SlideRule API for specified
      processing levels (surface types), with options to filter and
      save the results. Each processing level targets different surface
      types like ground, canopy, etc.

      :param processing_levels: List of processing levels to request, default is
                                ["all", "ground", "canopy", "top_of_canopy"]
      :type processing_levels: list, optional
      :param res: ATL06-SR segment resolution in meters, default is 20
      :type res: int, optional
      :param len: ATL06-SR segment length in meters, default is 40
      :type len: int, optional
      :param ats: Along-track sigma, default is 20
      :type ats: int, optional
      :param cnt: Minimum number of photons for segment, default is 10
      :type cnt: int, optional
      :param maxi: Maximum iterations for surface fit, default is 6
      :type maxi: int, optional
      :param h_sigma_quantile: Quantile for filtering by h_sigma, default is 1.0
      :type h_sigma_quantile: float, optional
      :param save_to_parquet: Whether to save results to parquet files, default is False
      :type save_to_parquet: bool, optional
      :param filename: Base filename for saved data, default is "atl06sr"
      :type filename: str, optional
      :param region: Region bounds as [minx, miny, maxx, maxy] in lat/lon,
                     default is None (derived from DEM)
      :type region: list or None, optional
      :param time_range: ``"all"`` (default) requests all ICESat-2 data from mission
                         start to present. ``"buffered"`` activates time filtering
                         via the cascade: ``t0``/``t1`` > ``scene_date`` ±
                         ``time_buffer_days`` > XML metadata ±
                         ``time_buffer_days`` > fall back to all.
      :type time_range: str, optional
      :param scene_date: Scene acquisition date, used when ``time_range="buffered"``.
                         If None, auto-detected from stereopair XML metadata.
      :type scene_date: str or datetime-like, optional
      :param time_buffer_days: Days before/after scene_date defining the time window,
                               default is 365
      :type time_buffer_days: int, optional
      :param t0: Explicit start date (e.g. "2020-01-01"), used when
                 ``time_range="buffered"``. Overrides ``scene_date``.
      :type t0: str or datetime-like, optional
      :param t1: Explicit end date (e.g. "2024-12-31").
                 Defaults to present if only ``t0`` is provided.
      :type t1: str or datetime-like, optional

      :returns: Results are stored in the class attributes
      :rtype: None

      .. rubric:: Notes

      This method makes SlideRule API calls which require internet connectivity.
      It also samples ESA WorldCover data for land cover classification of the
      ICESat-2 data points. The method includes filtering to improve data quality
      by removing points with high uncertainty and from early mission cycles.



   .. py:method:: sample_esa_worldcover()

      Sample ESA WorldCover 10m values into every filtered processing
      level that doesn't already have them.

      Normally not needed when data is requested via
      ``request_atl06sr_multi_processing``, which samples WorldCover
      automatically before caching. Use this when working with
      manually-loaded data.



   .. py:method:: to_csv_for_pc_align(key='ground', filename_prefix='atl06sr_for_pc_align')

      Export ATL06-SR data to CSV format for use with pc_align.

      Creates a CSV file from the filtered ATL06-SR data that is formatted
      for use with the ASP pc_align tool, containing longitude, latitude,
      and height above datum.

      :param key: Processing level to export, default is "ground"
      :type key: str, optional
      :param filename_prefix: Prefix for the output CSV file, default is "atl06sr_for_pc_align"
      :type filename_prefix: str, optional

      :returns: Path to the created CSV file
      :rtype: str

      .. rubric:: Notes

      The ASP pc_align tool requires input data in a specific format.
      This method converts the ATL06-SR GeoDataFrame to the required
      CSV format with columns for longitude, latitude, and height.



   .. py:attribute:: alt


   .. py:attribute:: atl06sr_processing_levels


   .. py:attribute:: atl06sr_processing_levels_filtered


.. py:data:: ICESAT2_MISSION_START

.. py:data:: logger

