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/__init__.py +4 -0
- pyarea/calibration.py +644 -0
- pyarea/directory.py +403 -0
- pyarea/file.py +752 -0
- pyarea/nav.py +2837 -0
- pyarea/navigation/__init__.py +3 -0
- pyarea/navigation/area_navigation.py +183 -0
- pyarea/navigation/hrit_navigation.py +475 -0
- pyarea/navigation/proj4_navigation.py +107 -0
- pyarea/sensors.py +249 -0
- pyarea/utils.py +316 -0
- pyarea-0.2.0.dist-info/METADATA +156 -0
- pyarea-0.2.0.dist-info/RECORD +16 -0
- pyarea-0.2.0.dist-info/WHEEL +5 -0
- pyarea-0.2.0.dist-info/licenses/LICENSE +165 -0
- pyarea-0.2.0.dist-info/top_level.txt +1 -0
pyarea/file.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import struct
|
|
4
|
+
from functools import cached_property
|
|
5
|
+
from io import BytesIO
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from pyarea.calibration import (
|
|
10
|
+
Calibrator,
|
|
11
|
+
DefaultCalibrator,
|
|
12
|
+
GOESCalibrator,
|
|
13
|
+
GVARCalibrator,
|
|
14
|
+
cal_type_from_name,
|
|
15
|
+
)
|
|
16
|
+
from pyarea.directory import DIRECTORY_BYTES, area_directory
|
|
17
|
+
from pyarea.nav import AreaNav
|
|
18
|
+
from pyarea.utils import INT32SIZE
|
|
19
|
+
|
|
20
|
+
_, name = os.path.split(__file__)
|
|
21
|
+
logger = logging.getLogger(name)
|
|
22
|
+
|
|
23
|
+
_AAA_PRE_BANDLIST_LEN = 4 + 512 + 116 # validity code, common documentation, VAS calibration info
|
|
24
|
+
_AAA_CAL_MIN_WORDS = 117
|
|
25
|
+
|
|
26
|
+
class AreaFile(BytesIO):
|
|
27
|
+
"""A McIDAS AREA file: directory, navigation, calibration and image data.
|
|
28
|
+
|
|
29
|
+
Besides the generic AREA parts this reads the pre-GVAR SMS/GOES-1..7
|
|
30
|
+
VISSR/VAS products (Mode A, AA and AAA), including their per-line band
|
|
31
|
+
lists and calibration; see the ``read_*`` methods.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
INTEGER_FORMAT = 'i'
|
|
35
|
+
|
|
36
|
+
def __init__(self, source=None, lazy=True):
|
|
37
|
+
|
|
38
|
+
if not isinstance(source, bytes):
|
|
39
|
+
self.is_remote = False
|
|
40
|
+
self.source = source
|
|
41
|
+
with open(source, 'rb') as src:
|
|
42
|
+
d = src.read()
|
|
43
|
+
super().__init__(d)
|
|
44
|
+
|
|
45
|
+
else:
|
|
46
|
+
self.is_remote = True
|
|
47
|
+
self.source = None
|
|
48
|
+
super().__init__(source)
|
|
49
|
+
|
|
50
|
+
self.sz = len(self.getbuffer())
|
|
51
|
+
|
|
52
|
+
self.directory = area_directory(self.getbuffer()[:DIRECTORY_BYTES])
|
|
53
|
+
self.adir_bytes = self.directory.dir_bytes
|
|
54
|
+
for problem in self.directory.check(self.sz):
|
|
55
|
+
logger.warning('%s: %s', self.source, problem)
|
|
56
|
+
|
|
57
|
+
# as per http://www.ssec.wisc.edu/mcidas/doc/prog_man/current/formats-1.html#34971
|
|
58
|
+
# after the directory bytes the blocks are, in order: nav, cal, aux, data, comments
|
|
59
|
+
self.navigation_offset = self.directory.nav_block_offset
|
|
60
|
+
self.calibration_offset = self.directory.cal_block_offset
|
|
61
|
+
self.aux_offset = self.directory.aux_block_offset
|
|
62
|
+
self.data_offset = self.directory.data_block_offset
|
|
63
|
+
|
|
64
|
+
# the directory's own prefix length is what the data is laid out with; the documented parts
|
|
65
|
+
# (validity code, documentation, calibration, band list) do not always add up to it in real files
|
|
66
|
+
self.line_prefix_len = self.directory.line_prefix_length
|
|
67
|
+
parts = (self.directory.prefix_doc_length + self.directory.prefix_cal_length
|
|
68
|
+
+ self.directory.prefix_band_length + (4 if self.directory.validity_code != 0 else 0))
|
|
69
|
+
if parts != self.line_prefix_len:
|
|
70
|
+
logger.debug('Line prefix length %d does not match its parts (%d) in %s.',
|
|
71
|
+
self.line_prefix_len, parts, self.source)
|
|
72
|
+
|
|
73
|
+
self.nav_bytes = self.cal_bytes = self.aux_bytes = None
|
|
74
|
+
self.nav = self.cal = self.aux = None
|
|
75
|
+
self.has_navigation = self.has_calibration = self.has_auxiliary = False
|
|
76
|
+
self.nav_size = self.cal_size = self.aux_size = 0
|
|
77
|
+
self._read_blocks()
|
|
78
|
+
|
|
79
|
+
logger.debug(f'Has navigation: {self.has_navigation}, has calibration: {self.has_calibration}, '
|
|
80
|
+
f'Has auxiliary: {self.has_auxiliary}')
|
|
81
|
+
self.areaNav = None
|
|
82
|
+
|
|
83
|
+
# setup some info that will be accessed while reading data etc
|
|
84
|
+
self.datawidth = self.directory.bytes_per_element
|
|
85
|
+
self.num_bands = self.directory.spectral_band_count
|
|
86
|
+
self.elements = self.directory.elements
|
|
87
|
+
self.claimed_lines = self.directory.lines
|
|
88
|
+
|
|
89
|
+
self.line_data_len = self.num_bands * self.elements * self.datawidth
|
|
90
|
+
self.line_len = self.line_prefix_len + self.line_data_len
|
|
91
|
+
self.lines = self._actual_lines()
|
|
92
|
+
self.data_block_len = self.lines * self.line_len
|
|
93
|
+
|
|
94
|
+
self.prefix_len = self.line_prefix_len // self.datawidth
|
|
95
|
+
self.data_len = self.data_block_len // self.datawidth
|
|
96
|
+
|
|
97
|
+
if lazy:
|
|
98
|
+
self.data = None
|
|
99
|
+
else:
|
|
100
|
+
self.data = self.__readdata__()
|
|
101
|
+
|
|
102
|
+
def _block_end(self, offset):
|
|
103
|
+
"""End of the block starting at ``offset``: the next block's start, or the end of the file."""
|
|
104
|
+
starts = [o for o in (self.navigation_offset, self.calibration_offset, self.aux_offset, self.data_offset)
|
|
105
|
+
if o > offset]
|
|
106
|
+
return min(starts) if starts else self.sz
|
|
107
|
+
|
|
108
|
+
def _read_blocks(self):
|
|
109
|
+
"""Read the nav, cal and aux blocks as 32-bit words, each from its own offset."""
|
|
110
|
+
fmt = self.directory.byte_order
|
|
111
|
+
for name, offset in (('nav', self.navigation_offset), ('cal', self.calibration_offset),
|
|
112
|
+
('aux', self.aux_offset)):
|
|
113
|
+
if offset <= 0 or offset >= self.sz:
|
|
114
|
+
continue
|
|
115
|
+
size = self._block_end(offset) - offset
|
|
116
|
+
size -= size % INT32SIZE
|
|
117
|
+
if size <= 0:
|
|
118
|
+
continue
|
|
119
|
+
raw = bytes(self.getbuffer()[offset:offset + size])
|
|
120
|
+
words = struct.unpack(f'{fmt}{size // INT32SIZE}{self.INTEGER_FORMAT}', raw)
|
|
121
|
+
setattr(self, f'{name}_size', size)
|
|
122
|
+
setattr(self, f'{name}_bytes', raw)
|
|
123
|
+
setattr(self, name, words)
|
|
124
|
+
setattr(self, f'has_{"navigation" if name == "nav" else "calibration" if name == "cal" else "auxiliary"}',
|
|
125
|
+
True)
|
|
126
|
+
|
|
127
|
+
def _actual_lines(self):
|
|
128
|
+
"""The number of lines really present in the data block.
|
|
129
|
+
|
|
130
|
+
Truncated files are real, so this can be less than the directory's
|
|
131
|
+
line count; everything that sizes an array uses this number.
|
|
132
|
+
"""
|
|
133
|
+
if self.data_offset <= 0 or self.line_len <= 0:
|
|
134
|
+
return self.claimed_lines
|
|
135
|
+
actual = max(0, min(self.claimed_lines, (self.sz - self.data_offset) // self.line_len))
|
|
136
|
+
if actual != self.claimed_lines:
|
|
137
|
+
logger.warning('%s: directory claims %d lines but the data block only has %d.',
|
|
138
|
+
self.source, self.claimed_lines, actual)
|
|
139
|
+
return actual
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def actual_lines(self):
|
|
143
|
+
"""Alias of :attr:`lines`: the number of lines present in the file."""
|
|
144
|
+
return self.lines
|
|
145
|
+
|
|
146
|
+
def _line_array(self):
|
|
147
|
+
"""The data block as a ``(lines, bytes per line)`` uint8 array, line prefixes included."""
|
|
148
|
+
raw = self.getbuffer()[self.data_offset:self.data_offset + self.lines * self.line_len]
|
|
149
|
+
return np.frombuffer(raw, dtype=np.uint8).reshape(self.lines, self.line_len)
|
|
150
|
+
|
|
151
|
+
def _pixel_array(self):
|
|
152
|
+
"""The pixels as a native-endian ``(lines, elements, bands)`` array (BIP, as in the file).
|
|
153
|
+
|
|
154
|
+
As in VisAD, 1- and 2-byte values are unsigned and 4-byte values (RAD from an ADDE server, times the
|
|
155
|
+
directory's scaling) are signed.
|
|
156
|
+
"""
|
|
157
|
+
if self.datawidth not in (1, 2, 4):
|
|
158
|
+
raise NotImplementedError(f'{self.source}: {self.datawidth} bytes per element is not supported.')
|
|
159
|
+
pixel_bytes = self._line_array()[:, self.line_prefix_len:self.line_prefix_len + self.line_data_len]
|
|
160
|
+
if self.datawidth == 1:
|
|
161
|
+
return pixel_bytes.reshape(self.lines, self.elements, self.num_bands)
|
|
162
|
+
kind = 'i' if self.datawidth == 4 else 'u'
|
|
163
|
+
file_dtype = np.dtype(f'{self.directory.byte_order}{kind}{self.datawidth}')
|
|
164
|
+
pixels = pixel_bytes.copy().view(file_dtype).reshape(self.lines, self.elements, self.num_bands)
|
|
165
|
+
return pixels.astype(file_dtype.newbyteorder('='), copy=False)
|
|
166
|
+
|
|
167
|
+
def __readdata__(self):
|
|
168
|
+
"""Read the image as a ``(bands, lines, elements)`` array."""
|
|
169
|
+
return np.ascontiguousarray(self._pixel_array().transpose(2, 0, 1))
|
|
170
|
+
|
|
171
|
+
def __getattribute__(self, name):
|
|
172
|
+
if name == 'data':
|
|
173
|
+
value = object.__getattribute__(self, name)
|
|
174
|
+
if value is None:
|
|
175
|
+
self.data = self.__readdata__()
|
|
176
|
+
return self.data
|
|
177
|
+
else:
|
|
178
|
+
return object.__getattribute__(self, name)
|
|
179
|
+
else:
|
|
180
|
+
return object.__getattribute__(self, name)
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def istim(self):
|
|
184
|
+
"""
|
|
185
|
+
Computes an approximation of scan time in miliseconds of a swath if the image was produced by
|
|
186
|
+
GOES 8-15 instruments
|
|
187
|
+
:return:
|
|
188
|
+
"""
|
|
189
|
+
sens = self.areaDirectory.sensor
|
|
190
|
+
if sens.startswith('GOES'):
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
instr = sens[-2:]
|
|
194
|
+
iinstr = int(instr)
|
|
195
|
+
if iinstr >= 8:
|
|
196
|
+
return int(round((self.origNumElements * self.resolution[1]) * 954) / 20834.)
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def imgbox(self):
|
|
202
|
+
"""
|
|
203
|
+
Property
|
|
204
|
+
Computes and returns the bounding box as a tuple (stline, endline, stelem, endelem)
|
|
205
|
+
"""
|
|
206
|
+
start_line = self.directory.line_ul
|
|
207
|
+
end_line = start_line + self.lines
|
|
208
|
+
start_elem = self.directory.element_ul
|
|
209
|
+
end_elem = start_elem + self.elements
|
|
210
|
+
return start_line, end_line, start_elem, end_elem
|
|
211
|
+
|
|
212
|
+
@property
|
|
213
|
+
def resolution(self):
|
|
214
|
+
return self.directory.line_res, self.directory.element_res
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def size(self):
|
|
218
|
+
return self.lines, self.elements
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def npdtype(self):
|
|
222
|
+
return f'{self.directory.byte_order}{"i" if self.datawidth == 4 else "u"}{self.datawidth}'
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def file_name(self):
|
|
227
|
+
"""
|
|
228
|
+
Property
|
|
229
|
+
returns the file name of the AREA file
|
|
230
|
+
"""
|
|
231
|
+
if self.source:
|
|
232
|
+
_, name = os.path.split(self.source)
|
|
233
|
+
return name
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def navigation(self):
|
|
238
|
+
"""The navigation object for this file's nav block, or None if the file has no nav block.
|
|
239
|
+
|
|
240
|
+
Raises ``NotImplementedError`` for a nav block of a type pyarea has no navigation for.
|
|
241
|
+
"""
|
|
242
|
+
if self.areaNav is None and self.nav is not None:
|
|
243
|
+
nav = AreaNav(navblock=self.nav, auxblock=self.aux, byte_order=self.directory.byte_order,
|
|
244
|
+
int_format=self.INTEGER_FORMAT)
|
|
245
|
+
nav.setImageStart(self.directory.line_ul, self.directory.element_ul)
|
|
246
|
+
nav.setRes(*self.resolution)
|
|
247
|
+
nav.setMag(1, 1)
|
|
248
|
+
# AREA lines and elements are counted from 0 here, for every navigation (GMS-5 included, as in the Satpy
|
|
249
|
+
# reader). VisAD's GMSXnav test counts from 1 and flips the lines, but the lines of real GMS-5 AREA files
|
|
250
|
+
# already run north to south, so there is no flip (checked by overlaying coastlines on a GMS-5 image).
|
|
251
|
+
nav.setStart(0, 0)
|
|
252
|
+
self.areaNav = nav
|
|
253
|
+
return self.areaNav
|
|
254
|
+
|
|
255
|
+
# ------------------------------------------------------------------
|
|
256
|
+
# Pre-GVAR (SMS/GOES-1..7 VISSR/VAS) products
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def source_type(self):
|
|
260
|
+
"""The 4-character source type from the directory (``VISR``, ``VAS``, ``AAA``, ``GVAR``...)."""
|
|
261
|
+
return self.directory.source_type.decode('ascii', errors='replace').strip('\x00').strip()
|
|
262
|
+
|
|
263
|
+
@property
|
|
264
|
+
def cal_type(self):
|
|
265
|
+
"""The 4-character calibration type from the directory (``RAW``, ``BRIT``...)."""
|
|
266
|
+
return self.directory.cal_type.decode('ascii', errors='replace').strip('\x00').strip()
|
|
267
|
+
|
|
268
|
+
@cached_property
|
|
269
|
+
def aaa_cal(self):
|
|
270
|
+
"""The Mode AAA calibration block as
|
|
271
|
+
``{"sensor_source", "iab": {channel: (AB1, AB2)}, "ifab": {channel: IFAB}}``.
|
|
272
|
+
|
|
273
|
+
None for any other kind of file, or if the block is too short to be one.
|
|
274
|
+
"""
|
|
275
|
+
if self.source_type not in ('AAA', 'VAS') or self.cal is None or len(self.cal) < _AAA_CAL_MIN_WORDS:
|
|
276
|
+
return None
|
|
277
|
+
words = self.cal
|
|
278
|
+
return {
|
|
279
|
+
'sensor_source': int(words[0]),
|
|
280
|
+
'iab': {chan: (int(words[3 + (chan - 1) * 2]), int(words[4 + (chan - 1) * 2])) for chan in range(1, 39)},
|
|
281
|
+
'ifab': {chan: int(words[79 + (chan - 1)]) for chan in range(1, 39)},
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
@cached_property
|
|
285
|
+
def band_list(self):
|
|
286
|
+
"""The channel (1-38) in each band slot of each line, shape ``(lines, bands)``; 0 for an unused slot.
|
|
287
|
+
|
|
288
|
+
Read from the line prefix. The order and presence of channels can
|
|
289
|
+
change from line to line, so every line is resolved on its own.
|
|
290
|
+
None for files without such a prefix.
|
|
291
|
+
"""
|
|
292
|
+
if self.source_type not in ('AAA', 'VAS'):
|
|
293
|
+
return None
|
|
294
|
+
band_list_len = self.line_prefix_len - _AAA_PRE_BANDLIST_LEN
|
|
295
|
+
if band_list_len < max(self.num_bands, 1):
|
|
296
|
+
logger.warning('%s: line prefix of %d bytes is too short for a per-line band list.',
|
|
297
|
+
self.source, self.line_prefix_len)
|
|
298
|
+
return None
|
|
299
|
+
lines = self._line_array()
|
|
300
|
+
# only the first num_bands bytes are data, the rest is padding to a word
|
|
301
|
+
return lines[:, _AAA_PRE_BANDLIST_LEN:_AAA_PRE_BANDLIST_LEN + self.num_bands].copy()
|
|
302
|
+
|
|
303
|
+
@cached_property
|
|
304
|
+
def mode_aa_cal(self):
|
|
305
|
+
"""The per-line Mode AA calibration entries, or None.
|
|
306
|
+
|
|
307
|
+
A dict of ``(lines, 13)`` arrays: ``channel``, ``spin``, ``deltaf_code`` and ``ysubz``.
|
|
308
|
+
"""
|
|
309
|
+
if self.source_type != 'VAS':
|
|
310
|
+
return None
|
|
311
|
+
d = self.directory
|
|
312
|
+
n_entries, entry_bytes, header_bytes = 13, 8, 12
|
|
313
|
+
if d.prefix_cal_length < header_bytes + n_entries * entry_bytes:
|
|
314
|
+
logger.warning('%s: Mode AA calibration region is only %d bytes; calibration is unavailable.',
|
|
315
|
+
self.source, d.prefix_cal_length)
|
|
316
|
+
return None
|
|
317
|
+
start = (4 if d.validity_code != 0 else 0) + d.prefix_doc_length + header_bytes
|
|
318
|
+
raw = self._line_array()[:, start:start + n_entries * entry_bytes]
|
|
319
|
+
entries = raw.copy().view(f'{d.byte_order}i2').reshape(self.lines, n_entries, 4)
|
|
320
|
+
return {
|
|
321
|
+
'channel': entries[:, :, 0],
|
|
322
|
+
'spin': entries[:, :, 1],
|
|
323
|
+
'deltaf_code': entries[:, :, 2],
|
|
324
|
+
'ysubz': entries[:, :, 3],
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
@cached_property
|
|
328
|
+
def line_channel_spin(self):
|
|
329
|
+
"""The 13 channel/spin-count groups of each line's prefix: ``{"channel", "num_spins"}``, ``(lines, 13)``.
|
|
330
|
+
|
|
331
|
+
A second copy of the channel numbers, useful to cross-check :attr:`band_list`. None without a band list.
|
|
332
|
+
"""
|
|
333
|
+
if self.band_list is None:
|
|
334
|
+
return None
|
|
335
|
+
start = 4 + 512 + 12 # validity code, common documentation, day/time/scan header
|
|
336
|
+
raw = self._line_array()[:, start:start + 104]
|
|
337
|
+
groups = raw.copy().view(f'{self.directory.byte_order}u2').reshape(self.lines, 13, 4)
|
|
338
|
+
return {'channel': groups[:, :, 0], 'num_spins': groups[:, :, 1]}
|
|
339
|
+
|
|
340
|
+
def read_data(self):
|
|
341
|
+
"""The image of a single-band file as a ``(lines, elements)`` array."""
|
|
342
|
+
if self.num_bands != 1:
|
|
343
|
+
raise ValueError(f'{self.source}: read_data() is for single-band files, this one has {self.num_bands}; '
|
|
344
|
+
f'use read_channel() (Mode AAA) or read_ir_temperature_aa() (Mode AA).')
|
|
345
|
+
return self.data[0]
|
|
346
|
+
|
|
347
|
+
def _gather_slot(self, slots, present):
|
|
348
|
+
"""Pick one band slot per line out of the pixel array; absent lines get 0."""
|
|
349
|
+
pixels = self._pixel_array()
|
|
350
|
+
out = np.take_along_axis(pixels, np.broadcast_to(slots[:, None, None], pixels.shape[:2] + (1,)),
|
|
351
|
+
axis=2)[:, :, 0].copy()
|
|
352
|
+
out[~present] = 0
|
|
353
|
+
return out
|
|
354
|
+
|
|
355
|
+
def read_channel(self, channel):
|
|
356
|
+
"""Raw counts of one VAS channel (1-38) of a Mode AAA file.
|
|
357
|
+
|
|
358
|
+
Returns:
|
|
359
|
+
``(counts, present)``: counts of shape ``(lines, elements)``, and a boolean per line that is False where
|
|
360
|
+
the channel is not in that line's band list (its counts are 0 and must not be used).
|
|
361
|
+
"""
|
|
362
|
+
if self.band_list is None:
|
|
363
|
+
raise ValueError(f'{self.source}: there is no per-line band list.')
|
|
364
|
+
match = self.band_list == channel
|
|
365
|
+
present = match.any(axis=1)
|
|
366
|
+
return self._gather_slot(np.where(present, match.argmax(axis=1), 0), present), present
|
|
367
|
+
|
|
368
|
+
def read_ir_radiance(self, channel):
|
|
369
|
+
"""Mode AAA radiance of a VAS channel as float32, NaN on lines without the channel."""
|
|
370
|
+
if self.aaa_cal is None:
|
|
371
|
+
raise ValueError(f'{self.source}: there is no Mode AAA calibration block '
|
|
372
|
+
f'(source type {self.source_type!r}).')
|
|
373
|
+
lookup = 8 if channel == 13 else channel
|
|
374
|
+
cal = self.aaa_cal
|
|
375
|
+
if lookup not in cal['iab'] or lookup not in cal['ifab']:
|
|
376
|
+
raise ValueError(f'{self.source}: channel {lookup} is not in the calibration block.')
|
|
377
|
+
ab1, ab2 = cal['iab'][lookup]
|
|
378
|
+
counts, present = self.read_channel(channel)
|
|
379
|
+
radiance = GOESCalibrator.aaa_radiance(counts, ab1, ab2, cal['ifab'][lookup])
|
|
380
|
+
return np.where(present[:, None], radiance, np.nan).astype(np.float32)
|
|
381
|
+
|
|
382
|
+
def read_ir_temperature_aaa(self, channel):
|
|
383
|
+
"""Mode AAA brightness temperature (K) of a VAS channel as float32."""
|
|
384
|
+
coeffs = GOESCalibrator.vas_planck_coeffs(self.directory.satellite, channel)
|
|
385
|
+
return GOESCalibrator.aaa_temperature(self.read_ir_radiance(8 if channel == 13 else channel), coeffs)
|
|
386
|
+
|
|
387
|
+
def _mode_aa_line_calibration(self, band):
|
|
388
|
+
"""Per-line ``(cal_present, delta_f, ysubz)`` for an IR band of a Mode AA file."""
|
|
389
|
+
cal = self.mode_aa_cal
|
|
390
|
+
match = GOESCalibrator.mode_aa_code_to_band(cal['channel']) == band
|
|
391
|
+
cal_present = match.any(axis=1)
|
|
392
|
+
slot = np.where(cal_present, match.argmax(axis=1), 0)
|
|
393
|
+
rows = np.arange(match.shape[0])
|
|
394
|
+
deltaf_code = cal['deltaf_code'][rows, slot]
|
|
395
|
+
table = np.array(GOESCalibrator.MODE_AA_DELTA_F)
|
|
396
|
+
valid = (deltaf_code >= 0) & (deltaf_code < len(table))
|
|
397
|
+
delta_f = np.where(valid, table[np.clip(deltaf_code, 0, len(table) - 1)], 0)
|
|
398
|
+
return cal_present, delta_f, cal['ysubz'][rows, slot].astype(np.float64)
|
|
399
|
+
|
|
400
|
+
def _mode_aa_raw_counts(self, band):
|
|
401
|
+
"""``(raw, present)``: the raw counts of an IR band of a Mode AA file and the lines that carry it."""
|
|
402
|
+
if self.band_list is None:
|
|
403
|
+
raw = self.read_data().astype(np.float64)
|
|
404
|
+
return raw, np.ones(raw.shape[0], dtype=bool)
|
|
405
|
+
match = GOESCalibrator.mode_aa_code_to_band(self.band_list) == band
|
|
406
|
+
present = match.any(axis=1)
|
|
407
|
+
return self._gather_slot(np.where(present, match.argmax(axis=1), 0), present).astype(np.float64), present
|
|
408
|
+
|
|
409
|
+
def read_ir_temperature_aa(self, band):
|
|
410
|
+
"""Mode AA brightness temperature (K) of IR band 1-12 as float32, NaN where it is missing."""
|
|
411
|
+
if self.source_type != 'VAS':
|
|
412
|
+
raise ValueError(f"{self.source}: not a Mode AA ('VAS') file.")
|
|
413
|
+
if not 1 <= band <= 12:
|
|
414
|
+
raise ValueError(f'Mode AA IR band must be 1-12 (got {band}); band 13 is visible.')
|
|
415
|
+
if self.mode_aa_cal is None:
|
|
416
|
+
raise ValueError(f'{self.source}: there is no Mode AA calibration data.')
|
|
417
|
+
cal_present, delta_f, ysubz = self._mode_aa_line_calibration(band)
|
|
418
|
+
raw, raw_present = self._mode_aa_raw_counts(band)
|
|
419
|
+
valid_line = cal_present & raw_present
|
|
420
|
+
t = GOESCalibrator.mode_aa_temperature(raw, delta_f, ysubz, band)
|
|
421
|
+
return np.where(valid_line[:, None], t, np.nan).astype(np.float32)
|
|
422
|
+
|
|
423
|
+
def read_ir_temperature_a(self):
|
|
424
|
+
"""Mode A (single band) IR brightness temperature (K) as float32."""
|
|
425
|
+
if self.directory.band != 'IR':
|
|
426
|
+
raise ValueError(f'{self.source}: band is {self.directory.band!r}, not IR.')
|
|
427
|
+
if self.source_type in ('AAA', 'VAS'):
|
|
428
|
+
raise NotImplementedError(f'{self.source}: this is a multiband {self.source_type!r} file; use '
|
|
429
|
+
f'read_ir_temperature_aaa() or read_ir_temperature_aa().')
|
|
430
|
+
if self.cal_type.upper() == 'TEMP': # McFETCH already calibrated it
|
|
431
|
+
return self.read_calibrated('TEMP')
|
|
432
|
+
counts = self.read_data()
|
|
433
|
+
if counts.max() > 255:
|
|
434
|
+
raise ValueError(f'{self.source}: raw values exceed 8 bits (max {counts.max()}).')
|
|
435
|
+
return GOESCalibrator.mode_a_ir_temperature(counts)
|
|
436
|
+
|
|
437
|
+
@property
|
|
438
|
+
def gvar_calibrator(self):
|
|
439
|
+
"""A :class:`GVARCalibrator` built from this file's calibration block (GVAR, GOES-8 onward)."""
|
|
440
|
+
if self.source_type != 'GVAR':
|
|
441
|
+
raise ValueError(f'{self.source}: source type is {self.source_type!r}, not GVAR.')
|
|
442
|
+
cal = getattr(self, 'cal', None)
|
|
443
|
+
return GVARCalibrator(self.directory.sensor_source_number, cal if self.has_calibration else None)
|
|
444
|
+
|
|
445
|
+
def read_calibrated(self, units='TEMP', band=None):
|
|
446
|
+
"""Calibrate a single-band GVAR image.
|
|
447
|
+
|
|
448
|
+
Args:
|
|
449
|
+
units: ``'RAW'``, ``'RAD'``, ``'ALB'`` (percent, visible), ``'TEMP'`` (K, IR) or ``'BRIT'``.
|
|
450
|
+
band: The band number; by default the file's only band.
|
|
451
|
+
|
|
452
|
+
Returns:
|
|
453
|
+
float32 array of shape ``(lines, elements)``; use ``calibrated_unit`` for its unit.
|
|
454
|
+
"""
|
|
455
|
+
out = cal_type_from_name(units)
|
|
456
|
+
held = self.cal_type.upper()
|
|
457
|
+
if self.source_type != 'GVAR' or held in ('TEMP', 'RAD', 'ALB'):
|
|
458
|
+
# a file that already holds what is asked for (a McFETCH file in TEMP, GVAR or not) gives its own
|
|
459
|
+
# pixels; only raw GVAR files are calibrated here. ADDE stores TEMP, RAD and ALB as integers times
|
|
460
|
+
# the directory's scaling (word 59: a GOES-16 TEMP file has 19241 for 192.41 K and a
|
|
461
|
+
# scaling of 100), so those are divided by it.
|
|
462
|
+
if held != units.strip().upper():
|
|
463
|
+
raise ValueError(f'{self.source}: the file holds {held or "unknown"} data and '
|
|
464
|
+
f'only raw GVAR files can be calibrated to {units.strip().upper()}.')
|
|
465
|
+
data = self.read_data()
|
|
466
|
+
scale = self.directory.calibration_scale_factor
|
|
467
|
+
if out in (Calibrator.CAL_TEMP, Calibrator.CAL_RAD, Calibrator.CAL_ALB) and scale != 1:
|
|
468
|
+
# divide the integers, not their float32 copy: 4-byte values can have more than 24 bits
|
|
469
|
+
return (data.astype(np.float64) / scale).astype(np.float32)
|
|
470
|
+
return DefaultCalibrator().calibrate_array(data, band, out)
|
|
471
|
+
if band is None:
|
|
472
|
+
if self.num_bands != 1:
|
|
473
|
+
raise ValueError(f'{self.source}: this file has {self.num_bands} bands; pass band=.')
|
|
474
|
+
band = self.directory.bands[0]
|
|
475
|
+
return self.gvar_calibrator.calibrate_array(self.read_data(), band, out)
|
|
476
|
+
|
|
477
|
+
def read_vis(self, calibration='counts'):
|
|
478
|
+
"""VIS counts, or ``calibration='unnormalized_reflectance'`` for a relative reflectance in percent (0-100).
|
|
479
|
+
|
|
480
|
+
The counts are squared, see ``GOESCalibrator.vis_unnormalized_reflectance``.
|
|
481
|
+
"""
|
|
482
|
+
if self.directory.band != 'VIS':
|
|
483
|
+
raise ValueError(f'{self.source}: band is {self.directory.band!r}, not VIS.')
|
|
484
|
+
counts = self.read_data().astype(np.float32)
|
|
485
|
+
if calibration == 'counts':
|
|
486
|
+
return counts
|
|
487
|
+
if calibration == 'unnormalized_reflectance':
|
|
488
|
+
return GOESCalibrator.vis_unnormalized_reflectance(counts)
|
|
489
|
+
raise ValueError(f'Unsupported VIS calibration {calibration!r}.')
|
|
490
|
+
|
|
491
|
+
def get_nadir_sampling(self):
|
|
492
|
+
"""The sub-satellite point, altitude and nadir line/element spacing (see ``GOESNav.get_nadir_sampling``)."""
|
|
493
|
+
return self._goes_nav().get_nadir_sampling()
|
|
494
|
+
|
|
495
|
+
def _goes_nav(self):
|
|
496
|
+
nav = self.navigation
|
|
497
|
+
if nav is None or not hasattr(nav, 'get_nadir_sampling'):
|
|
498
|
+
raise ValueError(f'{self.source}: there is no GOES navigation block.')
|
|
499
|
+
return nav
|
|
500
|
+
|
|
501
|
+
def get_lonlats(self, lines=None, elems=None):
|
|
502
|
+
"""Earth-locate pixels with the file's navigation (GOES, GVAR, GMSX, ABIN or RECT).
|
|
503
|
+
|
|
504
|
+
Args:
|
|
505
|
+
lines: 0-based line indices in this file; all present lines by default.
|
|
506
|
+
elems: 0-based element indices; all by default.
|
|
507
|
+
|
|
508
|
+
Returns:
|
|
509
|
+
``(lon, lat)`` in degrees, shape ``(len(lines), len(elems))``, NaN off the earth.
|
|
510
|
+
|
|
511
|
+
Raises:
|
|
512
|
+
ValueError: the file has no navigation block.
|
|
513
|
+
NotImplementedError: the navigation has no vectorized ``to_latlon`` (every navigation pyarea ports has one).
|
|
514
|
+
"""
|
|
515
|
+
nav = self.navigation
|
|
516
|
+
if nav is None:
|
|
517
|
+
raise ValueError(f'{self.source}: there is no navigation block.')
|
|
518
|
+
if not hasattr(nav, 'to_latlon'):
|
|
519
|
+
raise NotImplementedError(f'{self.source}: {type(nav).__name__} cannot Earth-locate arrays yet; '
|
|
520
|
+
'use its toLatLon.')
|
|
521
|
+
lines = np.arange(self.lines) if lines is None else lines
|
|
522
|
+
elems = np.arange(self.elements) if elems is None else elems
|
|
523
|
+
line_grid, elem_grid = np.meshgrid(lines, elems, indexing='ij')
|
|
524
|
+
# file lines and elements are counted from 0 here, as in VisAD's AREAnav; the navigation adds the ul
|
|
525
|
+
# line/element and the resolution itself. (Earlier versions added 1, which moved every pixel by one.)
|
|
526
|
+
lat, lon = nav.to_latlon(line_grid, elem_grid)
|
|
527
|
+
return lon, lat
|
|
528
|
+
|
|
529
|
+
def __str__(self):
|
|
530
|
+
if self.source:
|
|
531
|
+
ads = f'AREA File: {self.source} \n'
|
|
532
|
+
else:
|
|
533
|
+
ads = '\n'
|
|
534
|
+
ads += str(self.directory)
|
|
535
|
+
return ads
|
|
536
|
+
|
|
537
|
+
@property
|
|
538
|
+
def nominal_datetime(self):
|
|
539
|
+
return self.directory.nominal_time
|
|
540
|
+
@property
|
|
541
|
+
def scan_datetime(self):
|
|
542
|
+
return self.directory.start_time
|
|
543
|
+
@property
|
|
544
|
+
def creation_datetime(self):
|
|
545
|
+
return self.directory.creation_time
|
|
546
|
+
|
|
547
|
+
def _data_block_bytes(self):
|
|
548
|
+
"""The data block as it goes in the file: each line's prefix as read, then its pixels in the file's byte
|
|
549
|
+
order and band-interleaved by pixel, from ``self.data`` (so a changed ``data`` is saved)."""
|
|
550
|
+
block = np.array(self._line_array()) # a copy: it keeps the line prefixes
|
|
551
|
+
pixels = np.asarray(self.data).transpose(1, 2, 0) # (lines, elements, bands)
|
|
552
|
+
if self.datawidth != 1:
|
|
553
|
+
kind = 'i' if self.datawidth == 4 else 'u'
|
|
554
|
+
pixels = pixels.astype(np.dtype(f'{self.directory.byte_order}{kind}{self.datawidth}'))
|
|
555
|
+
pixel_bytes = np.ascontiguousarray(pixels).view(np.uint8).reshape(self.lines, self.line_data_len)
|
|
556
|
+
block[:, self.line_prefix_len:self.line_prefix_len + self.line_data_len] = pixel_bytes
|
|
557
|
+
return block.tobytes()
|
|
558
|
+
|
|
559
|
+
def save(self, to_file_path=None, compress_level=None):
|
|
560
|
+
"""
|
|
561
|
+
Saves the AreaFile to disk. Optionally supply a string representing the coverage of the AreaFile to be
|
|
562
|
+
incorporated in the name. Optionally compress to gzip
|
|
563
|
+
:param folder: str, full path to folder where data will be saved
|
|
564
|
+
:param coverage: str, the coverage ex SH, NH for goes images
|
|
565
|
+
:param compress_level: int, if provided the image will be compressed using gzip and specified compresslevel
|
|
566
|
+
:return: str, the full path of the saved file
|
|
567
|
+
"""
|
|
568
|
+
|
|
569
|
+
assert os.path.isabs(to_file_path), 'to_file_path arg %s is not an absolute path' % to_file_path
|
|
570
|
+
try:
|
|
571
|
+
import gzip
|
|
572
|
+
with open(to_file_path, 'wb') as aft:
|
|
573
|
+
aft.seek(0)
|
|
574
|
+
aft.write(self.adir_bytes)
|
|
575
|
+
if self.navigation_offset>0 and self.nav_size>0:
|
|
576
|
+
aft.seek(self.navigation_offset)
|
|
577
|
+
aft.write(self.nav_bytes)
|
|
578
|
+
if self.calibration_offset > 0 and self.cal_size > 0:
|
|
579
|
+
aft.seek(self.calibration_offset)
|
|
580
|
+
aft.write(self.cal_bytes)
|
|
581
|
+
if self.aux_offset > 0 and self.aux_size > 0:
|
|
582
|
+
aft.seek(self.aux_offset)
|
|
583
|
+
aft.write(self.aux_bytes)
|
|
584
|
+
#if theer is not datLoc there si not AreaFile
|
|
585
|
+
aft.seek(self.data_offset)
|
|
586
|
+
aft.write(self._data_block_bytes())
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
if compress_level is not None:
|
|
590
|
+
|
|
591
|
+
afpz = to_file_path + '.z'
|
|
592
|
+
with open(to_file_path, 'rb') as f_in, gzip.open(afpz, 'wb', compresslevel=compress_level) as f_out:
|
|
593
|
+
for chunk in f_in:
|
|
594
|
+
f_out.write(chunk)
|
|
595
|
+
os.remove(to_file_path)
|
|
596
|
+
return afpz
|
|
597
|
+
|
|
598
|
+
return to_file_path
|
|
599
|
+
except Exception:
|
|
600
|
+
|
|
601
|
+
raise
|
|
602
|
+
|
|
603
|
+
@property
|
|
604
|
+
def imc_flip(self):
|
|
605
|
+
"""
|
|
606
|
+
Computes
|
|
607
|
+
|
|
608
|
+
Line Prefix COntent
|
|
609
|
+
Validity Code: 4 bytes
|
|
610
|
+
Documentation: 76 bytes. The documentation region
|
|
611
|
+
consists of the following:
|
|
612
|
+
- Block Header CRC: 2 bytes. Last three bits only;
|
|
613
|
+
bit is set if Block Header copy is good. This data
|
|
614
|
+
is usually 00,07.
|
|
615
|
+
- Scan Status: 4 bytes (OGE Table 3-6)
|
|
616
|
+
- Year, Day, Time from Block 0: 8 bytes
|
|
617
|
+
- Block Header: 30 bytes (OGE Table 3-5)
|
|
618
|
+
Bytes 17-24 now contain the time the block was disseminated from
|
|
619
|
+
the ground station.
|
|
620
|
+
- Additional Line Documentation: 32 bytes. 16 10-
|
|
621
|
+
bit fields, right-justified. (OGE Table 3-7)
|
|
622
|
+
The 6 bit field on the left hand side is not zero filled.
|
|
623
|
+
To get the 10 bit field a logical AND against 03FF (hex) must be used.
|
|
624
|
+
|
|
625
|
+
:return:
|
|
626
|
+
"""
|
|
627
|
+
if self.directory.source_type.decode() in ['GVAR', 'VISR']:
|
|
628
|
+
|
|
629
|
+
if self.directory.line_prefix_length == 0:
|
|
630
|
+
|
|
631
|
+
raise Exception('Cannot extract imc anf flip flags because the image lines have no documentation ' )
|
|
632
|
+
else:
|
|
633
|
+
raise Exception('The Area file was not produced from a GVAR stream. '
|
|
634
|
+
'The IMC and FLIP flags do not apply in this case.')
|
|
635
|
+
|
|
636
|
+
import ctypes as C
|
|
637
|
+
|
|
638
|
+
if self.directory.byte_order == '>':
|
|
639
|
+
klass = C.BigEndianStructure
|
|
640
|
+
else:
|
|
641
|
+
klass = C.LittleEndianStructure
|
|
642
|
+
|
|
643
|
+
class ISCAN(klass):
|
|
644
|
+
|
|
645
|
+
"""
|
|
646
|
+
' 0 Frame Start',
|
|
647
|
+
' 1 Frame End',
|
|
648
|
+
' 2 Frame break ( lines lost )',
|
|
649
|
+
' 3 Line break ( Pixels lost )',
|
|
650
|
+
' 4 Priority 1 frame data ',
|
|
651
|
+
' 5 Priority 2 frame data ',
|
|
652
|
+
' 6 East-to-west scan',
|
|
653
|
+
' 7 South-to-north scan',
|
|
654
|
+
' 8 IMC active',
|
|
655
|
+
' 9 Lost header block',
|
|
656
|
+
'10 Lost trailer block',
|
|
657
|
+
'11 Lost telemetry data',
|
|
658
|
+
'12 (Star sense) time break',
|
|
659
|
+
'13 Side 2 (secondary) active',
|
|
660
|
+
'14 Visible normalization active',
|
|
661
|
+
'15 IR calibration active',
|
|
662
|
+
'16 yaw-flipped mode (GOES-10)',
|
|
663
|
+
'17 IR detector 1 data not valid',
|
|
664
|
+
'18 IR detector 2 data not valid',
|
|
665
|
+
'19 IR detector 3 data not valid',
|
|
666
|
+
'20 IR detector 4 data not valid',
|
|
667
|
+
'21 IR detector 5 data not valid',
|
|
668
|
+
'22 IR detector 6 data not valid',
|
|
669
|
+
'23 IR detector 7 data not valid',
|
|
670
|
+
'24 Visible detector 1 data not valid',
|
|
671
|
+
'25 Visible detector 2 data not valid',
|
|
672
|
+
'26 Visible detector 3 data not valid',
|
|
673
|
+
'27 Visible detector 4 data not valid',
|
|
674
|
+
'28 Visible detector 5 data not valid',
|
|
675
|
+
'29 Visible detector 6 data not valid',
|
|
676
|
+
'30 Visible detector 7 data not valid',
|
|
677
|
+
'31 Visible detector 8 data not valid'
|
|
678
|
+
"""
|
|
679
|
+
_pack_ = 1
|
|
680
|
+
_layout_ = "ms" # what Python used implicitly; spelled out since 3.14 deprecates the default
|
|
681
|
+
|
|
682
|
+
_fields_ = (('frame_start', C.c_uint8, 1), # 0
|
|
683
|
+
('frame_end', C.c_uint8, 1), # 1
|
|
684
|
+
('frame_break', C.c_uint8, 1), # 2
|
|
685
|
+
('line_break', C.c_uint8, 1), # 3
|
|
686
|
+
('priority1', C.c_uint8, 1), # 4
|
|
687
|
+
('priority2', C.c_uint8, 1), # 5
|
|
688
|
+
('west_to_east', C.c_uint8, 1), # 6
|
|
689
|
+
('north_to_south', C.c_uint8, 1), # 7
|
|
690
|
+
('imc_active', C.c_uint8, 1), # 8
|
|
691
|
+
('header_lost', C.c_uint8, 1), # 9
|
|
692
|
+
('trailer_lost', C.c_uint8, 1), # 10
|
|
693
|
+
('telemetry_lost', C.c_uint8, 1), # 11
|
|
694
|
+
('time_break', C.c_uint8, 1), # 12
|
|
695
|
+
('side2', C.c_uint8, 1), # 13
|
|
696
|
+
('vis_normalization', C.c_uint8, 1), # 14
|
|
697
|
+
('ir_calibration', C.c_uint8, 1), # 15
|
|
698
|
+
('yaw_flip', C.c_uint8, 1), # 16
|
|
699
|
+
('irdet1_invalid', C.c_uint8, 1), ('irdet2_invalid', C.c_uint8, 1),
|
|
700
|
+
('irdet3_invalid', C.c_uint8, 1), ('irdet4_invalid', C.c_uint8, 1),
|
|
701
|
+
('irdet5_invalid', C.c_uint8, 1), ('irdet6_invalid', C.c_uint8, 1),
|
|
702
|
+
('irdet7_invalid', C.c_uint8, 1), ('visdet1_invalid', C.c_uint8, 1),
|
|
703
|
+
('visdet2_invalid', C.c_uint8, 1), ('visdet3_invalid', C.c_uint8, 1),
|
|
704
|
+
('visdet4_invalid', C.c_uint8, 1), ('visdet5_invalid', C.c_uint8, 1),
|
|
705
|
+
('visdet6_invalid', C.c_uint8, 1), ('visdet7_invalid', C.c_uint8, 1),
|
|
706
|
+
('visdet8_invalid', C.c_uint8, 1),)
|
|
707
|
+
|
|
708
|
+
def bstring(self):
|
|
709
|
+
return ''.join([str(getattr(self, e[0])) for e in self._fields_])
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
'''
|
|
713
|
+
line prefix length = doc + cal + band + 4 (if valcode is present)
|
|
714
|
+
line data length = nbands*nele*nbytes
|
|
715
|
+
line length = line prefix length + line data length
|
|
716
|
+
data block length = nlines * line length
|
|
717
|
+
'''
|
|
718
|
+
|
|
719
|
+
try:
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
mask = self.__datamask__().ravel()
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
# #
|
|
726
|
+
# for b in range(self.num_bands):
|
|
727
|
+
|
|
728
|
+
# t he line prefix is 4 bytes, so we view it as 1 byte
|
|
729
|
+
prfx1 = self.data_block[~mask].reshape(self.lines, self.prefix_len).view('u1')
|
|
730
|
+
# some story
|
|
731
|
+
|
|
732
|
+
# valid = prfx1.view('%si4' % self.BYTE_ORDER)
|
|
733
|
+
|
|
734
|
+
if self.directory.validity_code: # this is the validity code, if its value is present in yhe header
|
|
735
|
+
# one vcould also use byte position 23 or 24 , to chcek valid lines using block0 header
|
|
736
|
+
# valid_lines_mask = valid[:,0] == self.valcode
|
|
737
|
+
# valid_lines = prfx1[:,INT32SIZE:][valid_lines_mask]
|
|
738
|
+
lines = prfx1[:, INT32SIZE:]
|
|
739
|
+
else:
|
|
740
|
+
lines = prfx1
|
|
741
|
+
valid_lines_mask = lines[:, 22].view(bool)
|
|
742
|
+
valid_lines = lines[valid_lines_mask]
|
|
743
|
+
if not lines.size > 0:
|
|
744
|
+
raise Exception('The Area files dodo not have any valid lines as per block0 data form the line prefix')
|
|
745
|
+
aline = valid_lines[0]
|
|
746
|
+
astatus = ISCAN.from_buffer_copy(aline[2:6])
|
|
747
|
+
return astatus.imc_active, astatus.yaw_flip
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
except Exception as e:
|
|
751
|
+
raise Exception(f'Failed to fetch IMC and FLIP flags from {self.__class__.__name__} object, '
|
|
752
|
+
f'Error is {e}') from e
|