asp_plot.dem_benchmark#

Benchmark many DEMs against one altimetry reference (issue #169).

The report scores one DEM against ICESat-2 (or LOLA/MOLA). This module scores any number of DEMs – different scene combinations, joint multi-view triangulation vs. pairwise stereo + dem_mosaic, parameter sweeps – against the same fixed altimetry sample, so the numbers are directly comparable:

  • coverage inside a common area of interest (by default the intersection of all DEM footprints, so crop windows that differ per run compare fairly)

  • triangulation error, from the *-IntersectionErr.tif point2dem writes next to each *-DEM.tif (absent for a mosaic), in the table only: it is a consistency check on a run, not a quality ranking across geometries

  • altimetry residuals (altimetry minus DEM: n, median, NMAD, RMSE) before and, optionally, after a pc_align --compute-translation-only per DEM, with the translation that removed – on each DEM’s own points and on the points every DEM shares

  • a paired block bootstrap of the shared-point statistics: 95 % intervals on each DEM’s median and NMAD, on its NMAD difference to the best DEM, and the probability that it ranks first (issue #199)

  • optionally, each DEM’s difference against one of the candidates named as the reference (DEM minus reference median / NMAD)

  • optionally, the shared-point median and NMAD by slope class, with slope taken from one common DEM at every point (issue #211)

Every DEM is scored with the same recipe the report uses for one DEM: the cached ATL06-SR parquet is replayed (no SlideRule request), water returns are dropped with the ESA WorldCover classes stored in the cache, and dh outliers beyond 3σ are removed per DEM (after a gross-outlier cut at 30 NMAD). pc_align products and translated DEM copies are kept out of the candidates’ folders, under <directory>/dem_benchmark/<label>/, so nothing is written into the stereo runs.

Each DEM keeps a different set of points – its voids differ and the outlier cut runs per DEM – so the per-DEM numbers are not a fair ranking: a blend that fills voids is scored on harder ground than a single pair that skips it. The headline statistics (*_shared_* columns, the figure, the sort order) are therefore computed on the points valid in every DEM. Residuals are also spatially correlated along an ICESat-2 beam (40 m segments posted every 20 m, plus terrain and land cover), so the bootstrap resamples whole beam tracks, not points, and the DEMs are compared through their paired differences on the same replicates rather than through overlapping per-DEM intervals.

Examples

>>> from asp_plot.dem_benchmark import DEMBenchmark
>>> bench = DEMBenchmark(
...     directory="atlanta_mvs",
...     dems={
...         "MVS 3-scene": "atlanta_mvs/stereo_mvs3/run-DEM.tif",
...         "MVS 5-scene": "atlanta_mvs/stereo_mvs5/run-DEM.tif",
...         "3 pairs + mosaic": "atlanta_mvs/pairwise_mosaic-DEM.tif",
...     },
...     parquet="atlanta_mvs/atl06sr_all.parquet",
... )
>>> stats = bench.run()
>>> bench.summary_plot(save_dir="atlanta_mvs", fig_fn="dem_benchmark.png")

Attributes#

Classes#

DEMBenchmark

Score many DEMs against one altimetry sample.

Functions#

intersection_error_path(dem_fn)

Path of the point2dem --errorimage sibling of <prefix>-DEM.tif, or None.

label_from_dem_path(dem_fn)

Derive a short label for a DEM from its path.

parse_dem_specs(specs)

Turn CLI-style DEM specs into an ordered {label: path} mapping.

reference_dem_from_logs(dem_fn)

The reference DEM named in the stereo logs beside a DEM, or None.

Module Contents#

class asp_plot.dem_benchmark.DEMBenchmark(directory, dems, parquet=None, altimetry_csv=None, key='all', reference=None, aoi='intersection', filter_out='water', n_sigma=3, n_bootstrap=1000, seed=0, slope_dem='auto', slope_bins=SLOPE_BINS, slope_scale=SLOPE_SCALE_M, title=None)#

Score many DEMs against one altimetry sample.

Parameters:
  • directory (str) – Working folder. pc_align products, the pc_align CSV and the translated DEM copy for each candidate go under <directory>/dem_benchmark/<label>/. The translated copy is reused while it is newer than its DEM and the pc_align output, and otherwise rewritten (under a temporary name, then renamed), so two benchmarks sharing a directory and a label must not run at the same time.

  • dems (dict or list) – {label: dem_fn} (order preserved), or a list of paths / "label=path" strings (see parse_dem_specs()).

  • parquet (str or dict, optional) – ICESat-2 ATL06-SR parquet cache written by a prior report or Altimetry.request_atl06sr_multi_processing(save_to_parquet=True); either one path (used as processing level key) or a {key: path} mapping. Required for Earth DEMs.

  • altimetry_csv (str, optional) – LOLA/MOLA CSV (see request_planetary_altimetry). Required for Moon/Mars DEMs.

  • key (str, optional) – ATL06-SR processing level to score against, default "all".

  • reference (str, optional) – Label of the candidate the others are differenced against for the vs_ref_* columns. Default None (columns left NaN).

  • aoi (str, tuple or None, optional) – Area for the coverage and triangulation-error statistics: "intersection" (default) uses the common footprint of all DEMs; a (left, bottom, right, top) tuple is taken in the first DEM’s CRS; None uses each DEM’s own extent (not comparable across crops).

  • filter_out (str, list of str or None, optional) – ESA WorldCover group, or groups, dropped before differencing, default "water" (the report’s setting). ["water", "trees"] is the stable-terrain choice: years usually separate the imagery from the ICESat-2 passes, canopy height changes over that time, and a DSM and a 40 m ICESat-2 segment do not see the same surface in a forest. The groups are those of asp_plot.icesat2_source.WORLDCOVER_GROUPS; a choice other than the default is printed in the figure subtitle. None keeps every return. The filter applies to Earth DEMs only (LOLA and MOLA points carry no land cover), but the names are checked on every body and an unknown one raises ValueError.

  • n_sigma (float or None, optional) – Per-DEM dh outlier cut, default 3 (the report’s setting).

  • n_bootstrap (int, optional) – Replicates of the paired block bootstrap on the shared-point statistics, default 1000. 0 skips it (the *_ci_* and p_best columns stay NaN).

  • seed (int, optional) – Seed of the bootstrap’s random generator, default 0.

  • slope_dem (str, optional) – DEM to take slope from for the breakdown by slope class. The default "auto" uses the reference DEM the stereo logs beside the DEMs name (reference_dem_from_logs(), the DEM asp_report finds). When the logs name none, disagree, or name a file that does not exist, it uses the reference DEM if one was given and skips the breakdown if not. Otherwise the label of one of the candidates, or a path (a Copernicus DEM, a lidar DTM). None: no breakdown. Slope comes from slope_at_points() and is sampled once per point, so every candidate is binned the same way; slope from each candidate would put a point in different classes for different DEMs, and would sort a DEM’s own noise into the steep classes.

  • slope_bins (sequence of float, optional) – Edges of the slope classes in degrees, default SLOPE_BINS. Each class includes its lower edge and excludes its upper one.

  • slope_scale (float or None, optional) – Length scale of the slope in meters, default asp_plot.terrain.SLOPE_SCALE_M (30 m, about one ATL06-SR segment). A slope DEM with finer pixels is averaged to it first, so a 1 m candidate gives terrain slope and not the slope of roofs and canopy edges; a coarser DEM is used as it is. None or 0 uses the slope DEM’s own resolution.

  • title (str, optional) – Figure title.

Notes

After run(), stats_df holds one row per DEM with the columns in STATS_COLUMNS (residual columns are altimetry minus DEM, in meters). The dh_* columns are each DEM’s own surviving points; the *_shared_* columns are the n_shared points valid in every DEM (shared_ids), which is what the figure shows and the rows are sorted on. The median_ci_* / nmad_ci_* columns are 95 % bootstrap intervals on the shared-point statistics at the stage that is ranked (post-alignment when pc_align ran, bootstrap["stage"]), nmad_vs_best_ci_* the interval on the DEM’s NMAD minus the best DEM’s on the same replicates (a DEM whose interval includes 0 is not separable from the best), and p_best the fraction of replicates on which the DEM has the lowest NMAD.

altimetry maps each label to its Altimetry object, for per-DEM figures such as mapview_plot_atl06sr_to_dem() or histogram_by_landcover(); dh / dh_aligned map each label to the residual series scored, indexed by point id (aligned only when pc_align ran for it); blocks maps point id to the resampling block (beam track, or orbit) the bootstrap draws.

With slope_dem, stats_by_slope_df holds one row per DEM and slope class (columns SLOPE_STATS_COLUMNS), on the shared points in that class, with the bootstrap run again within each class; slope maps each shared point id to its slope in degrees. Steep classes are often thin, so read n_points and n_blocks with them. A horizontal offset between a DEM and the altimetry of Δx raises the residual by about Δx · tan(slope), so steep-class NMAD includes the altimetry’s geolocation error and, after alignment, the horizontal part of the pc_align translation, as well as the DEM’s own error.

aoi_area_km2()#

Area of the coverage/IE window in km² (None when each DEM uses its own extent).

histogram_plot(aligned='auto', bins=100, xlim=None, sort=True, save_dir=None, fig_fn=None, dpi=None)#

Overlaid residual histograms, one outline per DEM, on the points every DEM shares (each DEM’s own points when there are none).

Parameters:
  • aligned ({"auto", True, False}, optional) – Plot post-alignment residuals when every DEM has them ("auto", default), always (True, DEMs without them fall back to pre-alignment), or never (False).

  • bins (int, optional) – Histogram bins, default 100.

  • xlim (float, optional) – Half-width of the plotted range in meters; default 3× the largest NMAD among the DEMs. Residuals beyond it are not drawn (the legend counts all of them).

  • sort (bool, optional) – Order the legend best-first as in summary_plot(), default True.

Return type:

matplotlib.figure.Figure

label_directory(label)#

Working folder for one candidate.

run(pc_align=True, minimum_points=500, max_displacement=None)#

Score every DEM and return the stats table.

Parameters:
  • pc_align (bool, optional) – Also run pc_align --compute-translation-only per DEM and re-score against the translated copy. Default True. Existing pc_align outputs under the benchmark folder are reused, so a re-run makes no pc_align call and works offline; so are translated DEMs newer than their DEM and pc_align output.

  • minimum_points (int, optional) – Skip pc_align for a DEM with fewer valid dh points, default 500 (the report’s threshold).

  • max_displacement (float, optional) – pc_align --max-displacement in meters. Default None: 20 m on Earth, 500 m on the Moon/Mars, matching Alignment.

Returns:

self.stats_df: one row per DEM, columns STATS_COLUMNS.

Return type:

pandas.DataFrame

save_stats(csv_fn)#

Write stats_df to csv_fn (creating its folder) and return the path.

With a slope breakdown, stats_by_slope_df is written next to it as <stem>_by_slope.csv.

static slope_csv_path(csv_fn)#

Where save_stats() writes the slope table for csv_fn.

slope_plot(aligned='auto', sort=True, save_dir=None, fig_fn=None, dpi=None)#

Shared-point median (top) and NMAD (bottom) of every DEM by slope class, one line per DEM.

Each class is labelled with its number of points and of resampling blocks (beam tracks), and the error bars are the 95 % interval from the paired block bootstrap run within the class. Steep classes are usually thin, so their intervals are wide; a class with fewer than SLOPE_MIN_POINTS points is marked “too few” and not drawn.

The median shows a bias that changes with slope, which one pc_align translation cannot remove and the NMAD does not show.

A horizontal offset Δx between a DEM and the altimetry adds about Δx · tan(slope) to a residual, so NMAD rises with slope for reasons other than the DEM: the altimetry’s own geolocation error and, after alignment, the horizontal part of each DEM’s pc_align translation, whose range the subtitle prints. Compare with aligned=False to see how much of the steep-class NMAD the alignment contributes.

Parameters:
  • aligned ({"auto", True, False}, optional) – Plot post-alignment statistics when any DEM has them ("auto", default), always (True, DEMs without it fall back to pre-alignment), or never (False). Error bars are drawn only for the stage the bootstrap ran on (post-alignment when any DEM was aligned).

  • sort (bool, optional) – Order the legend best-first as in summary_plot(), default True.

Return type:

matplotlib.figure.Figure

summary_plot(sort=True, save_dir=None, fig_fn=None, dpi=None)#

One row per DEM, one panel per metric.

Panels: coverage (% valid inside the AOI, area printed) and altimetry-minus-DEM median and NMAD on the points every DEM shares – as dumbbells from before (open) to after (filled) pc_align when alignment ran, with the 95 % bootstrap interval as an error bar on the ranked marker. A translation-only pc_align leaves NMAD essentially unchanged by construction, so that panel’s two markers coincide; the median panel is where the alignment shows. Rows are sorted best-first by post-alignment NMAD (pre-alignment when pc_align did not run) unless sort=False; the best DEM’s NMAD is labelled best and every DEM whose paired NMAD difference to it includes zero is labelled ≈ best.

The IntersectionErr columns are not drawn. Across DEMs of different geometry the triangulation error ranks opposite to accuracy (a narrow pair’s rays intersect precisely, at the wrong height), so a panel of it next to the residuals misleads; the columns stay in the table as a consistency check on a run.

Return type:

matplotlib.figure.Figure

altimetry#
altimetry_csv#
property benchmark_directory#

Folder holding the per-label pc_align products and translated DEMs.

block_name = None#
blocks = None#
body#
bootstrap = None#
dh#
dh_aligned#
directory#
filter_out = 'water'#
key = 'all'#
n_bootstrap = 1000#
n_sigma = 3#
parquet#
reference = None#
seed = 0#
shared_ids = None#
slope = None#
slope_bins#
slope_dem = None#
slope_dem_name = None#
slope_scale#
stats_by_slope_df = None#
stats_df = None#
title = None#
asp_plot.dem_benchmark.intersection_error_path(dem_fn)#

Path of the point2dem --errorimage sibling of <prefix>-DEM.tif, or None.

asp_plot.dem_benchmark.label_from_dem_path(dem_fn)#

Derive a short label for a DEM from its path.

Strips the ASP -DEM.tif suffix; when what remains is a generic ASP output prefix (run, out, …) the containing folder is used instead, since that is what distinguishes one run from another.

Examples

>>> label_from_dem_path("atlanta_mvs/stereo_mvs3/run-DEM.tif")
'stereo_mvs3'
>>> label_from_dem_path("atlanta_mvs/pairwise_mosaic-DEM.tif")
'pairwise_mosaic'
asp_plot.dem_benchmark.parse_dem_specs(specs)#

Turn CLI-style DEM specs into an ordered {label: path} mapping.

Each spec is either a path (labelled via label_from_dem_path()) or label=path. Duplicate labels are disambiguated with the containing folder so two run-DEM.tif never collapse into one row.

asp_plot.dem_benchmark.reference_dem_from_logs(dem_fn)#

The reference DEM named in the stereo logs beside a DEM, or None.

This is the DEM asp_report finds for a run: the one the images were mapprojected onto, announced in the stereo logs. The logs are looked for in the DEM’s own folder, where point2dem writes by default. A relative path in a log is resolved as resolve_logged_path() does, against the folder above the DEM’s.

Returns None when the folder has no stereo logs or they name no DEM. The path returned may not exist (a run copied from another machine).

asp_plot.dem_benchmark.GENERIC_STEMS#
asp_plot.dem_benchmark.MAX_WINDOW_PIXELS = 16000000#
asp_plot.dem_benchmark.PLANETARY_BLOCK_COLUMNS = ('orbit', 'orbit_number', 'orbitnumber', 'track', 'track_id')#
asp_plot.dem_benchmark.POINT_ID = 'benchmark_point_id'#
asp_plot.dem_benchmark.SLOPE_STATS_COLUMNS = ['label', 'slope_bin', 'slope_min_deg', 'slope_max_deg', 'n_points', 'n_blocks',...#
asp_plot.dem_benchmark.STATS_COLUMNS = ['label', 'dem_fn', 'gsd_m', 'valid_pct', 'valid_area_km2', 'ie_median_m', 'ie_nmad_m',...#
asp_plot.dem_benchmark.logger#