Repository navigation
feat: expose soil-id semver as soil_id.__version__ (Section 6) - #394
Merged
Merged
Conversation
garobrik
approved these changes
Sep 25, 2026
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>
johannesparty
force-pushed
the
feat/soil-id-version
branch
from
September 25, 2026 18:19
c07a432 to
dff2072
Compare
johannesparty
force-pushed
the
feat/soil-id-fixes
branch
from
September 25, 2026 18:19
6f1c4a4 to
2a7edb6
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Foundation of the Section 6 stack (auto-flush the mobile soil-ID match cache when the algorithm changes). Stacked on #393.
What
soil_id/__version__.py:0.1→2.1.0— real semver. MAJOR = model generation ("v2"⇒ 2); MINOR bumped for the Soil ID Algorithm: certain shallow soils are always classified as 0% match #375/Rock fragment and texture input causes unpredictable / counter-intuitive score changes (global/HWSD) #377/Shallow soils (Leptosol) display a full 120 cm profile instead of truncating at the end of soil #378/US horizon: disjoint-property depths scored 0 (match) instead of masked #389 result fixes on fix(soil-id): global + US correctness fixes (on top of explain) #393. Clients flush cached matches on MAJOR.MINOR change; PATCH never flushes.__version__from the package so consumers can readsoil_id.__version__.modelmetadata from MAJOR (f"v{major}"="v2") so the legacy field stays in lockstep — no rank-output change (snapshots unaffected).Verify
PATTERN=test_version make test_unit→ 3 pass; a US snapshot test still passes (metadatamodelstill"v2").Notes
Downstream consumes this via terraso-backend (
soilId.soilIdAlgorithmVersion) → client-shared → mobile. Docs: terraso-wiki cross-repo-versioning update.🤖 Generated with Claude Code