8000 feat: accept small ammonium and sodium amounts without a declared maximum by rafatahmed · Pull Request #396 · 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)
- 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)
- An incidental nutrient needs a declared maximum only for the part the products add: sodium or chloride that comes only from the water, or whose product share is under 1 %, no longer keeps a recipe under review (#383)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ A recipe used to get one word, `requires_review` or `blocked`, and `ready` was n

- A tank count, tank capacity, stock solubility or reagent volume that does not fit no longer blocks the recipe or makes `flahax batch` and `flahax mix` exit 3. The exit code follows the recipe status; the `Preparation:` line and `summary['matrix']['preparation']` carry the equipment result. The sheets list the quantities as diagnostic only (no tick boxes) when the preparation does not fit (#371).
- A pH plan that cannot be made (solver incomplete, no reagent offered, model out of range) is a model-basis review, not a block, in line with ADR 0001. A precipitation risk, a warning until now, makes chemical stability review.
- A declared maximum that is exceeded still blocks. A missed target and an incidental nutrient without a declared maximum still mean review (amended 2026-11-29: a miss inside a declared range is not a miss, and an incidental nutrient needs a maximum only for the part the products add, so an ion that comes only from the water needs none), so `ready` is uncommon on the shipped catalogue: it needs every target met, every incidental nutrient given a maximum, a planned pH and no precipitation risk.
- A declared maximum that is exceeded still blocks. A missed target and an incidental nutrient without a declared maximum still mean review (amended 2026-11-29: a miss inside a declared range is not a miss, and an incidental nutrient needs a maximum only for the part the products add, so an ion that comes only from the water needs none; amended again 2026-11-30: ammonium the products add up to the documented allowance and sodium up to 5 mg/L need none either, as assumptions printed on every output, so `ready` is reachable without typing a maximum), so `ready` is uncommon on the shipped catalogue: it needs every target met, every incidental nutrient given a maximum, a planned pH and no precipitation risk.
- The tank-separation caveat and the unvalidated delivery and physical behaviour are standing qualifications, reported with every result and never a reason for review. `ready` reads "calculation complete, not physically validated"; no safety or accuracy claim is made.
- Ion balance stays information only (G10). Evidence from the published papers (Steiner 1960, Sonneveld and Voogt 1994, Sonneveld, Voogt and Spaans 1999, Nancollas et al. 1976) is reference material, not a default trigger.
6 changes: 4 additions & 2 deletions docs/site/agronomist/reading-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ report prints them, and `summary.json` records them in `formulation.match_criter
| `--ph` | target feed pH | 5.8 |
| `--ratio` | final litres per litre of concentrate | 100 |
| `--acid` | `FORMULA:MASS_FRACTION:DENSITY[:NAME]` from your certificate, for example `HNO3:0.60:1.37`; repeat for more | none: acids are never assumed |
| `--limit` | a maximum in the final solution, `SYMBOL=MG_PER_L`, for example `Cl=106.35`; repeat for more | none: limits are never assumed, and undeclared ones are not checked |
| `--limit` | a maximum in the final solution, `SYMBOL=MG_PER_L`, for example `Cl=106.35`; repeat for more | none: limits are never assumed, and undeclared ones are not checked; the only exceptions are the two small amounts below |
| `--ammonium-allowance` | percent of the nitrogen target (at most 1.5 mmol/L) of ammonium that the products may add without a declared maximum | 10; `0` declines |
| `--trace-sodium` | mg/L of sodium that the products may add without a declared maximum | 5; `0` declines |
| `--max-reagent-litres` | largest pH reagent volume per batch | volume / 200 |
| `--ec` | requested EC25 in mS/cm, compared with the estimated range and never enforced | none |
| `--products` | JSON array of your own product records | the packaged catalogue |
Expand Down Expand Up @@ -92,7 +94,7 @@ sheet says "Preparation: does not fit" and names the need (for example a third t

| Status | Meaning |
|---|---|
| `ready` | Calculation complete, not physically validated: every target is met within tolerance or inside its declared range, every declared maximum holds, no incidental nutrient the products add lacks a declared maximum (an ion that comes only from the water needs none), there is no precipitation risk and the model covers the recipe. |
| `ready` | Calculation complete, not physically validated: every target is met within tolerance or inside its declared range, every declared maximum holds, no incidental nutrient the products add lacks a declared maximum (an ion that comes only from the water needs none, and ammonium up to the allowance and sodium up to a trace are accepted as stated assumptions, printed as "Assumed:" lines and never limiting the recipe), there is no precipitation risk and the model covers the recipe. |
| `requires_review` | Review required: a target is missed outside its range, with its reason, an incidental nutrient the products add has no declared maximum, the pH could not be planned, or a readily forming phase (brushite, gypsum, calcite) is above saturation, which labels the recipe "precipitation risk" (see [saturation indices](../developer/water-to-delivery.md#saturation-indices-and-acceptance)). |
| `blocked` | Not usable as planned: a declared maximum is exceeded on the laboratory analysis. The reason is given. A review never downgrades a block. A pH plan that cannot be made, or chemistry that cannot be calculated, is a model-basis review, not a block. |

Expand Down
4 changes: 3 additions & 1 deletion docs/site/developer/water-to-delivery.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ percentage. An explicit `maximum_concentrations={'N_NH4': 0}` does prohibit
ammonium. Without a declared maximum, incidental ammonium has no limit and is
reported for review; the optional allowance that `recommend` reports in `ammoniumLimit`
when `max_ammonium_fraction` selects it (min(10% of total N, 1.5 mmol/L), Dutch soilless
practice (De Kreij, Voogt et al.)) is not applied by default.
practice (De Kreij, Voogt et al.)) is not applied by default. The batch and mix commands use the same
amount differently: ammonium the products add up to it needs no declared maximum (the batch summary lists it in
`assumed_limits`), and it never limits the recipe.
The optimizer's existing objective is unchanged; maxima are post-solve checks,
not a new constrained optimization algorithm. A rejected recipe is not proof
that every alternative recipe is infeasible.
Expand Down
16 changes: 15 additions & 1 deletion docs/site/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ usage: flahax batch [-h] [--formula FORMULA | --crop CROP | --targets TARGETS |
--sonneveld-targets SONNEVELD_TARGETS] [--preview-targets] [--list-formulas]
[--water WATER] [--water-share PERCENT] [--volume VOLUME] [--ph PH]
[--ph-min PH_MIN] [--ph-max PH_MAX] [--range-percent RANGE_PERCENT]
[--ammonium-allowance AMMONIUM_ALLOWANCE] [--trace-sodium MG_PER_L]
[--range SYMBOL=SHORTAGE:EXCESS] [--require-ranges] [--ratio RATIO]
[--available-tanks AVAILABLE_TANKS] [--fit-equipment] [--tank-capacity LITRES]
[--ec EC] [--acid FORMULA:FRACTION:DENSITY[:NAME[:SOLVENT_FRACTION]]]
Expand Down Expand Up @@ -131,7 +132,11 @@ limit (#84).

Limits are never assumed: declare each maximum with ``--limit
Cl=106.35`` (mg/L in the final solution); unspecified limits are not
checked. The packaged pH products (KOH 45%, KHCO3, K2CO3, H3PO4 75%,
checked. Two small amounts of nutrients the products add are accepted
without a maximum, shown on the result as assumptions and never limiting
the recipe: ammonium up to the Dutch soilless allowance
(``--ammonium-allowance``) and sodium up to a trace (``--trace-sodium``).
The packaged pH products (KOH 45%, KHCO3, K2CO3, H3PO4 75%,
HNO3 65%) are always evaluated; pass your own acid's certificate values
with ``--acid``.

Expand All @@ -156,6 +161,15 @@ options:
--range-percent RANGE_PERCENT
acceptable deviation, in percent either side of every positive target
(default 10; 0 turns the range off)
--ammonium-allowance AMMONIUM_ALLOWANCE
ammonium the products add needs no declared maximum up to this percent of
the nitrogen target (at most 1.5 mmol/L), shown on the result as an
assumption (default 10; 0 declines, then ammonium needs a declared
maximum)
--trace-sodium MG_PER_L
sodium the products add needs no declared maximum up to this many mg/L,
shown on the result as an assumption (default 5; 0 declines, then sodium
needs a declared maximum)
--range SYMBOL=SHORTAGE:EXCESS
a nutrient's own range, each side as 5% or 3mg (mg/L), for example K=2%:5%
or Ca=:4mg; an empty side keeps --range-percent
Expand Down
1 change: 1 addition & 0 deletions docs/site/start/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Development checkout 0.7.2.dev0 (unreleased).
| Recipe status and preparation | `summary['status']` can now be `ready`, and `summary['matrix']` lists target fit, chemical stability and model basis with their findings. A tank count, tank capacity, stock solubility or reagent volume that does not fit no longer blocks the recipe, and `flahax batch` and `flahax mix` no longer exit 3 for it: read `summary['matrix']['preparation']` (`fits`, `not_verified`, `does_not_fit`). A pH plan that cannot be made is a model-basis review, not a block. `blocked` reads "not usable as planned". Recalculate saved recipes. | [Batch report](../agronomist/reading-results.md#what-the-files-say); tests.test_status_matrix |
| Defaults | A 10 % acceptable range applies to every positive target unless you give `--range-percent` (`0` turns it off), so a mix whose misses all sit inside it is no longer a target miss; the stock temperature for the solubility check is 20 °C (was 25 °C), matching the catalogue's 20 °C solubility values. The chemistry stays at 25 °C. Recalculate saved recipes. | Pass `range_percent=0` and `temperature_c=25` to reproduce 0.7.1; tests.test_default_range_and_temperature. |
| Grower depth | The grower sheet and the `flahax mix` result show what the solution will contain (target, achieved, difference) before the tanks, list only the reasons that change what the grower does (a blocked stage, a limit exceeded, a stock that does not dissolve, the matrix reasons) and count the other notes in one line; chemistry notes are at the agronomist depth. `grower_sheet.key_reasons(summary)` returns only those blocking warnings (the `n` argument is gone). | Read output 2 or 3 for every note; tests.test_grower_layout. |
| Accepted small amounts | 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 no longer need a declared maximum: a recipe that was `requires_review` only for these is now `ready`, and the result lists them in `assumed_limits` and in an "Assumed:" line on every output. They never change a recipe. Decline with `--ammonium-allowance 0` and `--trace-sodium 0` (`ammonium_allowance_percent=0`, `trace_sodium_mg_per_l=0` in `BatchOptions`); `recommend()` is unchanged. | Read `assumed_limits`; tests.test_acceptable_incidental. |
| One source for statuses | `statuses['formulation']`, `statuses['ph']`, the stage statuses and the warnings are now written from the same findings as the matrix, so a `ready` recipe has no stage under review and no "targets missed" warning; a review is listed once, in the matrix (the `formulation:` and `ph_adjustment:` warnings are gone). `statuses['formulation']` is `infeasible` only for a miss outside the range or a declared maximum, and `statuses['stock']` is `qualified` when the preparation fits. An ion that comes only from the water, or whose product share is under 1 %, no longer needs a declared maximum. | Read `matrix` for reasons; tests.test_status_consistency, tests.test_water_only_incidental. |
| Stock status | `summary['statuses']['stock']` is `does_not_fit` (was `blocked`) when the stock cannot be held or dissolved with the declared equipment. | Read `statuses['stock']` and `matrix.preparation` together; test for `does_not_fit`, not `blocked`. |

Expand Down
23 changes: 22 additions & 1 deletion src/flahax/batch_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@

Limits are never assumed: declare each maximum with ``--limit
Cl=106.35`` (mg/L in the final solution); unspecified limits are not
checked. The packaged pH products (KOH 45%, KHCO3, K2CO3, H3PO4 75%,
checked. Two small amounts of nutrients the products add are accepted
without a maximum, shown on the result as assumptions and never limiting
the recipe: ammonium up to the Dutch soilless allowance
(``--ammonium-allowance``) and sodium up to a trace (``--trace-sodium``).
The packaged pH products (KOH 45%, KHCO3, K2CO3, H3PO4 75%,
HNO3 65%) are always evaluated; pass your own acid's certificate values
with ``--acid``.
"""
Expand Down Expand Up @@ -147,6 +151,8 @@ def build(args):
ph_min=args.ph_min,
ph_max=args.ph_max,
range_percent=args.range_percent,
ammonium_allowance_percent=args.ammonium_allowance,
trace_sodium_mg_per_l=args.trace_sodium,
ranges=args.range,
require_ranges=args.require_ranges,
ratio=args.ratio,
Expand Down Expand Up @@ -232,6 +238,21 @@ def main(argv=None):
help='acceptable deviation, in percent either side of every positive target '
'(default 10; 0 turns the range off)',
)
parser.add_argument(
'--ammonium-allowance',
type=number_in('--ammonium-allowance', 0, 100, above=False),
help='ammonium the products add needs no declared maximum up to this percent of the '
'nitrogen target (at most 1.5 mmol/L), shown on the result as an assumption '
'(default 10; 0 declines, then ammonium needs a declared maximum)',
)
parser.add_argument(
'--trace-sodium',
type=number_in('--trace-sodium', 0, above=False),
metavar='MG_PER_L',
help='sodium the products add needs no declared maximum up to this many mg/L, shown '
'on the result as an assumption (default 5; 0 declines, then sodium needs a '
'declared maximum)',
)
parser.add_argument(
'--range',
action='append',
Expand Down
49 changes: 49 additions & 0 deletions src/flahax/batch_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from .engine import load_library
from .fertilizer_workflow import plan_fertilizer_workflow
from .inputs import number, read_json
from .nitrogen import ammonium_allowance_preset
from .nutrient_acceptance import TRACE_SODIUM_MG_PER_L
from .ph_adjustment import REAGENTS
from .ph_adjustment import catalogue_ph_reagents, nutrient_salts
from .result_wording import reagent_preparation
Expand Down Expand Up @@ -142,6 +144,10 @@ class BatchOptions:
mode: str = 'fill'
irrigation_litres: float | None = None
temperature_c: float = 20
# Ammonium and sodium the products add need no declared maximum up to these amounts
# (None selects the default; 0 declines).
ammonium_allowance_percent: float | None = None
trace_sodium_mg_per_l: float | None = None
depth: int = 3
title: str | None = None
max_solid_reagent_grams: float | None = None
Expand Down Expand Up @@ -319,6 +325,48 @@ def parse_range(text):


DEFAULT_RANGE_PERCENT = 10.0
DEFAULT_AMMONIUM_ALLOWANCE_PERCENT = 10.0


def _incidental_amounts(options, targets):
"""The amounts of ammonium and sodium the products may add without a
declared maximum: the ammonium allowance (Dutch soilless practice) and a
trace of sodium. They decide whether a maximum is asked for; they never
limit the fit.
"""
percent = (
DEFAULT_AMMONIUM_ALLOWANCE_PERCENT
if options.ammonium_allowance_percent is None
else options.ammonium_allowance_percent
)
trace = (
TRACE_SODIUM_MG_PER_L
if options.trace_sodium_mg_per_l is None
else options.trace_sodium_mg_per_l
)
for name, value, high in (('ammonium allowance', percent, 100), ('trace sodium', trace, None)):
if (
isinstance(value, bool)
or not isinstance(value, (int, float))
or not math.isfinite(value)
):
raise DeliveryError('invalid_value', f'{name} must be a number')
if value < 0 or (high is not None and value > high):
raise DeliveryError('invalid_value', f'{name} is out of range')
amounts = {}
if trace:
amounts['Na'] = dict(mgPerL=float(trace), basis='a trace amount')
if percent:
record = ammonium_allowance_preset(targets, percent / 100)
if record:
amounts['N_NH4'] = dict(
mgPerL=record['mgPerL'],
basis=(
f'the ammonium allowance ({percent:g} % of the nitrogen target, at most '
'1.5 mmol/L; Dutch soilless practice)'
),
)
return amounts


def _deviation_ranges(options):
Expand Down Expand Up @@ -484,6 +532,7 @@ def run_batch(options):
available_tanks=options.available_tanks,
tank_capacities_litres=options.tank_capacities,
requested_ec_ms_cm=options.ec,
incidental_amounts=_incidental_amounts(options, targets),
)
if target_design is not None:
summary['sonneveld_target_design'] = target_design
Expand Down
Loading
0