Ehzoahis commited on
Commit
2cecaa0
·
verified ·
1 Parent(s): 6137a16

Publish verified NA-SAR-X 100k archive, manifest and PyTorch loader

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ retained_samples.csv filter=lfs diff=lfs merge=lfs -text
DATALOADER.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NASAR-X UTM256 PyTorch Dataset
2
+
3
+ Place this directory on PYTHONPATH, or run the example here. The default archive is the adjacent NASAR-X_UTM256_final_100k.tar. Linux and PyTorch, NumPy, and Python 3.10+ are required. The Gauss insar environment provides PyTorch 2.11.0. A batch contains one sample per row of the embedded retained_samples.csv, in manifest order, across 100,000 rows and 83,134 locations.
4
+
5
+ ```python
6
+ from torch.utils.data import DataLoader
7
+ from nasar_tar_dataset import NasarTarDataset
8
+
9
+ def main():
10
+ with NasarTarDataset() as ds:
11
+ sample = ds.by_id("32601:57:747|2024Q3")
12
+ loader = DataLoader(ds, batch_size=2, shuffle=True, num_workers=2,
13
+ persistent_workers=True, prefetch_factor=1)
14
+ for batch in loader:
15
+ sar = batch["sar"] # float32 [B, 8, 256, 256]
16
+ valid = batch["valid"] # bool [B, 256, 256]
17
+ # Optional model input with finite values; keep the mask for the loss.
18
+ finite_sar = sar.masked_fill(~batch["numeric_valid"], 0)
19
+ break
20
+
21
+ if __name__ == "__main__":
22
+ main()
23
+ ```
24
+
25
+ The eight SAR channels follow ds.channels: prime co-polarized and cross-polarized linear RTC, secondary co- and cross-polarized linear RTC, cosine and sine of interferometric phase, coherence, and incidence angle. The prime and secondary RTC views have two bands each. The IFG values are the stored cosine/sine representation. Per-pixel NaN and physical values pass through unchanged.
26
+
27
+ The dataset returns combined valid, eight-band numeric_valid, four-band rtc_positive_valid, and both acquisitions' raw uint8 and boolean mask-valid fields. The keys match the NPZ mask keys. Metadata includes sample_id, grid_id, quarter, grid_epsg, grid_transform (Rasterio affine a,b,c,d,e,f), valid_fraction, rtc_score, coh_block16_std, selection_role and modis_class_fractions (2021 MCD12Q1, IGBP 1–17 plus NoData). Default collation turns the tensors and numeric metadata into batches and returns a list for each string field. Scores that are undefined are NaN.
28
+
29
+ The first open walks the uncompressed TAR headers, reads and verifies the embedded CSV, and writes an atomic SQLite offset index beside the archive. Subsequent opens reuse it. For a read-only archive directory use index="/writable/path/nasar.offsets.sqlite". The per-archive index is bound to the device/inode, size and timestamps. Regenerate the index after moving or replacing the archive. Each worker opens its own file descriptor and uses positional reads; each item reads and decompresses one NPZ. Random-read throughput depends on storage latency, NPZ decompression and worker count. Large batches or prefetch settings require more shared memory. Use verify_sha=True to verify each compressed sample against the embedded manifest on access. The original manifest's absolute source paths are provenance; member addressing uses grid_id and quarter within this TAR.
30
+
31
+ Use ds[i], ds.index_of(sample_id), ds.by_id(sample_id), and ds.close() (or a context manager). Worker descriptors close when the DataLoader workers exit. Run python verify_dataloader.py for an end-to-end check of samples spanning the release, hashes, numeric arrays, masks, and repeated default-collated fork/spawn batches.
NASAR-X_UTM256_final_100k.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f58213ae1384d5154883505db617ed4abc2d761782767ad0664dd7f26f25f2e
3
+ size 180964229120
README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: NA-SAR-X
3
+ tags:
4
+ - remote-sensing
5
+ - synthetic-aperture-radar
6
+ - interferometry
7
+ size_categories:
8
+ - 100K<n<1M
9
+ ---
10
+
11
+ # NA-SAR-X
12
+
13
+ NA-SAR-X contains 100,000 paired SAR samples from 83,134 distinct 256 × 256 local UTM grids at 30 m spacing. There are 66,268 locations with one quarter and 16,866 with two different quarters. Each sample contains primary and secondary RTC, interferometric phase cosine and sine, coherence, incidence angle, validity masks, georeferencing, and 2021 MODIS land-cover fractions.
14
+
15
+ Download the TAR and the Python loader to the same directory. The loader reads individual samples from the archive by index or by sample ID and builds a local offset index on first use. See [DATALOADER.md](DATALOADER.md) for channel order, masks, metadata, and a PyTorch example.
16
+
17
+ The final CSV is available separately and inside the archive. Its SHA-256 column refers to each NPZ payload. The path column records the original build location. Archive members are addressed by grid ID and quarter. All 100,000 archive members were read back and verified against the manifest. See [verification.json](verification.json).
18
+
19
+ Selection required a valid-pixel fraction of at least 0.995 and either an RTC quality score of at least 0.6 or a standard deviation of 16 × 16 coherence block means of at least 0.1. The additional 16,866 second-quarter samples prioritize urban locations and reduce nearby repeat sampling of forest, cropland, and grassland.
dataloader_validation.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"samples": 100000, "indices": [0, 1, 24999, 50000, 75001, 99999], "batch_size": 2, "workers": 2, "repeated_epochs": 2, "torch": "2.11.0+cu130", "engines_seconds": {"fork": 0.262, "spawn": 1.542}, "elapsed_seconds": 2.267, "result": "PASS"}
nasar_tar_dataset.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Map-style PyTorch dataset for the final NASAR-X UTM256 100k release (Linux)."""
2
+ import contextlib
3
+ import csv
4
+ import fcntl
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import operator
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import sqlite3
13
+ import tarfile
14
+ import tempfile
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torch.utils.data import Dataset
19
+
20
+ DEFAULT_TAR = Path(__file__).with_name("NASAR-X_UTM256_final_100k.tar")
21
+ MANIFEST_SHA = "cc051c100cb5efef1ec9be4d07f919c3088ee3d7ce67b2e37da1b88b6647abf4"
22
+ COUNT = 100_000
23
+ CHANNELS = ("prime_co", "prime_cross", "secondary_co", "secondary_cross",
24
+ "phase_cos", "phase_sin", "coherence", "incidence_angle")
25
+ SAR_KEYS = ("prime_rtc_view_0", "secondary_rtc_view_0", "ifg_view_0",
26
+ "coh_view_0", "inc_angle_view_0")
27
+ MASK_KEYS = ("valid", "numeric_valid", "rtc_positive_valid", "prime_mask_raw",
28
+ "secondary_mask_raw", "prime_mask_valid", "secondary_mask_valid")
29
+
30
+
31
+ def fingerprint(stat):
32
+ return [stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns]
33
+
34
+
35
+ def readonly(path):
36
+ return sqlite3.connect(path.as_uri() + "?mode=ro&immutable=1", uri=True)
37
+
38
+
39
+ def binding(archive):
40
+ return [1, MANIFEST_SHA, COUNT, fingerprint(archive.stat())]
41
+
42
+
43
+ def ensure_index(archive, index):
44
+ signature = binding(archive)
45
+ def cached():
46
+ if not index.exists():
47
+ return False
48
+ with contextlib.closing(readonly(index)) as db:
49
+ entry = db.execute("SELECT signature FROM nasar_binding").fetchone()
50
+ return entry is not None and json.loads(entry[0]) == signature
51
+
52
+ if cached():
53
+ return signature
54
+ index.parent.mkdir(parents=True, exist_ok=True)
55
+ with index.with_suffix(index.suffix + ".lock").open("a") as lock:
56
+ fcntl.flock(lock, fcntl.LOCK_EX)
57
+ if cached():
58
+ return signature
59
+ fd, tmp = tempfile.mkstemp(dir=index.parent, prefix=index.name + ".")
60
+ os.close(fd)
61
+ try:
62
+ with contextlib.closing(sqlite3.connect(tmp)) as db, archive.open("rb", buffering=0) as raw:
63
+ if fingerprint(os.fstat(raw.fileno())) != signature[-1]:
64
+ raise RuntimeError("TAR changed before indexing")
65
+ offsets = {}
66
+ manifest = None
67
+ with tarfile.open(fileobj=raw, mode="r:") as tar:
68
+ for member in tar:
69
+ if not member.isreg() or member.sparse is not None:
70
+ raise ValueError(f"Unsupported member {member.name}")
71
+ if member.name == "retained_samples.csv" and manifest is None:
72
+ with tar.extractfile(member) as stream:
73
+ manifest = stream.read()
74
+ elif member.name.startswith("samples/") and member.name.endswith(".npz") and member.name not in offsets:
75
+ if not 0 < member.size <= 4 * 1024**2:
76
+ raise ValueError(f"Unexpected NPZ size {member.name}")
77
+ if member.offset_data + member.size > signature[-1][2]:
78
+ raise ValueError(f"Truncated TAR member {member.name}")
79
+ offsets[member.name] = (member.offset_data, member.size)
80
+ else:
81
+ raise ValueError(f"Unexpected or duplicate member {member.name}")
82
+ if manifest is None or hashlib.sha256(manifest).hexdigest() != MANIFEST_SHA:
83
+ raise ValueError("Embedded manifest SHA-256 mismatch")
84
+ db.execute("CREATE TABLE samples (idx INTEGER PRIMARY KEY, sample_id TEXT UNIQUE, grid_id TEXT, quarter TEXT, offset INTEGER, length INTEGER, sha TEXT, valid_fraction REAL, rtc REAL, coh REAL, role TEXT)")
85
+ rows = csv.DictReader(io.StringIO(manifest.decode("utf-8")))
86
+ count = 0
87
+ for idx, row in enumerate(rows):
88
+ gid, quarter = row["grid_id"], row["quarter"]
89
+ if not re.fullmatch(r"\d+:\d+:\d+", gid) or not re.fullmatch(r"\d{4}Q[1-4]", quarter) or row["sample_id"] != gid + "|" + quarter:
90
+ raise ValueError("Invalid manifest sample identity")
91
+ name = f"samples/{gid.replace(':', '_')}/{quarter}.npz"
92
+ offset, length = offsets.pop(name)
93
+ db.execute("INSERT INTO samples VALUES (?,?,?,?,?,?,?,?,?,?,?)",
94
+ (idx, row["sample_id"], gid, quarter, offset, length, row["sha256"],
95
+ float(row["valid_fraction"]), float(row["rtc_score"] or "nan"),
96
+ float(row["coh_block16_std"] or "nan"), row["selection_role"]))
97
+ count += 1
98
+ if offsets or count != COUNT:
99
+ raise ValueError("Manifest and TAR membership differ")
100
+ if binding(archive) != signature or fingerprint(os.fstat(raw.fileno())) != signature[-1]:
101
+ raise RuntimeError("TAR changed during indexing")
102
+ db.execute("CREATE TABLE nasar_binding (signature TEXT)")
103
+ db.execute("INSERT INTO nasar_binding VALUES (?)", (json.dumps(signature),))
104
+ db.commit()
105
+ os.chmod(tmp, 0o600 | (archive.stat().st_mode & 0o044))
106
+ os.replace(tmp, index)
107
+ directory = os.open(index.parent, os.O_RDONLY)
108
+ try:
109
+ os.fsync(directory)
110
+ finally:
111
+ os.close(directory)
112
+ finally:
113
+ Path(tmp).unlink(missing_ok=True)
114
+ return signature
115
+
116
+
117
+ class NasarTarDataset(Dataset):
118
+ """Index order follows retained_samples.csv. Physical values retain nonfinite pixels."""
119
+ channels = CHANNELS
120
+
121
+ def __init__(self, archive=DEFAULT_TAR, index=None, verify_sha=False):
122
+ self.archive = Path(archive).expanduser().resolve()
123
+ self.index = (Path(index).expanduser().resolve() if index is not None
124
+ else self.archive.with_suffix(".offsets.sqlite"))
125
+ self.verify_sha = bool(verify_sha)
126
+ self._pid = self._db = self._fd = None
127
+ self._signature = ensure_index(self.archive, self.index)
128
+ self._index_signature = fingerprint(self.index.stat())
129
+
130
+ def __len__(self):
131
+ return COUNT
132
+
133
+ def close(self):
134
+ if self._db is not None:
135
+ self._db.close()
136
+ if self._fd is not None:
137
+ os.close(self._fd)
138
+ self._pid = self._db = self._fd = None
139
+
140
+ def __enter__(self):
141
+ return self
142
+
143
+ def __exit__(self, *_):
144
+ self.close()
145
+
146
+ def __del__(self):
147
+ if getattr(self, "_pid", None) is not None:
148
+ self.close()
149
+
150
+ def __getstate__(self):
151
+ state = self.__dict__.copy()
152
+ state.update(_pid=None, _db=None, _fd=None)
153
+ return state
154
+
155
+ def _open(self):
156
+ if binding(self.archive) != self._signature or fingerprint(self.index.stat()) != self._index_signature:
157
+ raise RuntimeError("Archive or index changed. Recreate the dataset.")
158
+ if self._pid != os.getpid():
159
+ self.close()
160
+ try:
161
+ self._fd = os.open(self.archive, os.O_RDONLY)
162
+ self._db = readonly(self.index)
163
+ if fingerprint(os.fstat(self._fd)) != self._signature[-1]:
164
+ raise RuntimeError("Archive changed while opening")
165
+ entry = self._db.execute("SELECT signature FROM nasar_binding").fetchone()
166
+ if json.loads(entry[0]) != self._signature:
167
+ raise RuntimeError("Offset index signature mismatch")
168
+ self._pid = os.getpid()
169
+ except BaseException:
170
+ self.close()
171
+ raise
172
+
173
+ def index_of(self, sample_id):
174
+ self._open()
175
+ row = self._db.execute("SELECT idx FROM samples WHERE sample_id=?", (sample_id,)).fetchone()
176
+ if row is None:
177
+ raise KeyError(sample_id)
178
+ return row[0]
179
+
180
+ def by_id(self, sample_id):
181
+ return self[self.index_of(sample_id)]
182
+
183
+ def __getitem__(self, idx):
184
+ idx = operator.index(idx)
185
+ if idx < 0:
186
+ idx += len(self)
187
+ if not 0 <= idx < len(self):
188
+ raise IndexError(idx)
189
+ self._open()
190
+ row = self._db.execute("SELECT sample_id,grid_id,quarter,offset,length,sha,valid_fraction,rtc,coh,role FROM samples WHERE idx=?", (idx,)).fetchone()
191
+ sid,gid,quarter,offset,length,sha,valid_fraction,rtc,coh,role = row
192
+ data = os.pread(self._fd, length, offset)
193
+ if len(data) != length or fingerprint(os.fstat(self._fd)) != self._signature[-1]:
194
+ raise IOError(f"TAR member changed or truncated: {sid}")
195
+ if self.verify_sha and hashlib.sha256(data).hexdigest() != sha:
196
+ raise IOError(f"SHA-256 mismatch: {sid}")
197
+ with np.load(io.BytesIO(data), allow_pickle=False) as z:
198
+ if str(z["grid_id"]) != gid or not np.isclose(float(z["valid_fraction"]), valid_fraction, rtol=0, atol=1e-14):
199
+ raise ValueError(f"Payload metadata mismatch: {sid}")
200
+ result = {k: torch.from_numpy(z[k]) for k in MASK_KEYS}
201
+ result.update(sar=torch.from_numpy(np.concatenate([z[k] for k in SAR_KEYS])),
202
+ sample_id=sid, grid_id=gid, quarter=quarter,
203
+ grid_epsg=int(z["grid_epsg"]), grid_transform=torch.from_numpy(z["grid_transform"]),
204
+ valid_fraction=float(z["valid_fraction"]), rtc_score=float("nan") if rtc is None else rtc,
205
+ coh_block16_std=float("nan") if coh is None else coh, selection_role=role,
206
+ modis_class_fractions=torch.from_numpy(z["modis_class_fractions"]))
207
+ return result
retained_samples.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc051c100cb5efef1ec9be4d07f919c3088ee3d7ce67b2e37da1b88b6647abf4
3
+ size 24192655
verification.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "archive": "NASAR-X_UTM256_final_100k.tar",
3
+ "archive_bytes": 180964229120,
4
+ "payload_bytes": 180863314758,
5
+ "manifest_sha256": "cc051c100cb5efef1ec9be4d07f919c3088ee3d7ce67b2e37da1b88b6647abf4",
6
+ "verified_samples": 100000,
7
+ "locations": 83134,
8
+ "missing": 0,
9
+ "duplicates": 0,
10
+ "unexpected_samples": 0,
11
+ "id_mismatches": 0,
12
+ "sha256_mismatches": 0
13
+ }
verify_dataloader.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only verification against selected members of the actual released TAR."""
2
+ import csv
3
+ import hashlib
4
+ import io
5
+ import json
6
+ import os
7
+ import tarfile
8
+ import time
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch.utils.data import DataLoader
13
+ from nasar_tar_dataset import DEFAULT_TAR, MASK_KEYS, SAR_KEYS, NasarTarDataset
14
+
15
+
16
+ def main():
17
+ indices = [0, 1, 24999, 50000, 75001, 99999]
18
+ start = time.monotonic()
19
+ with NasarTarDataset(verify_sha=True) as dataset:
20
+ assert len(dataset) == 100000
21
+ with tarfile.open(DEFAULT_TAR, "r:") as tar:
22
+ stream = io.TextIOWrapper(tar.extractfile(tar.next()), encoding="utf-8")
23
+ refs = {i: r for i, r in enumerate(csv.DictReader(stream)) if i in indices}
24
+ assert len(refs) == len(indices)
25
+ expected = {}
26
+ for i,r in refs.items():
27
+ s = dataset.by_id(r["sample_id"])
28
+ assert dataset.index_of(r["sample_id"]) == i
29
+ offset,n = dataset._db.execute("SELECT offset,length FROM samples WHERE idx=?", (i,)).fetchone()
30
+ payload = os.pread(dataset._fd, n, offset)
31
+ assert hashlib.sha256(payload).hexdigest() == r["sha256"]
32
+ with np.load(io.BytesIO(payload), allow_pickle=False) as z:
33
+ np.testing.assert_array_equal(s["sar"].numpy(), np.concatenate([z[k] for k in SAR_KEYS]))
34
+ for k in (*MASK_KEYS,"grid_transform","modis_class_fractions"):
35
+ np.testing.assert_array_equal(s[k].numpy(), z[k])
36
+ assert s["grid_epsg"] == int(z["grid_epsg"])
37
+ assert s["sar"].shape == (8,256,256)
38
+ assert s["quarter"] == r["quarter"] and s["selection_role"] == r["selection_role"]
39
+ for k in ("rtc_score","coh_block16_std","valid_fraction"):
40
+ np.testing.assert_allclose(s[k],float(r[k]), rtol=0, atol=1e-14)
41
+ expected[r["sample_id"]] = s
42
+ methods = {}
43
+ for method in ("fork", "spawn"):
44
+ loader = DataLoader(dataset, sampler=indices, batch_size=2, num_workers=2,
45
+ multiprocessing_context=method, persistent_workers=True, prefetch_factor=1)
46
+ started = time.monotonic()
47
+ for epoch in range(2):
48
+ ids = []
49
+ for batch in loader:
50
+ for j,sid in enumerate(batch["sample_id"]):
51
+ ref = expected[sid]
52
+ for k in ("sar",*MASK_KEYS,"modis_class_fractions","grid_transform"):
53
+ torch.testing.assert_close(batch[k][j],ref[k],rtol=0,atol=0,equal_nan=True)
54
+ ids.append(sid)
55
+ assert ids == [refs[i]["sample_id"] for i in indices]
56
+ del loader
57
+ methods[method] = round(time.monotonic()-started,3)
58
+ try:dataset.by_id("missing")
59
+ except KeyError:pass
60
+ else:raise AssertionError("Unknown ID accepted")
61
+ assert dataset[-1]["sample_id"] == refs[99999]["sample_id"]
62
+ assert dataset._fd is None and dataset._db is None
63
+ print(json.dumps(dict(samples=len(dataset), indices=indices, batch_size=2, workers=2,
64
+ repeated_epochs=2, torch=torch.__version__, engines_seconds=methods,
65
+ elapsed_seconds=round(time.monotonic()-start,3), result="PASS")))
66
+
67
+
68
+ if __name__ == "__main__":
69
+ torch.set_num_threads(1)
70
+ main()