8000 fix: resolve EC evidence and chemistry provenance audit findings by rafatahmed · Pull Request #247 · 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ each release, with numbers, sources and decisions, are in

### Fixed

- Withhold manufacturer-screening EC totals containing positive Ultrasol Magsul doses;
retain the disputed 1.2 mS/cm brochure value as evidence (#244).
- Record all chemistry input byte identities, the versioned PHREEQC extraction route and
a deterministic source-manifest digest; preserve all scientific records (#245).
- Replace broad priority claims with supported capabilities and a dated comparison (#246).
- Validate custom batch records and reagent densities before configuration; reject duplicate
product names before they can corrupt pH chemistry or reagent selection (#240, #241).

Expand Down
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ recursive-include tests *.py
include tests/reference_inventory.json
recursive-include tests/fixtures *.json *.pqi *.out *.sel *.screen *.dat *.md *.inp
recursive-include tools *.py *.ps1
include tools/chemistry_sources.json
include tools/requirements-benchmark-report.txt
recursive-include examples *.py *.md
prune examples/tutorial
Expand Down
10 changes: 8 additions & 2 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ underlying measurements.
database minteq.v4.dat, distributed with PHREEQC by the U.S. Geological
Survey (source pinned by SHA-256
ab0a8f7c7375e1bd997990f4bc3a9af497516f10e57f4aaa3cefb55dccac5ae7,
https://github.com/usgs-coupled-subtrees/phreeqc3-database/blob/master/minteq.v4.dat).
from https://water.usgs.gov/water-resources/software/PHREEQC/phreeqc-3.8.6-17100-x64.msi).
Release archive SHA-256:
6e5f6697fa727f919eb4e7c1c2bc20e8c2717378aaf77731efd831ef66578243.
Administrative extraction yields the unchanged 334121-byte member
phreeqc-3.8.6-17100-x64/database/minteq.v4.dat (CRLF retained).
minteq.v4.dat derives from the U.S. EPA MINTEQA2 version 4 database.
- Phase constants for kieserite (log K -0.123) and sylvite (log K 0.9)
from the PHREEQC 3.8.6 database pitzer.dat.
Expand All @@ -37,7 +41,9 @@ underlying measurements.
committed 2026-09-27), keeping only the species and phases FlahaX
uses, and added FlahaX extensions marked in the file by their own
"source" field (flahax-chelates-25c.dat, flahax-phases-25c.dat). The
original database is available from the USGS at the URL above.
original database is available inside the versioned USGS archive above.
Complete input identities and extension attribution are recorded in the
generated model's sources manifest; database_sha256 identifies the base only.
- The USGS User Rights Notice for PHREEQC applies to this data and is
reproduced in full at the end of this file.
- Please acknowledge: Parkhurst, D. L. and Appelo, C. A. J. (2013)
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ precipitates, what the pH will be, how much acid reaches a target pH, and how th
into stock tanks and injector flows. Every plan carries its units, model identifiers and source
hashes, so a result can be reviewed and reproduced.

To our knowledge, FlahaX is the first Python package to unite fertilizer formulation,
fertilizer-specific aqueous equilibrium chemistry and auditable delivery planning in one
dependency-free library, verified against PHREEQC.
FlahaX combines fertilizer formulation, fertilizer-specific aqueous equilibrium chemistry,
and delivery planning in a dependency-free Python library. Plans include units, model
identifiers, and source references; selected chemistry calculations are checked against
PHREEQC reference cases. The [dated competitor comparison](docs/site/evidence/competitor-comparison.md)
records versions, shared inputs, results, and limitations.

**Who it is for**

Expand Down
11 changes: 6 additions & 5 deletions docs/publication/field-article/draft.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ can predict these effects, but they are general geochemical tools and are
rarely used in day-to-day recipe design. Decision support systems such as
NUTRISENSE have shown the value of calculating and readjusting nutrient
solutions from analyses in closed systems <!-- TODO cite NUTRISENSE -->.
To our knowledge, no openly available tool combines fertilizer formulation
against the actual water with fertilizer-specific equilibrium chemistry,
acid planning and stock-tank planning, and none has been evaluated in the
field for that combination.
FlahaX combines formulation against source-water composition with
fertilizer-specific equilibrium chemistry, acid planning and stock-tank planning.
A [dated software comparison](../../site/evidence/competitor-comparison.md)
records selected tools, tested versions and limitations; it does not establish
priority or field accuracy.

FlahaX is an open-source (Apache-2.0) Python engine that does this
FlahaX is an open-source (Apache-2.0) Python engine
<!-- TODO cite JOSS paper when published -->. Its predictions so far are
verified only computationally, against PHREEQC. This study asks whether
those predictions hold on real farms.
Expand Down
10 changes: 6 additions & 4 deletions docs/publication/joss/paper.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,12 @@ nutrient solutions in closed hydroponic systems, a function FlahaX does not
provide. PHREEQC and its Python bindings [@phreeqpy] model aqueous
equilibrium in general, without fertilizer formulation.

To our knowledge, none of these combines fertilizer formulation against the
source water, fertilizer-specific aqueous equilibrium with precipitation,
acid planning to a target pH, and stock-tank and injector planning with an
audit trail in one installable package. FlahaX was built as a new package
FlahaX integrates formulation against source-water composition,
fertilizer-specific aqueous equilibrium calculations, acid planning to a target
pH, and stock-tank and injector planning through a shared chemistry model and
audit trail. A [dated software comparison](../../site/evidence/competitor-comparison.md)
records the tested versions, inputs, results, and limitations. These computational
comparisons do not establish experimental validation or priority. FlahaX was built as a new package
rather than as an extension of an existing one because the end-to-end audit
trail and the shared chemistry model run through every layer, from salt
selection to injector flow, and could not be added to a mass-balance solver
Expand Down
6 changes: 4 additions & 2 deletions docs/publication/story/ar.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ NUTRISENSE من الجامعة الزراعية في أثينا في الحقل

ما يضيفه FlahaX هو المسار الكامل في حزمة واحدة مفتوحة: من تحليل المياه إلى
الوصفة والكيمياء ثم خزانات المحلول المركّز، مع التحقق من الكيمياء مقارنةً
بـ PHREEQC. وعلى حدّ علمي، هو أول حزمة Python مفتوحة تنتقل من تحليل المياه إلى
خزانات المحلول المركّز بكيمياء جرى التحقق منها.
بحالات مرجعية مختارة من PHREEQC. وتوثّق
[مقارنة البرامج المؤرّخة](../../site/evidence/competitor-comparison.md)
الإصدارات المختبرة والمدخلات والحدود. ولا تثبت هذه المقارنات صحة النتائج
تجريبياً أو أسبقية الحزمة.

## ما لا يفعله بعد

Expand Down
7 changes: 4 additions & 3 deletions docs/publication/story/en.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ chemistry.

What FlahaX adds is the whole path in one open package: from the water
analysis through the recipe and the chemistry to the stock tanks, with the
chemistry checked against PHREEQC. To my knowledge it is the first open
Python package that goes from water analysis to stock tanks with verified
chemistry.
selected chemistry calculations checked against PHREEQC reference cases.
The [dated software comparison](../../site/evidence/competitor-comparison.md)
records tested versions, inputs and limitations. Those comparisons do not establish
experimental validation or priority.

## What it doesn't do yet

Expand Down
18 changes: 14 additions & 4 deletions docs/site/evidence/source-sheet-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ tanks. A B-side acid arrangement still needs grade/mixture/operating review.
Existing recipe phosphoric-acid mass is not an additional pH-correction dose.
No new compatibility database entries or approved StockPlan were generated.

## Visually verified SQM anchors
## SQM brochure values and screening applicability

`165357805552.pdf`, page 2: EC of **1 g product/L at 25 C**, in mS/cm.

Expand All @@ -87,13 +87,23 @@ No new compatibility database entries or approved StockPlan were generated.
| Ultrasol MKP | 0.7 |
| Ultrasol MAP | 0.9 |
| Ultrasol Calcium | 1.2 |
| Ultrasol Magsul | 1.2 |
| Ultrasol Magsul | 1.2 (disputed; excluded from screening) |
| Ultrasol Magnit | 0.9 |

The brochure also lists Magnum P44 at 1.5; this acidifying urea-phosphate
product is not included in the pre-acid screening implementation. Acid/base
reactions require more than an additive conductivity assumption. Magsul is
**1.2**, not 0.9. Headline grades can differ from detailed guaranteed analysis:
reactions require more than an additive conductivity assumption. The brochure prints
**1.2** for Magsul, but this conflicts with chemistry calculations and remains unresolved.
The source is retained with SHA-256
`28a15230851581f66255fe45f67f6e3b580d88f5cfbbc65a7cb97a9c5171ad48`.
A pure MgSO4·7H2O calculation at 1 g/kg water gives an EC range near 0.7251 mS/cm.
Comparing it with 1 g/L assumes dilute-water concentration equivalence; the model is not
a replacement manufacturer measurement or proof of measured accuracy. Neither 0.9 nor
0.7251 is adopted as an anchor. See the retained [discrepancy review](audit/2026-10-17-flahax-vs-horticalc/review.md).
Positive Magsul doses, alone or in mixtures, return `not_supported` with
`disputed_product_ec_evidence`, the disputed source value, and no complete EC total.
Zero doses do not affect supported requests. The ion API retains its own inputs and limits.
Headline grades can differ from detailed guaranteed analysis:
e.g. Magnit's nitrate-N table is 10.7%, not the rounded headline 11.

## What can now be calculated without new measurements
Expand Down
65 changes: 64 additions & 1 deletion docs/site/models/reaction-qualification.md
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,74 @@ python tools/qualify_chemistry_model.py --database PATH/minteq.v4.dat --report a

This command reads the model and databases and writes only the requested report.
It records model/source hashes, per-reaction checks, source correspondence and
parameter status. A changed base hash fails. No solver or model-builder function
parameter status. A changed base or extension hash, byte count, missing source,
or changed manifest digest fails. No solver or model-builder function
is imported by the checker. Atom, charge and basis sums use rational arithmetic;
log-K comparison allows only a bound calculated from binary floating-point ULPs
and the number of terms. That bound is not thermodynamic uncertainty.

## Reproducing the exact chemistry inputs

The original base is **334,121 bytes**, including its CRLF line endings, from the
**PHREEQC 3.8.6-17100 Windows release distribution**. It is not the current MINTEQ
file on upstream `master`. The versioned [USGS installer](https://water.usgs.gov/water-resources/software/PHREEQC/phreeqc-3.8.6-17100-x64.msi)
is 16,846,848 bytes with SHA-256
`6e5f6697fa727f919eb4e7c1c2bc20e8c2717378aaf77731efd831ef66578243`.
Administrative extraction with `msiexec /a` yields
`phreeqc-3.8.6-17100-x64/database/minteq.v4.dat`, whose SHA-256 is the base hash above.
No edits or newline conversion are applied. This extraction was reproduced on
12 November 2026 from the hash-verified release archive. It does not replace a
database or require a system-wide installation. `tools/provision_phreeqc.ps1`
already documents the pinned download/extraction procedure; running it is an
explicit reference-provisioning action, not part of the model builder.

`tools/chemistry_sources.json` records the three build inputs, their byte lengths,
SHA-256 hashes, UTF-8 decoding policy and origins. The two extension URLs are pinned
to repository revision `de50f8963a65a9f0f99462ffc731350de64472fc`; their bytes also
remain in the source distribution under `tests/fixtures/phreeqc/database/`.
The phase extension attributes kieserite and sylvite to `pitzer.dat` in the same
release archive (lines 357 and 433, respectively). Only their 25 C reactions and
log K values are selected; temperature expressions are not imported. The Pitzer
file is attribution evidence, not an additional input consumed during regeneration.
The manifest also distinguishes the cited struvite constant, fixed urea identity,
and selected project chelate profile.

The generated `chemistry_25c.json` schema 2 contains this manifest as `sources`.
`database_sha256` remains a compatibility field for **the base alone**.
`source_url` identifies the versioned release archive, not a raw database file;
the archive member and hashes are in the base source record.
`sources_sha256` covers the complete manifest: sort records by `filename`, serialize
with Python JSON `sort_keys=True`, `separators=(',', ':')`, `ensure_ascii=True`,
`allow_nan=False`, encode UTF-8 without a trailing newline, then SHA-256.
No build timestamp or machine path participates. The builder hashes and decodes
the same bytes and refuses inputs that differ from the pinned source manifest.

With the original base already extracted, regeneration and qualification are offline:

```text
python tools/build_chemistry_model.py PATH/minteq.v4.dat --output regenerated.json
python tools/qualify_chemistry_model.py --database PATH/minteq.v4.dat --model regenerated.json --report audit.json
python -c "from pathlib import Path; assert Path('regenerated.json').read_bytes() == Path('src/flahax/data/chemistry_25c.json').read_bytes()"
```

`--output` writes only the requested JSON; it does not rewrite the source model or
coverage documentation. Repeated regeneration from identical inputs must be
byte-identical. Provenance-only changes preserve every reaction, constant, species,
phase, basis and alias. Hash agreement establishes identity, not thermodynamic accuracy.

An optional retrieval test downloads the versioned installer and pinned extension
files into memory, checks byte counts and hashes, and never installs or executes them:

```text
# Set FLAHAX_VERIFY_SOURCE_DOWNLOADS=1 in your shell, then:
python -m unittest tests.test_chemistry_source_downloads
```

This is independent of `FLAHAX_REQUIRE_PHREEQC`. With the download flag unset it is
explicitly skipped; offline integrity checks still run. When enabled, retrieval
unavailability and content mismatch are distinct failures. The installer checksum
and member identity remain necessary even if a versioned server URL is later replaced.

| Parameter origin | What is established | What is not established |
|---|---|---|
| Pinned MINTEQ compilation | Equation/log-K correspondence and basis conversion | Independent revalidation of every underlying measurement |
Expand Down
26 changes: 21 additions & 5 deletions src/flahax/calculated_ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,22 @@
'reference_g_per_litre': 1.0,
'reference_temperature_c': 25.0,
}
# Reviewed against the rendered table, not OCR. Magsul is 1.2, not 0.9.
# The brochure prints 1.2 for Magsul, but this conflicts with the ion calculation.
# Retain that evidence without treating it as a usable or corrected anchor.
_DISPUTED = {
'Ultrasol Magsul': {
'status': 'disputed',
'published_ec_ms_cm': 1.2,
'reason': 'Published brochure value conflicts with chemistry calculations; unresolved.',
'review': 'docs/site/evidence/source-sheet-review.md',
},
}
_ANCHORS = {
'Ultrasol K Plus': 1.3,
'Ultrasol SOP': 1.5,
'Ultrasol MKP': 0.7,
'Ultrasol MAP': 0.9,
'Ultrasol Calcium': 1.2,
'Ultrasol Magsul': 1.2,
'Ultrasol Magnit': 0.9,
}

Expand All @@ -50,7 +58,9 @@ def estimate_manufacturer_ec(
are assumptions, not manufacturer validation. A total fertilizer loading
cap of 1 g/L is a conservative software policy, NOT a validated range.
No uncertainty bound or model for concentrated A/B stocks is asserted.
Unknown products never disappear into a falsely complete total.
Unknown or disputed products never disappear into a falsely complete total.
Positive Magsul doses return disputed_product_ec_evidence; its published
value is retained as disputed evidence, not replaced by a model prediction.
"""
if not isinstance(doses_g_per_litre, Mapping):
raise DeliveryError('invalid_type', 'doses must map exact commercial product names to g/L')
Expand All @@ -65,7 +75,10 @@ def estimate_manufacturer_ec(
isinstance(channel, str) and channel.startswith('tank:') and len(channel) > 5
):
raise DeliveryError('unknown_channel', 'expected irrigation or tank:<id>')
missing = sorted(k for k, v in doses.items() if v > 0 and k not in _ANCHORS)
disputed = {k: dict(_DISPUTED[k]) for k, v in doses.items() if v > 0 and k in _DISPUTED}
missing = sorted(
k for k, v in doses.items() if v > 0 and k not in _ANCHORS and k not in _DISPUTED
)
result = dict(
status='screening_estimate',
ec_ms_cm=None,
Expand All @@ -81,6 +94,7 @@ def estimate_manufacturer_ec(
model='manufacturer-anchor-additive-screening-v1',
doses_g_per_litre=doses,
missing_products=missing,
disputed_products=disputed,
assumptions=[
'Pre-acid; no precipitation or speciation corrections.',
'Linear dose scaling and additive EC; unvalidated mixture approximation.',
Expand All @@ -89,7 +103,9 @@ def estimate_manufacturer_ec(
],
)
reason = None
if temperature_c != 25:
if disputed:
reason = 'disputed_product_ec_evidence'
elif temperature_c != 25:
reason = 'temperature_outside_reference'
elif channel != 'irrigation':
reason = 'concentrated_stock_model_unavailable'
Expand Down
4 changes: 3 additions & 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.

Loading
Loading
0