| 1 |
{ |
| 2 |
"cells": [ |
| 3 |
{ |
| 4 |
"cell_type": "markdown", |
| 5 |
"id": "cda28b8e", |
| 6 |
"metadata": {}, |
| 7 |
"source": [ |
| 8 |
"# Supervised Wishart evaluation on real data\n", |
| 9 |
"\n", |
| 10 |
"This notebook builds C-PolSARPro training inputs from the real San Francisco label map,\n", |
| 11 |
"runs the legacy supervised Wishart classifier on the same ROI as the Python version,\n", |
| 12 |
"and compares the two outputs.\n" |
| 13 |
] |
| 14 |
}, |
| 15 |
{ |
| 16 |
"cell_type": "code", |
| 17 |
"execution_count": null, |
| 18 |
"id": "3b746136", |
| 19 |
"metadata": {}, |
| 20 |
"outputs": [], |
| 21 |
"source": [ |
| 22 |
"%load_ext autoreload\n", |
| 23 |
"%autoreload 2\n", |
| 24 |
"\n", |
| 25 |
"import os\n", |
| 26 |
"import subprocess\n", |
| 27 |
"from pathlib import Path\n", |
| 28 |
"\n", |
| 29 |
"import dask.array as da\n", |
| 30 |
"import matplotlib.pyplot as plt\n", |
| 31 |
"import numpy as np\n", |
| 32 |
"import xarray as xr\n", |
| 33 |
"from dask.diagnostics import ProgressBar\n", |
| 34 |
"from scipy.ndimage import label as cc_label\n", |
| 35 |
"\n", |
| 36 |
"from polsarpro.classification import (\n", |
| 37 |
" _label_training_clusters,\n", |
| 38 |
" _update_wishart_class_centers,\n", |
| 39 |
" wishart_supervised,\n", |
| 40 |
")\n", |
| 41 |
"from polsarpro.dev.io import read_psp_bin\n", |
| 42 |
"from polsarpro.io import open_netcdf_beam\n", |
| 43 |
"from polsarpro.util import S_to_T3, boxcar\n", |
| 44 |
"\n", |
| 45 |
"c_psp_root = Path(\"/home/c_psp/Soft\")\n", |
| 46 |
"c_classifier = c_psp_root / \"bin\" / \"data_process_sngl\" / \"wishart_supervised_classifier.exe\"\n", |
| 47 |
"\n", |
| 48 |
"input_alos_data = Path(\"/data/psp/test_files/SAN_FRANCISCO_ALOS1_slc.nc\")\n", |
| 49 |
"input_test_dir = Path(\"/data/psp/SAN_FRANCISCO_ALOS1/T3\")\n", |
| 50 |
"label_file = Path(\"/polsarpro-dev/data/sample_labels_sf_alos1.nc\")\n", |
| 51 |
"mask_file = input_test_dir / \"mask_valid_pixels.bin\"\n", |
| 52 |
"\n", |
| 53 |
"output_test_dir = Path(\"/data/psp/res/wishart_supervised_real_data\")\n", |
| 54 |
"output_test_dir.mkdir(parents=True, exist_ok=True)\n", |
| 55 |
"\n", |
| 56 |
"boxcar_size = [7, 7]\n", |
| 57 |
"\n", |
| 58 |
"\n", |
| 59 |
"def write_config_file(directory: Path, nrow: int, ncol: int) -> Path:\n", |
| 60 |
" \"\"\"Create the minimal PSP config.txt needed by read_psp_bin.\"\"\"\n", |
| 61 |
" directory = Path(directory)\n", |
| 62 |
" directory.mkdir(parents=True, exist_ok=True)\n", |
| 63 |
" config_path = directory / \"config.txt\"\n", |
| 64 |
" config_path.write_text(\n", |
| 65 |
" f\"\"\"Nrow\n", |
| 66 |
"{nrow}\n", |
| 67 |
"---------\n", |
| 68 |
"Ncol\n", |
| 69 |
"{ncol}\n", |
| 70 |
"---------\n", |
| 71 |
"PolarCase\n", |
| 72 |
"monostatic\n", |
| 73 |
"---------\n", |
| 74 |
"PolarType\n", |
| 75 |
"full\n", |
| 76 |
"\"\"\"\n", |
| 77 |
" )\n", |
| 78 |
" return config_path\n", |
| 79 |
"\n", |
| 80 |
"\n", |
| 81 |
"def write_area_file(training_labels: np.ndarray, file_name: Path) -> dict[int, int]:\n", |
| 82 |
" \"\"\"Write the text file consumed by create_class_map() in the C implementation.\"\"\"\n", |
| 83 |
" file_name = Path(file_name)\n", |
| 84 |
" file_name.parent.mkdir(parents=True, exist_ok=True)\n", |
| 85 |
"\n", |
| 86 |
" # The legacy C parser ignores the explicit class value written in the file and\n", |
| 87 |
" # instead assigns semantic labels from the class-block position (1, 2, 3, ...).\n", |
| 88 |
" # To preserve original labels when a crop removes an intermediate class, we must\n", |
| 89 |
" # still emit empty blocks for missing class ids.\n", |
| 90 |
" class_values = list(range(1, int(training_labels.max()) + 1))\n", |
| 91 |
" lines = [\"classes\", str(len(class_values))]\n", |
| 92 |
" polygons_per_class = {}\n", |
| 93 |
"\n", |
| 94 |
" for class_value in class_values:\n", |
| 95 |
" regions, nregions = cc_label(training_labels == class_value)\n", |
| 96 |
" polygons_per_class[class_value] = int(nregions)\n", |
| 97 |
" lines.extend([\"class\", str(class_value), \"areas\", str(nregions)])\n", |
| 98 |
"\n", |
| 99 |
" for region_id in range(1, nregions + 1):\n", |
| 100 |
" coords = np.argwhere(regions == region_id)\n", |
| 101 |
" lines.extend([\"area\", str(region_id), str(len(coords))])\n", |
| 102 |
" for point_id, (yy, xx) in enumerate(coords, start=1):\n", |
| 103 |
" lines.extend([\"pt\", str(point_id), str(float(yy)), \"x\", str(float(xx))])\n", |
| 104 |
"\n", |
| 105 |
" file_name.write_text(\"\\n\".join(lines) + \"\\n\")\n", |
| 106 |
" return polygons_per_class\n", |
| 107 |
"\n", |
| 108 |
"\n", |
| 109 |
"def write_cluster_file(filtered_t3: xr.Dataset, training_labels: np.ndarray, file_name: Path):\n", |
| 110 |
" \"\"\"Write the C cluster binary: ncluster as float32, then one T3 center per cluster.\"\"\"\n", |
| 111 |
" file_name = Path(file_name)\n", |
| 112 |
" file_name.parent.mkdir(parents=True, exist_ok=True)\n", |
| 113 |
"\n", |
| 114 |
" lab, cluster_classes = _label_training_clusters(training_labels.astype(np.int32, copy=False))\n", |
| 115 |
" lab_da = da.from_array(lab, chunks=lab.shape)\n", |
| 116 |
" centers = _update_wishart_class_centers(filtered_t3, lab_da, nclass=len(cluster_classes) - 1).compute()\n", |
| 117 |
"\n", |
| 118 |
" rows = []\n", |
| 119 |
" for center in np.asarray(centers):\n", |
| 120 |
" rows.append(\n", |
| 121 |
" [\n", |
| 122 |
" np.real(center[0, 0]),\n", |
| 123 |
" np.real(center[0, 1]),\n", |
| 124 |
" np.imag(center[0, 1]),\n", |
| 125 |
" np.real(center[0, 2]),\n", |
| 126 |
" np.imag(center[0, 2]),\n", |
| 127 |
" np.real(center[1, 1]),\n", |
| 128 |
" np.real(center[1, 2]),\n", |
| 129 |
" np.imag(center[1, 2]),\n", |
| 130 |
" np.real(center[2, 2]),\n", |
| 131 |
" ]\n", |
| 132 |
" )\n", |
| 133 |
"\n", |
| 134 |
" with open(file_name, \"wb\") as f:\n", |
| 135 |
" np.array([len(rows)], dtype=np.float32).tofile(f)\n", |
| 136 |
" np.asarray(rows, dtype=np.float32).ravel().tofile(f)\n", |
| 137 |
"\n", |
| 138 |
" return lab, cluster_classes, np.asarray(rows, dtype=np.float32)\n", |
| 139 |
"\n", |
| 140 |
"\n", |
| 141 |
"def summarize_agreement(reference: np.ndarray, candidate: np.ndarray, labels: np.ndarray):\n", |
| 142 |
" summary = {\n", |
| 143 |
" \"overall_agreement\": float((reference == candidate).mean()),\n", |
| 144 |
" \"agreement_outside_training\": float((reference[labels == 0] == candidate[labels == 0]).mean()),\n", |
| 145 |
" \"agreement_on_training\": float((reference[labels > 0] == candidate[labels > 0]).mean()),\n", |
| 146 |
" }\n", |
| 147 |
"\n", |
| 148 |
" classes = np.unique(np.concatenate([reference.ravel(), candidate.ravel()]))\n", |
| 149 |
" per_class = []\n", |
| 150 |
" for class_value in classes:\n", |
| 151 |
" mask = reference == class_value\n", |
| 152 |
" if mask.any():\n", |
| 153 |
" per_class.append((int(class_value), int(mask.sum()), float((candidate[mask] == class_value).mean())))\n", |
| 154 |
"\n", |
| 155 |
" return summary, per_class\n" |
| 156 |
] |
| 157 |
}, |
| 158 |
{ |
| 159 |
"cell_type": "markdown", |
| 160 |
"id": "475a1b89", |
| 161 |
"metadata": {}, |
| 162 |
"source": [ |
| 163 |
"## Prepare the image and the C training files\n", |
| 164 |
"\n", |
| 165 |
"This notebook uses the full image by default. If we later need a faster turnaround,\n", |
| 166 |
"we can uncomment the optional manual crop below and apply the same slice to the image\n", |
| 167 |
"and the label map.\n", |
| 168 |
"\n", |
| 169 |
"If a manual crop is used, small differences may appear near the crop borders. The\n", |
| 170 |
"legacy C executable effectively averages with surrounding context from the original\n", |
| 171 |
"scene, while the Python workflow here applies the boxcar on the already cropped data.\n", |
| 172 |
"This is a user-side comparison detail rather than a critical algorithm issue, and we\n", |
| 173 |
"do not change the internal Python workflow for it because that would complicate and\n", |
| 174 |
"break the current usage pattern.\n", |
| 175 |
"\n", |
| 176 |
"For the legacy comparison we intentionally point the C executable to the PolSARPro `T3`\n", |
| 177 |
"directory and run it with `-iodf T3`. This avoids the ambiguous `S2` path, where the\n", |
| 178 |
"legacy code switches between `T3` and `T4` depending on `PolarCase` in `config.txt`.\n" |
| 179 |
] |
| 180 |
}, |
| 181 |
{ |
| 182 |
"cell_type": "code", |
| 183 |
"execution_count": null, |
| 184 |
"id": "0d9a17b7", |
| 185 |
"metadata": {}, |
| 186 |
"outputs": [], |
| 187 |
"source": [ |
| 188 |
"labels_ds = xr.open_dataset(label_file)\n", |
| 189 |
"labels_full = labels_ds[\"labels\"].astype(np.int16)\n", |
| 190 |
"\n", |
| 191 |
"row1, row2 = 0, labels_full.sizes[\"y\"]\n", |
| 192 |
"col1, col2 = 0, labels_full.sizes[\"x\"]\n", |
| 193 |
"\n", |
| 194 |
"# Optional manual crop for quicker iteration if needed later.\n", |
| 195 |
"# row1, row2 = 8000, 12000\n", |
| 196 |
"# col1, col2 = 200, 1100\n", |
| 197 |
"\n", |
| 198 |
"labels_roi = labels_full.isel(y=slice(row1, row2), x=slice(col1, col2)).copy()\n", |
| 199 |
"labels_np = labels_roi.values.astype(np.int16, copy=False)\n", |
| 200 |
"\n", |
| 201 |
"print(f\"ROI rows: {row1}:{row2} ({row2-row1})\")\n", |
| 202 |
"print(f\"ROI cols: {col1}:{col2} ({col2-col1})\")\n", |
| 203 |
"print(\"Semantic classes:\", np.unique(labels_np[labels_np > 0]).tolist())\n", |
| 204 |
"print(\"Training pixels:\", int((labels_np > 0).sum()))\n", |
| 205 |
"\n", |
| 206 |
"S_roi = open_netcdf_beam(input_alos_data).isel(y=slice(row1, row2), x=slice(col1, col2))\n", |
| 207 |
"T3_roi = boxcar(S_to_T3(S_roi), dim_az=boxcar_size[0], dim_rg=boxcar_size[1])\n", |
| 208 |
"\n", |
| 209 |
"area_file = output_test_dir / \"wishart_training_areas.txt\"\n", |
| 210 |
"cluster_file = output_test_dir / \"wishart_training_clusters.bin\"\n", |
| 211 |
"\n", |
| 212 |
"polygons_per_class = write_area_file(labels_np, area_file)\n", |
| 213 |
"lab, cluster_classes, cluster_centers = write_cluster_file(T3_roi, labels_np, cluster_file)\n", |
| 214 |
"\n", |
| 215 |
"print(\"Polygons per class:\", polygons_per_class)\n", |
| 216 |
"print(\"Connected components:\", len(cluster_classes) - 1)\n", |
| 217 |
"print(\"Area file:\", area_file)\n", |
| 218 |
"print(\"Cluster file:\", cluster_file)\n", |
| 219 |
"print(\"First cluster center:\")\n", |
| 220 |
"cluster_centers[0]\n" |
| 221 |
] |
| 222 |
}, |
| 223 |
{ |
| 224 |
"cell_type": "markdown", |
| 225 |
"id": "35a44c4d", |
| 226 |
"metadata": {}, |
| 227 |
"source": [ |
| 228 |
"## Run the C implementation\n", |
| 229 |
"\n", |
| 230 |
"The `area` file only restores cluster-to-class mapping in the legacy code; the actual\n", |
| 231 |
"cluster statistics come from the binary file we just generated from the Python-side T3 means.\n", |
| 232 |
"\n", |
| 233 |
"The legacy executable also returns exit code `1` even when it completes successfully,\n", |
| 234 |
"so the cell below accepts both `0` and `1` as non-error return codes.\n" |
| 235 |
] |
| 236 |
}, |
| 237 |
{ |
| 238 |
"cell_type": "code", |
| 239 |
"execution_count": null, |
| 240 |
"id": "a78b5316", |
| 241 |
"metadata": {}, |
| 242 |
"outputs": [], |
| 243 |
"source": [ |
| 244 |
"c_cmd = [\n", |
| 245 |
" str(c_classifier),\n", |
| 246 |
" \"-id\", str(input_test_dir),\n", |
| 247 |
" \"-od\", str(output_test_dir),\n", |
| 248 |
" \"-iodf\", \"T3\",\n", |
| 249 |
" \"-af\", str(area_file),\n", |
| 250 |
" \"-nwr\", str(boxcar_size[0]),\n", |
| 251 |
" \"-nwc\", str(boxcar_size[1]),\n", |
| 252 |
" \"-ofr\", str(row1),\n", |
| 253 |
" \"-ofc\", str(col1),\n", |
| 254 |
" \"-fnr\", str(row2 - row1),\n", |
| 255 |
" \"-fnc\", str(col2 - col1),\n", |
| 256 |
" \"-cf\", str(cluster_file),\n", |
| 257 |
" \"-bmp\", \"0\",\n", |
| 258 |
" \"-errf\", \"/tmp/MemoryAllocError.txt\",\n", |
| 259 |
" \"-mask\", str(mask_file),\n", |
| 260 |
"]\n", |
| 261 |
"\n", |
| 262 |
"print(\" \".join(c_cmd))\n", |
| 263 |
"completed = subprocess.run(c_cmd, check=False)\n", |
| 264 |
"if completed.returncode not in (0, 1):\n", |
| 265 |
" raise RuntimeError(f\"C classifier failed with exit code {completed.returncode}\")\n", |
| 266 |
"write_config_file(output_test_dir, nrow=row2 - row1, ncol=col2 - col1)" |
| 267 |
] |
| 268 |
}, |
| 269 |
{ |
| 270 |
"cell_type": "markdown", |
| 271 |
"id": "2148dae5", |
| 272 |
"metadata": {}, |
| 273 |
"source": [ |
| 274 |
"## Run the Python implementation on the same ROI\n" |
| 275 |
] |
| 276 |
}, |
| 277 |
{ |
| 278 |
"cell_type": "code", |
| 279 |
"execution_count": null, |
| 280 |
"id": "901bc686", |
| 281 |
"metadata": {}, |
| 282 |
"outputs": [], |
| 283 |
"source": [ |
| 284 |
"out_file = output_test_dir / \"wishart_supervised.nc\"\n", |
| 285 |
"\n", |
| 286 |
"# remove if file already exists as xarray will not overwrite existing files and will error instead\n", |
| 287 |
"if out_file.exists():\n", |
| 288 |
" out_file.unlink()\n", |
| 289 |
"\n", |
| 290 |
"with ProgressBar():\n", |
| 291 |
" out_py = wishart_supervised(\n", |
| 292 |
" S_roi,\n", |
| 293 |
" training_labels=labels_roi,\n", |
| 294 |
" boxcar_size=boxcar_size,\n", |
| 295 |
" ).to_netcdf(out_file)\n", |
| 296 |
"\n", |
| 297 |
"out_py = xr.open_dataset(out_file) \n", |
| 298 |
"class_py = out_py[\"wishart_supervised_class\"].values.astype(np.int16)\n", |
| 299 |
"class_py\n" |
| 300 |
] |
| 301 |
}, |
| 302 |
{ |
| 303 |
"cell_type": "code", |
| 304 |
"execution_count": null, |
| 305 |
"id": "6973d522", |
| 306 |
"metadata": {}, |
| 307 |
"outputs": [], |
| 308 |
"source": [ |
| 309 |
"print(out_file)" |
| 310 |
] |
| 311 |
}, |
| 312 |
{ |
| 313 |
"cell_type": "markdown", |
| 314 |
"id": "8ab0a7c8", |
| 315 |
"metadata": {}, |
| 316 |
"source": [ |
| 317 |
"## Numerical comparison\n" |
| 318 |
] |
| 319 |
}, |
| 320 |
{ |
| 321 |
"cell_type": "code", |
| 322 |
"execution_count": null, |
| 323 |
"id": "1823326e", |
| 324 |
"metadata": {}, |
| 325 |
"outputs": [], |
| 326 |
"source": [ |
| 327 |
"c_output_path = output_test_dir / f\"wishart_supervised_class_{boxcar_size[0]}x{boxcar_size[1]}.bin\"\n", |
| 328 |
"class_c = read_psp_bin(c_output_path).astype(np.int16)\n", |
| 329 |
"summary, per_class = summarize_agreement(class_c, class_py, labels_np)\n", |
| 330 |
"\n", |
| 331 |
"print(\"Agreement summary\")\n", |
| 332 |
"for key, value in summary.items():\n", |
| 333 |
" print(f\"- {key}: {value:.4f}\")\n", |
| 334 |
"\n", |
| 335 |
"print(\"\\nAgreement by C class\")\n", |
| 336 |
"for class_value, npix, agreement in per_class:\n", |
| 337 |
" print(f\"- class {class_value}: {npix} px, agreement={agreement:.4f}\")\n", |
| 338 |
"\n", |
| 339 |
"print(\"\\nClass histograms\")\n", |
| 340 |
"for source_name, arr in [(\"C\", class_c), (\"Python\", class_py)]:\n", |
| 341 |
" values, counts = np.unique(arr, return_counts=True)\n", |
| 342 |
" print(source_name, dict(zip(values.tolist(), counts.tolist())))\n" |
| 343 |
] |
| 344 |
}, |
| 345 |
{ |
| 346 |
"cell_type": "markdown", |
| 347 |
"id": "cc5eba77", |
| 348 |
"metadata": {}, |
| 349 |
"source": [ |
| 350 |
"## Quick-look plots\n" |
| 351 |
] |
| 352 |
}, |
| 353 |
{ |
| 354 |
"cell_type": "code", |
| 355 |
"execution_count": null, |
| 356 |
"id": "c9e6e489", |
| 357 |
"metadata": {}, |
| 358 |
"outputs": [], |
| 359 |
"source": [ |
| 360 |
"disagreement = np.where(class_c == class_py, 0, class_py)\n", |
| 361 |
"\n", |
| 362 |
"fig, axes = plt.subplots(2, 2, figsize=(14, 12), constrained_layout=True)\n", |
| 363 |
"\n", |
| 364 |
"l1 = axes[0, 0].imshow(labels_np[::8], cmap=\"tab10\", interpolation=\"nearest\", vmin=0, vmax = np.max(labels_np))\n", |
| 365 |
"axes[0, 0].set_title(\"Training labels\")\n", |
| 366 |
"axes[0, 0].axis(\"off\")\n", |
| 367 |
"fig.colorbar(l1, ax=axes[0, 0], fraction=0.046)\n", |
| 368 |
"\n", |
| 369 |
"l2 =axes[0, 1].imshow(class_c[::8], cmap=\"tab10\", interpolation=\"nearest\", vmin=0, vmax = np.max(labels_np))\n", |
| 370 |
"axes[0, 1].set_title(\"C supervised Wishart\")\n", |
| 371 |
"axes[0, 1].axis(\"off\")\n", |
| 372 |
"fig.colorbar(l2, ax=axes[0, 1], fraction=0.046)\n", |
| 373 |
"\n", |
| 374 |
"l3 = axes[1, 0].imshow(class_py[::8], cmap=\"tab10\", interpolation=\"nearest\", vmin=0, vmax = np.max(labels_np))\n", |
| 375 |
"axes[1, 0].set_title(\"Python supervised Wishart\")\n", |
| 376 |
"axes[1, 0].axis(\"off\")\n", |
| 377 |
"fig.colorbar(l3, ax=axes[1, 0], fraction=0.046)\n", |
| 378 |
"\n", |
| 379 |
"im = axes[1, 1].imshow(disagreement[::8], cmap=\"magma\", interpolation=\"nearest\")\n", |
| 380 |
"axes[1, 1].set_title(\"Disagreement map (0 means match)\")\n", |
| 381 |
"axes[1, 1].axis(\"off\")\n", |
| 382 |
"fig.colorbar(im, ax=axes[1, 1], fraction=0.046)\n", |
| 383 |
"\n", |
| 384 |
"plt.show()\n" |
| 385 |
] |
| 386 |
}, |
| 387 |
{ |
| 388 |
"cell_type": "markdown", |
| 389 |
"id": "db7acde7", |
| 390 |
"metadata": {}, |
| 391 |
"source": [ |
| 392 |
"Interpretation:\n", |
| 393 |
"\n", |
| 394 |
"If agreement is high but not perfect, that is expected. The goal here is to verify that the\n", |
| 395 |
"Python implementation lands in the same regime as the C executable on the real training setup,\n", |
| 396 |
"not to force bit-identical output.\n" |
| 397 |
] |
| 398 |
} |
| 399 |
], |
| 400 |
"metadata": { |
| 401 |
"kernelspec": { |
| 402 |
"display_name": "psp", |
| 403 |
"language": "python", |
| 404 |
"name": "python3" |
| 405 |
}, |
| 406 |
"language_info": { |
| 407 |
"codemirror_mode": { |
| 408 |
"name": "ipython", |
| 409 |
"version": 3 |
| 410 |
}, |
| 411 |
"file_extension": ".py", |
| 412 |
"mimetype": "text/x-python", |
| 413 |
"name": "python", |
| 414 |
"nbconvert_exporter": "python", |
| 415 |
"pygments_lexer": "ipython3", |
| 416 |
"version": "3.12.13" |
| 417 |
} |
| 418 |
}, |
| 419 |
"nbformat": 4, |
| 420 |
"nbformat_minor": 5 |
| 421 |
} |