8000 Field-test fixes for flahax mix; main becomes 0.6.0.dev0 (#98, #99) by rafatahmed · Pull Request #101 · 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 @@ -2,6 +2,7 @@

## Unreleased

- Field test of `flahax mix` (2026-10-23): fix what a first session ran into. The formula step listed nothing and Enter looped on 'This one is needed.' (#98): Enter now lists every formula (and every chemical in step 4) to choose by number, a miss says how to see the list, and the step says the fertilizers come in step 4. A blocked plan said 'do not mix' while showing unrelated notes, because the ph_adjustment and formulation blocks carried no message: they now say why ("the feed mixes at pH 6.90 and needs an acid to reach pH 5.80; none was offered: add an acid", each candidate's reason, a declared maximum broken, or the targets missed by more than 1 %), and that reason comes first. The terminal no longer points to a report.html it did not write; small batches show their volume (0.01 L, not 0 L); a water analysis that fails the 5 % screen can be corrected one value at a time instead of retyped; the engine says 'None of the available products supplies B' instead of 'No salt in this library'. A water report without measured chloride keeps the #84 rule (closed on chloride, never another ion) and now says what to do (#100, owner decision 2026-10-23): `flahax mix` notes at entry that chloride is not measured, and the balancing errors end with 'Ask your lab for chloride and sodium'. `main` now carries 0.6.0.dev0 (#99), so installing from GitHub with `--upgrade` replaces an installed 0.5.0; the publishing procedure opens the next development version after each release, and CITATION.cff keeps the released version.
- Package sourced stock solubility for 20 products (owner approval 2026-10-23), so `flahax mix` and `flahax batch` check that each concentrate dissolves at the entered temperature. Values are the CRC Handbook aqueous solubility table (18 products, 0-40 °C), Yara's CALCINIT sheet for calcium nitrate (ag grade; its 20 °C value is a floor from 20 to 40 °C, not checked below 20 °C) and the U.S. Coast Guard CHRIS compilation for urea, converted to grams of product as sold per litre at a density of 1 g/cm3: a lower bound, so a stock that would not dissolve is never passed. The six chelates, CH - micro and potassium citrate have no sourced data and stay `not_checked`. Checks remain single-salt in pure water, with no safety margin.
- Accept correctly printed supplier labels (#93, owner decision 2026-10-23). A label's charge balance against its chemical may now differ by up to 1 % (was 0.1 %): printed values are rounded and commercial grades are not the pure salt, so Yara's YaraLiva Calcinit label (N-NO3 14.4 %, N-NH4 1.1 %, CaO 26.3 %; -0.56 %) was refused. A one-point typing error (Ca 19.8 % for 18.8 %) moves the balance by about 2 % and is still refused. One limit now serves supplier grades and materials defined by formula or ions. An old magnesium nitrate analysis (N 11.0 %, Mg 9.65 %; 0.55 %) is no longer flagged.
- Open FlahaX to growers and agronomists with `flahax mix`, an interactive five-step entry (specification, water analysis, crop formula, fertilizers available, pH requirement) that saves waters, formulas, product stores, acids and sessions under `$FLAHAX_HOME` (default `~/.flahax`) in the formats `flahax batch` reads, and writes a batch sheet at the chosen depth: grower (tank A and tank B cards with prepared litres and grams, the acid container, checks after mixing), agronomist (adds the nutrient table: target, from water, required, achieved, final, difference; limits; pH path) or developer and manager (adds the full report). Lab reports are typed in their own units (mg/L, meq/L, mmol/L, alkalinity as CaCO3, micronutrients in mg/L or µmol/L); Enter is not measured, 0 a measured zero, `<DL` below detection; missing alkalinity is flagged at entry. Stock volumes follow the fill mode: fill the tanks full (the smallest container sets the irrigation volume) or make one irrigation (`stock_volumes.prepare_stocks`, `tank_too_small`). Two concentrate tanks (owner decision 2026-10-22): magnesium sulfate shares tank B with the phosphates, a waiver of Yara p. 65 listed on the report; a compound containing phosphate goes to tank B; more than two tanks is refused (`too_many_tanks`). Supplier label grades enter the chemistry and pH stages (graded id `<catalogue id>+<grade_id>`; an inconsistent label is `identity_inconsistent`), and compounds are declared from their data sheet (`declared_ions`: nitrogen forms, oxides, micronutrients, chelating agent, optional Na and Cl; checked by implied protons per phosphate between HPO4 2- and H2PO4-; one flag per unstated ion; their chelate sodium counted in the Na row); a product that cannot be modelled is formulated but gets no pH plan (`ph_not_planned_for_product`). Stock solubility is checked per product at the entered temperature from sourced data (`stock_solubility.check_stock_solubility`); no data is packaged yet, so every product shows not checked until the owner approves the sourced table. The review reasons on every output now quote the recipe that is weighed (#91).
Expand Down
8 changes: 8 additions & 0 deletions docs/publishing.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ pushing a tag.
6. After upload: check PyPI metadata, install `flahax==<version>` in a fresh
environment, run the manual's examples and both CLI entry points, and
record the date, run URL and hashes in [release evidence](site/evidence/release-evidence.md).
7. **Open the next development version** (#99): on a short branch, set
`pyproject.toml`, `flahax.__version__`, the manual's title and the API
reference to `<next>.dev0` (for example 0.6.0.dev0 after 0.5.0), and leave
`CITATION.cff` at the released version. A development version sorts after
the release and before the next one, so
`pip install --upgrade "git+https://github.com/rafatahmed/Flahax.git@main"`
replaces an installed release; with the released number on `main`, pip
keeps the old package.

**Old tags run old workflows.** For a Release event, GitHub runs
`publish.yml` as it exists at the tagged commit. Tags before `v0.4.0` carry the
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "flahax"
version = "0.5.0"
version = "0.6.0.dev0"
description = "Plant-nutrient chemistry engine: fertilizer formulation, aqueous equil 10BC8 ibrium chemistry and auditable delivery planning."
readme = "README.md"
requires-python = ">=3.11"
Expand Down
2 changes: 1 addition & 1 deletion src/flahax/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
"transition_plan",
"validate_delivery_request",
]
__version__ = "0.5.0"
__version__ = "0.6.0.dev0"
from .equilibrium_delivery import EquilibriumPhPlan, plan_equilibrium_delivery
__all__ += ["EquilibriumPhPlan", "plan_equilibrium_delivery"]
__all__ += ["AqueousResult", "AcidResult", "catalogue_dose_totals", "plan_catalogue_nitric_target"]
Expand Down
2 changes: 1 addition & 1 deletion src/flahax/data/API_REFERENCE.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/flahax/data/USER_GUIDE.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# FlahaX 0.5.0 — User Manual
# FlahaX 0.6.0.dev0 — User Manual

Fertilizer formulation • bounded chemistry • reviewed delivery planning

Expand Down
2 changes: 1 addition & 1 deletion src/flahax/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ def _recover(library, ready, excluded, targets, short):
_supplies(salt, symbol) for salt in library if assay_conflict(salt) is None
)
if not supplied:
warnings.append(f"No salt in this library supplies {symbol}.")
warnings.append(f"None of the available products supplies {symbol}.")
continue
already = any(_supplies(item, symbol) for item in ready)
for salt in holders:
Expand Down
34 changes: 30 additions & 4 deletions src/flahax/fertilizer_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,28 @@ def unreviewed_reason(recommendation):
+ '; check them, or declare maximum concentrations') if found else None


def limit_message(recommendation):
"""Why a recipe is not feasible, in plain words: a declared maximum it breaks, else the targets it misses by >1 %."""
broken = [f'{v["symbol"]} would be {v["ppm"]:.3g} mg/L, above the declared maximum {v["maximumPpm"]:.3g} mg/L'
for v in recommendation['limitViolations']]
if broken:
return '; '.join(broken)
missed = [f'{r["symbol"]} {r["deltaPct"]:+.1f} %' for r in recommendation['rows']
if r['target'] and r['deltaPct'] is not None and abs(r['deltaPct']) > 1]
return ('targets missed by more than 1 %: ' + ', '.join(missed)) if missed else 'no recipe meets the targets'


def no_reagent_message(plan):
"""Why no pH reagent was selected: none offered in the needed direction, or the reasons each one failed."""
need = 'an acid' if plan.direction == 'acid' else 'a base'
tried = [c for c in plan.candidates if c.direction == plan.direction and c.status != 'not_applicable']
if not tried:
return (f'the feed mixes at pH {plan.unadjusted_ph:.2f} and needs {need} to reach pH {plan.target_ph:.2f}; '
f'none was offered: add {need}')
return f'no {plan.direction} reaches pH {plan.target_ph:.2f} acceptably: ' + '; '.join(
f'{(c.product_record or {}).get("name") or c.product_id}: {c.message or c.error_code or c.status}' for c in tried)


def _water_ppm(totals, mass, volume):
return nutrient_mg_per_litre(totals, mass, volume)

Expand Down Expand Up @@ -180,7 +202,8 @@ def missing(name, config, required):
return bool(absent)

stages['formulation'] = WorkflowStage('calculated' if recommendation['feasible'] else 'blocked',
value=recommendation, error_code=None if recommendation['feasible'] else 'infeasible_recipe')
value=recommendation, error_code=None if recommendation['feasible'] else 'infeasible_recipe',
message=None if recommendation['feasible'] else limit_message(recommendation))
if recommendation['feasible'] and recommendation['requiresReview']:
stages['formulation'].status = 'requires_review'
stages['formulation'].message = unreviewed_reason(recommendation)
Expand Down Expand Up @@ -316,7 +339,8 @@ def chemical_states():
if recipe is None:
stages['titration'] = WorkflowStage('needs_input', required_inputs=('final_volume',))
elif not recommendation['feasible']:
stages['titration'] = WorkflowStage('blocked', error_code='infeasible_recipe')
stages['titration'] = WorkflowStage('blocked', error_code='infeasible_recipe',
message=limit_message(recommendation))
else:
def titration_plan():
if not isinstance(titration['water_analysis'], Mapping):
Expand Down Expand Up @@ -346,7 +370,8 @@ def titration_plan():
elif stages['chemistry'].status not in USABLE:
stages['acid_selection'] = WorkflowStage('blocked', error_code='chemistry_required')
elif not recommendation['feasible']:
stages['acid_selection'] = WorkflowStage('blocked', error_code='infeasible_recipe')
stages['acid_selection'] = WorkflowStage('blocked', error_code='infeasible_recipe',
message=limit_message(recommendation))
else:
state = stages['chemistry'].value['mixed']
selection = run('acid_selection', lambda: plan_acid_options(
Expand Down Expand Up @@ -392,7 +417,8 @@ def mix(candidate):
if plan is not None:
chosen = plan.selected
if chosen is None:
stages['ph_adjustment'] = WorkflowStage('blocked', value=plan, error_code='no_acceptable_reagent')
stages['ph_adjustment'] = WorkflowStage('blocked', value=plan, error_code='no_acceptable_reagent',
message=no_reagent_message(plan))
elif assess_incidental(chosen.recommendation['rows'],
assessed_limits(maximum_concentrations, chosen.recommendation))['limitViolations']:
# Final acceptance on the laboratory basis: a hard limit is never downgraded to review.
Expand Down
11 changes: 8 additions & 3 deletions src/flahax/grower_sheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
"""


def litres(value):
"""A volume a grower can measure: one decimal from 10 L, three below (never '0 L' for a small batch)."""
return number(value, 1 if value >= 10 else 3)


def key_reasons(summary, n=3):
"""The warnings a grower must read, blocking ones first (a blocked stage, a hard limit, a stock that won't dissolve)."""
stopped = tuple(f'{name}:' for name, s in summary['stages'].items() if s['status'] == 'blocked')
Expand Down Expand Up @@ -45,8 +50,8 @@ def _grams(product):

def _tank_card(tank, volumes, blocked):
name = tank['name']
head = (f'prepare <b>{number(volumes["prepared_litres"][name], 1)} L</b> in your '
f'{number(volumes["capacity_litres"][name], 1)} L tank') if volumes else ''
head = (f'prepare <b>{litres(volumes["prepared_litres"][name])} L</b> in your '
f'{litres(volumes["capacity_litres"][name])} L tank') if volumes else ''
box = '<span class="muted">-</span>' if blocked else '<span class="tick"></span>'
rows = ''.join(f'<tr><td>{box}</td><td>{text(p["name"])}</td><td class="num">{_grams(p)}</td></tr>'
for p in tank['products'])
Expand All @@ -63,7 +68,7 @@ def _reagent_card(summary, volumes):
title = 'Acid' if chosen['direction'] == 'acid' else 'pH reagent'
per_1000 = chosen['volume_ml_per_batch'] * 1000.0 / summary['batch_litres']
container = (f'<p>Acid container: add <b>{number(chosen["volume_ml_per_batch"], 1)} mL</b> to water and make up to '
f'<b>{number(volumes["prepared_litres"]["acid"], 1)} L</b>.</p>') if volumes else ''
f'<b>{litres(volumes["prepared_litres"]["acid"])} L</b>.</p>') if volumes else ''
return (f'<div class="card"><h2>{title}</h2><p><b>{text(chosen["product"])}</b> ({text(chosen["formula"])}): '
f'{number(per_1000, 1)} mL per 1,000 L of irrigation, on its own injector.</p>{container}'
'<p class="small"><b>Add acid to water, never water to acid.</b></p></div>')
Expand Down
10 changes: 7 additions & 3 deletions src/flahax/measured_water.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
'H3BO3': 'B', 'MoO4-2': 'Mo', 'Ure': 'N_UREA'}


ASK_LAB = ('Ask your lab for chloride and sodium: FlahaX closes the analysis at its measured pH on chloride, '
'so chloride must be measured and above zero.')


def nutrient_mg_per_litre(totals, water_mass_kg=1., final_volume_litres=1.):
"""Elemental mg/L in the final volume from water totals in mol/kg water."""
ppm = {}
Expand Down Expand Up @@ -284,16 +288,16 @@ def balance_water_analysis(totals, *, measured_ph, alkalinity_eq_per_kg=None, ba
raise DeliveryError('fixed_balance_ion',
f'the analysis is {imbalance:.2f}% out of balance and {balance_ion} is held fixed '
'(measured zero, below detection or named fixed); chemistry needs review or a further '
'analysis. No other ion is adjusted automatically.')
f'analysis. No other ion is adjusted automatically. {ASK_LAB}')
if analysed <= 0:
raise DeliveryError('missing_balance_ion', f'{balance_ion} must be present in the analysis to balance on it')
raise DeliveryError('missing_balance_ion', f'{balance_ion} must be present in the analysis to balance on it. {ASK_LAB}')
charge = BALANCE_IONS[balance_ion]
for _ in range(100):
if abs(state.charge_balance) <= 1e-12:
break
working[balance_ion] -= state.charge_balance / charge
if working[balance_ion] <= 0:
raise DeliveryError('balance_ion_exhausted', f'{balance_ion} cannot absorb the charge imbalance')
raise DeliveryError('balance_ion_exhausted', f'{balance_ion} cannot absorb the charge imbalance. {ASK_LAB}')
if carbon_source == 'alkalinity':
working['CO3-2'] = _carbon_for_alkalinity(working, measured_ph, alkalinity_eq_per_kg, phases)
state = solve(working, measured_ph, phases=phases, start=state)
Expand Down
Loading
Loading
0