8000 feat: bound phosphate beyond its fit at its limiting conductivity, narrowing the EC range by rafatahmed · Pull Request #400 · rafatahmed/Flahax · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Development checkout: 0.7.2.dev0. Default recipes and statuses can differ from 0
- When the preparation does not fit, the grower sheet, batch sheet, report and command line list the quantities as diagnostic only, with no tick boxes; the recipe status and exit code are unchanged (#371).
- A 10 % acceptable range applies by default (`--range-percent 0` turns it off) and the stock temperature for the solubility check is 20 °C (was 25 °C), so more mixes are `ready` and catalogue solubility values at 20 °C can be checked; the chemistry stays at 25 °C (#380)
- Every output names a target miss the same way (outside the declared range) and is written in plain figures: the full report says "Targets met: Yes" for a recipe inside its range, the agronomist table and the full-screen view show no signed zero, the EC uncertainty and uncovered species are sentences instead of Python data, and a reason is listed once per page (#387, #388)
- The EC range is narrower: phosphate beyond the ionic strength of its fit is bounded at its own limiting conductivity (36 and 57 per charge) instead of 80, which cuts every packaged formula's range by 41 to 46 % (cucumber 2.243 to 2.325 mS/cm, was 2.389); the species without a coefficient keep the 80 bound, and the developer page says why (#392)
- Ammonium the products add up to the allowance (10 % of the nitrogen target, at most 1.5 mmol/L) and sodium up to 5 mg/L need no declared maximum, so a recipe that was review only for these is ready; they are listed as assumptions on every output, never change a recipe, and can be declined (`--ammonium-allowance 0`, `--trace-sodium 0`) (#395)
- The grower sheet and the `flahax mix` result are one clean page: status and its reasons, what the solution will contain (target against achieved), the tanks, the reagent and the checks; chemistry notes (ion balance, assay differences, saturation, model limits) are counted in one line and listed at the agronomist depth (#385)
- Statuses, stage messages and warnings are written from the same findings as the status matrix, so a `ready` recipe no longer lists a stage under review or a "targets missed" warning, and a review reason appears once; `statuses['stock']` is `qualified` when the preparation fits (#382)
Expand Down
22 changes: 20 additions & 2 deletions docs/site/developer/conductivity.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,9 @@ applied.

**The range.** `low` is the sum over the species with a coefficient. `high`
is `low` plus `|z| x 80 x m` for each species without one (`LAMBDA_MAX_PER_CHARGE = 80.0`, the
assumed molar conductivity per charge), for each H2PO4- or HPO4-2 beyond the fit
ionic strength, and for the charge a supplied pH leaves unbalanced
assumed molar conductivity per charge), plus `|z| x limit x m` for each H2PO4- or HPO4-2 beyond
the fit ionic strength (`PHOSPHATE_LIMITING_PER_CHARGE`: 36 and 57 per charge, their
limiting conductivities), and for the charge a supplied pH leaves unbalanced
(`unrecorded_counterions_eq_per_kgw`). `ec25_ms_cm` is `low` only when `low == high`;
otherwise it is `None`. There is no midpoint in any output. `known_species_subtotal_ms_cm` is
`low`, `bounded` is true and `uncovered_bound_ms_cm` is `high - low`; the audit carries
Expand All @@ -177,6 +178,23 @@ dispositions this factor as an explicit model assumption, not a proven physical
bound. Species-specific coefficients require separate source, unit and domain
qualification before adoption; no coefficient is changed here.

**What sets the width of the range.** On the 13 packaged formulas (reverse-osmosis water, 10,000 L,
1:100, pH 5.8) the range is 2.5 to 6.0 % of the EC. Most of the width came from phosphate, not
from the species without a coefficient. Phosphate has a fitted coefficient, but the recipes' ionic
strength (0.0155 to 0.0349 mol/kg) is above the fit's limit (0.0140), so H2PO4- and HPO4-2
are bounded; they set 77 to 87 % of the width. The bound was 80 per charge, the sulfate value;
it is now their own limiting conductivity, an upper limit at any ionic strength (CRC Handbook of
Chemistry and Physics, "Ionic Conductivity and Diffusion at Infinite Dilution"). That narrowed every
packaged formula's range by 41 to 46 %; for the packaged cucumber from 2.243 to 2.389 down
to 2.243 to 2.325 mS/cm.

The rest stays bounded at 80 per charge, for a stated reason: ion pairs (MgH2PO4+, NH4SO4-, CaNO3+,
CaH2PO4+ and the like) and the EDTA complexes have no measured conductivity in any source the
model uses, and together they add 0.02 to 0.08 mS/cm to a range. A coefficient estimated without
a measurement would make the range look tighter than the evidence allows. The low end still counts
no phosphate at all, so a measured EC is expected nearer the high end of a range than the low one.
Narrowing the range further needs measured phosphate conductivity above ionic strength 0.014.

Assay charge residual: it is reported in `assay_charge_residual` (the percent over the
declared-form absolute equivalents for catalogue and plan inputs, over the speciated absolute
equivalents for raw totals) and never changes the status. A calculated pH carries the water's
Expand Down
16 changes: 14 additions & 2 deletions src/flahax/irrigation_ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ def poly(c):
# without a coefficient, phosphate beyond its fit domain and charge the
# recorded ions do not carry.
LAMBDA_MAX_PER_CHARGE = 80.0
# Phosphate beyond its fit domain keeps its own, tighter bound: at finite ionic strength an
# ion conducts no more than at infinite dilution. Limiting conductivity per charge at 25 C,
# same units: H2PO4- 36 and HPO4-2 114 / 2 = 57 (CRC Handbook of Chemistry and Physics,
# "Ionic Conductivity and Diffusion at Infinite Dilution"; the same table gives sulfate,
# 80.0 per charge, which is where LAMBDA_MAX_PER_CHARGE comes from).
PHOSPHATE_LIMITING_PER_CHARGE = {'H2PO4-': 36.0, 'HPO4-2': 57.0}
_CORE_AUDIT_KEYS = frozenset(
(
'temperature_reference_c',
Expand Down Expand Up @@ -416,7 +422,12 @@ def _ec_from_state(
if ph_mode == 'supplied' and abs(excess) > max(1e-12, 0.001 * equivalents):
unrecorded = excess
low = float_sum(contributions.values())
bound = float_sum(LAMBDA_MAX_PER_CHARGE * abs(s['charge']) * s['molal'] for s in missing)
bound = float_sum(
PHOSPHATE_LIMITING_PER_CHARGE.get(s['name'], LAMBDA_MAX_PER_CHARGE)
* abs(s['charge'])
* s['molal']
for s in missing
)
if unrecorded is not None:
bound += LAMBDA_MAX_PER_CHARGE * abs(unrecorded)
status, reason = ('range', None) if bound > 0 else ('estimated', None)
Expand All @@ -427,7 +438,8 @@ def _ec_from_state(
)
if outside_fit:
warnings += (
'Phosphate conductivity is beyond its recorded fit domain; those species are bounded.',
'Phosphate conductivity is beyond its recorded fit domain; those species are bounded '
'at their limiting conductivity.',
)
if unrecorded is not None:
warnings += ('Charge the recorded ions do not carry is bounded the same way.',)
Expand Down
27 changes: 27 additions & 0 deletions tests/test_ec_fit_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from flahax.calculated_ph import calculate_equilibrium_ph
from flahax.delivery_contracts import DeliveryError
from flahax.irrigation_ec import (
LAMBDA_MAX_PER_CHARGE,
_ec_from_state,
calculate_ec_from_totals,
ionic_molal_conductivity,
Expand Down Expand Up @@ -65,6 +66,32 @@ def test_public_out_of_fit_is_a_range_and_the_covered_ions_still_count(self):
)
self.assertTrue(result.warnings)

def test_phosphate_beyond_its_fit_is_bounded_at_its_limiting_conductivity(self):
# CRC Handbook, ionic conductivity at infinite dilution, 25 C: H2PO4- 36 and
# 1/2 HPO4-2 57 per charge. An ion conducts no more than that at finite ionic strength;
# everything else without a coefficient keeps the 80 per charge bound (#392).
limit = {'H2PO4-': 36.0, 'HPO4-2': 57.0}
result = calculate_ec_from_totals(
{'Na+': 0.02, 'PO4-3': 0.02},
solution_id='outside',
ph_mode='calculated',
phase_policy='dissolved',
)
self.assertEqual(result.status, 'range')
phosphate = {m['name'] for m in result.missing_species} & set(limit)
self.assertEqual(phosphate, set(limit))
expected = sum(
limit.get(m['name'], LAMBDA_MAX_PER_CHARGE) * abs(m['charge']) * m['molal']
for m in result.missing_species
)
self.assertAlmostEqual(result.uncovered_bound_ms_cm, expected, places=12)
at_80 = sum(
LAMBDA_MAX_PER_CHARGE * abs(m['charge']) * m['molal'] for m in result.missing_species
)
self.assertLess(result.uncovered_bound_ms_cm, at_80)
warnings = result.warnings
self.assertTrue(any('limiting conductivity' in w for w in warnings), warnings)

def test_state_boundary_and_reporting_cutoff(self):
state = calculate_equilibrium_ph(
{'K+': 0.001, 'PO4-3': 0.001},
Expand Down
6 changes: 5 additions & 1 deletion tests/test_irrigation_ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from flahax.irrigation_ec import (
COEFFICIENTS_SHA256,
LAMBDA_MAX_PER_CHARGE,
PHOSPHATE_LIMITING_PER_CHARGE,
QUALIFIER,
DeclaredPureWater,
assay_charge_residual,
Expand Down Expand Up @@ -298,7 +299,10 @@ def test_unrecorded_counterions_are_bounded_too(self): # Review Focus 1
self.assertIsNone(r.uncertainty_ms_cm)
low, high = r.ec25_range_ms_cm
floor = sum(
LAMBDA_MAX_PER_CHARGE * abs(s['charge']) * s['molal'] for s in r.missing_species
PHOSPHATE_LIMITING_PER_CHARGE.get(s['name'], LAMBDA_MAX_PER_CHARGE)
* abs(s['charge'])
* s['molal']
for s in r.missing_species
) + LAMBDA_MAX_PER_CHARGE * abs(r.unrecorded_counterions_eq_per_kgw)
self.assertAlmostEqual(high - low, floor, places=12)
self.assertTrue(r.missing_species)
Expand Down
10 changes: 5 additions & 5 deletions tests/test_sonneveld_appendix_i.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def test_fixed_bicarbonate_equivalent_dose(self):
self.assertLess(max(abs(totals[k] / v - 1) for k, v in COLUMN_D.items()), 0.001)
self.assertAlmostEqual(chemistry.ph, 4.5097, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[0], 2.0794, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.1874, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.13561, places=4)

def test_ph_target_original_inventory_is_a_near_fit(self):
# Dose from the retained-carbon pH 5.5 replay with this product
Expand All @@ -186,7 +186,7 @@ def test_ph_target_original_inventory_is_a_near_fit(self):
self.assertAlmostEqual(totals['K'], 8.84854, places=4)
self.assertAlmostEqual(totals['Na'] * ATOMIC_MASS['Na'], 0.71268, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[0], 2.07118, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.18113, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.12984, places=4)

def test_ph_target_with_sodium_nitrate_discloses_sodium(self):
acid = 1.8317694626
Expand All @@ -203,7 +203,7 @@ def test_ph_target_with_sodium_nitrate_discloses_sodium(self):
)
self.assertAlmostEqual(dose, 29.640, places=3)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[0], 2.09162, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.20175, places=4)
self.assertAlmostEqual(chemistry.ec25_range_ms_cm[1], 2.15036, places=4)
# Illustrative 1 mg/L sodium ceiling, not a crop recommendation.
limits = assess_incidental(fit['rows'], {'Na': 1.0})
self.assertEqual([row['symbol'] for row in limits['limitViolations']], ['Na'])
Expand Down Expand Up @@ -311,7 +311,7 @@ def test_batch_workflow_finds_acid_for_ph_5_5(self):
self.assertEqual(chemistry.status, 'range')
low, high = chemistry.ec25_range_ms_cm
self.assertAlmostEqual(low, 2.0916, delta=0.002)
self.assertAlmostEqual(high, 2.2017, delta=0.002)
self.assertAlmostEqual(high, 2.1504, delta=0.002)
for key, target in COLUMN_D.items():
self.assertAlmostEqual(totals[key], target, delta=target * 0.001, msg=key)

Expand Down Expand Up @@ -434,7 +434,7 @@ def test_rounded_copper_stock_preserves_sodium_nitrate_free_feed(self):
self.assertEqual(chemistry.status, 'range')
low, high = chemistry.ec25_range_ms_cm
self.assertAlmostEqual(low, 2.092, delta=0.002)
self.assertAlmostEqual(high, 2.202, delta=0.002)
self.assertAlmostEqual(high, 2.1503, delta=0.002)

def test_batch_verifies_rounded_copper_stock_without_sodium_nitrate(self):
from flahax.report_html import render_batch_sheet, render_report
Expand Down
0