Debian Codegraph @

polsarpro/dev/io.py

raw
1 import logging
2 from pathlib import Path
3
4 import numpy as np
5 import xarray as xr
6
7 log = logging.getLogger(__name__)
8
9
10 def read_T3_psp(input_dir: str):
11 """Reads a T3 matrix in the PolSARPro format.
12
13 Args:
14 input_dir (str): Input directory containing the elements of the T3 matrix and the configuration file config.txt.
15 """
16
17 input_path = Path(input_dir)
18
19 if not input_path.is_dir():
20 raise FileNotFoundError(f"Directory {input_dir} not found.")
21
22 pth_cfg = input_path / "config.txt"
23 if pth_cfg.is_file():
24 # read config and store in a dict
25 dict_cfg = {}
26 with open(pth_cfg, "r") as f:
27 lines = f.readlines()
28 lines = [line.replace("\n", "") for line in lines if "---" not in line]
29 for i in range(0, len(lines), 2):
30 dict_cfg[lines[i]] = lines[i + 1]
31 else:
32 raise FileNotFoundError("Configuration file config.txt does not exist.")
33
34 valid_mask_path = input_path / "mask_valid_pixels.bin"
35 is_valid_mask = True
36 if valid_mask_path.is_file():
37 valid_mask = read_psp_bin(valid_mask_path).astype(bool)
38 else:
39 is_valid_mask = False
40 log.info("Valid pixel mask not found, skipping.")
41
42 # image dimensions (azimuth, range)
43 naz = int(dict_cfg["Nrow"])
44 nrg = int(dict_cfg["Ncol"])
45
46 T3 = {}
47
48 for c in range(3):
49 for r in range(c + 1):
50 elt = f"T{r+1}{c+1}"
51 if r == c:
52 data = read_psp_bin(input_path / f"{elt}.bin", dtype="float32")
53
54 if is_valid_mask:
55 data = np.where(valid_mask, data, np.nan)
56 T3[f"m{r+1}{c+1}"] = (("y", "x"), data)
57 else:
58 data_real = read_psp_bin(
59 input_path / f"{elt}_real.bin", dtype="float32"
60 )
61 data_imag = read_psp_bin(
62 input_path / f"{elt}_imag.bin", dtype="float32"
63 )
64 if is_valid_mask:
65 data = np.where(valid_mask, data, np.nan + 1j * np.nan)
66 T3[f"m{r+1}{c+1}"] = (("y", "x"), data_real + 1j * data_imag)
67
68 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
69 return xr.Dataset(T3, attrs=attrs).chunk({"x": 512, "y": 512})
70
71
72 def read_C3_psp(input_dir: str):
73 """Reads a C3 matrix in the PolSARpro format.
74
75 Args:
76 input_dir (str): Input directory containing the elements of the C3 matrix and the configuration file config.txt.
77 """
78
79 input_path = Path(input_dir)
80
81 if not input_path.is_dir():
82 raise FileNotFoundError(f"Directory {input_dir} not found.")
83
84 pth_cfg = input_path / "config.txt"
85 if pth_cfg.is_file():
86 # read config and store in a dict
87 dict_cfg = {}
88 with open(pth_cfg, "r") as f:
89 lines = f.readlines()
90 lines = [line.replace("\n", "") for line in lines if "---" not in line]
91 for i in range(0, len(lines), 2):
92 dict_cfg[lines[i]] = lines[i + 1]
93 else:
94 raise FileNotFoundError("Configuration file config.txt does not exist.")
95
96 valid_mask_path = input_path / "mask_valid_pixels.bin"
97 is_valid_mask = True
98 if valid_mask_path.is_file():
99 valid_mask = read_psp_bin(valid_mask_path).astype(bool)
100 else:
101 is_valid_mask = False
102 log.info("Valid pixel mask not found, skipping.")
103
104 # image dimensions (azimuth, range)
105 naz = int(dict_cfg["Nrow"])
106 nrg = int(dict_cfg["Ncol"])
107
108 C3 = {}
109
110 for c in range(3):
111 for r in range(c + 1):
112 elt = f"C{r+1}{c+1}"
113 if r == c:
114 data = read_psp_bin(input_path / f"{elt}.bin", dtype="float32")
115
116 if is_valid_mask:
117 data = np.where(valid_mask, data, np.nan)
118 C3[f"m{r+1}{c+1}"] = (("y", "x"), data)
119 else:
120 data_real = read_psp_bin(
121 input_path / f"{elt}_real.bin", dtype="float32"
122 )
123 data_imag = read_psp_bin(
124 input_path / f"{elt}_imag.bin", dtype="float32"
125 )
126 if is_valid_mask:
127 data = np.where(valid_mask, data, np.nan + 1j * np.nan)
128 C3[f"m{r+1}{c+1}"] = (("y", "x"), data_real + 1j * data_imag)
129
130 attrs = {"poltype": "C3", "description": "Covariance matrix (3x3)"}
131 return xr.Dataset(C3, attrs=attrs).chunk("auto").chunk({"x": 512, "y": 512})
132
133
134 def read_psp_bin(file_name: str, dtype: str = "float32"):
135 """Reads a raster bin file in the PolSARPro format.
136
137 Args:
138 file_name (str): Input file.
139 Note:
140 The parent directory must contain a config.txt file.
141 """
142 file_path = Path(file_name)
143 input_dir = file_path.parent
144
145 pth_cfg = input_dir / "config.txt"
146 if pth_cfg.exists():
147 # read config and store in a dict
148 cfg = {}
149 with open(pth_cfg, "r") as f:
150 lines = f.readlines()
151 lines = [line.replace("\n", "") for line in lines if "---" not in line]
152 for i in range(0, len(lines), 2):
153 cfg[lines[i]] = lines[i + 1]
154 else:
155 raise FileNotFoundError("Configuration file config.txt does not exist.")
156
157 # image dimensions (azimuth, range)
158 naz = int(cfg["Nrow"])
159 nrg = int(cfg["Ncol"])
160
161 return np.fromfile(file_path, dtype=dtype, count=naz * nrg).reshape((naz, nrg))