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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch datasets for the released NA-SAR tensor layout.
|
| 2 |
+
|
| 3 |
+
The public API intentionally uses the dataset name, not the storage format:
|
| 4 |
+
|
| 5 |
+
from nasar_dataset import NASARRTCDataset, NASARInSARDataset
|
| 6 |
+
|
| 7 |
+
RTC item:
|
| 8 |
+
patch_id, rtc_view_0, inc_angle_view_0, rtc_view_1, inc_angle_view_1
|
| 9 |
+
|
| 10 |
+
InSAR item:
|
| 11 |
+
patch_id, ifg_view_0, coh_view_0, inc_angle_view_0,
|
| 12 |
+
ifg_view_1, coh_view_1, inc_angle_view_1
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from io import BytesIO
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
import tarfile
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _normalize_rtc(arr: np.ndarray, norm_stats: tuple[float, float]) -> np.ndarray:
|
| 26 |
+
"""Clip to [p1, p99] and rescale to [0, 1]. Zeros stay zero."""
|
| 27 |
+
p1, p99 = norm_stats
|
| 28 |
+
valid = arr > 0
|
| 29 |
+
arr = np.where(valid, np.clip((arr - p1) / (p99 - p1), 0.0, 1.0), 0.0)
|
| 30 |
+
return arr.astype(np.float32)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _prepare_rtc(
|
| 34 |
+
arr: np.ndarray,
|
| 35 |
+
log_scale: bool,
|
| 36 |
+
alpha: float,
|
| 37 |
+
norm_stats: tuple[float, float] | None,
|
| 38 |
+
) -> np.ndarray:
|
| 39 |
+
"""Apply the same RTC preprocessing used during NASAR pretraining."""
|
| 40 |
+
arr = arr.astype(np.float32, copy=True)
|
| 41 |
+
arr = np.where(np.isfinite(arr) & (arr > 0.0), arr, 0.0)
|
| 42 |
+
if log_scale:
|
| 43 |
+
arr = np.log1p(alpha * arr)
|
| 44 |
+
if norm_stats is not None and log_scale:
|
| 45 |
+
arr = _normalize_rtc(arr, norm_stats)
|
| 46 |
+
return arr
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _copy_array(arr: np.ndarray) -> np.ndarray:
|
| 50 |
+
"""Detach an array from an opened np.load handle."""
|
| 51 |
+
return arr.astype(np.float32, copy=True)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class _NASARBase:
|
| 55 |
+
"""Shared metadata and tensor-path handling for NA-SAR datasets."""
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
nasar_root: str = "/datasets/disk3/NA-SAR",
|
| 60 |
+
parquet_path: str | None = None,
|
| 61 |
+
years: list[int] | None = None,
|
| 62 |
+
min_quality_score: float | None = None,
|
| 63 |
+
shard_size: int = 10_000,
|
| 64 |
+
) -> None:
|
| 65 |
+
self.root = Path(nasar_root)
|
| 66 |
+
self.parquet_path = Path(parquet_path) if parquet_path is not None else self.root / "metadata.parquet"
|
| 67 |
+
self.shard_size = shard_size
|
| 68 |
+
|
| 69 |
+
need_quality = min_quality_score is not None
|
| 70 |
+
cols = ["patch_id", "npz_path", "sample_key", "shard_path"]
|
| 71 |
+
if years is not None:
|
| 72 |
+
cols.append("prime_date_view_0")
|
| 73 |
+
if need_quality:
|
| 74 |
+
cols.append("quality_score")
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
df = pd.read_parquet(self.parquet_path, columns=cols)
|
| 78 |
+
except Exception:
|
| 79 |
+
df = pd.read_parquet(self.parquet_path)
|
| 80 |
+
|
| 81 |
+
if years is not None:
|
| 82 |
+
year_set = set(years)
|
| 83 |
+
prime_years = pd.to_datetime(df["prime_date_view_0"], utc=True).dt.year
|
| 84 |
+
df = df[prime_years.isin(year_set)]
|
| 85 |
+
|
| 86 |
+
if need_quality:
|
| 87 |
+
if "quality_score" not in df.columns:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"min_quality_score requested but 'quality_score' column not found in "
|
| 90 |
+
f"{self.parquet_path}"
|
| 91 |
+
)
|
| 92 |
+
df = df[df["quality_score"] >= min_quality_score]
|
| 93 |
+
|
| 94 |
+
if "npz_path" not in df.columns and "shard_path" not in df.columns:
|
| 95 |
+
df = df.copy()
|
| 96 |
+
df["npz_path"] = [
|
| 97 |
+
str(Path("npz") / f"{i // self.shard_size:06d}" / f"{patch_id}.npz")
|
| 98 |
+
for i, patch_id in enumerate(df["patch_id"])
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
self.patch_ids: list[str] = df["patch_id"].tolist()
|
| 102 |
+
self.use_shards = "shard_path" in df.columns
|
| 103 |
+
if self.use_shards:
|
| 104 |
+
self.sample_keys: list[str] = df["sample_key"].tolist()
|
| 105 |
+
self.shard_paths: list[Path] = [self._resolve_tensor_path(p) for p in df["shard_path"]]
|
| 106 |
+
else:
|
| 107 |
+
self.tensor_paths: list[Path] = [self._resolve_tensor_path(p) for p in df["npz_path"]]
|
| 108 |
+
|
| 109 |
+
def _resolve_tensor_path(self, path: str | Path) -> Path:
|
| 110 |
+
path = Path(path)
|
| 111 |
+
if path.is_absolute():
|
| 112 |
+
return path
|
| 113 |
+
return self.root / path
|
| 114 |
+
|
| 115 |
+
def __len__(self) -> int:
|
| 116 |
+
return len(self.patch_ids)
|
| 117 |
+
|
| 118 |
+
def _open_npz(self, idx: int):
|
| 119 |
+
if not self.use_shards:
|
| 120 |
+
return np.load(self.tensor_paths[idx])
|
| 121 |
+
|
| 122 |
+
member_name = f"{self.sample_keys[idx]}.npz"
|
| 123 |
+
with tarfile.open(self.shard_paths[idx], "r") as tar:
|
| 124 |
+
member = tar.extractfile(member_name)
|
| 125 |
+
if member is None:
|
| 126 |
+
raise FileNotFoundError(f"{member_name} not found in {self.shard_paths[idx]}")
|
| 127 |
+
data = member.read()
|
| 128 |
+
return np.load(BytesIO(data))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class NASARRTCDataset(_NASARBase):
|
| 132 |
+
"""Dataset for RTC contrastive learning.
|
| 133 |
+
|
| 134 |
+
RTC arrays are stored as raw linear backscatter. By default, this loader
|
| 135 |
+
applies log compression and normalization to match the NASAR pretraining
|
| 136 |
+
data path.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
nasar_root: str = "/datasets/disk3/NA-SAR",
|
| 142 |
+
parquet_path: str | None = None,
|
| 143 |
+
log_scale: bool = True,
|
| 144 |
+
alpha: float = 20.0,
|
| 145 |
+
years: list[int] | None = None,
|
| 146 |
+
random_temporal: bool = True,
|
| 147 |
+
min_quality_score: float | None = 0.53,
|
| 148 |
+
norm_stats: tuple[float, float] | None = (0.14, 2.38),
|
| 149 |
+
shard_size: int = 10_000,
|
| 150 |
+
) -> None:
|
| 151 |
+
super().__init__(
|
| 152 |
+
nasar_root=nasar_root,
|
| 153 |
+
parquet_path=parquet_path,
|
| 154 |
+
years=years,
|
| 155 |
+
min_quality_score=min_quality_score,
|
| 156 |
+
shard_size=shard_size,
|
| 157 |
+
)
|
| 158 |
+
self.log_scale = log_scale
|
| 159 |
+
self.alpha = alpha
|
| 160 |
+
self.random_temporal = random_temporal
|
| 161 |
+
self.norm_stats = norm_stats
|
| 162 |
+
|
| 163 |
+
def __getitem__(self, idx: int) -> dict:
|
| 164 |
+
patch_id = self.patch_ids[idx]
|
| 165 |
+
prefix = "secondary_rtc" if self.random_temporal and bool(np.random.randint(2)) else "prime_rtc"
|
| 166 |
+
with self._open_npz(idx) as z:
|
| 167 |
+
return {
|
| 168 |
+
"patch_id": patch_id,
|
| 169 |
+
"rtc_view_0": _prepare_rtc(
|
| 170 |
+
z[f"{prefix}_view_0"], self.log_scale, self.alpha, self.norm_stats
|
| 171 |
+
),
|
| 172 |
+
"inc_angle_view_0": _copy_array(z["inc_angle_view_0"]),
|
| 173 |
+
"rtc_view_1": _prepare_rtc(
|
| 174 |
+
z[f"{prefix}_view_1"], self.log_scale, self.alpha, self.norm_stats
|
| 175 |
+
),
|
| 176 |
+
"inc_angle_view_1": _copy_array(z["inc_angle_view_1"]),
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class NASARInSARDataset(_NASARBase):
|
| 181 |
+
"""Dataset for InSAR contrastive learning."""
|
| 182 |
+
|
| 183 |
+
def __init__(
|
| 184 |
+
self,
|
| 185 |
+
nasar_root: str = "/datasets/disk3/NA-SAR",
|
| 186 |
+
parquet_path: str | None = None,
|
| 187 |
+
years: list[int] | None = None,
|
| 188 |
+
min_quality_score: float | None = 0.53,
|
| 189 |
+
shard_size: int = 10_000,
|
| 190 |
+
) -> None:
|
| 191 |
+
super().__init__(
|
| 192 |
+
nasar_root=nasar_root,
|
| 193 |
+
parquet_path=parquet_path,
|
| 194 |
+
years=years,
|
| 195 |
+
min_quality_score=min_quality_score,
|
| 196 |
+
shard_size=shard_size,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def __getitem__(self, idx: int) -> dict:
|
| 200 |
+
patch_id = self.patch_ids[idx]
|
| 201 |
+
with self._open_npz(idx) as z:
|
| 202 |
+
return {
|
| 203 |
+
"patch_id": patch_id,
|
| 204 |
+
"ifg_view_0": _copy_array(z["ifg_view_0"]),
|
| 205 |
+
"coh_view_0": _copy_array(z["coh_view_0"]),
|
| 206 |
+
"inc_angle_view_0": _copy_array(z["inc_angle_view_0"]),
|
| 207 |
+
"ifg_view_1": _copy_array(z["ifg_view_1"]),
|
| 208 |
+
"coh_view_1": _copy_array(z["coh_view_1"]),
|
| 209 |
+
"inc_angle_view_1": _copy_array(z["inc_angle_view_1"]),
|
| 210 |
+
}
|