8000 refactor: gather the nitrogen rules in nitrogen.py and break the remedies cycle by rafatahmed · Pull Request #326 · 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 @@ -22,6 +22,7 @@ Development checkout: 0.7.1.dev0.

### Changed

- The nitrogen rules live in `flahax.nitrogen`: the three forms, `nitrogen_rows`, `fitted_targets`, `total_nitrogen`, the ammonium allowance and `total_n_report`, moved from `composition` and `engine`. `evaluate_remedies` takes the planner as an argument, so `fertilizer_workflow` and `evaluated_remedies` no longer import each other. No recipe, total-N report or ammonium cap differs.
- `run_batch` and `BatchOptions` move from `flahax.batch_cli` to `flahax.batch_request`, the water reader to `flahax.water_input`, and `read_json` to `flahax.inputs`; `flahax batch`, `flahax mix` and `flahax.batch_cli.main` behave as before and no output differs. Code that imported those names from `batch_cli` imports them from the new modules.
- `flahax.grower_report` is split into `batch_summary`, `report_html`, `result_wording` and `report_format`. `summarize_batch`, `render_report` and `render_batch_sheet` import from `flahax` as before and no report, sheet or summary differs. Other names move to the new modules; the reason and row helpers lose their underscore.
- One number check, `flahax.inputs.number`, replaces nine private copies in the engine modules and three guards in `flahax batch`. Error codes are unchanged. A numeric string is no longer coerced to a number in delivery contracts, and the stock, pH and stability evidence checks raise `DeliveryError` (still a `ValueError`) for a malformed number.
Expand Down
2 changes: 1 addition & 1 deletion src/flahax/batch_volumetric_stocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from .aqueous_model import solve
from .calculated_ph import calculate_equilibrium_ph
from .composition import fitted_targets
from .nitrogen import fitted_targets
from .delivery_contracts import DeliveryError
from .inputs import number

Expand Down
92 changes: 0 additions & 92 deletions src/flahax/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,98 +170,6 @@ class InputError(ValueError):
"""The caller passed a profile or a salt the balance cannot use."""


NITROGEN_FORMS = ("N_NO3", "N_NH4", "N_UREA")
# A declared total and the sum of its forms agree within this relative
# amount (decimal input such as 150 against 100 + 30 + 20).
TOTAL_NITROGEN_TOLERANCE = 1e-6


def nitrogen_rows(targets) -> dict:
"""The nitrogen requirements fitted for a formula (decisions D1 and
D2, gates G23 and G24).

Each form is its own requirement on the elemental-N basis: N_NO3 as
declared, N_UREA as declared or 0 when absent (a declared zero, with
no allowance), and N_NH4 only when it is declared above 0. An absent
or zero N_NH4 is no ammonium requirement at all: no row and no ban.
A formula that declares no nitrogen form has no nitrogen rows.

Total N ("N", elemental mg/L) is a target too. Alone it is one row
over the sum of the three forms and imposes no form split; the urea
safeguard still holds, so urea products stay out unless urea is
declared. Total N is nitrate + ammonium + urea, and urea that is not
asked for is a zero requirement, not an unknown. So a declared
nitrate and a positive ammonium determine the total (urea is
declared or zero): the forms are scored once and the declared total
must agree with their sum. An explicit zero N_NH4 asks for nothing
(decision G24), so it does not determine the total. When the forms
leave the total open, both are scored (the overlap is reported by
total_n_report) and no other form target is invented. A total below
the declared forms, or a total that disagrees with forms that
determine it, raises InputError before any fitting.
"""
total = targets.get("N")
if total is None and not any(form in targets for form in NITROGEN_FORMS):
return {}
determined = "N_NO3" in targets and targets.get("N_NH4", 0) > 0
if total is not None:
declared = total_nitrogen(targets)
slack = TOTAL_NITROGEN_TOLERANCE * max(abs(total), 1.0)
if determined and abs(total - declared) > slack:
raise InputError(
f"targets declare total N {total:g} mg/L but N_NO3 + N_NH4 + N_UREA = "
f"{declared:g} mg/L; declare either the total or consistent forms"
)
if declared - total > slack:
raise InputError(
f"targets declare nitrogen forms summing to {declared:g} mg/L, which "
f"exceed the declared total N of {total:g} mg/L"
)
rows = {}
if total is not None and not determined and total > 0:
rows["N"] = total
if "N_NO3" in targets:
rows["N_NO3"] = targets["N_NO3"]
if targets.get("N_NH4", 0) > 0:
rows["N_NH4"] = targets["N_NH4"]
rows["N_UREA"] = targets.get("N_UREA", 0)
if total == 0 and "N_NO3" not in targets:
rows["N_NO3"] = 0 # a declared zero total admits no nitrate product either
return rows


def fitted_targets(targets) -> dict:
"""The targets as fitted: other nutrients unchanged, nitrogen as
``nitrogen_rows``.

A zero N_NH4 is dropped (no requirement, no ban) and an absent
N_UREA becomes a declared zero whenever any nitrogen form is
declared.
"""
nitrogen = nitrogen_rows(targets)
fitted = {
s: v for s, v in targets.items() if (s not in NITROGEN_FORMS and s != "N") or s in nitrogen
}
fitted.update(nitrogen)
return fitted


def total_nitrogen(profile) -> float:
"""Elemental N summed over the three forms (N_NO3 + N_NH4 + N_UREA),
in the profile's units.
"""
return math.fsum(float(profile.get(form) or 0.0) for form in NITROGEN_FORMS)


def target_total_nitrogen(targets) -> float:
"""Total N a formula asks for: the declared total when the targets
carry one, otherwise the sum of the declared forms.
"""
if targets.get("N") is not None:
return float(targets["N"])
return total_nitrogen(targets)


def _finite(value) -> float:
try:
number = float(value)
Expand Down
92 changes: 7 additions & 85 deletions src/flahax/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@
InputError,
assay_conflict,
assay_drift,
fitted_targets,
imbalance_note,
is_carbonate,
total_nitrogen,
target_total_nitrogen,
NITROGEN_FORMS,
target_ion_balance,
validate_profile,
validate_targets,
)
from .nitrogen import (
NITROGEN_FORMS,
ammonium_allowance,
fitted_targets,
total_n_report,
total_nitrogen,
)
from .nutrient_acceptance import assess_incidental, name_sources
from .product_conversion import counterion_sodium_mg_per_l, material_inventory
from .deviation_ranges import assessment as range_assessment, effective_ranges, normalize_ranges
Expand Down Expand Up @@ -75,14 +78,6 @@
PH_REAGENT = "ph_reagent"
# Relative aim below a stated maximum (1 ppm of the limit).
CEILING_MARGIN = 1e-6
# Ammonium allowance (G23): when a formula declares no NH4-N requirement
# (absent or 0), incidental NH4-N may reach min(10% of total target N,
# 1.5 mmol/L NH4 = 21.01 mg/L N). Dutch soilless practice: NH4 at 5-15%
# of total N with at most 1-1.5 mmol/L (Van der Lugt et al. 2016
# handbook, after De Kreij, Voogt et al.).
AMMONIUM_FRACTION = 0.10
AMMONIUM_CAP_MG_PER_L = 1.5 * 14.0067
AMMONIUM_BASIS = "Dutch soilless practice (De Kreij, Voogt et al.)"


def load_library() -> dict:
Expand Down Expand Up @@ -734,52 +729,6 @@ def solve_weights(
return solved


def ammonium_allowance(targets: dict, maxima: dict, fraction: float | None) -> dict | None:
"""The ammonium allowance (G23) for fitted targets, added to maxima
as N_NH4.

It applies when the targets have no NH4-N requirement and no N_NH4
maximum is stated: min(fraction x total target N,
AMMONIUM_CAP_MG_PER_L). None adds no maximum.
"""
if fraction is None:
return None
if (
isinstance(fraction, bool)
or not isinstance(fraction, (int, float))
or not 0 <= fraction <= 1
):
raise InputError("max_ammonium_fraction must be a number in [0, 1]")
total_n = target_total_nitrogen(targets)
# A positive N_NH4 target keeps its own row; absent or 0 gets the
# allowance (G23).
if total_n <= 0 or "N_NH4" in targets or "N_NH4" in maxima:
return None
limit = min(fraction * total_n, AMMONIUM_CAP_MG_PER_L)
maxima["N_NH4"] = limit
return {
"mgPerL": limit,
"fractionOfTotalN": fraction,
"absoluteCapMgPerL": AMMONIUM_CAP_MG_PER_L,
"basis": AMMONIUM_BASIS,
}


def ammonium_allowance_preset(targets: dict, fraction: float = AMMONIUM_FRACTION) -> dict | None:
"""The optional ammonium allowance preset for ``targets``, as a
disclosed record, without applying it.

Returns the same record ``ammoniumLimit`` carries (mgPerL,
fractionOfTotalN, absoluteCapMgPerL, basis), or None when the
targets already state NH4-N or have no nitrogen. To apply it, pass
``max_ammonium_fraction=fraction`` to ``recommend`` or declare
``maximum_concentrations={'N_NH4': record['mgPerL']}``.
"""
return ammonium_allowance(
fitted_targets(validate_targets(dict(targets), "targets")), {}, fraction
)


def _chosen(salts: list[dict], grams: list[float]) -> list[dict]:
chosen = []
for salt, gram in zip(salts, grams):
Expand Down Expand Up @@ -1248,33 +1197,6 @@ def _provenance(record: dict) -> dict:
}


def total_n_report(rows: list[dict], targets: dict) -> dict:
"""Total N as the sum of the three forms in the final rows (water,
products and any reagent), against the declared total or the sum of
the declared forms (D1, D2). The target is None when neither a form
nor a total is declared. fitted is True when the total is its own
row; overlapForms then lists the forms scored beside it (the urea
safeguard's zero is not an overlap).
"""
declared = "N" in targets or any(form in targets for form in NITROGEN_FORMS)
target = target_total_nitrogen(targets) if declared else None
final = total_nitrogen({row["symbol"]: row["final"] for row in rows})
fitted = "N" in targets
return {
"target": target,
"final": final,
"deltaPct": 100.0 * (final - target) / target if target else None,
"unit": "mg/L as N",
"forms": list(NITROGEN_FORMS),
"fitted": fitted,
"overlapForms": [
form
for form in NITROGEN_FORMS
if fitted and form in targets and (form != "N_UREA" or targets[form] > 0)
],
}


def _report(
rows: list[dict], grams: list[float], warnings: list[str], maxima: dict | None = None
) -> dict:
Expand Down
9 changes: 5 additions & 4 deletions src/flahax/evaluated_remedies.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,10 +430,13 @@ def _joint_start_retry(option, request, workflow, expanded, seen):
return retry, dict(adjustment, joint=dict(joint, starting_points=starts))


def evaluate_remedies(workflow, request, options=(), max_evaluations=20):
def evaluate_remedies(workflow, request, options=(), max_evaluations=20, *, plan):
"""Re-run declared alternatives and rank checked results within the
scenario budget.

``plan`` is the planner each scenario runs through, called as
``plan(**request)``; ``plan_fertilizer_workflow`` passes itself.

Options have unique id, kind (catalogue/treatment/equipment), and
changes. Catalogue bundles require available=True; treatment
requires evidence source/revision. Options from
Expand Down Expand Up @@ -506,15 +509,13 @@ def evaluate_remedies(workflow, request, options=(), max_evaluations=20):
next_action='Increase the evaluation budget; this scenario has no result.',
)
else:
from .fertilizer_workflow import plan_fertilizer_workflow

candidate_request = deepcopy(request)
candidate_request.update(changes)
if adjustment is not None:
candidate_request['ph_adjustment'] = adjustment
evaluations += 1
try:
candidate = plan_fertilizer_workflow(**candidate_request)
candidate = plan(**candidate_request)
except InputError as exc:
candidate = None
result.update(
Expand Down
7 changes: 4 additions & 3 deletions src/flahax/fertilizer_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from .stock_planning import plan_stocks
from .acid_selection import plan_acid_options
from .deviation_ranges import normalize_ranges
from .evaluated_remedies import evaluate_remedies
from .ph_adjustment import normalize_target_ph, plan_coupled_ph
from .requirement_fit import PH_TOLERANCE, declared_error_percent, met, reagent_shift_exceeds
from .nutrient_acceptance import (
Expand Down Expand Up @@ -999,9 +1000,9 @@ def mix(candidate):
if not callable(equipment_check):
raise DeliveryError('invalid_type', 'equipment_check must be callable')
request['equipment_check'] = equipment_check
from .evaluated_remedies import evaluate_remedies

output.remedies = evaluate_remedies(output, request, remedy_options, max_remedy_evaluations)
output.remedies = evaluate_remedies(
output, request, remedy_options, max_remedy_evaluations, plan=plan_fertilizer_workflow
)
output.canonical_result = CanonicalResult.capture(
output,
dict(
Expand Down
3 changes: 2 additions & 1 deletion src/flahax/joint_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from types import MappingProxyType

from .aqueous_model import chemistry, solve
from .composition import NITROGEN_FORMS, validate_profile, validate_targets
from .composition import validate_profile, validate_targets
from .nitrogen import NITROGEN_FORMS
from .delivery_contracts import DeliveryError
from .inputs import number
from .engine import score
Expand Down
4 changes: 2 additions & 2 deletions src/flahax/label_reconciliation.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@

from .composition import ATOMIC
from .material_chemistry import COMPLEXES, ION_TABLE, NUTRIENT_CHARGES
from .nitrogen import NITROGEN_FORMS

_N_FORMS = ('N_NO3', 'N_NH4', 'N_UREA')
_SUBSCRIPTS = str.maketrans('0123456789', '₀₁₂₃₄₅₆₇₈₉')
# Hydroxide is the proton deficit the charge balance closes
# (material_chemistry._IMPLICIT).
Expand Down Expand Up @@ -93,7 +93,7 @@ def charge_surplus(ion_forms: Mapping, elements: Mapping) -> LabelReconciliation
return LabelReconciliation({}, 0.0, 'an unstated ion closes the charge balance')
charges = _mean_charges(ion_forms)
equivalents = {
key: charges[key] * value / ATOMIC['N' if key in _N_FORMS else key]
key: charges[key] * value / ATOMIC['N' if key in NITROGEN_FORMS else key]
for key, value in declared.items()
if charges.get(key)
}
Expand Down
10 changes: 5 additions & 5 deletions src/flahax/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from .composition import ATOMIC, ATOMIC_CONVENTION, theoretical_assay
from .delivery_contracts import DeliveryError
from .inputs import number
from .nitrogen import NITROGEN_FORMS

_RESOURCE = 'data/material_identities.json'
_RAW = files('flahax').joinpath(_RESOURCE).read_bytes()
Expand Down Expand Up @@ -186,7 +187,6 @@ def _oxide_factor(element: str, count: int, oxygens: int) -> float:
}
COMPOSITIONS = frozenset({'single', 'disclosed', 'undisclosed', 'declared_ions'})
CHELATING_AGENTS = ('EDTA', 'DTPA', 'o,o-EDDHA', None)
N_FORMS = ('N_NO3', 'N_NH4', 'N_UREA')
_BANDS = ('typical', 'minimum', 'maximum')
# Disclosed blend: declared vs component-implied analysis, relative and
# absolute (% points).
Expand Down Expand Up @@ -456,7 +456,7 @@ def _charge_residual_percent(identity: dict, declared: dict) -> float | None:
if charge == 0:
continue
has_cation, has_anion = has_cation or charge > 0, has_anion or charge < 0
moles = percent / ATOMIC['N' if nutrient in N_FORMS else nutrient]
moles = percent / ATOMIC['N' if nutrient in NITROGEN_FORMS else nutrient]
signed += charge * moles
absolute += abs(charge) * moles
if not (has_cation and has_anion) or absolute <= 0:
Expand All @@ -478,7 +478,7 @@ def _analysis_targets(
if key != 'N':
return [_nutrient_key(key, label, conversions, extra)]
theory = load_identities()[identity_id]['theoretical_analysis'] if identity_id else {}
forms = {form: theory[form] for form in N_FORMS if theory.get(form, 0) > 0}
forms = {form: theory[form] for form in NITROGEN_FORMS if theory.get(form, 0) > 0}
if not forms:
raise DeliveryError(
'invalid_value', f'{label}: total N needs an identity whose theory states N forms'
Expand Down Expand Up @@ -526,7 +526,7 @@ def make_grade(record: Mapping) -> Grade:
analysis = record.get('analysis')
if not isinstance(analysis, Mapping) or not analysis:
raise DeliveryError('invalid_value', f'{label}: analysis must be a non-empty mapping')
if 'N' in analysis and set(analysis) & set(N_FORMS):
if 'N' in analysis and set(analysis) & set(NITROGEN_FORMS):
raise DeliveryError('invalid_value', f'{label}: state total N or its forms, not both')
conversions: dict = {}
split: dict = {}
Expand Down Expand Up @@ -633,7 +633,7 @@ def declared_ions_check(grade: Grade) -> DeclaredCheck:
) # deferred: product_conversion imports this module

declared = {**grade.minimum, **grade.typical}
missing = [form for form in N_FORMS if form not in declared]
missing = [form for form in NITROGEN_FORMS if form not in declared]
if missing:
return DeclaredCheck(
False,
Expand Down
Loading
0