fieldcheck-workshop 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. fieldcheck_workshop-0.1.0/.github/workflows/autoformat.yml +47 -0
  2. fieldcheck_workshop-0.1.0/.github/workflows/ci.yml +28 -0
  3. fieldcheck_workshop-0.1.0/.github/workflows/doc.yml +49 -0
  4. fieldcheck_workshop-0.1.0/.github/workflows/publish-pypi.yml +52 -0
  5. fieldcheck_workshop-0.1.0/.github/workflows/ruff.yml +17 -0
  6. fieldcheck_workshop-0.1.0/.gitignore +22 -0
  7. fieldcheck_workshop-0.1.0/PKG-INFO +7 -0
  8. fieldcheck_workshop-0.1.0/README.md +30 -0
  9. fieldcheck_workshop-0.1.0/archive/analysis.py +38 -0
  10. fieldcheck_workshop-0.1.0/archive/baseline.json +1 -0
  11. fieldcheck_workshop-0.1.0/data/README.md +50 -0
  12. fieldcheck_workshop-0.1.0/data/all_invalid.csv +4 -0
  13. fieldcheck_workshop-0.1.0/data/malformed.csv +2 -0
  14. fieldcheck_workshop-0.1.0/data/tiny.csv +9 -0
  15. fieldcheck_workshop-0.1.0/examples/README.md +33 -0
  16. fieldcheck_workshop-0.1.0/examples/compare_baseline.py +35 -0
  17. fieldcheck_workshop-0.1.0/examples/count.py +5 -0
  18. fieldcheck_workshop-0.1.0/examples/docstring.txt +21 -0
  19. fieldcheck_workshop-0.1.0/examples/environment_info.py +30 -0
  20. fieldcheck_workshop-0.1.0/examples/inspect_rows.py +28 -0
  21. fieldcheck_workshop-0.1.0/examples/logging_demo.py +10 -0
  22. fieldcheck_workshop-0.1.0/examples/test_cleanup.py +16 -0
  23. fieldcheck_workshop-0.1.0/examples/test_mock.py +15 -0
  24. fieldcheck_workshop-0.1.0/examples/test_report_demo.py +19 -0
  25. fieldcheck_workshop-0.1.0/examples/test_sorting.py +13 -0
  26. fieldcheck_workshop-0.1.0/examples/test_tdd_demo.py +14 -0
  27. fieldcheck_workshop-0.1.0/pyproject.toml +35 -0
  28. fieldcheck_workshop-0.1.0/src/fieldcheck/__init__.py +5 -0
  29. fieldcheck_workshop-0.1.0/src/fieldcheck/cli.py +78 -0
  30. fieldcheck_workshop-0.1.0/src/fieldcheck/core.py +149 -0
  31. fieldcheck_workshop-0.1.0/src/fieldcheck/io.py +44 -0
  32. fieldcheck_workshop-0.1.0/tests/test_core.py +7 -0
  33. fieldcheck_workshop-0.1.0/tests/test_report.py +14 -0
  34. fieldcheck_workshop-0.1.0/tests/test_scalar.py +31 -0
@@ -0,0 +1,47 @@
1
+ name: Autoformat Python
2
+
3
+ on:
4
+ push:
5
+ branches: ["**"]
6
+
7
+ permissions:
8
+ contents: write
9
+
10
+ concurrency:
11
+ group: ruff-format-${{ github.ref }}
12
+ cancel-in-progress: true
13
+
14
+ jobs:
15
+ format:
16
+ runs-on: ubuntu-latest
17
+
18
+ steps:
19
+ - name: Check out branch
20
+ uses: actions/checkout@v7
21
+ with:
22
+ ref: ${{ github.ref_name }}
23
+
24
+ - name: Apply Ruff formatting
25
+ uses: astral-sh/ruff-action@v4.1.0
26
+ with:
27
+ args: format
28
+
29
+ - name: Commit and push formatting changes
30
+ run: |
31
+ git add -u
32
+
33
+ # Check if there are any changes
34
+ if git diff --cached --quiet; then
35
+ echo "No changes to commit."
36
+ exit 0
37
+ fi
38
+
39
+ # Configure Git identity
40
+ git config user.name "github-actions[bot]"
41
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
42
+
43
+ # Commit changes
44
+ git commit -m "style: apply Ruff formatting"
45
+
46
+ # Push changes (requires token)
47
+ git push origin ${{ github.ref_name }}
@@ -0,0 +1,28 @@
1
+ name: checks
2
+ on: [push, pull_request]
3
+ permissions:
4
+ contents: read
5
+ jobs:
6
+ test:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: [3.12, 3.13]
11
+
12
+ steps:
13
+ - name: Checkout code
14
+ uses: actions/checkout@v7
15
+
16
+ - name: Set up uv and Python ${{ matrix.python-version }}
17
+ uses: astral-sh/setup-uv@v9.0.0
18
+ with:
19
+ version: "0.13.7"
20
+ python-version: ${{ matrix.python-version }}
21
+
22
+ - name: Install dependencies
23
+ run: |
24
+ uv sync
25
+
26
+ - name: Run tests with coverage
27
+ run: |
28
+ uv run pytest --cov=fieldcheck
@@ -0,0 +1,49 @@
1
+ name: Documentation
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+ pages: write
11
+ id-token: write
12
+
13
+ concurrency:
14
+ group: github-pages
15
+ cancel-in-progress: false
16
+
17
+ jobs:
18
+ docs:
19
+ runs-on: ubuntu-latest
20
+ environment:
21
+ name: github-pages
22
+ url: ${{ steps.deployment.outputs.page_url }}
23
+
24
+ steps:
25
+ - name: Checkout code
26
+ uses: actions/checkout@v7
27
+ - uses: astral-sh/setup-uv@v9.0.0
28
+ with:
29
+ version: "0.13.7"
30
+ python-version: "3.12"
31
+
32
+ - name: Install dependencies
33
+ run: |
34
+ uv sync
35
+
36
+ - name: Build documentation
37
+ run: uv run pdoc fieldcheck -o site
38
+
39
+ - name: Configure Pages
40
+ uses: actions/configure-pages@v5
41
+
42
+ - name: Upload artifact
43
+ uses: actions/upload-pages-artifact@v4
44
+ with:
45
+ path: site
46
+
47
+ - name: Deploy to GitHub Pages
48
+ id: deployment
49
+ uses: actions/deploy-pages@v5
@@ -0,0 +1,52 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - name: Checkout code
16
+ uses: actions/checkout@v7
17
+ with:
18
+ fetch-depth: 0
19
+ persist-credentials: false
20
+
21
+ - uses: astral-sh/setup-uv@v9.0.0
22
+ with:
23
+ python-version: "3.12"
24
+
25
+ - name: Build package
26
+ run: |
27
+ uv sync
28
+ uv build
29
+
30
+ - name: Upload artifacts
31
+ uses: actions/upload-artifact@v5
32
+ with:
33
+ name: distributions
34
+ path: dist/
35
+
36
+ publish:
37
+ needs: build
38
+ runs-on: ubuntu-latest
39
+ environment: pypi
40
+
41
+ permissions:
42
+ id-token: write
43
+
44
+ steps:
45
+ - name: Download artifacts
46
+ uses: actions/download-artifact@v6
47
+ with:
48
+ name: distributions
49
+ path: dist/
50
+
51
+ - name: Publish to PyPI
52
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,17 @@
1
+ name: checks-ruff
2
+ on: [push, pull_request]
3
+ permissions:
4
+ contents: read
5
+ jobs:
6
+ test:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v7.0.1
10
+ - uses: astral-sh/setup-uv@v9.0.0
11
+ with:
12
+ version: "0.13.7"
13
+ python-version: "3.12"
14
+ - run: |
15
+ uv run ruff check .
16
+ uv run ruff format --check .
17
+ uv run ruff format .
@@ -0,0 +1,22 @@
1
+ .venv/
2
+ __pycache__/
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ .coverage
6
+ htmlcov/
7
+ dist/
8
+ reports/
9
+ *.egg-info/
10
+ api-docs/
11
+ .uv-cache/
12
+ analysis.log
13
+
14
+ # Output from the original ad hoc script
15
+ report.json
16
+
17
+
18
+ # Custom
19
+ .idea/
20
+ .python-version
21
+ uv.lock
22
+ project-review.md
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.5
2
+ Name: fieldcheck-workshop
3
+ Version: 0.1.0
4
+ Summary: Synthetic reflectance analysis for a research software workshop
5
+ Requires-Python: <3.16,>=3.12
6
+ Requires-Dist: numpy<3,>=2
7
+ Requires-Dist: pdoc
@@ -0,0 +1,30 @@
1
+ # Fieldcheck: an ad hoc analysis
2
+
3
+ whatever - first change happning here in the repro.
4
+
5
+ This is the starting material for Lab 1. It contains one Python script and
6
+ synthetic CSV data. You will develop this script into a structured, tested,
7
+ documented Python package during the workshop.
8
+
9
+ Copy this folder to `fieldcheck-work`, beside the `course-2026` materials folder.
10
+ Open a terminal in your copy and try:
11
+
12
+ ```sh
13
+ python analysis.py
14
+ ```
15
+
16
+ Use `python3` if that is your Python 3 launcher. The script uses only Python's
17
+ standard library. No package installation or project environment is needed yet.
18
+ It reads `data/tiny.csv` and writes `report.json` in the current directory.
19
+
20
+ Read the course's `docs/EXERCISE.md` for the data rules and worked answer, then
21
+ follow Lab 1 in `docs/WORKBOOK.md`. Keep the CSV inputs unchanged. Record what
22
+ happens when you run the script and the issues you find while reading it.
23
+ Look beyond numerical correctness: can you understand, reuse, test,
24
+ or run this program on another input? Do not repair it during Lab 1.
25
+
26
+ The later labs introduce functions, package structure, uv, Git, tests,
27
+ documentation, automation, and delivery. Their scaffolds are in the course
28
+ materials; they are not part of this starting script.
29
+
30
+ All data are synthetic. Do not publish this teaching project.
@@ -0,0 +1,38 @@
1
+ import csv
2
+ import json
3
+ import math
4
+
5
+ f = open("data/tiny.csv")
6
+ rows = list(csv.DictReader(f))
7
+ values = []
8
+
9
+ for row in rows:
10
+ red = float(row["red"])
11
+ nir = float(row["nir"])
12
+ quality = int(row["quality"])
13
+ if red + nir == 0:
14
+ value = float("nan")
15
+ else:
16
+ value = (nir - red) / (nir + red)
17
+ values.append(value)
18
+ print(row["id"], value)
19
+
20
+ valid_values = []
21
+ for value in values:
22
+ if math.isfinite(value):
23
+ valid_values.append(value)
24
+
25
+ n = sum(value != 0 for value in valid_values)
26
+ mean = sum(valid_values) / len(valid_values)
27
+ print("total:", len(values), "valid:", n, "mean:", mean)
28
+
29
+ out = open("report.json", "w")
30
+ json.dump(
31
+ {
32
+ "n_total": len(values),
33
+ "n_valid": sum(value != 0 for value in valid_values),
34
+ "mean_ndvi": sum(valid_values) / len(valid_values),
35
+ },
36
+ out,
37
+ )
38
+ out.close()
@@ -0,0 +1 @@
1
+ {"n_total": 8, "n_valid": 5, "mean_ndvi": 0.18333333333333335}
@@ -0,0 +1,50 @@
1
+ # Synthetic observations
2
+
3
+ These hand-authored rows are teaching data, not satellite observations.
4
+ `red` and `nir` are already-scaled dimensionless reflectances. The workshop's
5
+ [0,1] and binary quality rules are an explicit simplification, not a universal
6
+ satellite-product specification. Real products need their own scaling, masks,
7
+ spatial alignment, and scientific validation.
8
+
9
+ For `tiny.csv`, valid NDVIs are `[0.5, -0.5, 0, 1]`; the other four rows are
10
+ invalid. Expected counts: total 8, valid 4. Expected mean: 0.25. Compare floating
11
+ point values with a tolerance; no random inputs or network downloads are needed.
12
+
13
+ ## Work out the answer before running the code
14
+
15
+ For each row, apply the quality, finite-value, range, and positive-denominator
16
+ rules before calculating `(nir - red) / (nir + red)`.
17
+
18
+ | Row | Red | NIR | Quality | Expected NDVI | Reason |
19
+ | --- | --- | --- | --- | --- | --- |
20
+ | `a` | `0.2` | `0.6` | `0` | `0.5` | Clear, finite bands within range. |
21
+ | `b` | `0.6` | `0.2` | `0` | `-0.5` | A negative result remains a valid measurement. |
22
+ | `c` | `0.3` | `0.3` | `0` | `0.0` | Equal nonzero bands; zero must count as valid. |
23
+ | `d` | `0.0` | `0.8` | `0` | `1.0` | One zero band is allowed; the sum is positive. |
24
+ | `e` | `0.0` | `0.0` | `0` | `NaN` | Both bands zero: the denominator would be zero. |
25
+ | `f` | `NaN` | `0.4` | `0` | `NaN` | A band is missing. |
26
+ | `g` | `0.2` | `0.8` | `1` | `NaN` | The quality flag excludes an otherwise finite result. |
27
+ | `h` | `1.2` | `0.4` | `0` | `NaN` | Red exceeds the workshop's allowed range. |
28
+
29
+ The four retained values sum to `1.0`; dividing by `4` gives `0.25`.
30
+ These hand-computed expectations are the independent reference for the tests.
31
+
32
+ Run `uv run python examples/inspect_rows.py` from the project root to display
33
+ what your current implementation actually computes. Compare row IDs with the
34
+ table, including excluded rows. The helper calls your code; its output is an
35
+ observation, not proof of correctness. The starter will disagree on rows `g`
36
+ and `h` and on the valid count. After Labs 4 and 5 all rows should agree.
37
+
38
+ ## Connect the exercise to your EO work
39
+
40
+ Before using these checks on a real product, identify its band mapping, scale
41
+ and offset, nodata values, quality-mask definition, and spatial/temporal
42
+ alignment. Write down which observations the statistic should include. The
43
+ binary flag and `[0,1]` rule above are choices for this exercise, not product
44
+ metadata. An eight-row test does not establish the scientific suitability of
45
+ a real dataset or processing chain.
46
+
47
+ The [USGS NDVI reference](https://www.usgs.gov/landsat-missions/landsat-normalized-difference-vegetation-index)
48
+ documents the ratio and shows that band mappings and stored index values depend
49
+ on the product. Use the documentation for your actual product when transferring
50
+ the workflow.
@@ -0,0 +1,4 @@
1
+ id,red,nir,quality
2
+ a,0,0,0
3
+ b,0.2,0.8,1
4
+ c,nan,0.4,0
@@ -0,0 +1,2 @@
1
+ id,red,nir,quality
2
+ a,0.2,oops,0
@@ -0,0 +1,9 @@
1
+ id,red,nir,quality
2
+ a,0.2,0.6,0
3
+ b,0.6,0.2,0
4
+ c,0.3,0.3,0
5
+ d,0.0,0.8,0
6
+ e,0.0,0.0,0
7
+ f,nan,0.4,0
8
+ g,0.2,0.8,1
9
+ h,1.2,0.4,0
@@ -0,0 +1,33 @@
1
+ # Worked demonstrations
2
+
3
+ Run commands from the project root, beside `pyproject.toml`.
4
+
5
+ - `uv run --locked python examples/environment_info.py`: record interpreter and
6
+ package versions plus metadata, lockfile, and input checksums for Lab 2.
7
+ - `uv run python examples/inspect_rows.py`: display each current NDVI and the
8
+ summary. Compare row IDs against the independent table in `data/README.md`;
9
+ the extracted baseline disagrees, and the repaired project should agree after Lab 5.
10
+ - `uv run python examples/count.py`: the extracted baseline reports the deliberately wrong
11
+ count 1; after Lab 4, count 2 and mean 0.25.
12
+ - `uv run pytest examples/test_tdd_demo.py -q`: intentionally fails initially.
13
+ The slides show a formula, a new excluded-row test, and then a quality guard.
14
+ This is separate from the real `src/fieldcheck/core.py` lab implementation.
15
+ - `uv run pytest examples/test_report_demo.py -q`: fails on the extracted baseline;
16
+ passes after the day-one repairs. Lab 7 copies it into `tests/test_report.py`.
17
+
18
+ Normal `uv run pytest -q` only discovers `tests/`, so these staged demonstrations
19
+ cannot accidentally make the ordinary suite red. `ruff` still checks their code.
20
+
21
+ Additional demonstrations (not extra required labs):
22
+
23
+ - `uv run python examples/logging_demo.py`: INFO and WARNING in `analysis.log`;
24
+ change INFO to DEBUG to see all three messages. The file appends by default.
25
+ - `uv run pytest examples/test_cleanup.py examples/test_mock.py -q`: two passes.
26
+ - `uv run pytest examples/test_sorting.py -q`: four passes. Try `sorted(set(values))`
27
+ in a disposable copy; the duplicate case must fail.
28
+ - `docstring.txt`: NumPy-style replacement for the scalar function's docstring.
29
+
30
+ `compare_baseline.py` is for Lab 2 only. It runs the archived ad hoc script in a
31
+ temporary directory and compares its summary with the package. It passes for
32
+ the package checkpoint and deliberately fails after the numerical repairs.
33
+ Do not include it in the normal test suite or CI.
@@ -0,0 +1,35 @@
1
+ """Lab 2 only: check that extraction preserves the original tiny-data summary.
2
+
3
+ This is a characterization check, not evidence of scientific correctness.
4
+ It is expected to fail once Labs 4-5 intentionally repair the calculation.
5
+ """
6
+
7
+ import json
8
+ import math
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ from fieldcheck import ndvi, summarize
16
+ from fieldcheck.io import read_csv
17
+
18
+ root = Path(__file__).resolve().parents[1]
19
+ with tempfile.TemporaryDirectory(prefix="fieldcheck-baseline-") as directory:
20
+ temporary = Path(directory)
21
+ shutil.copytree(root / "data", temporary / "data")
22
+ subprocess.run(
23
+ [sys.executable, str(root / "archive/analysis.py")],
24
+ cwd=temporary,
25
+ check=True,
26
+ capture_output=True,
27
+ text=True,
28
+ )
29
+ baseline = json.loads((temporary / "report.json").read_text())
30
+ actual = summarize(ndvi(*read_csv(root / "data/tiny.csv")))
31
+ assert actual["n_total"] == baseline["n_total"], (actual, baseline)
32
+ assert actual["n_valid"] == baseline["n_valid"], (actual, baseline)
33
+ assert math.isclose(actual["mean_ndvi"], baseline["mean_ndvi"], abs_tol=1e-12)
34
+ print("Original tiny-data behavior preserved: total=8 valid=5 mean=0.183333")
35
+ print("This preserves known defects. It does not establish a correct analysis.")
@@ -0,0 +1,5 @@
1
+ """Minimal input for the guided summary-count debugging demonstration."""
2
+
3
+ from fieldcheck.core import summarize
4
+
5
+ print(summarize([0.0, 0.5, float("nan")]))
@@ -0,0 +1,21 @@
1
+ """Compute NDVI for one observation.
2
+
3
+ Parameters
4
+ ----------
5
+ red, nir : float
6
+ Already-scaled, dimensionless reflectances in [0, 1].
7
+ quality : int
8
+ 0 means clear; 1 excludes the row.
9
+
10
+ Returns
11
+ -------
12
+ float
13
+ (nir - red) / (nir + red), or NaN for excluded rows, nonfinite
14
+ or out-of-range bands, or a zero denominator.
15
+ Negative and zero results are valid.
16
+
17
+ Raises
18
+ ------
19
+ ValueError
20
+ If quality is neither 0 nor 1.
21
+ """
@@ -0,0 +1,30 @@
1
+ """Print reproducibility evidence without treating local paths as portable."""
2
+
3
+ import hashlib
4
+ import json
5
+ import platform
6
+ import sys
7
+ from importlib.metadata import version
8
+ from pathlib import Path
9
+
10
+
11
+ def main():
12
+ root = Path(__file__).resolve().parents[1]
13
+ evidence = {
14
+ "python": platform.python_version(),
15
+ "executable": sys.executable,
16
+ "in_virtual_environment": sys.prefix != sys.base_prefix,
17
+ "packages": {
18
+ name: version(name)
19
+ for name in ("fieldcheck-workshop", "numpy", "pytest", "ruff")
20
+ },
21
+ "sha256": {
22
+ name: hashlib.sha256((root / name).read_bytes()).hexdigest()
23
+ for name in ("pyproject.toml", "uv.lock", "data/tiny.csv")
24
+ },
25
+ }
26
+ print(json.dumps(evidence, indent=2))
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
@@ -0,0 +1,28 @@
1
+ """Show the current calculation; compare it with the hand-worked data/README.md."""
2
+
3
+ import csv
4
+ import math
5
+ from pathlib import Path
6
+
7
+ from fieldcheck.core import ndvi_value, summarize
8
+
9
+
10
+ def main():
11
+ print("Current implementation: compare each row with data/README.md")
12
+ values = []
13
+ with Path("data/tiny.csv").open(encoding="utf-8", newline="") as stream:
14
+ for row in csv.DictReader(stream):
15
+ value = ndvi_value(
16
+ float(row["red"]), float(row["nir"]), int(row["quality"])
17
+ )
18
+ values.append(value)
19
+ displayed = f"{value:.6f}" if math.isfinite(value) else "NaN (excluded)"
20
+ print(f"{row['id']}: {displayed}")
21
+ report = summarize(values)
22
+ mean = report["mean_ndvi"]
23
+ displayed_mean = "None" if mean is None else f"{mean:.6f}"
24
+ print(f"total={report['n_total']} valid={report['n_valid']} mean={displayed_mean}")
25
+
26
+
27
+ if __name__ == "__main__":
28
+ main()
@@ -0,0 +1,10 @@
1
+ """Standalone file-logging demonstration; inspect analysis.log afterward."""
2
+
3
+ import logging
4
+
5
+ logging.basicConfig(
6
+ filename="analysis.log", level=logging.INFO, format="%(levelname)s: %(message)s"
7
+ )
8
+ logging.debug("Reading one row")
9
+ logging.info("Analysis started")
10
+ logging.warning("Some rows were excluded")
@@ -0,0 +1,16 @@
1
+ """Observe fixture setup and teardown with pytest -s."""
2
+
3
+ import pytest
4
+
5
+
6
+ @pytest.fixture
7
+ def opened_file(tmp_path):
8
+ stream = (tmp_path / "sample.txt").open("w+")
9
+ yield stream
10
+ stream.close()
11
+ assert stream.closed
12
+
13
+
14
+ def test_file(opened_file):
15
+ opened_file.write("sample")
16
+ assert not opened_file.closed
@@ -0,0 +1,15 @@
1
+ """Mock an unavailable input boundary, not the scientific calculation."""
2
+
3
+ from unittest.mock import MagicMock
4
+
5
+ from fieldcheck import cli
6
+
7
+
8
+ def test_read_failure(monkeypatch, tmp_path):
9
+ read = MagicMock(side_effect=OSError("unavailable"))
10
+ monkeypatch.setattr(cli, "read_csv", read)
11
+ output = tmp_path / "out.json"
12
+ args = ["input.csv", "--output", str(output)]
13
+ assert cli.main(args) == 2
14
+ read.assert_called_once()
15
+ assert not output.exists()
@@ -0,0 +1,19 @@
1
+ """Integration example: expected to pass after the day-one repairs.
2
+
3
+ Run from the project folder: uv run pytest examples/test_report_demo.py -q.
4
+ """
5
+
6
+ import json
7
+
8
+ import pytest
9
+
10
+ from fieldcheck.cli import main
11
+
12
+
13
+ def test_report(tmp_path):
14
+ output = tmp_path / "report.json"
15
+ assert main(["data/tiny.csv", "--output", str(output)]) == 0
16
+ report = json.loads(output.read_text())
17
+ assert report["n_valid"] == 4
18
+ assert report["mean_ndvi"] == pytest.approx(0.25)
19
+ assert len(report["input_sha256"]) == 64
@@ -0,0 +1,13 @@
1
+ """A quiz: order alone does not show that all observations were preserved."""
2
+
3
+ from collections import Counter
4
+
5
+ import pytest
6
+
7
+
8
+ @pytest.mark.parametrize("values", [[], [1], [2, 1], [1, 2, 1]])
9
+ def test_sorting(values):
10
+ result = sorted(values)
11
+ for index in range(1, len(result)):
12
+ assert result[index - 1] <= result[index]
13
+ assert Counter(result) == Counter(values)
@@ -0,0 +1,14 @@
1
+ """Intentionally red first step of the TDD demonstration.
2
+
3
+ Run explicitly; examples/ is outside the ordinary tests/ discovery directory.
4
+ """
5
+
6
+ import pytest
7
+
8
+
9
+ def ndvi_value(red, nir, quality):
10
+ return 0.0 # Deliberately unfinished: complete this in the demonstration.
11
+
12
+
13
+ def test_clear():
14
+ assert ndvi_value(0.2, 0.6, 0) == pytest.approx(0.5)
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "fieldcheck-workshop"
7
+ version = "0.1.0"
8
+ description = "Synthetic reflectance analysis for a research software workshop"
9
+ requires-python = ">=3.12,<3.16"
10
+ dependencies = [
11
+ "numpy>=2,<3",
12
+ "pdoc",
13
+ ]
14
+
15
+ [project.scripts]
16
+ fieldcheck = "fieldcheck.cli:main"
17
+
18
+ [dependency-groups]
19
+ dev = ["pytest>=8,<10", "pytest-cov>=6,<8", "ruff>=0.14,<1"]
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/fieldcheck"]
23
+
24
+ [tool.pytest.ini_options]
25
+ testpaths = ["tests"]
26
+ addopts = "-ra"
27
+ filterwarnings = ["error"]
28
+
29
+ [tool.ruff]
30
+ extend-exclude = ["archive"]
31
+ target-version = "py312"
32
+ line-length = 88
33
+
34
+ [tool.ruff.lint]
35
+ select = ["E4", "E7", "E9", "F", "I", "B"]
@@ -0,0 +1,5 @@
1
+ """Synthetic-data analysis for teaching."""
2
+
3
+ from .core import ndvi, ndvi_value, summarize
4
+
5
+ __all__ = ["ndvi", "ndvi_value", "summarize"]
@@ -0,0 +1,78 @@
1
+ """Command-line boundary: parse, read, calculate, record provenance, report."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import platform
8
+ from importlib.metadata import version
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ from fieldcheck.core import ndvi, summarize
14
+ from fieldcheck.io import read_csv
15
+
16
+ logger = logging.getLogger(__name__)
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format="%(levelname)s: %(message)s",
20
+ )
21
+
22
+
23
+ def main(argv=None):
24
+ """
25
+ Summarize NDVI from synthetic reflectance CSV and write report.
26
+
27
+ Reads red/NIR/quality data, computes NDVI, and saves summary stats
28
+ including input hash and version info.
29
+
30
+ Parameters
31
+ ----------
32
+ argv : list, optional
33
+ Command-line arguments (for testing). Defaults to sys.argv.
34
+
35
+ Returns
36
+ -------
37
+ int
38
+ Exit code: 0 on success, 2 on error.
39
+ """
40
+ parser = argparse.ArgumentParser(description="Summarize synthetic reflectance CSV")
41
+ parser.add_argument("input", default="data/tiny.csv", type=Path)
42
+ parser.add_argument(
43
+ "--output", default="reports/report.json", type=Path, required=True
44
+ )
45
+ parser.add_argument("--verbose", action="store_true")
46
+ args = parser.parse_args(argv)
47
+ logging.basicConfig(
48
+ level=logging.DEBUG if args.verbose else logging.INFO,
49
+ format="%(levelname)s: %(message)s",
50
+ )
51
+ if args.input.resolve() == args.output.resolve():
52
+ parser.error("input and output paths must differ")
53
+ try:
54
+ red, nir, quality = read_csv(args.input)
55
+ values = ndvi(red, nir, quality)
56
+ report = summarize(values)
57
+ if report["n_valid"] == 0:
58
+ raise ValueError("need at least 1 valid observations")
59
+ report["input_sha256"] = hashlib.sha256(args.input.read_bytes()).hexdigest()
60
+ report["versions"] = {
61
+ "python": platform.python_version(),
62
+ "numpy": np.__version__,
63
+ "fieldcheck": version("fieldcheck-workshop"),
64
+ }
65
+ args.output.parent.mkdir(parents=True, exist_ok=True)
66
+ args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
67
+ except (OSError, ValueError) as exc:
68
+ logger.error("%s", exc)
69
+ return 2
70
+ logger.info(
71
+ "Wrote %s (%s/%s valid)", args.output, report["n_valid"], report["n_total"]
72
+ )
73
+ return 0
74
+
75
+
76
+ # python cli.py --input data/tiny.csv --input data/test.csv
77
+ if __name__ == "__main__":
78
+ raise SystemExit(main())
@@ -0,0 +1,149 @@
1
+ """Small, readable research-calculation example for the workshop."""
2
+
3
+ import logging
4
+ import math
5
+
6
+ import numpy as np
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def ndvi_value(red, nir, quality):
12
+ """Return one index, or NaN for an excluded/invalid measurement.
13
+
14
+ Bands are already-scaled, dimensionless reflectances in [0, 1].
15
+ Quality is 0 (clear) or 1 (excluded); other codes raise ValueError.
16
+ Negative and zero NDVI values remain valid.
17
+
18
+ Parameters
19
+ ----------
20
+ red : float
21
+ value of red
22
+ nir : float
23
+ near infrared value
24
+ quality : int
25
+ quality of the value
26
+
27
+ Returns
28
+ -------
29
+ float
30
+ gives back the calculated nvdi value
31
+ """
32
+ # Move the calculation from archive/analysis.py here; return its value.
33
+ # Preserve its existing numerical behavior for now, including its defects.
34
+ if quality not in [0, 1]:
35
+ raise ValueError
36
+ if (
37
+ red + nir <= 0
38
+ or quality != 0
39
+ or not (math.isfinite(nir) and 0 <= nir <= 1)
40
+ or not (math.isfinite(red) and 0 <= red <= 1)
41
+ ):
42
+ value = float("nan")
43
+ else:
44
+ value = (nir - red) / (nir + red)
45
+ return value
46
+
47
+
48
+ def ndvi(red, nir, quality):
49
+ """
50
+ Compute NDVI (Normalized Difference Vegetation Index) for multiple pixels.
51
+
52
+ Ts, returning a vector of NDVI values.
53
+
54
+ Parameters
55
+ ----------
56
+ red : array_like
57
+ Array of red band reflectance values (0 to 1). Must be 1-D.
58
+ nir : array_like
59
+ Array of near-infrared (NIR) band reflectance values (0 to 1). Must be 1-D
60
+ and of the same shape as `red`.
61
+ quality : array_like
62
+ Array of quality flags (e.g., 0 = valid, non-zero = invalid). Must be 1-D
63
+ and of the same shape as `red`.
64
+
65
+ Returns
66
+ -------
67
+ ndvi_values : numpy.ndarray
68
+ 1-D array of NDVI values computed as `(nir - red) / (nir + red)` for valid
69
+ pixels. Returns `nan` for invalid pixels (e.g., when `quality != 0` or
70
+ `nir + red <= 0`).
71
+
72
+ Raises
73
+ ------
74
+ ValueError
75
+ If `red`, `nir`, or `quality` are not 1-D arrays of the same shape.
76
+
77
+ See Also
78
+ --------
79
+ ndvi_value : Scalar version of this function for single values.
80
+ numpy.ndarray : Array data type used for input and output.
81
+
82
+ Notes
83
+ -----
84
+ - NDVI is defined as: (NIR - Red) / (NIR + Red)
85
+ - Values range from -1 to +1.
86
+ - Returns `nan` for invalid or zero-sum cases.
87
+ - Input arrays must be finite and in [0, 1] (enforced in `ndvi_value`).
88
+
89
+ Examples
90
+ --------
91
+ >>> red = [0.2, 0.3, 0.0]
92
+ >>> nir = [0.6, 0.4, 0.1]
93
+ >>> quality = [0, 0, 1] # third pixel is invalid
94
+ >>> ndvi(red, nir, quality)
95
+ array([ 0.5 , -0.16666667, nan])
96
+ """
97
+ red = np.asarray(red, dtype=float)
98
+ nir = np.asarray(nir, dtype=float)
99
+ quality = np.asarray(quality)
100
+ if red.ndim != 1 or nir.shape != red.shape or quality.shape != red.shape:
101
+ raise ValueError("red, nir, and quality must be equally shaped 1-D arrays")
102
+ result = []
103
+ for index in range(len(red)):
104
+ result.append(ndvi_value(red[index], nir[index], quality[index]))
105
+ return np.array(result, dtype=float)
106
+
107
+
108
+ def summarize(values):
109
+ """
110
+ Count finite values and compute their mean.
111
+
112
+ Parameters
113
+ ----------
114
+ values : array_like
115
+ 1-D array of numeric values (e.g., NDVI).
116
+
117
+ Returns
118
+ -------
119
+ dict
120
+ Dictionary with:
121
+ - 'n_total': total number of values
122
+ - 'n_valid': number of finite values
123
+ - 'mean_ndvi': mean of finite values, or None if none
124
+
125
+ Examples
126
+ --------
127
+ >>> summarize([1.0, 2.0, float('nan'), 3.0])
128
+ {'n_total': 4, 'n_valid': 3, 'mean_ndvi': 2.0}
129
+ """
130
+ values = np.asarray(values, dtype=float)
131
+ if values.ndim != 1:
132
+ raise ValueError("values must be 1-D")
133
+ # Supplied boundary: the extracted loop works with ordinary Python numbers.
134
+ values = values.tolist()
135
+ # Move the finite-value loop and summary calculations here.
136
+ valid_values = []
137
+ for value in values:
138
+ if math.isfinite(value):
139
+ valid_values.append(value)
140
+ n = len(valid_values)
141
+ mean = sum(valid_values) / n if n else None
142
+ out = {
143
+ "n_total": len(values),
144
+ "n_valid": n,
145
+ "mean_ndvi": mean,
146
+ }
147
+ return out
148
+ # Use None for an empty mean so the supplied CLI can reject that analysis.
149
+ # raise NotImplementedError("Extract the summary from analysis.py")
@@ -0,0 +1,44 @@
1
+ """Read a tiny CSV; data validation belongs at the input boundary."""
2
+
3
+ import csv
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+
9
+ def read_csv(path: Path):
10
+ """
11
+ Read red, nir, and quality columns from CSV.
12
+
13
+ Additional columns (e.g., id) are allowed.
14
+
15
+ Parameters
16
+ ----------
17
+ path : Path
18
+ Path to input CSV file.
19
+
20
+ Returns
21
+ -------
22
+ tuple of (np.ndarray, np.ndarray, np.ndarray)
23
+ red, nir, and quality arrays (float, float, int).
24
+
25
+ Raises
26
+ ------
27
+ ValueError
28
+ If required columns are missing or values are invalid.
29
+ """
30
+ with path.open(encoding="utf-8", newline="") as stream:
31
+ reader = csv.DictReader(stream)
32
+ if not {"red", "nir", "quality"}.issubset(reader.fieldnames or []):
33
+ raise ValueError("CSV requires red,nir,quality columns")
34
+ red, nir, quality = [], [], []
35
+ for row_number, row in enumerate(reader, 2):
36
+ try:
37
+ red.append(float(row["red"]))
38
+ nir.append(float(row["nir"]))
39
+ quality.append(int(row["quality"]))
40
+ except (ValueError, TypeError) as exc:
41
+ raise ValueError(
42
+ f"invalid numeric value on CSV row {row_number}"
43
+ ) from exc
44
+ return np.array(red), np.array(nir), np.array(quality, dtype=int)
@@ -0,0 +1,7 @@
1
+ import pytest
2
+
3
+ from fieldcheck import ndvi_value
4
+
5
+
6
+ def test_positive_clear_observation():
7
+ assert ndvi_value(0.2, 0.6, 0) == pytest.approx(0.5)
@@ -0,0 +1,14 @@
1
+ import json
2
+
3
+ import pytest
4
+
5
+ from fieldcheck.cli import main
6
+
7
+
8
+ def test_report(tmp_path):
9
+ output = tmp_path / "report.json"
10
+ assert main(["data/tiny.csv", "--output", str(output)]) == 0
11
+ report = json.loads(output.read_text())
12
+ assert report["n_valid"] == 4
13
+ assert report["mean_ndvi"] == pytest.approx(0.25)
14
+ assert len(report["input_sha256"]) == 64
@@ -0,0 +1,31 @@
1
+ import math
2
+
3
+ import pytest
4
+
5
+ from fieldcheck.core import ndvi_value
6
+
7
+
8
+ @pytest.mark.parametrize("red,nir, q, expected", [(0.2, 0.6, 0, 0.5)])
9
+ def test_scalar_regular(red, nir, q, expected):
10
+ assert ndvi_value(red, nir, q) == pytest.approx(expected)
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ "red,nir,q",
15
+ [
16
+ (0.2, 0.6, 1),
17
+ (1.1, 0.6, 0),
18
+ (0.0, 0.0, 0),
19
+ (float("nan"), 0.6, 0),
20
+ (float("nan"), 0.6, 0),
21
+ (0.2, float("nan"), 0),
22
+ ],
23
+ )
24
+ def test_scalar_isnan(red, nir, q):
25
+ assert math.isnan(ndvi_value(red, nir, q))
26
+
27
+
28
+ @pytest.mark.parametrize("red,nir, q", [(0.2, 0.6, 2)])
29
+ def test_scalar_raise(red, nir, q):
30
+ with pytest.raises(ValueError):
31
+ ndvi_value(red, nir, q)