8000 Hardening 3a/4: PEP 8 formatting, file headers, CI style check by rafatahmed · Pull Request #120 · 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
14 changes: 14 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ permissions:
contents: read

jobs:
style:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.13"
- name: Install ruff (development tool only)
run: python -m pip install ruff==0.8.4
- name: PEP 8 lint (settings in pyproject.toml)
run: ruff check .
- name: Formatting
run: ruff format --check .

test:
runs-on: ubuntu-latest
strategy:
Expand Down
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

- PEP 8 style and file headers (hardening 3a/4; owner decisions 2026-10-23: line length 99, header template). All Python code is formatted with `ruff format` (PEP 8, 99 columns; quote style kept), which leaves the code's meaning unchanged; one statement per line, PEP 8 spacing and blank lines throughout. Every Python file (161) starts with the header in PEP 8 order: a shebang only on runnable tools and examples, the SPDX copyright and license lines and the disclaimer, then the module docstring (36 test files gained one). `flahax/__init__.py` now lists `__all__` (135 names, unchanged) and `__version__` before its imports, instead of 13 `__all__ +=` lines between them. Unused imports and variables are removed (including an unused H3PO4 term in the phosphate loop; H3PO4 is still in the mass balance), two lambdas assigned to names became functions, and the ambiguous name `l` became `line`. Style settings live in `pyproject.toml` (ruff is a development tool, not a runtime dependency); a new CI `style` job runs `ruff check` and `ruff format --check`, and `tests/test_file_headers.py` checks the header order. Line length is enforced after the remaining long strings and comments are rewrapped (3b). CONTRIBUTING.md documents the conventions.
- Every error code is explained (hardening 2/4). The shipped user guide gains an error code reference: all 91 `DeliveryError` codes, grouped by what you were doing (input values and files, water analysis, products and materials, recipe and pH, chemistry model, stocks and injection, delivery plans and EC), each with its meaning and what to do; 68 were undocumented. `tests/test_error_catalogue.py` fails if a raised code is missing from the guide. A material whose formula cannot be used now says why: it cannot be read (check the brackets and the element symbols), has fractional atoms, does not split into the fertilizer ions FlahaX knows, or splits in more than one way; it said 'give its formula' even when one was given. The exception audit found no other user-facing exception outside `InputError` and `DeliveryError`: the remaining `TypeError`s are argument-type checks, the `AssertionError`s belong to the reference-fixture comparison helper, and the internal `ValueError`s are caught and re-raised.
- Entry points refuse bad input with a plain message instead of a traceback (#117, from the entry-point audit). `flahax batch --ratio 0` crashed with a ZeroDivisionError; every number option is now checked at the command line with its range (`--ratio`, `--volume` and `--max-reagent-litres` above 0, `--ph` 0-14, `--water-share` above 0 up to 100). Every JSON file (water, targets, products, rules, saved items and sessions) and JSON on stdin is read by one reader that names the file and the line and column (`missing_file`, `invalid_json`); a water value that is not a number, or a non-numeric `--acid` assay or density, is named in the message. The `flahax batch` terminal shows the acid with the same 0.1 mL rounding as the sheet and report.
- Package identity and attribution (owner decisions 2026-10-23). Metadata: author Rafat A. Al Khashan with public contact email, maintainers Rafat A. Al Khashan and Flaha Agri Tech (affiliation), a description that names the grower command and the A/B stock planning, fuller keywords, Development Status 4 - Beta, Console and end-user audiences, Python 3.14 (now also in CI), and Changelog, Citation and Growers-guide links. NOTICE now credits every data source the package ships (USGS PHREEQC 3.8.6 minteq.v4.dat and pitzer.dat, the FlahaX chelate and phase extensions, McCleskey et al. 2012, Pethybridge et al. 2006, the CRC Handbook, Yara, the U.S. Coast Guard CHRIS database, Haifa, Sigma-Aldrich, ChemicalBook, SQM and the crop-formula authors) and reproduces the USGS User Rights Notice, which applies to PHREEQC data: it requires modified data to say what changed, by whom and when, so chemistry_25c.json and NOTICE now carry that statement (the sylvite constant, from pitzer.dat, was not credited before). CITATION.cff gains a current abstract, release date, affiliation, contact and a references list checked against Crossref. The README gains an Author and credits section; `tests/test_attribution.py` fails if a shipped data source is not credited. Zenodo archiving is documented as an owner step in the publishing procedure.
Expand Down
18 changes: 18 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ Keep code and documentation product-focused. Do not add assistant attribution
or generated-by branding. Maintain source/license attribution where required.
Never commit credentials, executables or private/local-only source material.

## Code style

FlahaX follows PEP 8 with a line length of 99 characters (the team allowance PEP 8 gives). The
settings are in `pyproject.toml`; `ruff` is a development tool only, never a runtime dependency.

```bash
python -m pip install ruff==0.8.4
ruff format .
ruff check .
```

Every Python file starts, in this order, with: a shebang (`#!/usr/bin/env python3`) only for
runnable tools and examples; the header comments (SPDX copyright and license, and the
disclaimer); the module docstring; `from __future__` imports; module dunders such as `__all__`
and `__version__`; then the imports. No encoding line is needed. Code must also run on
Python 3.11: inside an f-string, use the other quote type in replacement fields.
`tests/test_file_headers.py` and the CI `style` job check all of this.

## Required validation

```powershell
Expand Down
4 changes: 4 additions & 0 deletions benchmarks/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# SPDX-FileCopyrightText: 2026 Flaha. Created by Rafat A. Al Khashan.
# SPDX-License-Identifier: Apache-2.0
# Disclaimer: planning software provided without warranty (Apache-2.0, section 7);
# its results are calculations, not dosing instructions.
"""Development-only Benchmark v1; not part of the installed FlahaX package."""
147 changes: 99 additions & 48 deletions benchmarks/cases.py
10BC8
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
# SPDX-FileCopyrightText: 2026 Flaha. Created by Rafat A. Al Khashan.
# SPDX-License-Identifier: Apache-2.0
# Disclaimer: planning software provided without warranty (Apache-2.0, section 7);
# its results are calculations, not dosing instructions.
"""Fixed Benchmark v1 inputs, independent scoring, and correctness gates."""

import hashlib
import json
import math
Expand All @@ -12,13 +17,13 @@
# Analytic numerical systems, not fertilizer identities. Each reference receives
# precisely these rows and RHS; no library filtering or regularization is hidden.
NNLS_CASES = {
"exact": ([[1., 0.], [0., 1.], [1., 1.]], [2., 3., 5.]),
"infeasible": ([[1.], [1.]], [1., 3.]),
"water_exceeds_target": ([[1., 0.], [0., 1.]], [-1., 2.]),
"duplicate_columns": ([[1., 1.], [2., 2.]], [3., 6.]),
"near_dependent": ([[1., 1.], [1., 1.000001], [0., .000001]], [2., 2.000001, .000001]),
"trace_scale": ([[1., 0.], [0., 1.]], [1e-8, 1.]),
"zero_target": ([[1., 0.], [0., 1.]], [0., 1.]),
"exact": ([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], [2.0, 3.0, 5.0]),
"infeasible": ([[1.0], [1.0]], [1.0, 3.0]),
"water_exceeds_target": ([[1.0, 0.0], [0.0, 1.0]], [-1.0, 2.0]),
"duplicate_columns": ([[1.0, 1.0], [2.0, 2.0]], [3.0, 6.0]),
"near_dependent": ([[1.0, 1.0], [1.0, 1.000001], [0.0, 0.000001]], [2.0, 2.000001, 0.000001]),
"trace_scale": ([[1.0, 0.0], [0.0, 1.0]], [1e-8, 1.0]),
"zero_target": ([[1.0, 0.0], [0.0, 1.0]], [0.0, 1.0]),
}


Expand All @@ -38,11 +43,12 @@ def read_fixture(relative):
def objective(matrix, rhs, weights):
if len(weights) != len(matrix[0]) or any(not math.isfinite(x) or x < 0 for x in weights):
raise ValueError("Invalid nonnegative solution")
return float(sum((sum(a*x for a, x in zip(row, weights)) - b)**2
for row, b in zip(matrix, rhs)))
return float(
sum((sum(a * x for a, x in zip(row, weights)) - b) ** 2 for row, b in zip(matrix, rhs))
)


def evaluate_recipe(products, result, targets, water, *, absolute_mg_l=.01, relative=.01):
def evaluate_recipe(products, result, targets, water, *, absolute_mg_l=0.01, relative=0.01):
"""Reconstruct target nutrients from returned rounded doses, not solver rows.

Catalogue-assay evaluator: unassayed counterions are outside this target-fit
Expand All @@ -57,26 +63,35 @@ def evaluate_recipe(products, result, targets, water, *, absolute_mg_l=.01, rela
raise ValueError("Invalid, duplicate or unidentified returned dose")
seen.add(ident)
for ion, percent in by_id[ident]["elements"].items():
delivered[ion] = delivered.get(ion, 0.) + dose * percent * 10.
delivered[ion] = delivered.get(ion, 0.0) + dose * percent * 10.0
rows = []
for ion, target in targets.items():
actual = delivered.get(ion, 0.)
actual = delivered.get(ion, 0.0)
error = actual - target
rows.append({
"ion": ion, "target_mg_l": target, "delivered_mg_l": actual,
"error_mg_l": error,
"error_percent": 100 * error / target if target > 0 else None,
"tolerance_mg_l": max(absolute_mg_l, relative * abs(target)),
"passes": abs(error) <= max(absolute_mg_l, relative * abs(target)),
})
return {"rows": rows, "whole_recipe_passes": all(r["passes"] for r in rows),
"products_used": len(seen), "delivered_assay_mg_l": delivered,
"solver_feasible": result.get("feasible"),
"incidental_requires_review": result.get("requiresReview")}
rows.append(
{
"ion": ion,
"target_mg_l": target,
"delivered_mg_l": actual,
"error_mg_l": error,
"error_percent": 100 * error / target if target > 0 else None,
"tolerance_mg_l": max(absolute_mg_l, relative * abs(target)),
"passes": abs(error) <= max(absolute_mg_l, relative * abs(target)),
}
)
return {
"rows": rows,
"whole_recipe_passes": all(r["passes"] for r in rows),
"products_used": len(seen),
"delivered_assay_mg_l": delivered,
"solver_feasible": result.get("feasible"),
"incidental_requires_review": result.get("requiresReview"),
}


def solve_fixture(data):
from flahax.aqueous_model import solve, nitric_target

row = data["selected_rows"][-1]
if data.get("nitric_acid_molal") is not None:
plan = nitric_target(data["runtime_totals"], data["initial_ph"], row["pH"])
Expand All @@ -89,47 +104,83 @@ def evaluate_chemistry(data, result, acid=None):
row, tol = data["selected_rows"][-1], data["tolerances"]
checks = []

def check(quantity, actual, expected, absolute, relative=0.):
def check(quantity, actual, expected, absolute, relative=0.0):
limit = absolute + relative * abs(expected)
checks.append({"quantity": quantity, "actual": actual, "reference": expected,
"absolute_error": abs(actual-expected), "tolerance": limit,
"passes": math.isfinite(actual) and abs(actual-expected) <= limit})
checks.append(
{
"quantity": quantity,
"actual": actual,
"reference": expected,
"absolute_error": abs(actual - expected),
"tolerance": limit,
"passes": math.isfinite(actual) and abs(actual - expected) <= limit,
}
)

phase_case = "phases" in data
for component, residual in result.residuals.items():
check("conservation:" + component, residual, 0., 1e-15 + 1e-9 * result.totals[component])
check("ionic_strength_mol_kgw", result.ionic_strength, row["mu"], 1e-9, .03)
check("conservation:" + component, residual, 0.0, 1e-15 + 1e-9 * result.totals[component])
check("ionic_strength_mol_kgw", result.ionic_strength, row["mu"], 1e-9, 0.03)
# pH is prescribed for these captures, not an independently solved pH test.
check("prescribed_pH", result.ph, row["pH"], 1e-12)
for key, expected in row.items():
if key.startswith("m_"):
check(key, result.species[key[2:]], expected,
tol["molality_absolute" if phase_case else "runtime_molality_absolute"],
tol["molality_relative" if phase_case else "runtime_molality_relative"])
check(
key,
result.species[key[2:]],
expected,
tol["molality_absolute" if phase_case else "runtime_molality_absolute"],
tol["molality_relative" if phase_case else "runtime_molality_relative"],
)
elif key.startswith("si_"):
check(key, result.saturation_indices[key[3:]], expected,
tol["si_absolute" if phase_case else "runtime_si_absolute"])
elif key.startswith("la_") and not phase_case and row.get("m_" + key[3:], 0.) > 1e-10:
check(key, math.log10(result.activities[key[3:]]), expected,
tol["runtime_log_activity_absolute"])
check(
key,
result.saturation_indices[key[3:]],
expected,
tol["si_absolute" if phase_case else "runtime_si_absolute"],
)
elif key.startswith("la_") and not phase_case and row.get("m_" + key[3:], 0.0) > 1e-10:
check(
key,
math.log10(result.activities[key[3:]]),
expected,
tol["runtime_log_activity_absolute"],
)
for phase in data.get("phases", []):
amount = result.precipitated.get(phase, 0.)
check("phase_mol_kgw:" + phase, amount, row[phase] / row["mass_H2O"],
tol["phase_absolute"], tol["phase_relative"])
amount = result.precipitated.get(phase, 0.0)
check(
"phase_mol_kgw:" + phase,
amount,
row[phase] / row["mass_H2O"],
tol["phase_absolute"],
tol["phase_relative"],
)
si = result.saturation_indices.get(phase)
# Inapplicable phases may be absent when their components are absent.
if si is not None:
checks.append({"quantity": "phase_complementarity:" + phase,
"amount_mol_kgw": amount, "saturation_index": si,
"passes": amount >= 0 and si <= 1e-7
and (amount == 0 or abs(si) <= 1e-7)})
checks.append(
{
"quantity": "phase_complementarity:" + phase,
"amount_mol_kgw": amount,
"saturation_index": si,
"passes": amount >= 0 and si <= 1e-7 and (amount == 0 or abs(si) <= 1e-7),
}
)
if acid is not None:
for name in ("nitric_acid_molal", "fix_h_nitric_acid_molal"):
check(name, acid, data[name], tol["acid_absolute"], tol["acid_relative"])
checks.append({"quantity": "iterations", "actual": result.iterations,
"passes": 0 <= result.iterations < 1500})
return {"passes": all(c["passes"] for c in checks),
"iterations": result.iterations, "checks": checks}
checks.append(
{
"quantity": "iterations",
"actual": result.iterations,
"passes": 0 <= result.iterations < 1500,
}
)
return {
"passes": all(c["passes"] for c in checks),
"iterations": result.iterations,
"checks": checks,
}


def require_chemistry(data, result, acid=None):
Expand Down
Loading
Loading
0