Debian Codegraph @

notebooks/dev/test-wishart-real-data.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "# H-A-Alpha Wishart evaluation"
8 ]
9 },
10 {
11 "cell_type": "code",
12 "execution_count": null,
13 "metadata": {},
14 "outputs": [],
15 "source": [
16 "%load_ext autoreload\n",
17 "%autoreload 2\n",
18 "\n",
19 "import os\n",
20 "\n",
21 "from pathlib import Path\n",
22 "import xarray as xr\n",
23 "from polsarpro.io import open_netcdf_beam\n",
24 "from polsarpro.dev.io import read_psp_bin\n",
25 "from polsarpro.decompositions import h_a_alpha\n",
26 "from polsarpro.classification import wishart_h_a_alpha\n",
27 "from polsarpro.util import S_to_T3\n",
28 "import shutil\n",
29 "\n",
30 "# optional import for progress bar\n",
31 "from dask.diagnostics import ProgressBar\n",
32 "\n",
33 "# change to your local C-PolSARpro install dir\n",
34 "c_psp_dir = \"/home/c_psp/Soft/bin/\"\n",
35 "os.environ[\"PATH\"]+=os.pathsep+f\"{c_psp_dir}/data_process_sngl/\"\n",
36 "os.environ[\"PATH\"]+=os.pathsep+f\"{c_psp_dir}/data_convert/\"\n",
37 "\n",
38 "# change to your data paths\n",
39 "# original dataset\n",
40 "input_alos_data = Path(\"/data/psp/test_files/SAN_FRANCISCO_ALOS1_slc.nc\")\n",
41 "\n",
42 "# input files from C\n",
43 "input_test_dir = Path(\"/data/psp/SAN_FRANCISCO_ALOS1/T3\")\n",
44 "# input_test_dir = Path(\"/data/psp/SAN_FRANCISCO_ALOS1/\")\n",
45 "\n",
46 "# output files from C\n",
47 "output_test_dir = Path(\"/data/psp/res/wishart_c\")\n",
48 "if not os.path.isdir(output_test_dir):\n",
49 " os.mkdir(output_test_dir)\n",
50 "\n",
51 "\n",
52 "def write_config_file(directory: Path, nrow: int, ncol: int) -> Path:\n",
53 " \"\"\"\n",
54 " Create a config.txt file in the given directory with specified dimensions.\n",
55 "\n",
56 " Args:\n",
57 " directory: Target directory.\n",
58 " nrow: Number of rows.\n",
59 " ncol: Number of columns.\n",
60 "\n",
61 " Returns:\n",
62 " Path to the created config file.\n",
63 " \"\"\"\n",
64 " directory = Path(directory)\n",
65 " directory.mkdir(parents=True, exist_ok=True)\n",
66 "\n",
67 " config_path = directory / \"config.txt\"\n",
68 "\n",
69 " content = f\"\"\"Nrow\n",
70 "{nrow}\n",
71 "---------\n",
72 "Ncol\n",
73 "{ncol}\n",
74 "---------\n",
75 "PolarCase\n",
76 "bistatic\n",
77 "---------\n",
78 "PolarType\n",
79 "full \n",
80 "\"\"\"\n",
81 "\n",
82 " config_path.write_text(content)\n",
83 "\n",
84 " return config_path\n",
85 "\n",
86 "def summarize_agreement(reference , candidate):\n",
87 " import numpy as np\n",
88 " reference = np.asarray(reference)\n",
89 " candidate = np.asarray(candidate)\n",
90 " summary = {\n",
91 " \"overall_agreement\": float((reference == candidate).mean()),\n",
92 " }\n",
93 "\n",
94 " classes = np.unique(np.concatenate([reference.ravel(), candidate.ravel()]))\n",
95 " per_class = []\n",
96 " for class_value in classes:\n",
97 " mask = reference == class_value\n",
98 " if mask.any():\n",
99 " per_class.append((int(class_value), int(mask.sum()), float((candidate[mask] == class_value).mean())))\n",
100 "\n",
101 " return summary, per_class\n",
102 "\n",
103 "\n",
104 "\n",
105 "\n",
106 "# compute large image\n",
107 "row1, row2 = 0, 18432\n",
108 "col1, col2 = 0, 1248\n",
109 "\n",
110 "# smaller window\n",
111 "# row1, row2 = 8000, 8500\n",
112 "# row1, row2 = 8000, 12000\n",
113 "# col1, col2 = 200, 1100"
114 ]
115 },
116 {
117 "cell_type": "markdown",
118 "metadata": {},
119 "source": [
120 "## Run the C-version on some test data\n",
121 "### Compute H-A-alpha\n",
122 "\n",
123 "#### Note: \n",
124 "We compute the decomposition on the whole image and then apply the window to the classification. \n",
125 "This is to avoid offset problems (classification uses the same offsets on input image a decmposition results.)"
126 ]
127 },
128 {
129 "cell_type": "code",
130 "execution_count": null,
131 "metadata": {},
132 "outputs": [],
133 "source": [
134 "# only activate flags for H, A & Alpha\n",
135 "\n",
136 "input_dict = dict(\n",
137 " id=input_test_dir,\n",
138 " od=output_test_dir,\n",
139 " iodf=\"S2T3\",\n",
140 " nwr=7,\n",
141 " nwc=7,\n",
142 " ofr=0,\n",
143 " ofc=0,\n",
144 " fnr=18432,\n",
145 " fnc=1248,\n",
146 " fl1=0,\n",
147 " fl2=0,\n",
148 " fl3=1,\n",
149 " fl4=1,\n",
150 " fl5=1,\n",
151 " fl6=0,\n",
152 " fl7=0,\n",
153 " fl8=0,\n",
154 " fl9=0,\n",
155 " errf=\"/tmp/MemoryAllocError.txt\",\n",
156 " mask=f\"{input_test_dir}/mask_valid_pixels.bin\",\n",
157 ")\n",
158 "\n",
159 "# making input string: -param1 value1 -param2 value2 etc\n",
160 "param_str = \" \".join([f\"-{k} {input_dict[k]}\" for k in input_dict])\n",
161 "cmd = f\"h_a_alpha_decomposition.exe {param_str}\"\n",
162 "print(cmd)\n",
163 "# os.system(cmd)\n",
164 "\n",
165 "# CPSP does not create another config file in output dir\n",
166 "# shutil.copy(input_test_dir / \"config.txt\", output_test_dir)\n",
167 "\n",
168 "# write_config_file(directory=output_test_dir, nrow=row2-row1, ncol=col2-col1)"
169 ]
170 },
171 {
172 "cell_type": "markdown",
173 "metadata": {},
174 "source": [
175 "### Compute Wishart using H-A-Alpha results"
176 ]
177 },
178 {
179 "cell_type": "code",
180 "execution_count": null,
181 "metadata": {},
182 "outputs": [],
183 "source": [
184 "input_dict = dict(\n",
185 " id=input_test_dir,\n",
186 " od=output_test_dir,\n",
187 " # iodf=\"S2\",\n",
188 " iodf=\"T3\",\n",
189 " nwr=7,\n",
190 " nwc=7,\n",
191 " ofr=row1, # offsets are applied to input data and HAA results\n",
192 " ofc=col1,\n",
193 " fnr=row2-row1,\n",
194 " fnc=col2-col1,\n",
195 " hf=f\"{output_test_dir}/entropy.bin\",\n",
196 " af=f\"{output_test_dir}/anisotropy.bin\",\n",
197 " alf=f\"{output_test_dir}/alpha.bin\",\n",
198 " nit=\"10\",\n",
199 " pct=\"10\",\n",
200 " bmp=0,\n",
201 " errf=\"/tmp/MemoryAllocError.txt\",\n",
202 " mask=f\"{input_test_dir}/mask_valid_pixels.bin\",\n",
203 ")\n",
204 "\n",
205 "# making input string: -param1 value1 -param2 value2 etc\n",
206 "param_str = \" \".join([f\"-{k} {input_dict[k]}\" for k in input_dict])\n",
207 "cmd = f\"wishart_h_a_alpha_classifier.exe {param_str}\"\n",
208 "print(cmd)\n",
209 "# WARNING: this takes long!\n",
210 "# os.system(cmd)\n",
211 "\n",
212 "# need adapted conf file to read in python\n",
213 "write_config_file(directory=output_test_dir, nrow=row2-row1, ncol=col2-col1)"
214 ]
215 },
216 {
217 "cell_type": "markdown",
218 "metadata": {},
219 "source": [
220 "## Load ALOS data and C outputs"
221 ]
222 },
223 {
224 "cell_type": "code",
225 "execution_count": null,
226 "metadata": {},
227 "outputs": [],
228 "source": [
229 "# uncomment to test on S matrix made with SNAP\n",
230 "S = open_netcdf_beam(input_alos_data).persist()#.chunk(\"auto\")\n",
231 "\n",
232 "flags = (\"entropy\", \"anisotropy\", \"alpha\")\n",
233 "\n",
234 "dct = {}\n",
235 "for it in flags:\n",
236 " dat = read_psp_bin(output_test_dir / f\"haa_full/{it}.bin\")\n",
237 " dct[it] = ((\"y\", \"x\"), dat)\n",
238 "\n",
239 "haa = xr.Dataset(dct, attrs={\"poltype\":\"h_a_alpha\"})#.chunk(\"auto\")\n",
240 "# haa"
241 ]
242 },
243 {
244 "cell_type": "markdown",
245 "metadata": {},
246 "source": [
247 "## Apply the decomposition"
248 ]
249 },
250 {
251 "cell_type": "code",
252 "execution_count": null,
253 "metadata": {},
254 "outputs": [],
255 "source": [
256 "file_out = \"/data/psp/res/test_wishart_h_a_alpha.nc\"\n",
257 "# netcdf writer cannot overwrite\n",
258 "if os.path.isfile(file_out):\n",
259 " os.remove(file_out)\n",
260 "\n",
261 "# to stay consistent with C, we first compute HAA \n",
262 "# on the whole image then crop before Wishart\n",
263 "with ProgressBar():\n",
264 " # haa = h_a_alpha(S, boxcar_size=[7, 7], flags=flags)#.chunk(\"auto\")\n",
265 "\n",
266 " # haa = haa.isel(y=slice(row1, row2), x=slice(col1, col2))\n",
267 " # T3 = S_to_T3(S) \n",
268 " res = wishart_h_a_alpha(\n",
269 " # T3.isel(y=slice(row1, row2), x=slice(col1, col2)),\n",
270 " S.isel(y=slice(row1, row2), x=slice(col1, col2)),\n",
271 " boxcar_size=[7, 7],\n",
272 " max_iter=10,\n",
273 " tol_pct=10,\n",
274 " h_a_alpha_result=haa.isel(y=slice(row1, row2), x=slice(col1, col2)),\n",
275 " ).to_netcdf(file_out)"
276 ]
277 },
278 {
279 "cell_type": "markdown",
280 "metadata": {},
281 "source": [
282 "# Numerical evaluation"
283 ]
284 },
285 {
286 "cell_type": "code",
287 "execution_count": null,
288 "metadata": {},
289 "outputs": [],
290 "source": [
291 "# open python output (comment if using compute)\n",
292 "out_py = xr.open_dataset(\"/data/psp/res/test_wishart_h_a_alpha.nc\")\n",
293 "\n",
294 "# open C-PolSARPro outputs\n",
295 "out_c = {}\n",
296 "\n",
297 "out_names = {\n",
298 " \"wishart_h_a_alpha_class\": \"wishart_H_A_alpha_class_7x7\",\n",
299 " \"wishart_h_alpha_class\": \"wishart_H_alpha_class_7x7\",\n",
300 "}\n",
301 "\n",
302 "for name in out_names:\n",
303 " file_name = output_test_dir / f\"{out_names[name]}.bin\"\n",
304 " out_c[name] = read_psp_bin(file_name)"
305 ]
306 },
307 {
308 "cell_type": "code",
309 "execution_count": null,
310 "metadata": {},
311 "outputs": [],
312 "source": [
313 "var_name = \"wishart_h_alpha_class\"\n",
314 "arr_c = out_c[var_name]\n",
315 "arr_py = out_py[var_name]\n",
316 "\n",
317 "import matplotlib.pyplot as plt\n",
318 "plt.figure(figsize=(15, 10))\n",
319 "plt.subplot(131)\n",
320 "plt.imshow((arr_c - arr_py)[::4], interpolation=\"none\", cmap=\"Dark2\")\n",
321 "plt.title(\"diff\")\n",
322 "plt.subplot(132)\n",
323 "plt.imshow(arr_c[::4], interpolation=\"none\", cmap=\"Dark2\")\n",
324 "plt.colorbar(fraction=0.046, pad=0.04)\n",
325 "plt.title(\"c\")\n",
326 "plt.subplot(133)\n",
327 "plt.imshow(arr_py[::4], interpolation=\"none\", cmap=\"Dark2\")\n",
328 "plt.colorbar(fraction=0.046, pad=0.04)\n",
329 "plt.title(\"py\")"
330 ]
331 },
332 {
333 "cell_type": "code",
334 "execution_count": null,
335 "metadata": {},
336 "outputs": [],
337 "source": [
338 "import numpy as np\n",
339 "summary, per_class = summarize_agreement(arr_c, arr_py)\n",
340 "\n",
341 "print(\"Agreement summary\")\n",
342 "for key, value in summary.items():\n",
343 " print(f\"- {key}: {value:.4f}\")\n",
344 "\n",
345 "print(\"\\nAgreement by C class\")\n",
346 "for class_value, npix, agreement in per_class:\n",
347 " print(f\"- class {class_value}: {npix} px, agreement={agreement:.4f}\")"
348 ]
349 },
350 {
351 "cell_type": "code",
352 "execution_count": null,
353 "metadata": {},
354 "outputs": [],
355 "source": [
356 "var_name = \"wishart_h_a_alpha_class\"\n",
357 "arr_c = out_c[var_name]\n",
358 "arr_py = out_py[var_name]\n",
359 "\n",
360 "import matplotlib.pyplot as plt\n",
361 "plt.figure(figsize=(15, 10))\n",
362 "plt.subplot(131)\n",
363 "plt.imshow((arr_c - arr_py)[::4], interpolation=\"none\", cmap=\"tab20\")\n",
364 "plt.colorbar(fraction=0.046, pad=0.04)\n",
365 "plt.title(\"diff\")\n",
366 "plt.subplot(132)\n",
367 "plt.imshow(arr_c[::4], interpolation=\"none\", cmap=\"tab20\")\n",
368 "plt.colorbar(fraction=0.046, pad=0.04)\n",
369 "plt.title(\"c\")\n",
370 "plt.subplot(133)\n",
371 "plt.imshow(arr_py[::4], interpolation=\"none\", cmap=\"tab20\")\n",
372 "plt.colorbar(fraction=0.046, pad=0.04)\n",
373 "plt.title(\"py\")"
374 ]
375 },
376 {
377 "cell_type": "code",
378 "execution_count": null,
379 "metadata": {},
380 "outputs": [],
381 "source": [
382 "import numpy as np\n",
383 "summary, per_class = summarize_agreement(arr_c, arr_py)\n",
384 "\n",
385 "print(\"Agreement summary\")\n",
386 "for key, value in summary.items():\n",
387 " print(f\"- {key}: {value:.4f}\")\n",
388 "\n",
389 "print(\"\\nAgreement by C class\")\n",
390 "for class_value, npix, agreement in per_class:\n",
391 " print(f\"- class {class_value}: {npix} px, agreement={agreement:.4f}\")"
392 ]
393 },
394 {
395 "cell_type": "markdown",
396 "metadata": {},
397 "source": [
398 "### Interpretation:\n",
399 "- Difference in agreement are likely due to differences in math computation and precision errors that are amplified in matrices with small determinants. Besides, C boxcar implementation is recursive, which also causes precision errors. In python we use convolutions which are not prone to this type of error.\n",
400 "- In 16 class classification, the sea is artificially divided into 2 classes which likely have very close centers, therefore small numeric errors will provoke class switching.\n",
401 "- We have tested with both numpy based determinant and matrix inversions and hard-coded 3x3 versions that align with C implementation and got the same results. "
402 ]
403 },
404 {
405 "cell_type": "markdown",
406 "metadata": {},
407 "source": [
408 "### Additional analysis\n",
409 "Display center to center distances \n",
410 "- between class pairs for each implementation\n",
411 "- between C and python classes "
412 ]
413 },
414 {
415 "cell_type": "code",
416 "execution_count": null,
417 "metadata": {},
418 "outputs": [],
419 "source": [
420 "from polsarpro.util import S_to_T3\n",
421 "from polsarpro.classification import _update_wishart_class_centers\n",
422 "T3 = S_to_T3(S)\n",
423 "nclass = 16\n",
424 "centers_c = _update_wishart_class_centers(T3, arr_c, nclass=nclass).compute()\n",
425 "centers_py = _update_wishart_class_centers(T3, arr_py.data, nclass=nclass).compute()\n",
426 "\n",
427 "def dist(m1, m2):\n",
428 " return float(np.sqrt(np.mean(abs(m1 - m2)**2)))\n",
429 "\n",
430 "# matrices storing the inter center distances\n",
431 "dmat_py = np.zeros((16, 16))\n",
432 "dmat_c = np.zeros((16, 16))\n",
433 "for i in range(0, nclass):\n",
434 " for j in range(0, nclass):\n",
435 " dmat_py[i, j] = dist(centers_py[i], centers_py[j])\n",
436 " dmat_c[i, j] = dist(centers_c[i], centers_c[j])\n",
437 "\n",
438 "# vector storing comparing C and python class centers\n",
439 "diff_vec = np.zeros(nclass)\n",
440 "for i in range(0, nclass):\n",
441 " diff_vec[i] = dist(centers_c[i], centers_py[i]) "
442 ]
443 },
444 {
445 "cell_type": "code",
446 "execution_count": null,
447 "metadata": {},
448 "outputs": [],
449 "source": [
450 "plt.subplot(1,2,1)\n",
451 "plt.imshow(dmat_c+1e-30, interpolation=\"none\")\n",
452 "plt.colorbar(fraction=0.046, pad=0.04)\n",
453 "plt.title(\"Center distances (C)\")\n",
454 "plt.subplot(1,2,2)\n",
455 "plt.imshow(dmat_py, interpolation=\"none\")\n",
456 "plt.colorbar(fraction=0.046, pad=0.04)\n",
457 "plt.title(\"Center distances (PY)\")\n",
458 "plt.tight_layout()"
459 ]
460 },
461 {
462 "cell_type": "code",
463 "execution_count": null,
464 "metadata": {},
465 "outputs": [],
466 "source": [
467 "# unique center to center distances\n",
468 "plt.plot(np.unique(dmat_py))\n",
469 "plt.plot(np.unique(dmat_c), \"--\")\n",
470 "plt.legend([\"py\", \"C\"])"
471 ]
472 },
473 {
474 "cell_type": "code",
475 "execution_count": null,
476 "metadata": {},
477 "outputs": [],
478 "source": [
479 "# center distances between C and python\n",
480 "plt.plot(np.arange(1, nclass + 1), diff_vec)"
481 ]
482 },
483 {
484 "cell_type": "code",
485 "execution_count": null,
486 "metadata": {},
487 "outputs": [],
488 "source": [
489 "out_py"
490 ]
491 }
492 ],
493 "metadata": {
494 "kernelspec": {
495 "display_name": "Python 3",
496 "language": "python",
497 "name": "python3"
498 },
499 "language_info": {
500 "codemirror_mode": {
501 "name": "ipython",
502 "version": 3
503 },
504 "file_extension": ".py",
505 "mimetype": "text/x-python",
506 "name": "python",
507 "nbconvert_exporter": "python",
508 "pygments_lexer": "ipython3",
509 "version": "3.12.13"
510 }
511 },
512 "nbformat": 4,
513 "nbformat_minor": 2
514 }