File size: 8,441 Bytes
8a14f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python3
"""
load_example.py — open a pair, check it, and show what is in it.

Shipped with the dataset so that the first thing anyone can do with it is
run something, rather than read about it. It opens one Sentinel-2 / Sentinel-1
pair, reproduces the checksum recorded in the sidecar, confirms the two
rasters are on the same grid, and prints what it found.

    python load_example.py                     # uses examples/
    python load_example.py --manifest manifest.csv --index 0
    python load_example.py --check 200         # verify 200 random pairs

Needs rasterio, numpy and xxhash; see requirements.txt.

The checksum is the part worth reading carefully. It is the xxHash64 of the
decoded pixel array in band order — not of the bytes on disk. Hashing the
file gives a different value, and a consumer who tries that concludes the
data is corrupt when it is not. The code below is the reference.
"""

from __future__ import annotations

import argparse
import csv
import json
import random
import sys
from pathlib import Path

try:
    import rasterio
    import xxhash
except ImportError as exc:
    sys.exit(f"missing dependency: {exc}. See requirements.txt.")


def checksum(tif: Path) -> str:
    """Reproduce a tile's recorded checksum.

    The array is read whole and in band order because that is the buffer the
    value was computed over when the tile was written; reading a single band,
    or reading it transposed, produces a different hash from the same file.
    """
    with rasterio.open(tif) as src:
        arr = src.read()  # (bands, height, width)
    return xxhash.xxh64(arr.tobytes()).hexdigest()


def load_pair(s2_tif: Path, s1_tif: Path) -> dict:
    """Open both members of a pair and report what they contain."""
    out: dict = {}
    for label, tif in (("s2", s2_tif), ("s1", s1_tif)):
        meta_path = tif.with_suffix(".json")
        if not tif.exists():
            out[label] = {"error": f"missing: {tif}"}
            continue
        meta = (
            json.loads(meta_path.read_text(encoding="utf-8"))
            if meta_path.exists()
            else {}
        )
        with rasterio.open(tif) as src:
            arr = src.read()
            info = {
                "shape": arr.shape,
                "dtype": str(arr.dtype),
                "crs": str(src.crs),
                "bounds": tuple(round(b, 6) for b in src.bounds),
                "bands": meta.get("dimensions", {}).get("bands"),
                "min": float(arr.min()),
                "max": float(arr.max()),
            }
        recorded = meta.get("integrity", {}).get("checksum")
        if recorded:
            here = xxhash.xxh64(arr.tobytes()).hexdigest()
            info["checksum"] = (
                "OK"
                if here == recorded
                else f"MISMATCH (file {here}, sidecar {recorded})"
            )
        info["meta"] = meta
        out[label] = info
    return out


def show(pair: dict) -> bool:
    """Print a pair and say whether it is sound. Returns True if it is."""
    ok = True
    s2, s1 = pair.get("s2", {}), pair.get("s1", {})
    for label, info in (("Sentinel-2", s2), ("Sentinel-1", s1)):
        if "error" in info:
            print(f"  {label}: {info['error']}")
            ok = False
            continue
        print(f"  {label}")
        print(f"    shape    : {info['shape']}  {info['dtype']}")
        print(f"    bands    : {info['bands']}")
        print(f"    crs      : {info['crs']}")
        print(f"    range    : {info['min']:g} .. {info['max']:g}")
        print(f"    checksum : {info.get('checksum', 'not recorded')}")
        if str(info.get("checksum", "")).startswith("MISMATCH"):
            ok = False

    # The pair is only a pair if both halves describe the same ground. Same
    # CRS and same bounds is what makes the two arrays index-comparable, and
    # it is the property the whole dataset rests on — so it is checked rather
    # than assumed.
    if "error" not in s2 and "error" not in s1:
        same_crs = s2["crs"] == s1["crs"]
        same_box = all(
            abs(a - b) < 1e-9 for a, b in zip(s2["bounds"], s1["bounds"], strict=True)
        )
        same_size = s2["shape"][1:] == s1["shape"][1:]
        print(
            f"  co-registration: crs {'=' if same_crs else 'DIFFER'}, "
            f"bounds {'=' if same_box else 'DIFFER'}, "
            f"size {'=' if same_size else 'DIFFER'}"
        )
        ok = ok and same_crs and same_box and same_size

        c = s2["meta"].get("classification", {})
        if c:
            print(
                f"  class    : {c.get('land_cover_class')} "
                f"(purity {c.get('label_purity')})"
            )
            for part in (c.get("label_composition") or [])[:3]:
                print(f"      {part.get('ratio'):>6.1%}  {part.get('class_name')}")
        q = s2["meta"].get("quality_metrics", {})
        if q.get("temporal_gap_days") is not None:
            print(
                f"  gap      : {q['temporal_gap_days']:.2f} days between "
                f"the two acquisitions"
            )
    return ok


def from_manifest(root: Path, manifest: Path, index: int) -> tuple:
    with manifest.open(newline="", encoding="utf-8") as fh:
        rows = list(csv.DictReader(fh))
    if not rows:
        sys.exit(f"{manifest} has no rows")
    row = rows[index % len(rows)]
    return root / row["s2_file"], root / row["s1_file"], rows


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument(
        "--root",
        type=Path,
        default=Path("."),
        help="dataset root; defaults to the current directory",
    )
    ap.add_argument(
        "--manifest",
        type=Path,
        default=None,
        help="manifest to read; defaults to the one found here",
    )
    ap.add_argument(
        "--index", type=int, default=0, help="which row of the manifest to open"
    )
    ap.add_argument(
        "--check",
        type=int,
        default=0,
        help="verify this many pairs drawn at random, and report",
    )
    ap.add_argument("--seed", type=int, default=42)
    args = ap.parse_args(argv)

    root = args.root.resolve()
    manifest = args.manifest
    if manifest is None:
        found = sorted(root.glob("*manifest*.csv"))
        manifest = found[0] if found else None

    if args.check:
        if manifest is None:
            sys.exit("--check needs a manifest")
        with manifest.open(newline="", encoding="utf-8") as fh:
            rows = list(csv.DictReader(fh))
        sample = random.Random(args.seed).sample(rows, min(args.check, len(rows)))
        good = bad = absent = 0
        for i, r in enumerate(sample, 1):
            s2, s1 = root / r["s2_file"], root / r["s1_file"]
            if not s2.exists() or not s1.exists():
                absent += 1
                continue
            res = load_pair(s2, s1)
            if all(res[k].get("checksum") == "OK" for k in ("s2", "s1")):
                good += 1
            else:
                bad += 1
                print(f"  FAILED: {r['pair_id']}")
            if i % 25 == 0:
                print(
                    f"  {i}/{len(sample)}  ok {good}  bad {bad}  missing {absent}",
                    flush=True,
                )
        print(
            f"\nverified {len(sample)} pairs: {good} ok, {bad} failed, {absent} missing"
        )
        return 1 if (bad or absent) else 0

    # No manifest and no arguments: fall back to examples/, which is there
    # precisely so the dataset can be opened before anything is unpacked.
    ex = root / "examples"
    if manifest is not None:
        s2, s1, rows = from_manifest(root, manifest, args.index)
        print(f"pair {args.index} of {len(rows):,} in {manifest.name}\n")
    elif ex.is_dir():
        tifs = sorted(ex.glob("S2_*.tif"))
        if not tifs:
            sys.exit(f"no example pair in {ex}")
        s2 = tifs[0]
        s1 = ex / (s2.name.replace("S2_", "S1_", 1))
        print(f"example pair from {ex}\n")
    else:
        sys.exit("no manifest and no examples/ folder here; pass --root or --manifest")

    ok = show(load_pair(s2, s1))
    print()
    print("This pair is sound." if ok else "This pair has a problem.")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())