pyarea 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyarea/directory.py ADDED
@@ -0,0 +1,403 @@
1
+ import ctypes as C
2
+ import logging
3
+ import os
4
+ import struct
5
+
6
+ import numpy as np
7
+
8
+ from pyarea.sensors import SENSORS, get_sensor
9
+ from pyarea.utils import yyyddd_hhmmss2datetime
10
+
11
+ _, n = os.path.split(os.path.abspath(__file__))
12
+ logger = logging.getLogger(n)
13
+
14
+ # the sensor names indexed by sensor number ("" where a number is not used)
15
+ _SENSOR_NAMES = tuple(SENSORS[n].name if n in SENSORS else "" for n in range(max(SENSORS) + 1))
16
+
17
+ # http://www.ssec.wisc.edu/mcidas/doc/prog_man/current/formats-1.html#13797
18
+ HEADER_FIELDS = (
19
+ # words 1-8
20
+ ('relative_position_within_dataset', C.c_int32),
21
+ ('image_type', C.c_int32),
22
+ ('sensor_source_number', C.c_int32),
23
+ ('yyyddd', C.c_int32),
24
+ ('hhmmss', C.c_int32),
25
+ ('line_ul', C.c_int32),
26
+ ('element_ul', C.c_int32),
27
+ ('_reserved1', C.c_int32),
28
+
29
+ # 9-16
30
+ ('lines', C.c_int32),
31
+ ('elements', C.c_int32),
32
+ ('bytes_per_element', C.c_int32),
33
+ ('line_res', C.c_int32),
34
+ ('element_res', C.c_int32),
35
+ ('spectral_band_count', C.c_int32),
36
+ ('line_prefix_length', C.c_int32),
37
+ ('project', C.c_int32),
38
+
39
+ # 17-24
40
+ ('file_yyyddd', C.c_int32),
41
+ ('file_hhmmss', C.c_int32),
42
+ ('spectral_band_map_1_32', C.c_int32),
43
+ ('spectral_band_map_33_64', C.c_int32),
44
+ ('sensor_specific', C.c_int32 * 4),
45
+
46
+ # 25-32
47
+ ('memo', C.c_char * 32),
48
+
49
+ # 33-36
50
+ ('_reserved2', C.c_int32),
51
+ ('data_block_offset', C.c_int32),
52
+ ('nav_block_offset', C.c_int32),
53
+ ('validity_code', C.c_int32),
54
+
55
+ # 37-44
56
+ ('program_data_load', C.c_int32 * 8),
57
+
58
+ # 45-48
59
+ ('band8_source_goesaa', C.c_int32),
60
+ ('image_yyyddd', C.c_int32),
61
+ ('image_hhmmss_or_ms', C.c_int32),
62
+ ('start_scan', C.c_int32),
63
+
64
+ # 49-56
65
+ ('prefix_doc_length', C.c_int32),
66
+ ('prefix_cal_length', C.c_int32),
67
+ ('prefix_band_length', C.c_int32),
68
+ ('source_type', C.c_char * 4),
69
+ ('cal_type', C.c_char * 4),
70
+ ('_reserved3', C.c_int32 * 3),
71
+
72
+ # 57-64
73
+ ('original_source_type', C.c_char*4),
74
+ ('units', C.c_int32),
75
+ ('scaling', C.c_int32),
76
+ ('aux_block_offset', C.c_int32),
77
+ ('aux_block_length', C.c_int32),
78
+ ('_reserved4', C.c_int32),
79
+ ('cal_block_offset', C.c_int32),
80
+ ('comment_count', C.c_int32)
81
+ )
82
+
83
+
84
+ class _DirectoryMixin:
85
+ """Behaviour shared by the big- and little-endian directory structures."""
86
+
87
+ sensors = _SENSOR_NAMES
88
+
89
+ def _setup(self, dir_bytes):
90
+ self.dir_bytes = dir_bytes
91
+ self.nominal_time = yyyddd_hhmmss2datetime(self.yyyddd, self.hhmmss)
92
+ self.creation_time = yyyddd_hhmmss2datetime(self.file_yyyddd, self.file_hhmmss)
93
+ # as in VisAD's AreaDirectory the actual start is used unless both of its words are zero
94
+ if self.image_yyyddd != 0 or self.image_hhmmss_or_ms != 0:
95
+ self.start_time = yyyddd_hhmmss2datetime(self.image_yyyddd, self.image_hhmmss_or_ms)
96
+ else:
97
+ self.start_time = self.nominal_time
98
+
99
+ # Word 19 maps bands 1-32 and word 20 bands 33-64 (bit 0 of word 19 is band 1). Word 20 is only
100
+ # documented as satellite specific for older sensors, so, like VisAD, stop at the declared band count:
101
+ # a map can have more bits set than bands (the AVHRR 3a/3b case).
102
+ self.bands_1_32 = [i + 1 for i in range(32) if (self.spectral_band_map_1_32 >> i) & 1]
103
+ self.bands_33_64 = [i + 33 for i in range(32) if (self.spectral_band_map_33_64 >> i) & 1]
104
+ self.bands = (self.bands_1_32 + self.bands_33_64)[:max(self.spectral_band_count, 0)]
105
+
106
+ self.comment_cards = list() if self.comment_count > 0 else None
107
+ self._card_names = set()
108
+
109
+
110
+ @property
111
+ def words(self):
112
+ """The 64 directory words as native int32 values, whatever byte order the file was written in."""
113
+ return np.frombuffer(self.dir_bytes, dtype=f'{self.byte_order}i4').astype(np.int32)
114
+
115
+ def __eq__(self, other):
116
+ """Equal when all 64 words are, like ``AreaDirectory.equals`` in VisAD (the byte order does not matter)."""
117
+ if not isinstance(other, _DirectoryMixin):
118
+ return NotImplemented
119
+ return bool(np.array_equal(self.words, other.words))
120
+
121
+ def __hash__(self):
122
+ return hash(self.words.tobytes())
123
+
124
+ @property
125
+ def buffer(self):
126
+ return C.string_at(C.byref(self), C.sizeof(self))
127
+
128
+ def __repr__(self):
129
+ return self.__str__()
130
+
131
+ @property
132
+ def source_type_name(self):
133
+ """The image source type (``VISR``, ``GVAR``...); for ``VISR`` the original source type when there is one."""
134
+ source = self.source_type.decode(errors='replace').strip('\x00 ')
135
+ original = self.original_source_type.decode(errors='replace').strip('\x00 ')
136
+ return original if source.upper() == 'VISR' and original else source
137
+
138
+ @property
139
+ def calibration_unit_name(self):
140
+ """The unit of the stored values (directory word 58, ASCII), or None where the file gives none."""
141
+ raw = self.dir_bytes[57 * 4:58 * 4]
142
+ if self.units in (0, _MCMISSING):
143
+ return None
144
+ return raw.decode('ascii', errors='replace').strip('\x00 ') or None
145
+
146
+ @property
147
+ def calibration_scale_factor(self):
148
+ """The scaling factor of the stored values (word 59); 1 where it is 0 or missing, as in VisAD."""
149
+ return 1 if self.scaling in (0, _MCMISSING) else self.scaling
150
+
151
+ def check(self, file_size=None):
152
+ """Sanity checks on the directory; returns a list of messages, empty when nothing looks wrong.
153
+
154
+ Args:
155
+ file_size: The size of the file in bytes, to check the block offsets against; skipped when omitted.
156
+ Truncated data (fewer lines than the directory claims) is reported by :class:`pyarea.file.AreaFile`,
157
+ which knows the line length.
158
+ """
159
+ problems = []
160
+ if self.sensor_info is None:
161
+ problems.append(f'Sensor source number {self.sensor_source_number} is not in the sensor table.')
162
+ if self.bytes_per_element not in (1, 2, 4):
163
+ problems.append(f'{self.bytes_per_element} bytes per element; only 1, 2 or 4 are defined.')
164
+ if self.lines <= 0 or self.elements <= 0:
165
+ problems.append(f'The image size is {self.lines} lines x {self.elements} elements.')
166
+ if self.data_block_offset <= 0:
167
+ problems.append('There is no data block offset.')
168
+ if file_size is not None:
169
+ for name in ('nav', 'cal', 'aux', 'data'):
170
+ offset = getattr(self, f'{name}_block_offset')
171
+ if offset >= file_size or offset < 0:
172
+ problems.append(f'The {name} block offset {offset} is outside the file ({file_size} bytes).')
173
+ return problems
174
+
175
+ def __str__(self):
176
+
177
+ r = f'\n{"-"*35} \n' \
178
+ f'{self.sensor} {self.cal_type.decode().strip()} {self.source_type_name} '\
179
+ f'image scanned at {self.start_time}\n' \
180
+ f'{"-"*35}\n' \
181
+ f'Nominal time: {self.nominal_time}\n'\
182
+ f'Bands: {self.bands}\n'\
183
+ f'Y resolution: {self.line_res}\n'\
184
+ f'X resolution: {self.element_res}\n'\
185
+ f'Size: {str(self.size)}\n' \
186
+ f'Data width: {self.bytes_per_element}\n'\
187
+ f'Bounding box: {self.imgbox}\n'\
188
+ f'Sensor source number: {self.sensor_source_number}\n'\
189
+ f'Byte order: {"big" if self.byte_order == ">" else "little"}-endian\n'\
190
+ f'Line prefix length: {self.line_prefix_length}\n'\
191
+ f'Block offsets: nav {self.nav_block_offset}, cal {self.cal_block_offset}, '\
192
+ f'aux {self.aux_block_offset}, data {self.data_block_offset}\n'
193
+
194
+ if self.comment_cards:
195
+ r+= 'Comment cards:\n'
196
+ for cc in self.comment_cards:
197
+ r+= f'\t{cc}\n'
198
+ return r
199
+
200
+ def add_comments(self, comment_bytes=None):
201
+ card_start = 0
202
+ for ci in range(self.comment_count):
203
+ card_end = card_start+80
204
+ card_bytes = comment_bytes[card_start:card_end]
205
+ card_txt = struct.unpack(f'{self.byte_order}80s', card_bytes)[0].decode('utf-8')
206
+ #card_txt = card_bytes.decode('utf-8', 'ignore')
207
+
208
+ try:
209
+ try:
210
+ card_name, sval = card_txt.split('=')
211
+ except Exception:
212
+ self.comment_cards.append(str(card_txt))
213
+ continue
214
+
215
+ card_name = card_name.strip()
216
+ try: # float
217
+ val = float(sval)
218
+ except ValueError:
219
+ try: # int
220
+ val = int(sval)
221
+ except ValueError:
222
+ val = sval.strip()
223
+
224
+ # clean special chars except ""
225
+ card_name = card_name.replace(' ', '_')
226
+ card_name = card_name.replace('(', '')
227
+ card_name = card_name.replace(')', '')
228
+ card_name = card_name.replace('[', '')
229
+ card_name = card_name.replace(']', '')
230
+ card_name = card_name.replace('{', '')
231
+ card_name = card_name.replace('}', '')
232
+ card_name = card_name.lower()
233
+ # print(f'{card_name} = {val}')
234
+ self.comment_cards.append(f'{card_name} = {val}')
235
+ if card_name not in self._card_names:
236
+ if not hasattr(self, card_name): # never replace a directory field or method
237
+ setattr(self, card_name, val)
238
+ self._card_names.add(card_name)
239
+ else: # a card that comes more than once becomes a list of its values
240
+ old_val = getattr(self, card_name)
241
+ if isinstance(old_val, list):
242
+ old_val.append(val)
243
+ else:
244
+ setattr(self, card_name, [old_val, val])
245
+ except Exception as e:
246
+ logger.error(f'Failed to parse card number {ci} on {self.id_text}. Error is {str(e)}')
247
+
248
+ card_start = card_end
249
+
250
+ @property
251
+ def id_text(self):
252
+ return (f'{self.sensor} {self.cal_type.decode()} {self.source_type_name} '
253
+ f'image scanned at {self.start_time}\n')
254
+
255
+ @property
256
+ def size(self):
257
+ return self.lines, self.elements
258
+
259
+ @property
260
+ def imgbox(self):
261
+ """
262
+ Property
263
+ Computes are returns the bounding box as a tuple (stline, endline, stelem, endelem)
264
+ """
265
+ start_line = self.line_ul
266
+ end_line = self.line_ul + self.lines
267
+ start_elem = self.element_ul
268
+ end_elem = self.element_ul + self.elements
269
+ return start_line, end_line, start_elem, end_elem
270
+
271
+
272
+ @property
273
+ def vis_imgbox(self):
274
+ """
275
+ Property
276
+ Computes are returns the bounding box as a tuple (stline, endline, stelem, endelem)
277
+ """
278
+ start_line = self.line_ul
279
+ end_line = self.line_ul + self.lines*self.line_res
280
+ start_elem = self.element_ul
281
+ end_elem = self.element_ul + self.elements*self.element_res
282
+ return start_line, end_line, start_elem, end_elem
283
+
284
+ @property
285
+ def sensor_name(self):
286
+ """The full name for the sensor/source number, e.g. ``GOES-3 infrared`` (empty if unknown)."""
287
+ number = self.sensor_source_number
288
+ return self.sensors[number] if 0 <= number < len(self.sensors) else ""
289
+
290
+ @property
291
+ def sensor_info(self):
292
+ """The :class:`pyarea.sensors.Sensor` for this file's sensor number, or None if it is not in the table."""
293
+ return get_sensor(self.sensor_source_number)
294
+
295
+ @property
296
+ def sensor(self):
297
+ """Short platform name, e.g. ``GOES-3`` or ``GOES8`` (None if there isn't one)."""
298
+ if 16 <= self.sensor_source_number <= 33: # SMS-1 to GOES-7
299
+ return self.satellite
300
+ text = self.sensor_name
301
+ if ' ' in text:
302
+ stext = text.split(' ')
303
+ if 'GOES' in stext:
304
+ return ''.join(stext[:2])
305
+ return self.satellite or text # e.g. "GMS infrared" -> GMS
306
+ else:
307
+ return text
308
+
309
+ @property
310
+ def satellite(self):
311
+ """The platform name from the sensor table (``SMS-1``, ``GOES-3``, ``NOAA-15``...), or None."""
312
+ info = self.sensor_info
313
+ return None if info is None else info.platform
314
+
315
+ @property
316
+ def band(self):
317
+ """``VIS`` or ``IR`` for visible and infrared sensors in the sensor table, otherwise None."""
318
+ info = self.sensor_info
319
+ return None if info is None else info.band
320
+
321
+ @property
322
+ def ssp(self):
323
+ try:
324
+ return self.center_latitude, self.center_longitude
325
+ except Exception:
326
+ return None, None
327
+
328
+
329
+ def get_units(self):
330
+ unit_options = list()
331
+ if self.comment_count:
332
+ for card in self.comment_cards:
333
+ if 'unit' in card:
334
+ n, v = card.split('=')
335
+ uname, ucomment = v.strip().split(' "')
336
+ unit_options.append(uname)
337
+
338
+ if unit_options:
339
+ return unit_options[self.units]
340
+
341
+
342
+ class _AreaDirectoryBE(_DirectoryMixin, C.BigEndianStructure):
343
+ _pack_ = 1
344
+ _layout_ = "ms" # what Python used implicitly; spelled out since 3.14 deprecates the default
345
+ _fields_ = HEADER_FIELDS
346
+
347
+
348
+ class _AreaDirectoryLE(_DirectoryMixin, C.LittleEndianStructure):
349
+ _pack_ = 1
350
+ _layout_ = "ms" # what Python used implicitly; spelled out since 3.14 deprecates the default
351
+ _fields_ = HEADER_FIELDS
352
+
353
+
354
+ _MCMISSING = -2139062144 # 0x80808080, the McIDAS "missing" value
355
+ _DIRECTORY_CLASSES = {'>': _AreaDirectoryBE, '<': _AreaDirectoryLE}
356
+ DIRECTORY_BYTES = 256
357
+
358
+
359
+ def _directory_plausibility(words):
360
+ """Score how plausible a directory is when its 64 words are read in one byte order."""
361
+ names = _DirectoryMixin.sensors
362
+ sensor, lines, elements = int(words[2]), int(words[8]), int(words[9])
363
+ score = 10 if 0 <= sensor < len(names) and names[sensor] else 0
364
+ score += 5 * (int(words[1]) == 4) # the AREA version number
365
+ return score + int(0 < lines < 200000) + int(0 < elements < 200000)
366
+
367
+
368
+ def detect_byte_order(dir_bytes):
369
+ """Return ``'>'`` or ``'<'``, whichever reads the directory as the more plausible one.
370
+
371
+ The AREA spec says files are big-endian, but plenty of real ones were
372
+ written little-endian, so both are tried and scored on the sensor number,
373
+ the version word and the image size. Ties go to big-endian.
374
+ """
375
+ scores = {order: _directory_plausibility(np.frombuffer(dir_bytes[:DIRECTORY_BYTES], dtype=f'{order}i4'))
376
+ for order in ('>', '<')}
377
+ best = max(scores, key=lambda order: (scores[order], order == '>'))
378
+ if scores[best] < 10:
379
+ logger.warning('Could not confidently detect the AREA byte order (scores %s); assuming big-endian.', scores)
380
+ return '>'
381
+ return best
382
+
383
+
384
+ def area_directory(dir_bytes, byte_order=None):
385
+ """Parse the 256-byte AREA directory.
386
+
387
+ Args:
388
+ dir_bytes: The first 256 bytes of the file.
389
+ byte_order: ``'>'`` or ``'<'``; detected from the content when omitted.
390
+
391
+ Returns:
392
+ A ctypes structure with the directory words as attributes and the
393
+ byte order it was read with in ``.byte_order``.
394
+ """
395
+ if len(dir_bytes) < DIRECTORY_BYTES:
396
+ raise ValueError(f'Truncated AREA directory: {len(dir_bytes)} bytes, expected {DIRECTORY_BYTES}')
397
+ dir_bytes = bytes(dir_bytes[:DIRECTORY_BYTES])
398
+ if byte_order is None:
399
+ byte_order = detect_byte_order(dir_bytes)
400
+ directory = _DIRECTORY_CLASSES[byte_order].from_buffer_copy(dir_bytes)
401
+ directory.byte_order = byte_order
402
+ directory._setup(dir_bytes)
403
+ return directory