Skip to content

feat: expose soil-id semver as soil_id.__version__ (Section 6) - #394

Merged
johannesparty merged 11 commits into
mainfrom
feat/soil-id-version
Sep 25, 2026
Merged

johannesparty merged 11 commits into
mainfrom
feat/soil-id-version

Conversation

@johannesparty

Copy link
Copy Markdown
Contributor

Foundation of the Section 6 stack (auto-flush the mobile soil-ID match cache when the algorithm changes). Stacked on #393.

What

Verify

PATTERN=test_version make test_unit → 3 pass; a US snapshot test still passes (metadata model still "v2").

Notes

Downstream consumes this via terraso-backend (soilId.soilIdAlgorithmVersion) → client-shared → mobile. Docs: terraso-wiki cross-repo-versioning update.

🤖 Generated with Claude Code

johannesparty and others added 11 commits September 25, 2026 11:16
list_soils_global built the per-component profile lists (hz_lyrs, snd_lyrs,
cly_lyrs, txt_lyrs, rf_lyrs, cec_lyrs, ph_lyrs, ec_lyrs) in cokey-group order,
then "reordered" them positionally by mucompdata_cond_prob.index — which, after
reset_index, is just 0..n-1, an identity op. So each soil was paired with a
DIFFERENT component's profile whenever the cokey order and the final sorted order
differed. Visible symptom: a shallow Lithic Leptosol (soil to 20 cm) displayed
with a deep soil's full 0-120 cm profile (and a deep soil shown a shallow one).

Key the profile lists by cokey and emit them in mucompdata_cond_prob order via a
cokey->position lookup (mucompdata is already filtered to c_bottom_depths.cokey,
so the lookup is total and 1:1). soilDepth was already correct (attached by a
merge on compname), which is why soilDepth vs the displayed profile depth was the
tell.

Adds test_shallow_soil_profile_not_padded: asserts max(bottom_depth) ==
min(soilDepth, 120) for every returned soil at the #378 Kenya point.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The final-score rule demoted shallow-soil groups (leptosols/lithosols/rendzinas/
rankers) to 0.001 when `bedrock is None OR bedrock > 50`. But the client doesn't
submit bedrock depth yet, so bedrock is None on essentially every request —
meaning these soils were always forced to ~0%, contradicting their own location
and properties scores.

Treat "no bedrock provided" as unknown, not "deep": derive an effective bedrock
from the deepest observed user horizon (recording soil to depth D implies rock is
below D), and demote only when effective_bedrock > LEPTOSOL_MAX_BEDROCK_CM. So a
shallow/no-data pedon leaves leptosols to rank on merit, while a pedon logged past
50 cm still (correctly) rules them out.

Threshold is a named constant (50, provisional — a soil scientist may prefer ~30;
change + regen). Adds test_shallow_soil_not_zeroed_without_bedrock covering both
the shallow (not demoted) and deep (demoted) cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The global per-slice distance called gower_distances(slice_mat) with no
theoretical_ranges, so each numeric feature was normalized by that slice's own
min-max — which includes the user's sample_pedon value. When candidates are
tightly clustered (common), that denominator is tiny, so a small property
difference is amplified toward the maximum distance, and changing one user input
rescales every candidate's distance ("rubber ruler"). This is why entering a
rock-fragment or texture value shifted scores counter-intuitively.

Pass fixed per-property ranges (reused from the US path's global_prop_bounds:
sand 10-92, clay 5-70, rfv 0-80) so the denominator is floored at 0.1*span,
matching the US behavior. Ranges are looked up by the slice's column names, which
are a subset of GLOBAL_HORIZON_PROP_BOUNDS.

Adds test_gower_distance.py: clustered candidates are damped with ranges and
unchanged when the slice already spans >10% of the theoretical range.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
check_pairwise_arrays ran SimpleImputer(strategy="mean") on the distance matrix,
so a candidate missing a property at a depth was filled with the column mean —
"an average soil" — instead of staying NaN. This masked the intended penalty: the
US/global soil-vs-non-soil infill only fires on NaN distances, but the imputer had
already removed them. Measured impact: across 6 US locations, 245/245 (100%) of
"no soil here" cells were mean-imputed to a moderate ~0.36 match instead of the
intended 1.0 penalty.

Keep NaN through the distance (ensure_all_finite="allow-nan") and make
_gower_distance_row skip a feature that is missing on either side, averaging over
the features actually present; a pair with no shared feature (e.g. a component
with no soil vs a pedon that has soil) becomes NaN, which the infill turns into
the max-dissimilarity penalty. With no missing data this reduces exactly to the
old formula, so complete-data distances — and their snapshots — are unchanged;
only missing-data pairs move. Affects both US and global (shared code).

Re-running the probe: the 245 no-soil cells now all yield NaN (0 masked). Adds
tests for the complete-data invariant, feature-skipping, and the all-missing->NaN
penalty path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Covers all four fixes on this branch: #378 (profile-list realignment), #375
(effective-bedrock shallow-soil scoring), and #377 (fixed gower ranges +
NaN-aware imputation). 29 snapshots updated (13 global, 16 US); changes are
value-only (component ordering/pairing, scores, depths) — verified deterministic
(a second run without --snapshot-update passes clean). US snapshots move because
the NaN-aware imputation is shared code.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Two latent bugs in us_soil.rank_soils:

1. #368-class array misalignment. The pedon property arrays (sand/clay/rfv/
   color) were built at length max_user_depth, but pedon_slice_index extends to
   depth 200 whenever bedrock is set — so p_hz_data.loc[i] raised KeyError once a
   slice index passed the deepest user horizon. Any bedrock input crashed the
   ranking. Fixed by depth-indexing into fixed-length 200 arrays (as the global
   path already does). Behaviorally inert when bedrock is None.

2. Slope compared categorically. pSlope arrives as a string, so the site Gower
   distance treated slope_r as a categorical exact-match feature instead of a
   scaled numeric difference. Coerce to float so slope contributes a proper
   numeric distance.

Regenerated the US test_us output snapshots (slope now numeric shifts most
site-influenced scores/ranks; raw API snapshots are unchanged).
In rank_soils (both paths) the soil-vs-non-soil depth matrix, the US site
distance matrix, and the final compname labels are built positionally from
mucompdata order (roughly location-score order), but the per-1cm-slice Gower
matrices are built from groupby(compname, sort=True) — a DIFFERENT order.
Positionally combining the two misapplied:
  - the per-depth no-soil mask (infill loop) — a shallow soil's "no soil
    below X cm" penalty landed on some other candidate, so shallow soils kept
    inflated horizon scores against deep user profiles;
  - the horizon-score -> compname mapping in the final assembly;
  - (US only) the D_site + D_horz sum, added in mismatched orders.

Fix: sort mucompdata by compname immediately after load so soil_matrix, the
site matrix, cokey_groups, and the final labels share one order and every
positional combine lines up.

Example (global, clay profile to 140 cm): a shallow Eutric Leptosol's horizon
score drops from 0.9325 (tied for best) to 0.1116, and its 40-125 cm band —
where the user has data but the soil is absent — is now penalized (dist ~0.90)
instead of masked. Regenerated US + global unit snapshots (determinism
verified). Needs bulk-accuracy before/after + scientist sign-off.
Where the pit and a candidate both have soil at a depth but share no comparable
property (e.g. the user recorded only color and the SSURGO component has only
texture), the per-slice Gower is NaN. The US infill's catch-all turned every
remaining NaN into 0, so that depth counted as a perfect match and inflated the
horizon score. The global path already leaves these NaN (masked). Match it: only
zero the NaN where NOT both sides have soil; leave both-soil NaN masked so the
weighted average excludes uninformative depths.

Tentative decision pending scientist sign-off (#389). Changes some US rankings
(candidates lose the spurious 0-credit at disjoint depths). Regenerated the US
explain-trace snapshot; test_us/test_global data has texture+color at every
depth so those snapshots are unaffected.

# Conflicts:
#	soil_id/tests/us/__snapshots__/test_explain_snapshot/test_explain_trace_snapshot.json
Adds a real semantic version so clients can detect algorithm changes and
flush cached soil-ID results:
- __version__.py 0.1 -> 2.1.0 (MAJOR=model gen 'v2'; MINOR bumped for the
  #375/#377/#378/#389 result fixes). Clients flush on MAJOR.MINOR change;
  PATCH never flushes.
- re-export __version__ from the package so consumers can read soil_id.__version__.
- derive the 'model' metadata from MAJOR (f'v{major}' = 'v2') so the legacy
  field stays in lockstep — no rank-output change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
render_soil_explain now takes either a URL or a file. A URL is normalized to
the trace form (force .json, add ?explain=true), fetched, rendered to a temp
.html, and opened in the browser. A file is rendered to stdout as before, but
a full site export ({"sites": [...]}) is auto-unwrapped to sites[0]'s
soilIdExplanation, so both a bare trace and a raw export "just work".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Base automatically changed from feat/soil-id-fixes to main September 25, 2026 18:42
@johannesparty
johannesparty merged commit 10004d9 into main Sep 25, 2026
9 checks passed
@johannesparty
johannesparty deleted the feat/soil-id-version branch September 25, 2026 18:47
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