fieldcheck-workshop 0.1.0__py3-none-any.whl
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.
- fieldcheck/__init__.py +5 -0
- fieldcheck/cli.py +78 -0
- fieldcheck/core.py +149 -0
- fieldcheck/io.py +44 -0
- fieldcheck_workshop-0.1.0.dist-info/METADATA +7 -0
- fieldcheck_workshop-0.1.0.dist-info/RECORD +8 -0
- fieldcheck_workshop-0.1.0.dist-info/WHEEL +4 -0
- fieldcheck_workshop-0.1.0.dist-info/entry_points.txt +2 -0
fieldcheck/__init__.py
ADDED
fieldcheck/cli.py
ADDED
|
@@ -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())
|
fieldcheck/core.py
ADDED
|
@@ -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")
|
fieldcheck/io.py
ADDED
|
@@ -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,8 @@
|
|
|
1
|
+
fieldcheck/__init__.py,sha256=rb9y0evNvpUGVEKq8FLmVE4n9Iw4Sh0PWRKrBw5BJWc,138
|
|
2
|
+
fieldcheck/cli.py,sha256=rIP1wSJYiRmRaCcdt5h7HLJDDNhNARjJstfVRr0_rqs,2460
|
|
3
|
+
fieldcheck/core.py,sha256=0uCZ80EICSnJoK8qKGuGwcyhX3XFr0qbnzcjY02B-Hw,4450
|
|
4
|
+
fieldcheck/io.py,sha256=M3qG3BtFk__GBzzw7jeuKGtyLyoSCFBzbAMNYiUMWok,1330
|
|
5
|
+
fieldcheck_workshop-0.1.0.dist-info/METADATA,sha256=3UGQWUu2hVxE_WxDEWR7la4T2QoBCGgdX4MTm5a54RY,213
|
|
6
|
+
fieldcheck_workshop-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
fieldcheck_workshop-0.1.0.dist-info/entry_points.txt,sha256=ypDw07hedQvBu6KjDkRs5P876SKySGcGHEuU4Ico6t4,51
|
|
8
|
+
fieldcheck_workshop-0.1.0.dist-info/RECORD,,
|