8000 fix: chemistry without unassurable gates (G1-G5, G8, G10, G11) by rafatahmed · Pull Request #219 · 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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ each release, with numbers, sources and decisions, are in

- The packaged catalogue is Flaha Agri Tech Analysis Ver 0.0: 24 fertilizers, 5 pH products and 13 crop formulas.

- A product label is reconciled with its compound, not refused: the charge its ions cannot
balance is reported ("label analysis differs from KNO₃: 1.91 % K not assigned to an ion") and
left out of the chemistry, while the nutrient fit keeps the label (G5, #214).

- The pH needs no completeness declaration. A water without `HCO3` or alkalinity shows "measure
alkalinity (HCO3) of the water"; ionic strength above 0.1 mol/kg shows "not calculated"; the
recipe is produced in both cases. Closed carbon, 25 °C and 1 L = 1 kg water are stated in the
summary. `calculate_equilibrium_ph` drops `complete_analysis` and takes `residual_charge`
(G1–G4, #215).

- A water analysis is taken as measured: its charge imbalance is reported and carried, and no
ion is added, removed or adjusted. Removed: the 5 % rejection, closing on Cl, Na or carbonate
(carbon from a titrated alkalinity stays), `balance_ion` water-file keys, the 0.1 % charge
gates of the acid and delivery planners, and the formula-imbalance flag (G10, G11, #216).

### Fixed

- Normalize POSIX mode-inspection/setup/restoration failures and attempt rollback
Expand Down
45 changes: 45 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# FlahaX

FlahaX plans one batch of hydroponic nutrient solution: one crop formula and one water give one recipe, plus the acid or base that sets the pH.

## Language

**Formula**:
A crop's target nutrient concentrations (mg/L).
_Avoid_: Nutrient solution, program, mix

**Recipe**:
The product weights chosen to meet a formula from a given water.
_Avoid_: Blend, result, plan

**Catalogue**:
The packaged products and formulas.
_Avoid_: Library, database

**pH reagent**:
A catalogue product used only to move pH.
_Avoid_: Acid, base, adjuster

**Label reconciliation**:
The charge a product label's ions cannot balance, reported and not refused.
_Avoid_: Label check, identity check, charge gate

**Ammonium allowance**:
The incidental NH₄-N, capped at 10 % of total N and 1.5 mmol/L, permitted when no NH₄ target is declared.
_Avoid_: Ammonium ban, zero ammonium

**Precipitation risk**:
A warning label from a phase whose constant is measured and which is known to form readily.
_Avoid_: Saturation block, precipitation gate

**EC range**:
The low–high conductivity estimate, with no midpoint.
_Avoid_: EC value, mean EC, estimated EC

**Stated model condition**:
A limit reported with the result, such as closed carbon, 25 °C or 1 L of solution taken as 1 kg of water.
_Avoid_: Declaration, assumption to confirm

**Tank A / Tank B**:
The two stock tanks: calcium and micronutrients in A, the sulfates and phosphates in B.
_Avoid_: Part A / Part B, Stock 1 / Stock 2
16 changes: 16 additions & 0 deletions docs/adr/0001-model-limits-are-reported-not-enforced.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Model limits are reported, never enforced as gates

Date: 2026-11-05 (decisions G1–G25 approved 2026-10-29)

FlahaX removes every gate that rests on a number or a condition nobody can guarantee: the 1 % and 0.1 % product charge limits, "EC not supported" above ionic strength 0.014, any positive saturation index blocking a recipe, stock "floors" that can never pass, the 5 % water imbalance rejection, and the zero-ammonium ban. Chemistry stays: it is computed from measured constants and declared analyses. Where the model reaches a limit, the limit is stated with the result (a stated model condition, an EC range, a precipitation risk label, a "needs input" status), and the nutrient recipe is still produced. Only a broken declared maximum blocks.

## Considered options

- **Keep the gates:** rejected. They made normal recipes fail, such as the potassium nitrate 13-0-46 label against pure KNO₃, and their thresholds had no source that could be defended.
- **Replace each gate with a new threshold:** rejected. A new number would be another unassurable value.

## Consequences

- A recipe can carry warnings and deviations; the grower reads them and decides. Reports must always show them.
- No new threshold, assumption, invented ion or midpoint may be introduced to restore a gate.
- Tests that asserted a refusal are rewritten to assert the report; no assertion is weakened.
2 changes: 1 addition & 1 deletion docs/publication/example/qatar_tomato.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def workflow(water, salts, label):
return plan_fertilizer_workflow(
salts, targets(), ppm(water.analytical_totals), TARGET_PH, final_volume=VolumeLitres(1000),
equilibrium=dict(water_balance=water, water_mass_kg=1000, water_analysis_id=label,
complete_analysis=True, carbon_boundary='closed', temperature_c=25, phases=[]))
carbon_boundary='closed', temperature_c=25, phases=[]))


def main():
Expand Down
3 changes: 3 additions & 0 deletions docs/releases/0.7.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

The full text of every change in 0.7.0, as recorded when each was merged, newest first. The [changelog](../../CHANGELOG.md) groups them into a short summary. 0.7.0 is not yet released.

- A product label is reconciled with its compound instead of refused (decision G5, #214). `flahax.label_reconciliation` takes the charge the declared ions of the compound cannot balance from the excess side's declared nutrients in proportion to their charge contribution and reports it as `unassigned_percent`; chemistry uses the label minus that amount and the nutrient fit keeps the label. A label that leaves a charged ion unstated (a chelate's sodium, a carbonate) or states one side only (an acid, urea, KOH) is closed by that ion, so nothing is unassigned. A blend has no defined compound and keeps its label, with the note "has no defined compound: its label analysis is used as declared". Potassium nitrate at N 13.0 and K 38.2 leaves about 1.91 % K unassigned. The 1 % label charge gate (`materials._CHARGE_RESIDUAL_LIMIT_PERCENT`), the grade-range exclusion test and the `identity_inconsistent` refusals in `mix_cli` and `fertilizer_workflow` are removed; a label naming a nutrient the compound's ions do not carry is still refused.
- The pH needs no declaration (decisions G1–G4, #215). `calculate_equilibrium_ph(totals, *, phases, temperature_c=25.0, carbon_boundary='closed', residual_charge=0.0)` no longer takes `complete_analysis` and solves to the net charge `residual_charge` (eq/kg water) instead of zero. In the workflow, a water with neither an `HCO3` key nor a measured alkalinity gives the chemistry and pH stages `needs_input` with the message "measure alkalinity (HCO3) of the water"; an ionic strength above 0.1 mol/kg gives `not_calculated` with "ionic strength above 0.1 mol/kg: outside the activity model's range"; `HCO3: 0` is a measured zero and is calculated. The recipe is produced in all three cases. The summary lists the stated model conditions: closed carbon, 25 °C only, and 1 L of solution taken as 1 kg of water.
- A water analysis is taken as measured (decisions G10 and G11, #216). `balance_water_analysis` no longer rejects an imbalance (the 5 % limit and `charge_imbalance_exceeded`), no longer closes on Cl-, Na+ or an adjusted carbonate (`balance_ion`, `maximum_imbalance_percent`, `balance_ion_uncertainty_percent` and `fixed` are removed, as are `missing_balance_ion`, `fixed_balance_ion`, `reconciliation_out_of_bounds` and `closed_on_alkalinity`), and returns `imbalance_percent` and `residual_charge_eq`, which the pH solves, the pH-adjustment planner and the joint problem's reference charge carry. Carbon taken from a titrated alkalinity stays, because it comes from a measurement. `calculate_ec_from_totals` takes `residual_charge_eq_per_kgw` for its calculated-pH mode, and a reagent search that leaves the activity model's range gives the pH-adjustment stage `not_calculated`. A water file with `balance_ion` or `balance_ion_uncertainty_percent` is refused with `unknown_field`. The 0.1 % initial-charge gates of the acid-option and delivery planners (`charge_imbalance`) are removed because their doses are found from charge differences. The formula-imbalance flag `exceedsWarning` and `ION_BALANCE_WARNING_PCT` are removed; `recommend` states the imbalance as "The formula's declared ions are not balanced: cations {c} vs anions {a} meq/L ({p} %)." and never claims no salt combination meets the targets.
- A target is met only within the numerical tolerance (decision G25, validated 2026-10-24): 1e-5 relative for a positive target, 1e-6 mg/L for a declared zero, 1e-4 pH units, in the new module `flahax.requirement_fit` (`met`, `RELATIVE_TOLERANCE`, `ZERO_TARGET_TOLERANCE_MG_PER_L`, `PH_TOLERANCE`) (#210). It replaces the ±1 % band (`engine.TOLERANCE_PCT`, removed) in `feasible`, in the short-target recovery, in the target-only diagnosis and in `unmetTargets`. `feasible` is every declared requirement met and no declared maximum exceeded. Every deviation is reported: in `plan_fertilizer_workflow` the formulation stage blocks (`infeasible_recipe`) only on a broken declared maximum; a missed target makes it `requires_review` with "targets missed: …" (each difference to three significant figures in fixed notation, for example +1400 %, before any incidental-nutrient review), and the batch, titration, nitric, acid and stock stages continue (`FinalSolutionRecipe.feasible` is true unless a declared maximum is broken). A deviation the formulation stage accepts never blocks a later stage, and `plan_equilibrium_delivery` plans an accepted empty recipe on the water alone (it formerly required a nonempty recipe): the titration, nitric (`plan_equilibrium_delivery`) and acid-selection (`plan_acid_options`) stages judge only the change their reagent makes. `maximum_nutrient_error_percent` is now optional with no default, and every stage rejects a declared value that is not finite and positive (`invalid_value`; the nitric adapter formerly accepted 0) (the titration stage formerly defaulted to 1 %, and each stage compared the whole deviation from the target); when given, it is a declared requirement on the reagent's own change to each positive target, measured from the recipe before the reagent, and a stage fails with `nutrient_tolerance_exceeded` only when that change exceeds it, or with `nutrient_limit_exceeded` when the reagent pushes a nutrient past a declared maximum. A declared zero is met within 1e-6 mg/L everywhere: in `limitViolations`, `requirementConflicts`, `unmetTargets` and on the sheets (5e-7 mg/L of urea from the water meets an absent or zero N_UREA; 2e-6 mg/L breaks it and blocks). The pH plan and the joint workflow use `PH_TOLERANCE` (1e-4) in place of the former 1e-3 in `ph_adjustment`; no tested pH result changed. A feed whose mixed pH is within 1e-4 of the target now reads "no pH reagent is needed" when no plan is selected, instead of asking for a base (#212). Because a target 0.0056 % short is now short, recovery admits a held-back product that is its only source: for Lettuce 2 (Howard Resh) on the packaged catalogue sodium molybdate replaces Micro Combi Mix 1 for Mo, which is then met exactly, sodium falls from 0.814 to 0.442 mg/L, and P finishes at 49.8384 mg/L for 50 (-0.323 %), a deviation the former band counted as met. The batch and mix sheets mark in red each target not met within the tolerance (formerly beyond 1 %), and the recovery warning reads "… stayed short of its target without it" (formerly "more than 1% short").
- N_NO3, N_NH4 and N_UREA are each their own fitted target (decision D1); total N is reported in `totalN` (target, final, difference, `fitted: false`) as the sum of the three forms and never fitted (#209, #201). An absent N_UREA is a declared zero, and urea-bearing products are not used unless the formula declares urea. N_NH4 absent or 0 is no ammonium requirement: no row and no ban (G24), so calcium nitrate stays usable. The ammonium the products bring is then held within min(10 % of total target N, 1.5 mmol/L NH4 = 21.01 mg/L N) (G23), with the basis "Dutch soilless practice (De Kreij, Voogt et al.)", reported in `ammoniumLimit` and shown on the batch summary, the report and the batch and mix sheets; a declared N_NH4 maximum replaces it and `max_ammonium_fraction=None` removes it. `solve_weights`, the coupled pH plan and the joint problem use the same nitrogen rows and allowance, and total N is recomputed after a pH reagent. For Cucumber (Howard Resh), N_NO3 140 and N_NH4 0, the allowance is 14 mg/L.
- The packaged catalogue is Flaha Agri Tech Analysis Ver 0.0 (Flaha Agri Tech, 2026-10-29; supplied by Flaha Agri Tech, not independent laboratory verification) (#206). `library.json` holds 29 products, 24 fertilizers and 5 pH products, 13 crop formulas and the 3 waters it held before. Every product carries the analysis review record (`analysisReview`), and the library records the analysis as a whole in `fertilizerAnalysis`. The pH products, all `role: ph_reagent` and never selected as nutrient salts, are Potassium Hydroxide (45% solution), Phosphoric Acid (75%), Nitric Acid (65% solution), Potassium Bicarbonate and Potassium Carbonate; `catalogue_ph_reagents()` returns all five, so `flahax batch` and `flahax mix` now evaluate the two packaged acids beside any acid given with `--acid`. New products: Nitric Acid (65% solution), Micro Combi Mix 1 and Micro Combi Mix 2. Removed products: Ammonium Dibasic Phosphate, Calcium Chloride (Dihydrate), CH - micro (kept as a retired reference in `retiredProductReferences`), Potassium Chloride, Potassium Citrate and Potassium Dibasic Phosphate; the packaged catalogue has no chloride product. Removed formulas: Chilli (maximumyield), Generic Bloom (maximumyield), Generic Dry Season (Howard Resh), Generic Grow (maximumyield), Generic Wet Season (Howard Resh), Generic for Berries (Growing Edge), Rice (Douglas Peckenpaugh) and Tropical Lettuce (Douglas Peckenpaugh). The catalogue Potassium Nitrate analysis is 2.57 % out of charge balance against KNO3, above the 1 % label limit, so chemistry stages that include it stop with `identity_inconsistent`; that limit is under review. NOTICE and the attribution test credit Flaha Agri Tech for the analysis.
Expand Down
22 changes: 10 additions & 12 deletions docs/site/agronomist/batch-command.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ and `Mo`.
- **Bicarbonate is required with a measured pH.** Write `"HCO3": 0` only if
the laboratory found none.

FlahaX checks the analysis at its measured pH. If the charges already balance
it is used as it is. If they are slightly off (up to 5 %), FlahaX closes the gap
on chloride for its chemistry only. Your measured values are still what every
target and limit is checked against, and the report shows both side by side. A
gap above 5 % is refused: ask the laboratory to check the analysis.
FlahaX uses the analysis as measured, at its measured pH. If the charges do not
balance, the imbalance is shown in the report and carried through the pH
calculation; no ion is added, removed or adjusted, and no imbalance size refuses
the analysis. Every target and limit is checked against your measured values.
Without `HCO3` (or an alkalinity) the pH shows "measure alkalinity (HCO3) of the
water", and the recipe is still produced.

**Blending with RO or desalinated water.** Add `--water-share 8` in step 3 to
use your analysed water as 8 % of the batch water and ion-free water for the
Expand Down Expand Up @@ -196,13 +197,10 @@ FlahaX 0.6.0 reported the following figures:
phase applicability now blocks approval:
- **Ammonium.** The recipe carries 9.2 mg/L NH4-N, a nutrient you did not
target and gave no maximum for. Check it, or declare a maximum.
- **The well analysis is 3.5 % out of charge balance.** For the chemistry,
FlahaX closed it on chloride (−9.5 %). That step is a modelling assumption,
not a measurement, so the pH and precipitation results need your judgement.
Your limits were still checked on the measured 1280.4 mg/L. State the
laboratory's chloride uncertainty in the water file
(`"balance_ion_uncertainty_percent"`) and FlahaX will accept the closure if
it falls within it.
- **The well analysis is 3.5 % out of charge balance.** FlahaX used it as
measured: the imbalance is reported and carried through the pH calculation,
and no ion (chloride or any other) is added, removed or adjusted. Your limits
were checked on the measured 1280.4 mg/L.
- **Hydroxylapatite and MnHPO4 are supersaturated.** Their names do not prove that
precipitation is absent at these conditions. Without applicable reviewed evidence,
the phase assessment prevents approval. The sheet retains the findings ([saturation
Expand Down
16 changes: 9 additions & 7 deletions docs/site/agronomist/formula-and-products.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,15 @@ maximum is not an assay.

Selection follows the table, per nutrient. Other flags:

- `identity_inconsistent`: the grade's charge residual exceeds 0.1 %, or its
range excludes the identity's theory. The range test is skipped for
`aqueous_solution` and `chelate_salt_defined` identities, whose theory is
the pure compound rather than the product as sold (a 75 % phosphoric acid
at P2O5 54.0–54.6 % or an Fe-EDTA at Fe 12.8–13.2 % is not flagged); the
charge-residual test still applies to them. Chemistry stages then apply the
existing assay-residual rule; nothing is rejected silently.
- A label that differs from its compound's proportions is not flagged. A label
states guaranteed minimums, not exact stoichiometry: chemistry uses the
compound in the amount its limiting declared nutrient supplies, and every
other declared nutrient's surplus is reported as not assigned to an ion
(potassium nitrate at 13.0 % N and 38.2 % K: "label analysis differs from
KNO₃: 1.91 % K not assigned to an ion"). The nutrient fit keeps the label.
The grade's charge residual is recorded as information. A product without a
defined compound (a blend such as Micro Combi Mix 2) keeps its label as
declared.
- `lot_outside_grade_range`: a lot measured outside the grade's minimum or
maximum, with no uncertainty stated. The certificate value is used and the
band end is widened to include it (grade N-NO3 13.5–13.9 % with a lot at
Expand Down
7 changes: 3 additions & 4 deletions docs/site/agronomist/reading-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ aerated water. One litre of water is taken as one kilogram.
A value of 0 is a measured zero and stays zero (`"Cl": 0` for chloride-free
water, `"HCO3": 0` for carbon-free water); an omitted ion is not measured.
Optional keys: `"below_detection": {"Mn": 0.01}` (detection limits in mg/L;
taken as zero, never adjusted), `"balance_ion": "Cl"` or `"Na"`, and
`"balance_ion_uncertainty_percent": 10`, the stated uncertainty of that ion.
taken as zero, never adjusted).

Targets and `--limit` maximums use these laboratory values. For the chemistry
only (pH, saturation, EC, reagent dose) the analysis is speciated at its
Expand Down Expand Up @@ -147,8 +146,8 @@ nitric = dict(id='my-nitric', name='Nitric acid 60%', source='supplier certifica
recordedAt='2026-10-22T00:00:00Z', chemicalFormula='HNO3', massFraction=.60, densityKgPerL=1.37)
workflow = plan_fertilizer_workflow(
products, targets, {}, 5.8, final_volume=VolumeLitres(1000),
equilibrium=dict(water_totals={}, water_mass_kg=1000, water_analysis_id='RO', complete_analysis=True,
carbon_boundary='closed', temperature_c=25, phases=[]),
equilibrium=dict(water_totals={}, water_mass_kg=1000, water_analysis_id='RO',
temperature_c=25, phases=[]),
ph_adjustment=dict(products=[nitric] + catalogue_ph_reagents(), maximum_reagent_volume_litres=5))
summary = summarize_batch(workflow, products, title='Tomato', water_label='RO water')
from pathlib import Path
Expand Down
6 changes: 3 additions & 3 deletions docs/site/developer/python-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,11 +268,11 @@ from flahax import balance_water_analysis
# Fully specified synthetic electrolyte; not a site prescription.
analysis_totals = {"Na+": 0.002, "Cl-": 0.002, "CO3-2": 0.0}
balanced = balance_water_analysis(analysis_totals, measured_ph=7.8)
print(balanced.imbalance_percent, balanced.balance_ion, balanced.balance_adjustment_molal)
print(balanced.imbalance_percent, balanced.residual_charge_eq)
```

The remaining charge is closed on `Cl-` (or `Na+`) and reported. An imbalance
above 5% is rejected. Titrated alkalinity can replace inorganic carbon via
The analysis is taken as measured: its charge imbalance is reported and carried
as `residual_charge_eq`, and no ion is added or adjusted to close it. Titrated alkalinity can replace inorganic carbon via
`alkalinity_eq_per_kg`. In `plan_fertilizer_workflow`, add `measured_ph` to the
`equilibrium` record. See the user manual, section 11, and
[water-to-delivery](water-to-delivery.md#measured-ph-water-balancing).
Expand Down
Loading
Loading
0