Datasets:
Update Event-SAR loader: shared-mask filtering, product modes and aligned crops
Browse files- README.md +48 -1
- SHA256SUMS +2 -2
- event_sar_dataset.py +244 -48
README.md
CHANGED
|
@@ -235,7 +235,7 @@ from torch.utils.data import DataLoader
|
|
| 235 |
from event_sar_dataset import EventSARWebDataset
|
| 236 |
|
| 237 |
ds = EventSARWebDataset('/path/to/Event-SAR-HF', min_shared_valid_ratio=0.95)
|
| 238 |
-
#
|
| 239 |
loader = DataLoader(ds, batch_size=None, num_workers=2)
|
| 240 |
sample = next(iter(loader))
|
| 241 |
rtc = sample['arrays']['prime_rtc_view_0']
|
|
@@ -249,6 +249,53 @@ Variable sizes and orbit counts require an appropriate batching/collation policy
|
|
| 249 |
The loader preserves raw values; models should handle NaNs using the supplied
|
| 250 |
masks and apply their own normalization.
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
## Provenance and integrity
|
| 253 |
|
| 254 |
SAR observations are Sentinel-1 products processed with ASF HyP3. Exact source
|
|
|
|
| 235 |
from event_sar_dataset import EventSARWebDataset
|
| 236 |
|
| 237 |
ds = EventSARWebDataset('/path/to/Event-SAR-HF', min_shared_valid_ratio=0.95)
|
| 238 |
+
# Threshold applies inclusively to the cropped common_valid mask.
|
| 239 |
loader = DataLoader(ds, batch_size=None, num_workers=2)
|
| 240 |
sample = next(iter(loader))
|
| 241 |
rtc = sample['arrays']['prime_rtc_view_0']
|
|
|
|
| 249 |
The loader preserves raw values; models should handle NaNs using the supplied
|
| 250 |
masks and apply their own normalization.
|
| 251 |
|
| 252 |
+
The loader supports aligned crops and product selection:
|
| 253 |
+
|
| 254 |
+
```python
|
| 255 |
+
from event_sar_dataset import EventSARDataset, event_sar_collate
|
| 256 |
+
|
| 257 |
+
ds = EventSARDataset(
|
| 258 |
+
'/path/to/Event-SAR-HF',
|
| 259 |
+
event_type=['earthquake', 'volcano'],
|
| 260 |
+
mode='all', # rtc, insar, or all (default)
|
| 261 |
+
stages=['event'],
|
| 262 |
+
crop_size=512,
|
| 263 |
+
crop_mode='all', # random, central, or all
|
| 264 |
+
min_shared_valid_ratio=0.95,
|
| 265 |
+
)
|
| 266 |
+
loader = DataLoader(ds, batch_size=4, collate_fn=event_sar_collate)
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
`rtc` returns reference/secondary VV/VH; `insar` returns cos/sin phase, wrapped
|
| 270 |
+
phase and coherence. `all` includes both plus DEM, slope and incidence. Explicit
|
| 271 |
+
`include_dem`, `include_slope`, `include_inc_angle` flags override auxiliary
|
| 272 |
+
defaults (off for rtc/insar, on for all). Unselected arrays are not decompressed.
|
| 273 |
+
|
| 274 |
+
Filtering uses only the cropped `common_valid` mask, intersecting VV/InSAR across
|
| 275 |
+
all original stages/views regardless of mode or selected stages. This mask does
|
| 276 |
+
not require valid VH or auxiliary products. No channel-specific thresholds are
|
| 277 |
+
used. A failing crop is skipped, with no random retries. The output
|
| 278 |
+
`shared_valid_ratio` reports actual crop coverage. Scores and score filters are
|
| 279 |
+
not exposed: the historical 3–5 review ratings are not final decisions. They
|
| 280 |
+
remain in raw source metadata solely as provenance.
|
| 281 |
+
|
| 282 |
+
`all` crop mode produces separate nonoverlapping tiles (1024 -> four 512 tiles);
|
| 283 |
+
dimensions must divide exactly. `random` produces one repeatable crop per sample
|
| 284 |
+
and epoch. Call `set_epoch(epoch)` before iteration; recreate persistent workers
|
| 285 |
+
after changing epochs. `central` selects the image center. `event_ids` and
|
| 286 |
+
`sample_keys` support custom selections. Raw values and NaNs remain unchanged.
|
| 287 |
+
|
| 288 |
+
Outputs include event date, center coordinates, magnitude/type (Mw or VEI),
|
| 289 |
+
stages, crop window and adjusted grid. Original patch coordinates are saved in
|
| 290 |
+
Parquet (`transform`, CRS, bounds, dimensions) and JSON (`grid`). Earthquake JSON
|
| 291 |
+
also preserves `reviewed_box` row/column offsets; volcano grids are event-centered.
|
| 292 |
+
Loader-created `crop_window` coordinates are relative to the native exported
|
| 293 |
+
patch and are generated at runtime, not stored on HF.
|
| 294 |
+
|
| 295 |
+
The collator returns a list to accommodate variable orbit counts. When filtering,
|
| 296 |
+
length is unknown until iteration; `num_candidate_crops` is an upper bound.
|
| 297 |
+
Shards are partitioned across workers/ranks; training must handle uneven counts.
|
| 298 |
+
|
| 299 |
## Provenance and integrity
|
| 300 |
|
| 301 |
SAR observations are Sentinel-1 products processed with ASF HyP3. Exact source
|
SHA256SUMS
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
|
| 2 |
0606d77d5ecc2be5a31a1fdc219d705b3c7f45bc7391d4790a3b9916bcea8f09 data/event-sar-train-000000.tar
|
| 3 |
44d862083610272f8e261ef430e064f5ba80bfa869a42e90920859a469827040 data/event-sar-train-000001.tar
|
| 4 |
702338fa86986f4f8af1b6ea3bb1455d9b6993a1b5824ad2188449ddefd24247 data/event-sar-train-000002.tar
|
|
@@ -94,7 +94,7 @@ da792a7ad2e255e68c49c0ea84afd558e6cd51bb957dd90ab10879abd73b52da data/event-sar
|
|
| 94 |
571acf3d40ad03c4ab550aa1c6529774bb7d82f4471444e3bbfc35e0bc4980ae data/event-sar-train-000092.tar
|
| 95 |
5fdb8bd47e985f970ce7646b4609d29fb132c9f5d3b1f263f0f6a368dfadefc2 data/event-sar-train-000093.tar
|
| 96 |
c617e627c8e1afed60771017bee649c16a16d57a71fe34af185d23079277f7bb data/event-sar-train-000094.tar
|
| 97 |
-
|
| 98 |
367947f8b5dd59d1840ea345dc8841f69ecc68f6d9f81a81ef98a3d114c30df3 file_metadata.parquet
|
| 99 |
ff9794d4d6c93098fbd254574a950a67a48995ded91da617a03b0fc0a6438ad4 metadata.parquet
|
| 100 |
9e4798ef54fbaa2b9670ffe144e43859bf5b060b3f7b6ff8dd0f8718c4c93aca previews/README.md
|
|
|
|
| 1 |
+
6b3e396c2300e4ca2580f4fe5df68d593dfa14c77ff22bf989b94971189770cc README.md
|
| 2 |
0606d77d5ecc2be5a31a1fdc219d705b3c7f45bc7391d4790a3b9916bcea8f09 data/event-sar-train-000000.tar
|
| 3 |
44d862083610272f8e261ef430e064f5ba80bfa869a42e90920859a469827040 data/event-sar-train-000001.tar
|
| 4 |
702338fa86986f4f8af1b6ea3bb1455d9b6993a1b5824ad2188449ddefd24247 data/event-sar-train-000002.tar
|
|
|
|
| 94 |
571acf3d40ad03c4ab550aa1c6529774bb7d82f4471444e3bbfc35e0bc4980ae data/event-sar-train-000092.tar
|
| 95 |
5fdb8bd47e985f970ce7646b4609d29fb132c9f5d3b1f263f0f6a368dfadefc2 data/event-sar-train-000093.tar
|
| 96 |
c617e627c8e1afed60771017bee649c16a16d57a71fe34af185d23079277f7bb data/event-sar-train-000094.tar
|
| 97 |
+
3f833bf01f651cca9ef21323acabd3035da205d6165aada9aa7501a946f7c853 event_sar_dataset.py
|
| 98 |
367947f8b5dd59d1840ea345dc8841f69ecc68f6d9f81a81ef98a3d114c30df3 file_metadata.parquet
|
| 99 |
ff9794d4d6c93098fbd254574a950a67a48995ded91da617a03b0fc0a6438ad4 metadata.parquet
|
| 100 |
9e4798ef54fbaa2b9670ffe144e43859bf5b060b3f7b6ff8dd0f8718c4c93aca previews/README.md
|
event_sar_dataset.py
CHANGED
|
@@ -1,64 +1,260 @@
|
|
| 1 |
-
"""PyTorch
|
| 2 |
|
| 3 |
-
|
|
|
|
| 4 |
"""
|
| 5 |
from __future__ import annotations
|
|
|
|
| 6 |
from io import BytesIO
|
|
|
|
| 7 |
import json
|
| 8 |
from pathlib import Path
|
| 9 |
import tarfile
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
import pandas as pd
|
| 12 |
import torch
|
| 13 |
-
from torch.utils.data import IterableDataset,get_worker_info
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
if isinstance(
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
class EventSARWebDataset(IterableDataset):
|
| 28 |
-
"""Stream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
``
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
"""
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
self.
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def __iter__(self):
|
| 46 |
-
worker=get_worker_info()
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
for member in tar:
|
| 53 |
-
if not member.isfile():
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
if
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming PyTorch loader for local Event-SAR NPZ/JSON tar shards.
|
| 2 |
|
| 3 |
+
Scientific values (including NaNs) remain unchanged. See NASAR/EVENT_SAR.md.
|
| 4 |
+
This file is standalone so it can also accompany the published dataset.
|
| 5 |
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
+
|
| 8 |
from io import BytesIO
|
| 9 |
+
import hashlib
|
| 10 |
import json
|
| 11 |
from pathlib import Path
|
| 12 |
import tarfile
|
| 13 |
+
|
| 14 |
import numpy as np
|
| 15 |
import pandas as pd
|
| 16 |
import torch
|
| 17 |
+
from torch.utils.data import IterableDataset, get_worker_info
|
| 18 |
+
|
| 19 |
+
STAGES = ['pre0', 'pre1', 'event', 'post0', 'post1']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def decode_event_sar(sample, *, products=None):
|
| 23 |
+
"""Decode a record, optionally decompressing only selected product families."""
|
| 24 |
+
def selected(key):
|
| 25 |
+
return products is None or key.split("_view_")[0] in products
|
| 26 |
+
payload = sample.get('npz.bin', sample.get('npz'))
|
| 27 |
+
if isinstance(payload, (bytes, bytearray, memoryview)):
|
| 28 |
+
with np.load(BytesIO(payload), allow_pickle=False) as archive:
|
| 29 |
+
arrays = {key: archive[key] for key in archive.files if selected(key)}
|
| 30 |
+
else:
|
| 31 |
+
arrays = {k: np.asarray(v, dtype=np.uint8 if k.startswith('common_valid') else np.float32)
|
| 32 |
+
for k, v in payload.items() if v is not None and selected(k)}
|
| 33 |
+
metadata = sample['json']
|
| 34 |
+
if isinstance(metadata, (str, bytes, bytearray)):
|
| 35 |
+
metadata = json.loads(metadata)
|
| 36 |
+
if 'metadata_json' in metadata:
|
| 37 |
+
metadata = json.loads(metadata['metadata_json'])
|
| 38 |
+
return {'sample_key': metadata['hf_export']['sample_key'], 'arrays': arrays, 'metadata': metadata}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def event_sar_collate(samples):
|
| 42 |
+
"""Keep variable orbit counts and nested metadata as a list of samples."""
|
| 43 |
+
return samples
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _choices(value):
|
| 47 |
+
return [value] if isinstance(value, str) else list(value)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _ratio(value, name):
|
| 51 |
+
if not 0 <= value <= 1:
|
| 52 |
+
raise ValueError(f'{name} must be in [0, 1]')
|
| 53 |
+
|
| 54 |
|
| 55 |
class EventSARWebDataset(IterableDataset):
|
| 56 |
+
"""Stream earthquake/volcano samples with aligned crops and coverage checks.
|
| 57 |
+
|
| 58 |
+
``event_type`` accepts earthquake, volcano, a sequence, all, or None.
|
| 59 |
+
``mode`` selects rtc, insar or all (default). Auxiliary DEM, slope and
|
| 60 |
+
incidence arrays default on only in all mode, with explicit include flags.
|
| 61 |
+
``stage`` squeezes its axis; ``stages`` preserves the leading stage axis.
|
| 62 |
+
|
| 63 |
+
``min_shared_valid_ratio`` checks the cropped common_valid mask, inclusive.
|
| 64 |
+
This exported mask intersects VV/InSAR across ALL original stages/views,
|
| 65 |
+
regardless of loading mode or selected stages. No channel thresholds or
|
| 66 |
+
historical review score filters are applied.
|
| 67 |
|
| 68 |
+
``all`` crops tile row-major without overlap (dimensions must divide exactly).
|
| 69 |
+
Random crops are reproducible from seed, epoch and sample key; call set_epoch
|
| 70 |
+
before each iteration (recreate persistent worker loaders after changing it).
|
| 71 |
+
No implicit resizing, padding, filling, normalization or missing-view synthesis.
|
| 72 |
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, root, event_type=None, min_shared_valid_ratio=None,
|
| 75 |
+
stage=None, sample_keys=None, as_torch=True, *, stages=None,
|
| 76 |
+
event_ids=None, crop_size=None, crop_mode='central',
|
| 77 |
+
mode='all', include_dem=None, include_inc_angle=None,
|
| 78 |
+
include_slope=None, seed=0, shuffle_shards=False):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.root = Path(root)
|
| 81 |
+
self.as_torch = as_torch
|
| 82 |
+
self.stage = stage
|
| 83 |
+
if stage is not None and stages is not None:
|
| 84 |
+
raise ValueError('Use stage or stages, not both')
|
| 85 |
+
self.stages = tuple(_choices(stages) if stages is not None else
|
| 86 |
+
([stage] if stage is not None else STAGES))
|
| 87 |
+
if not self.stages or len(set(self.stages)) != len(self.stages) or set(self.stages) - set(STAGES):
|
| 88 |
+
raise ValueError(f'stages must be a nonempty unique selection from {STAGES}')
|
| 89 |
+
self.stage_indices = [STAGES.index(s) for s in self.stages]
|
| 90 |
+
if crop_mode == 'center':
|
| 91 |
+
crop_mode = 'central'
|
| 92 |
+
if crop_mode not in ('random', 'central', 'all'):
|
| 93 |
+
raise ValueError('crop_mode must be random, central or all')
|
| 94 |
+
if crop_size is not None and (isinstance(crop_size, bool) or not isinstance(crop_size, int) or crop_size <= 0):
|
| 95 |
+
raise ValueError('crop_size must be a positive integer or None')
|
| 96 |
+
self.crop_size, self.crop_mode = crop_size, crop_mode
|
| 97 |
+
if min_shared_valid_ratio is not None:
|
| 98 |
+
_ratio(min_shared_valid_ratio, 'min_shared_valid_ratio')
|
| 99 |
+
self.min_shared_valid_ratio = min_shared_valid_ratio
|
| 100 |
+
if mode not in ('all', 'rtc', 'insar'):
|
| 101 |
+
raise ValueError('mode must be all, rtc or insar')
|
| 102 |
+
self.mode = mode
|
| 103 |
+
self.products = {'common_valid'}
|
| 104 |
+
if mode in ('all', 'rtc'):
|
| 105 |
+
self.products.update(('prime_rtc', 'secondary_rtc'))
|
| 106 |
+
if mode in ('all', 'insar'):
|
| 107 |
+
self.products.update(('ifg', 'wrapped_phase', 'coh'))
|
| 108 |
+
for product, flag in [('dem', include_dem), ('inc_angle', include_inc_angle),
|
| 109 |
+
('slope_deg', include_slope)]:
|
| 110 |
+
if flag is not None and not isinstance(flag, bool):
|
| 111 |
+
raise ValueError(f'include flag for {product} must be bool or None')
|
| 112 |
+
if flag if flag is not None else mode == 'all':
|
| 113 |
+
self.products.add(product)
|
| 114 |
+
if mode == 'all':
|
| 115 |
+
self.products.update(('common_valid_dem_vh', 'common_valid_all'))
|
| 116 |
+
self.seed, self.epoch = int(seed), 0
|
| 117 |
+
self.shuffle_shards = shuffle_shards
|
| 118 |
+
frame = pd.read_parquet(self.root / 'metadata.parquet')
|
| 119 |
+
if event_type is not None and not (isinstance(event_type, str) and event_type == 'all'):
|
| 120 |
+
types = _choices(event_type)
|
| 121 |
+
if not types or set(types) - {'earthquake', 'volcano'}:
|
| 122 |
+
raise ValueError('event_type must select earthquake and/or volcano')
|
| 123 |
+
frame = frame[frame.event_type.isin(types)]
|
| 124 |
+
# Release score columns refer to an earlier review, not final decisions.
|
| 125 |
+
frame = frame.drop(columns=['score', 'original_score'], errors='ignore').copy()
|
| 126 |
+
if sample_keys is not None:
|
| 127 |
+
frame = frame[frame.sample_key.isin(_choices(sample_keys))]
|
| 128 |
+
if event_ids is not None:
|
| 129 |
+
frame = frame[frame.event_id.isin(_choices(event_ids))]
|
| 130 |
+
if crop_size is not None:
|
| 131 |
+
if ((frame.height < crop_size) | (frame.width < crop_size)).any():
|
| 132 |
+
raise ValueError('crop_size exceeds a selected patch; resizing/padding is not implicit')
|
| 133 |
+
if crop_mode == 'all' and ((frame.height % crop_size != 0) | (frame.width % crop_size != 0)).any():
|
| 134 |
+
raise ValueError('all mode requires patch dimensions divisible by crop_size')
|
| 135 |
+
if frame.sample_key.duplicated().any():
|
| 136 |
+
raise ValueError('Duplicate sample keys in metadata.parquet')
|
| 137 |
+
self.frame = frame.reset_index(drop=True)
|
| 138 |
+
self.rows = {row['sample_key']: row for row in frame.to_dict('records')}
|
| 139 |
+
self.keys = set(self.rows)
|
| 140 |
+
self.shards = sorted(frame.shard_path.unique())
|
| 141 |
+
self.num_source_samples = len(frame)
|
| 142 |
+
self.num_candidate_crops = (int(((frame.height // crop_size) * (frame.width // crop_size)).sum())
|
| 143 |
+
if crop_size and crop_mode == 'all' else len(frame))
|
| 144 |
+
|
| 145 |
+
def set_epoch(self, epoch):
|
| 146 |
+
self.epoch = int(epoch)
|
| 147 |
+
|
| 148 |
+
def __len__(self):
|
| 149 |
+
if self.min_shared_valid_ratio is not None:
|
| 150 |
+
raise TypeError('Length depends on crop validity; use num_candidate_crops as an upper bound')
|
| 151 |
+
return self.num_candidate_crops
|
| 152 |
+
|
| 153 |
+
def _windows(self, height, width, key):
|
| 154 |
+
size = self.crop_size
|
| 155 |
+
if size is None:
|
| 156 |
+
yield 0, 0, height, width
|
| 157 |
+
elif self.crop_mode == 'all':
|
| 158 |
+
for top in range(0, height, size):
|
| 159 |
+
for left in range(0, width, size):
|
| 160 |
+
yield top, left, size, size
|
| 161 |
+
elif self.crop_mode == 'central':
|
| 162 |
+
yield (height - size) // 2, (width - size) // 2, size, size
|
| 163 |
+
else:
|
| 164 |
+
digest = hashlib.sha256(f'{self.seed}:{self.epoch}:{key}'.encode()).digest()
|
| 165 |
+
rng = np.random.default_rng(int.from_bytes(digest[:8], 'little'))
|
| 166 |
+
yield int(rng.integers(height - size + 1)), int(rng.integers(width - size + 1)), size, size
|
| 167 |
+
|
| 168 |
+
def _prepare(self, sample):
|
| 169 |
+
row = self.rows[sample['sample_key']]
|
| 170 |
+
arrays = {k: v for k, v in sample['arrays'].items()
|
| 171 |
+
if k.split('_view_')[0] in self.products}
|
| 172 |
+
if 'common_valid' not in arrays:
|
| 173 |
+
raise ValueError(f'{sample["sample_key"]}: missing common_valid mask')
|
| 174 |
+
height, width = int(row['height']), int(row['width'])
|
| 175 |
+
for key, array in arrays.items():
|
| 176 |
+
if array.shape[-2:] != (height, width):
|
| 177 |
+
raise ValueError(f'{sample["sample_key"]}: inconsistent shape for {key}')
|
| 178 |
+
if '_view_' in key and (array.ndim != 4 or array.shape[0] != len(STAGES)):
|
| 179 |
+
raise ValueError(f'{sample["sample_key"]}: expected (5,C,H,W) for {key}')
|
| 180 |
+
metadata = sample['metadata']
|
| 181 |
+
events = metadata.get('context', {}).get('event_metadata', [])
|
| 182 |
+
if not events:
|
| 183 |
+
events = json.loads(row.get('event_metadata_json', '[]'))
|
| 184 |
+
event = events[0] if isinstance(events, list) and events else (events if isinstance(events, dict) else {})
|
| 185 |
+
kind = row['event_type']
|
| 186 |
+
magnitude = (event.get('moment_magnitude') if kind == 'earthquake' else
|
| 187 |
+
event.get('vei', event.get('event_magnitude')))
|
| 188 |
+
for top, left, h, w in self._windows(height, width, sample['sample_key']):
|
| 189 |
+
cropped = {}
|
| 190 |
+
for key, array in arrays.items():
|
| 191 |
+
value = array[..., top:top+h, left:left+w]
|
| 192 |
+
if '_view_' in key:
|
| 193 |
+
value = value[self.stage_indices]
|
| 194 |
+
cropped[key] = value
|
| 195 |
+
mask = cropped['common_valid']
|
| 196 |
+
shared_valid_ratio = float((np.isfinite(mask) & (mask != 0)).mean())
|
| 197 |
+
if self.min_shared_valid_ratio is not None and shared_valid_ratio < self.min_shared_valid_ratio:
|
| 198 |
+
continue
|
| 199 |
+
# Source metadata remains intact; output grid is explicitly crop-specific.
|
| 200 |
+
a, b, c, d, e, f = list(row['transform'])[:6]
|
| 201 |
+
c, f = c + a * left + b * top, f + d * left + e * top
|
| 202 |
+
corners = [(c + a*x + b*y, f + d*x + e*y) for x, y in ((0, 0), (w, 0), (0, h), (w, h))]
|
| 203 |
+
grid = {'crs': row['crs'], 'transform': [a, b, c, d, e, f], 'height': h, 'width': w,
|
| 204 |
+
'bounds': [min(x for x, y in corners), min(y for x, y in corners),
|
| 205 |
+
max(x for x, y in corners), max(y for x, y in corners)]}
|
| 206 |
+
if self.stage is not None:
|
| 207 |
+
cropped = {k: v[0] if '_view_' in k else v for k, v in cropped.items()}
|
| 208 |
+
# Copy isolates yielded tiles from each other and releases large parent arrays.
|
| 209 |
+
cropped = {k: np.array(v, copy=True, order='C') for k, v in cropped.items()}
|
| 210 |
+
if self.as_torch:
|
| 211 |
+
cropped = {k: torch.from_numpy(v) for k, v in cropped.items()}
|
| 212 |
+
out = dict(sample, arrays=cropped, event_type=kind, event_id=row['event_id'],
|
| 213 |
+
patch_id=row['patch_id'], mode=self.mode,
|
| 214 |
+
stages=list(self.stages), event_date=event.get('event_time_utc'),
|
| 215 |
+
event_center={'latitude': event.get('event_latitude'), 'longitude': event.get('event_longitude')},
|
| 216 |
+
event_magnitude=magnitude, magnitude_type='Mw' if kind == 'earthquake' else 'VEI',
|
| 217 |
+
crop_window=[top, left, h, w], crop_key=f'{sample["sample_key"]}:r{top}:c{left}:h{h}:w{w}',
|
| 218 |
+
grid=grid, shared_valid_ratio=shared_valid_ratio)
|
| 219 |
+
if self.stage is not None:
|
| 220 |
+
out['selected_stage'] = self.stage
|
| 221 |
+
yield out
|
| 222 |
+
|
| 223 |
def __iter__(self):
|
| 224 |
+
worker = get_worker_info()
|
| 225 |
+
workers, wid = (worker.num_workers, worker.id) if worker else (1, 0)
|
| 226 |
+
rank, world = 0, 1
|
| 227 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 228 |
+
rank, world = torch.distributed.get_rank(), torch.distributed.get_world_size()
|
| 229 |
+
shards = list(self.shards)
|
| 230 |
+
if self.shuffle_shards:
|
| 231 |
+
np.random.default_rng(self.seed + self.epoch).shuffle(shards)
|
| 232 |
+
for shard in shards[rank * workers + wid::world * workers]:
|
| 233 |
+
pending = {}
|
| 234 |
+
with tarfile.open(self.root / shard, 'r|') as tar:
|
| 235 |
for member in tar:
|
| 236 |
+
if not member.isfile() or '.' not in member.name:
|
| 237 |
+
continue
|
| 238 |
+
if member.name.endswith('.npz.bin'):
|
| 239 |
+
key, ext = member.name[:-8], 'npz'
|
| 240 |
+
else:
|
| 241 |
+
key, ext = member.name.rsplit('.', 1)
|
| 242 |
+
if key not in self.keys or ext not in ('npz', 'json'):
|
| 243 |
+
continue
|
| 244 |
+
record = pending.setdefault(key, {})
|
| 245 |
+
if ext in record:
|
| 246 |
+
raise ValueError(f'Duplicate {ext} member for {key} in {shard}')
|
| 247 |
+
record[ext] = tar.extractfile(member).read()
|
| 248 |
+
if len(record) != 2:
|
| 249 |
+
continue
|
| 250 |
+
sample = decode_event_sar(record, products=self.products)
|
| 251 |
+
del pending[key]
|
| 252 |
+
if sample['sample_key'] != key:
|
| 253 |
+
raise ValueError(f'Sample key mismatch in {shard}: {key}')
|
| 254 |
+
yield from self._prepare(sample)
|
| 255 |
+
if pending:
|
| 256 |
+
raise ValueError(f'Incomplete NPZ/JSON sample in {shard}')
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
EventSARDataset = EventSARWebDataset
|
| 260 |
+
__all__ = ['STAGES', 'decode_event_sar', 'EventSARWebDataset', 'EventSARDataset', 'event_sar_collate']
|