Repository navigation
fix: global soil correctness — profile alignment (#378), shallow-soil scoring (#375), gower ranges + NaN-aware imputation (#377) - #380
johannesparty wants to merge 5 commits into
Conversation
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>
Bulk-accuracy validation (global, 2667 pedons) — paired before/afterRan the global bulk harness on
Movement: 91 improved · 140 worsened · 2436 unchanged, This is expected, not a regression. The net dip is the NaN-aware imputation fix (#377) removing scores that were inflated by the very bug it fixes, and it sometimes deflates a data-poor soil that happened to be the ground truth. Concrete example below. Worked example: pedon
|
| candidate | properties score (before → after) | rank (before → after) |
|---|---|---|
| Haplic Ferralsol (truth) | 0.788 → 0.346 | 1 → 9 |
| Podzol | 0.908 → 0.676 | 2 → 7 |
| Haplic Acrisol | 0.811 → 0.811 | 3 → 1 |
| Gleysol | 0.777 → 0.777 | 4 → 2 |
- Acrisol and Gleysol are byte-identical before/after — they have complete data through the pedon's depths, so the NaN-aware change is a no-op (this is the "complete-data unchanged" invariant, confirmed live).
- Ferralsol and Podzol dropped because their reference profiles lack real soil/data at some of the pedon's depths. Before, mean-imputation filled those gaps with "an average soil," inflating their properties scores to 0.788 / 0.908 (above the complete-data soils). After, those no-soil depths get the intended max-dissimilarity penalty, so the scores fall to realistic levels.
So Ferralsol's pre-fix rank #1 was itself a symptom of the imputation bug; the metric records "1 → 9 = worse," but #1 was a mirage.
The trade-off worth a domain call
Penalizing "no soil at a depth the pedon reached" is defensible, but it systematically deflates soils with thin/shallow reference profiles — and global HWSD references are often sparse, so this can push down true soils. Whether that's the right behavior for a pedon-vs-reference depth mismatch is a soil-science question; worth a soil scientist's sign-off before merge (handle to @-mention TBD). The threshold constant in #375 (LEPTOSOL_MAX_BEDROCK_CM = 50) is a related provisional call.
Also note
The single biggest "drop" (PK0027, Calcaric Cambisol 3→13) was not a real regression — after the fix a Calcaric Cambisols component ranks #1, but under the disambiguation suffix Calcaric cambisols2, which the scorer didn't match. Fixed in #379 (strip trailing dedup digit); it recovers such cases but doesn't materially change the aggregate.
Fixes three verified global-soil bugs (one shared with US). Each fix has a regression test; snapshots regenerated against the pinned CI DB image and verified deterministic. Paired bulk-accuracy validation to follow as a comment.
Fixes
#378 — profile lists mis-paired with components
list_soils_globalbuilt per-component profile lists in cokey order, then "reordered" positionally bymucompdata_cond_prob.index(an identity op afterreset_index), so each soil was shown a different component's profile. Symptom: a shallow Lithic Leptosol (soil to 20 cm) displayed with a deep soil's full 0–120 cm profile; property values mis-paired too. Fixed by keying the lists oncokey. (soilDepthwas already correct via acompnamemerge — that mismatch was the tell.)#375 — shallow soils forced to 0% when no bedrock given
The rule demoted leptosols/lithosols/rendzinas/rankers to 0.001 when
bedrock is None OR bedrock > 50. The client doesn't submit bedrock, soNonewas universal → these soils were always ~0%. Now derives an effective bedrock from the deepest observed user horizon (recording soil to depth D ⇒ rock below D) and demotes only when it exceedsLEPTOSOL_MAX_BEDROCK_CM(50, a named constant — provisional; a scientist may prefer ~30).#377 — rock-fragment/texture input caused counter-intuitive score swings
Two shared root causes:
theoretical_ranges(reused from the US path: sand 10–92, clay 5–70, rfv 0–80), flooring the denominator.SimpleImputer(strategy="mean")filled a candidate's missing property (or a depth with no soil) with "an average soil", so the soil-vs-non-soil infill (which only fires on NaN) never applied its penalty — measured at 245/245 (100%) of no-soil cells across 6 US locations.gower_distancesis now NaN-aware: it skips a feature missing on either side and averages over present features; a pair with no shared feature becomes NaN → the infill applies the max-dissimilarity penalty. With complete data it reduces exactly to the old formula, so complete-data distances are unchanged (only missing-data pairs move). This is shared code, so it affects US too.Tests
test_shallow_soil_profile_not_padded(Shallow soils (Leptosol) display a full 120 cm profile instead of truncating at the end of soil #378),test_shallow_soil_not_zeroed_without_bedrock(Soil ID Algorithm: certain shallow soils are always classified as 0% match #375)test_gower_distance.py: fixed-range damping (Rock fragment and texture input causes unpredictable / counter-intuitive score changes (global/HWSD) #377 pt1), complete-data-unchanged invariant, feature-skipping, all-missing→NaN penalty (Rock fragment and texture input causes unpredictable / counter-intuitive score changes (global/HWSD) #377 pt2)Snapshots
29 updated (13 global, 16 US), value-only, verified deterministic. US moves because the imputation fix is shared.
Validation
Paired before/after bulk-accuracy run (recall@k delta) in progress — results to follow as a comment. Uses the tooling in #379.
Fixes #378, #375, #377.
🤖 Generated with Claude Code