8000 feat: declared equipment, equipment-aware search, unverified solubility and saved inputs (D3-D7, C6) by rafatahmed · Pull Request #298 · 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,21 @@ Development checkout: 0.7.1.dev0.
### Added

- Total nitrogen (`N`, mg/L as N) is a target alone or with nitrogen forms. Alone it imposes no form split; with all three forms it must agree with their sum; with some forms both are scored and `totalN.overlapForms` lists the overlap (#291).
- `flahax batch` takes `--available-tanks` and `--tank-capacity`; the report lists the tanks the recipe needs against yours, and a tank too small for its stock blocks without changing the recipe (#293).
- `--fit-equipment` and `available_product_search(on_equipment_miss=True)` search other products for a recipe that fits the declared tanks; tanks and separation rules never change, and the mode and equipment are saved in `remedies` (#294).
- A saved result keeps `supplied_inputs`, bound to its input fingerprint, and `saved_input_differences` names what a recalculation changed (#297).

### Changed

- An absent or zero `N_NH4` target is no requirement and no maximum. The ammonium allowance is now an opt-in preset (`max_ammonium_fraction`), so default recipes may use ammonium nitrate and report NH4-N for review (#290).
- Products sharing an exact name are rejected as `ambiguous_product_name` before dose resolution (#288).
- `plan_stocks` no longer raises `missing_solubility_limit`: with no limit at the temperature it keeps the quantities, lists the product in `StockPlan.unverified` and approves nothing (#295).

### Fixed

- Coupled recipes are assessed at the emitted reagent dose, and search provenance survives dose reassessment (#288).
- Each solubility row states that it is a single-product value and whether its temperature is verified; a value rec 8000 orded at another temperature is flagged, not silently accepted (#295).
- The glossary defines stock assignment, required and available tanks, equipment fit and single-product solubility (#296).
- The README troubleshooting row cites the error codes the CLI emits (#287).
- Catalogue lookups, the sensitivity matrix and cold-solve memory no longer make the full test suite take about an hour (#289).

Expand Down
24 changes: 24 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,30 @@ The usual nutrient stock channels, with calcium and micronutrients in A and sulf
phosphates in B. Actual layouts depend on separation constraints, equipment and mixture evidence.
_Avoid_: Part A / Part B, Stock 1 / Stock 2

**Stock assignment**:
The grouping of a recipe's products into concentrate tanks so that no separation rule is broken, found without any
mixture approval. It uses the fewest tanks and does not depend on how many tanks the grower has.
_Avoid_: Tank grouping, Tank assignment, Separation assignment

**Required tanks**:
The number of tanks the stock assignment needs (`tanks.required_tanks`), set by the separation rules alone.
_Avoid_: Tank count, Tanks needed

**Available tanks**:
The tanks the grower declares (`--available-tanks`, `tanks.available_tanks`). When none are declared two are assumed
and the summary says so (`available_tanks_declared` false).
_Avoid_: Tank count, Owned tanks

**Equipment fit**:
Whether the available tanks, and their declared capacities, hold the required tanks' stock (`tanks.equipment.fit`).
A mismatch is reported and blocks; the recipe and the equipment are never changed to make it fit.
_Avoid_: Tank check, Capacity gate

**Single-product solubility**:
A product's own recorded solubility compared with its stock concentration. It is never mixed-stock approval, and its
qualification lists what stays unverified: the mixture, and the temperature when the value was recorded at another one.
_Avoid_: Solubility check, Mixture solubility

**Sonneveld target design**:
The A–D calculation from a crop/system baseline, explicit nutrient corrections and irrigation
EC to finished-feed targets.
Expand Down
10 changes: 10 additions & 0 deletions docs/site/agronomist/batch-command.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,16 @@ flahax batch --formula "Tomato (Howard Resh)" --water well.json --water-share 8
both product lists.
- `--volume` sets the batch size (default 1000 L), `--ph` the target pH
(default 5.8) and `--ratio` the injection ratio (default 1:100).
- `--available-tanks` states how many concentrate tanks you have and `--tank-capacity`
(repeated once per tank, in litres) their sizes. The recipe does not change with the
equipment: the report shows the tanks the recipe needs, whether yours are enough, and
any tank too small for its stock. Without these options two tanks are assumed and the
summary says the equipment was not declared.
- `--fit-equipment`, with `--alternative-products`, searches those products for a recipe that
fits your declared tanks when the first recipe does not. Your tanks, injection ratio and the
separation rules are never changed, nothing is searched without the flag, and the summary
records the search mode and the equipment it was held to (`remedies.mode`,
`remedies.declared_equipment`).

All options are listed in [batch report, sheet and tanks](reading-results.md).

Expand Down
8 changes: 8 additions & 0 deletions docs/site/agronomist/solubility-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ labelled so (it is slightly higher than a "g/L solution" value). Where a source
no volume basis the row says "volume basis unspecified by source". `mixture_approved` is
always `False`.

Each row's `qualification` states what the verdict does not establish: `scope` is
`single_product`, `temperature_matched` is true only when the value's source temperature
equals the tank temperature (null when the source states none), and `unverified` lists
`temperature` when it does not match and always `mixture`. A mismatch never changes the
check or the doses: the value is used as recorded, not extrapolated, and the batch
warnings name each product and its source temperature as "not verified at" the tank
temperature.

When a table gives several temperatures, the point nearest the tank temperature is used
(the lower one on a tie). The table values are grams of product per litre of solution at
an assumed density of 1 g/mL, and the row says so.
Expand Down
9 changes: 7 additions & 2 deletions docs/site/agronomist/tanks-and-solubility.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ its required evidence, alternative search and the downstream validation gate.

## Required evidence

Every salt in the recipe needs a sourced solubility-limit record that covers the requested temperature:
Every salt in the recipe should have a sourced solubility-limit record that covers the requested temperature:

```text
productId
Expand All @@ -55,11 +55,16 @@ Every incompatibility must be an explicit `separate` compatibility-rule record.
The planner rejects:

- an infeasible nutrient recipe;
- a missing or temperature-out-of-range solubility limit;
- a required concentration above its limit;
- a tank smaller than required stock volume; and
- an assignment that violates all available separation constraints.

A salt with no limit that covers the requested temperature does not stop the plan. Its stock
concentration and tank assignment are kept, the plan stays `requires_review`, nothing is approved,
and `StockPlan.unverified` lists it as `{salt_id, aspect: 'solubility_limit',
requested_temperature_c, recorded_ranges_c}`; the recorded ranges are empty when the product has
no record at all. Only a limit that is known and exceeded raises `solubility_exceeded`.

## Deterministic assignment

The planner evaluates valid tank assignments in tank-ID order and chooses one that uses the fewest tanks. It prefers the first model-qualified assignment at that minimum; without a qualified model, a structural layout remains under review. This is an explainable constraint solution, not a chemical equilibrium calculation.
Expand Down
25 changes: 25 additions & 0 deletions docs/site/developer/water-to-delivery.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,21 @@ Inspect `resolved_requirements`, `introduced_requirements` and
`remaining_requirements`, plus the immutable candidate `snapshot` and
`calculation_id`. These results do not imply delivery or physical approval.

**Equipment-aware search.** `available_product_search(products, on_equipment_miss=True)`
also runs when the declared equipment cannot hold the recipe: the stocks stage failed
with an error such as `too_many_tanks`, `tank_too_small` or `solubility_exceeded`, which
adds the requirement `equipment:fit`. Every candidate keeps the declared tanks, injection
ratio, temperature and separation rules; only the products change, and a candidate that
fits lists `equipment:fit` in `resolved_requirements`. Without the option nothing is
searched. `workflow.remedies.mode` records `analyze_supplied_doses` when no scenario was
evaluated and `find_suitable_doses` when one was, and `declared_equipment` records the
tanks (id and litres), injection ratio, temperature and the number of rules and limits,
so a saved result shows the equipment the search was held to. A caller that judges equipment
itself, as `flahax batch` does in its report, passes `equipment_check` to
`plan_fertilizer_workflow`: a callable that takes the workflow and returns None when the recipe
fits or `{error_code, message}`; an object with a `declaration` attribute has that record saved
as `declared_equipment` and, in the saved inputs, as `equipment_declaration`.

The search covers only the supplied scenarios and product bundles. It does not
combine separate options automatically, enumerate the whole market, prove a
minimum-cost equipment solution or select a manufacturer model. Budget skips and
Expand Down Expand Up @@ -445,6 +460,16 @@ returns a detached payload. `Store.save('results', name, archive)` and
result. Historical results preserve their historical source identities; rendering
is not recalculation against the current engine.

The summary keeps `supplied_inputs`: the targets, water, volume, pH, limits, equipment and
every product record with its assay, exactly as supplied. `calculation_identity.input_sha256`
is the hash of that object, and `load_result` rejects a saved result whose inputs no longer
match it. Results saved before this field existed still load, but carry no inputs.
`saved_input_differences(saved, recalculated)` (from `flahax.result_acceptance`) lists each
input path that differs between two results as `{path, saved, recalculated}`, so a
recalculation with changes names what changed; it needs both results to carry their inputs.
The equipment the stock check used and its defaults are in `tanks`, and the search mode and
declared equipment are in `remedies`.

New saved mix sessions retain their answer fields and add `saved_state` with
`schema_version=1`, `inputs_sha256`, named-item `references` fingerprints and
package `sources` fingerprints. Execution rejects changed answers, referenced
Expand Down
9 changes: 8 additions & 1 deletion docs/site/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ The same from files in one command, for scripts.
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]
[--ratio RATIO] [--ec EC]
[--ratio RATIO] [--available-tanks AVAILABLE_TANKS] [--fit-equipment]
[--tank-capacity LITRES] [--ec EC]
[--acid FORMULA:FRACTION:DENSITY[:NAME[:SOLVENT_FRACTION]]]
[--limit SYMBOL=MG_PER_L] [--max-reagent-litres MAX_REAGENT_LITRES]
[--volumetric-stocks VOLUMETRIC_STOCKS]
Expand Down Expand Up @@ -149,6 +150,12 @@ options:
--volume VOLUME final batch litres (default 1000)
--ph PH target feed pH (default 5.8)
--ratio RATIO final litres per litre of concentrate (default 100)
--available-tanks AVAILABLE_TANKS
concentrate tanks you have (default: two assumed, and the report says so)
--fit-equipment when the recipe does not fit your tanks, search --alternative-products for
one that does (your equipment and the separation rules are never changed)
--tank-capacity LITRES
capacity of a tank in litres; repeat once per tank, in tank order
--ec EC requested EC25 in mS/cm, compared with the estimated range (never
enforced)
--acid FORMULA:FRACTION:DENSITY[:NAME[:SOLVENT_FRACTION]]
Expand Down
64 changes: 63 additions & 1 deletion src/flahax/batch_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from .engine import load_library
from .fertilizer_workflow import plan_fertilizer_workflow
from .grower_report import (
EquipmentCheck,
reagent_amount,
reagent_preparation,
render_batch_sheet,
Expand Down Expand Up @@ -114,6 +115,21 @@ def read_json(path, what):
) from None


def int_at_least(name, low):
"""An argparse type: a whole number of at least ``low``."""

def parse(text):
try:
value = int(text)
except ValueError:
raise argparse.ArgumentTypeError(f'{name} {text!r} is not a whole number') from None
if value < low:
raise argparse.ArgumentTypeError(f'{name} must be at least {low}, not {text}')
return value

return parse


def number_in(name, low, high=None, *, above=True):
"""An argparse type: a finite number above ``low`` (or at least,
with ``above=False``) and at most ``high``.
Expand Down Expand Up @@ -471,6 +487,9 @@ class BatchOptions:
products: str | None = None
rules: str | None = None
tank_litres: dict | None = None
available_tanks: int | None = None
tank_capacities: list | None = None
fit_equipment: bool = False
mode: str = 'fill'
irrigation_litres: float | None = None
temperature_c: float = 25
Expand Down Expand Up @@ -694,6 +713,23 @@ def run_batch(options):
if options.alternative_products is not None
else []
)
if options.fit_equipment and not alternative_products:
raise DeliveryError(
'invalid_value', '--fit-equipment searches the --alternative-products; supply them'
)
equipment_check = (
EquipmentCheck(
products,
rules=rules,
injection_ratio=options.ratio,
temperature_c=options.temperature_c,
available_tanks=options.available_tanks,
tank_capacities_litres=options.tank_capacities,
batch_litres=volume,
)
if options.fit_equipment
else None
)
if alternative_products:
from .evaluated_remedies import available_product_search

Expand All @@ -707,7 +743,9 @@ def run_batch(options):
remedies.insert(
0,
available_product_search(
alternative_products, preferences=options.alternative_search_preferences
alternative_products,
preferences=options.alternative_search_preferences,
on_equipment_miss=options.fit_equipment,
),
)
additional_ids = [*options.confirmed_products, *(p['id'] for p in alternative_products)]
Expand Down Expand Up @@ -741,6 +779,7 @@ def run_batch(options):
else None
),
remedy_options=remedies,
equipment_check=equipment_check,
max_remedy_evaluations=len(options.confirmed_products)
+ (options.alternative_search_budget if alternative_products else 0),
)
Expand All @@ -752,6 +791,8 @@ def run_batch(options):
injection_ratio=options.ratio,
rules=rules,
temperature_c=options.temperature_c,
available_tanks=options.available_tanks,
tank_capacities_litres=options.tank_capacities,
requested_ec_ms_cm=options.ec,
)
if target_design is not None:
Expand Down Expand Up @@ -849,6 +890,9 @@ def build(args):
products=args.products,
reagents=args.reagents,
rules=args.rules,
available_tanks=args.available_tanks,
tank_capacities=args.tank_capacity,
fit_equipment=args.fit_equipment,
)
)
return render(summary), summary
Expand Down Expand Up @@ -903,6 +947,24 @@ def main(argv=None):
default=100,
help='final litres per litre of concentrate (default 100)',
)
parser.add_argument(
'--available-tanks',
type=int_at_least('--available-tanks', 1),
help='concentrate tanks you have (default: two assumed, and the report says so)',
)
parser.add_argument(
'--fit-equipment',
action='store_true',
help='when the recipe does not fit your tanks, search --alternative-products for '
'one that does (your equipment and the separation rules are never changed)',
)
parser.add_argument(
'--tank-capacity',
action='append',
type=number_in('--tank-capacity', 0),
metavar='LITRES',
help='capacity of a tank in litres; repeat once per tank, in tank order',
)
parser.add_argument(
'--ec',
type=number_in('--ec', 0),
Expand Down
1 change: 1 addition & 0 deletions src/flahax/canonical_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ def result_statuses(summary):
ec=(summary.get('ec') or {}).get('status', 'not_assessed'),
stock='blocked'
if stocks['required_tanks'] > stocks['available_tanks']
or any(not row['fits'] for row in stocks.get('equipment', {}).get('fit', ()))
or any(row['status'] == 'exceeds' for row in summary['solubility'])
else 'requires_review',
delivery='not_validated',
Expand Down
Loading
0