Skip to content

feat(explain): soil-ID scoring explain trace + HTML renderer (pre-fix) - #392

Merged
johannesparty merged 30 commits into
mainfrom
feat/soil-id-explain-prefix
Sep 25, 2026
Merged

johannesparty merged 30 commits into
mainfrom
feat/soil-id-explain-prefix

Conversation

@johannesparty

Copy link
Copy Markdown
Contributor

What

The soil-ID explain instrumentation: a trace Recorder + schema (explain.py), HTML renderer (scripts/render_soil_explain.py), and hooks in rank_soils (US) and rank_soils_global that emit a full scoring trace (inputs → per-horizon distances → decay → component totals → normalized scores), plus unit + end-to-end snapshot tests.

Stacking / ordering

Tests

Full suite green: 169 passed, no ranking regressions; explain snapshot regenerated for the pre-fix baseline.

🤖 Generated with Claude Code

johannesparty and others added 26 commits September 11, 2026 23:23
rank_soils assigned pElev_dict only in the `pElev is None` branch but
dereferenced it unconditionally, so a caller-supplied pElev raised
UnboundLocalError (not caught by the surrounding except). Move the
lookup+parse inside the `if pElev is None:` guard so a provided
elevation is used as-is.

Add a regression test that calls rank_soils with a numeric pElev.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Off by default (explain=None). When a Recorder is passed, rank_soils_global
captures location (distance/share/cond_prob), per-slice horizon Gower (raw values
+ post-infill distances + normalization), color, scores, and rule overrides;
build_trace assembles a path-agnostic JSON trace with per-candidate score
components and depth bands consolidated from identical consecutive slices.
Verified end-to-end on a live global site; normal-path regression tests pass.
Generic over score_components (works for US + global): per-candidate cards with a
location formula line, a depth-band horizon table (your value vs candidate per
feature, one-sided data shown as —, per-slice distance), color, US site score,
override badges, and a combined-score bar. Reads a trace JSON, emits self-contained
HTML.
…ped columns, legend

- pit table gets depth/texture/rock-frag headers; 'rfv None' -> —
- feature names humanized (sandpct_intpl -> 'sand %', etc.)
- each feature is a color-tinted, divider-separated group (you/candidate pair)
- note explaining the comparison window (recorded depths; above the first horizon
  isn't recorded) + a legend for the combined-score formula
- capture each candidate's full profile (0..depth), keyed by within-group position
- horizon bands now span 0..max(pit, candidate): candidate-only depths (above your
  first horizon or deeper than your pit) and user-only depths (candidate has no
  soil) both shown, with — for the missing side and greyed 'not compared' rows
- renderer: centered headers, heavier divider before slice-dist, greyed
  out-of-window rows, clearer note
…d/clay and cond_prob derivation

- horizon bands now break at 20 cm so the ×0.2 (top) vs ×1.0 (below) weighting is
  visible even when values are constant
- pit table shows the sand%/clay%/rfv% each texture+rfv class maps to (the numbers
  the comparison uses); legend explains the conversion
- location breakdown shows location_score = decay×share and that cond_prob is that
  normalized across all candidates (Fan et al. 2018)
Add a weighted-combine summary line under the horizon table showing
horizon distance = Sum(wt * cm * slice dist) / Sum(wt * cm) -> horizon score,
and clarify in the note that slice dist is the plain average of the deltas
(wt is not applied within a band, only when combining bands across depth).
Mirror the global explain instrumentation on the US path (us_soil.rank_soils):
capture inputs + derived sand/clay/rfv, full candidate profiles, per-slice
Gower detail (post-infill distances), location, and combined scores onto the
same Recorder schema so the existing renderer handles US and global.

US-specific: color is compared as l/a/b horizon features (not a separate
track), and a new 'site' component captures the slope/elevation/depth Gower
distance. explain.py gains the site component; render_soil_explain.py's
location renderer degrades gracefully when the decay coefficient is absent
(US bakes it into cond_prob upstream). All capture is guarded by
explain is not None, so the default ranking path is unchanged.
Capture candidate profiles over the full canonical property set (sand/clay/rfv,
plus color for US) from the un-subset rank frame, not just the user-entered
columns. A property the user didn't enter is dropped from the Gower comparison
(all-NaN) but its candidate values are still informative, so the report now
shows it — greyed, marked (not entered), with — on the user side and no Δ —
rather than silently omitting the column.
…ce snapshot

- soil_id/tests/test_explain.py: pure/synthetic unit tests (no DB/API) pinning
  the trace schema and helpers — build_trace ranking, location decay, the
  shallow-candidate depth penalty, the 'not entered' property column, the US
  site component — plus HTML renderer smoke tests for both global and US shapes.
- soil_id/tests/us/test_explain_snapshot.py: end-to-end syrupy snapshot of the
  trace from the real US ranking path (cached API fixtures), with a render()
  smoke assertion. Refreshed by make regen_snapshots.
…tooltip

- Rank chip reads 'Candidate #N' instead of '#N'.
- 'you' -> 'soil pit' everywhere (headers, notes, legend, pit title).
- Horizon section retitled 'Soil horizons — depth-layer properties' with a note
  explaining a horizon is a depth layer.
- Spell out the normalized difference in the note (Δ = |pit − candidate| ÷ range)
  and add a per-cell hover title showing the actual |a − b| ÷ range = Δ.
Update the render smoke test's section assertion accordingly.
The horizon note described range as just 'the spread across the soils compared
at this depth', omitting the fixed-range floor added in #377. The actual
denominator is max(observed spread, 10% of the property's plausible range).
Also note the slice dist is an equal-weighted average of the Δ's present.
…otal → normalized)

The old Location box claimed cond_prob = location_score ÷ Σ, a reconstruction
that did NOT reproduce the real value. Capture the true intermediates from
process_distance_scores (Fan et al.) — per-map-unit distance_score, per-component
comp_distance_score, and the grand total — for both paths, and render Location
as a left-to-right flow:

  inputs (distance, share) → decayed (share × decay = distance score) →
  [component total, when the soil spans >1 map unit] → normalized
  (comp_distance_score ÷ total = cond_prob)

cond_prob is now shown exactly (verified against the algorithm). Map-unit
occurrences are NOT itemized: a component's total aggregates occurrences some of
which are filtered before ranking, so listing survivors would mislead. Global
shows the decay factor; US shows only the distance score. Tests updated.
…ue scores

- Location 'decayed' box now shows the actual formula with the distance
  substituted: decay = max(0.25, e^(-0.00036888 x distance_m)), plus a note that
  it floors at 0.25 (~10 km).
- New 'Combined score' roll-up at the bottom of each card showing how the parts
  combine: properties = weighted avg(horizon, site|color); combined =
  (properties + location) / 2 (with the rule override noted when it fires).
  Verified to reproduce properties/combined exactly for US and global.
- The scoring inputs (location, horizon, site, color) and the combined score are
  now highlighted blue so the roll-up is easy to follow.
…loor distance

- US Location 'decayed' box now shows the effective decay (= distance_score ÷
  share), so the decay value is visible even though US doesn't expose its
  data-source-dependent coefficient.
- Combined-score roll-up now states the weights explicitly (horizon 1,
  site 0.5 / color 0.3, location 1) and notes location is ~half the final score,
  and that every score is normalized ≤ 1 (except the 1.001/0.001 rule overrides).
- Corrected the decay note: the 0.25 floor is reached at ~3.8 km (not 10 km);
  the rate ≈ a halving every ~1.9 km.
…3.8 km)

The comment claimed 'Decays to 0.25 @ 10km', but exp(-0.00036888 * distance)
reaches the 0.25 floor at ~3.8 km (it's ~0.025 at 10 km, already floored). Fix
the comment to describe the actual behavior. No code change.
Site component now shows the per-feature Gower weights (slope 1, elev 0.5,
depth 1.5) and the full derivation: site distance = Σ(Δ×weight)/Σweight,
similarity = 1 − that, site score = ×0.5 site weight — reproducing the score
exactly. Added a small '(floors at 0.25 by ~3.8 km)' hint in the decayed box.
Each horizon feature's Δ = |pit − candidate| ÷ range. Now surface that range:
when it's the same at every compared depth, show it once in the column header
(Δ ÷ [X]); when it varies with depth, the header shows the [min–max] span and
each cell shows its own [range].
… both paths

- Combined score is now a flat weighted sum of the base scores, each shown with
  its share of the final: location 50%, horizon 33.3%/38.5%, site 16.7% / color
  11.5% (a re-expression of the nested properties/combined math; exact nested
  form kept as a small line). Reproduces combined exactly.
- Site component now shows the RAW similarity (1 − site distance) as its
  headline; its 0.5 weight is folded into the % in the roll-up (consistent with
  how color is shown). No trace/algorithm change.
- Decay explanation now renders on BOTH paths: global shows the full formula and
  that −0.00036888 = ln(0.025)/10km (raw ~2.5% at 10km, floored to 0.25/25% past
  ~3.8km); US notes the coefficient is data-source-specific with the effective
  decay shown.
…or note

Capture the data source (SSURGO/STATSGO for US, HWSD2 for global) and map it to
its decay coefficient (SSURGO -0.008, STATSGO -0.0002772, HWSD2 -0.00036888), so
the Location 'decayed' box shows the real formula with numbers on BOTH paths
(e.g. US: decay = max(0.25, e^(-0.008 x 21)) = 0.845). The note below states the
source, coefficient, and the per-source distance at which decay hits the 0.25
floor (SSURGO ~173 m, HWSD2 ~3.8 km, STATSGO ~5 km) — replacing the hardcoded
3.8 km hint that was wrong for US.
- Location 'component total' box now itemizes the visible map-unit occurrences
  (candidates of the same series) that sum toward it, e.g.
  'wilkes 1.000 + wilkes2 0.845 = 1.845', with a '(+ N other map units)' remainder
  when some occurrences were filtered before ranking.
- Each candidate card now notes its app visibility: the best-scoring instance of
  a series is 'shown in the app as #N'; a lower-scoring duplicate is 'not shown
  separately in the app; folded into <name> (app #M)'. Computed in build_trace by
  grouping on compname_grp.
…olumn

Capture the pit's complete recorded profile (pedon_full: every property at every
recorded depth) before the per-slice comparison drops uncompared columns, and
use it for the 'soil pit' values in the horizon table. Previously the pit column
only showed properties that entered the Gower at each depth, so a property the
user recorded but a candidate can't be compared against (e.g. color vs a
colorless SSURGO component) silently vanished at depths where other properties
were shared. Now the pit column always shows what was entered; Δ still appears
only where the property was actually compared.
This explain branch now sits BELOW the soil-id fixes, so the trace reflects
pre-fix values (e.g. effective_bedrock_cm == raw bedrock, max_user_depth
property arrays). The fix commits stacked on top will re-regenerate it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Stage-1 replay left explain hooks referencing fix concepts that aren't
defined yet on the pre-fix branch (rode in via non-conflicting explain
commits, invisible to the snapshot test which doesn't hit those paths):
- demote-rule hook used effective_bedrock / LEPTOSOL_MAX_BEDROCK_CM (#375);
  now describes the pre-fix rule (bedrock > 50).
- candidate-columns hook used GLOBAL_HORIZON_PROP_BOUNDS (#377); now falls
  back to the columns present. #375/#377 restore these when they land on top.

ruff F821 clean across soil_id/; full suite 170 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
johannesparty and others added 3 commits September 14, 2026 10:08
…recompute

The report recomputed the horizon distance from the per-band segments
(Σ depth_weight·cm·slice_dist ÷ Σ depth_weight·cm) and printed it next to the
real score, so "1 − distance = score" didn't hold — the band grouping + NaN
masking don't reproduce the algorithm's depth-weighted, mask-aware D_sum. Take
the distance straight from the real score (distance = 1 − score = D_sum); the
per-depth table remains as the supporting detail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The site component displayed 'site distance = Σ(Δ×weight)÷Σweight'
recomputed from the entered features, but the algorithm's real site
distance also includes an elevation comparison against a server-fetched
elevation (used when elevation isn't entered), so 1 − distance did not
equal the shown similarity. Take the distance straight from the score
(1 − similarity), matching the horizon fix; the feature table remains
the supporting breakdown.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The global explain path took full_cols = all columns of the candidate
frame, which includes the string id columns (compname, cokey, comppct).
Building candidate_full then did round(float(v)) over each row and blew
up with 'could not convert string to float: Dystric Fluvisols' whenever
a global site was explained. Restrict full_cols to the numeric horizon
property set (sandpct/claypct/rfv), matching the US path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread soil_id/explain.py Resolved
@johannesparty
johannesparty deleted the branch main September 25, 2026 17:07
Base automatically changed from fix/rank-soils-caller-elevation to main September 25, 2026 17:07
@johannesparty johannesparty reopened this Sep 25, 2026
@johannesparty
johannesparty merged commit 13b0537 into main Sep 25, 2026
4 checks passed
@johannesparty
johannesparty deleted the feat/soil-id-explain-prefix branch September 25, 2026 18:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants