forked from pytroll/satpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
olci_nc.py
426 lines (327 loc) · 14.2 KB
/
olci_nc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Satpy developers
#
# This file is part of satpy.
#
# satpy is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# satpy is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# satpy. If not, see <http://www.gnu.org/licenses/>.
"""Sentinel-3 OLCI reader.
This reader supports an optional argument to choose the 'engine' for reading
OLCI netCDF4 files. By default, this reader uses the default xarray choice of
engine, as defined in the :func:`xarray.open_dataset` documentation`.
As an alternative, the user may wish to use the 'h5netcdf' engine, but that is
not default as it typically prints many non-fatal but confusing error messages
to the terminal.
To choose between engines the user can do as follows for the default::
scn = Scene(filenames=my_files, reader='olci_l1b')
or as follows for the h5netcdf engine::
scn = Scene(filenames=my_files,
reader='olci_l1b', reader_kwargs={'engine': 'h5netcdf'})
References:
- :func:`xarray.open_dataset`
"""
import logging
from contextlib import suppress
from functools import reduce
import dask.array as da
import numpy as np
import xarray as xr
from satpy import CHUNK_SIZE
from satpy.readers import open_file_or_filename
from satpy.readers.file_handlers import BaseFileHandler
from satpy.utils import angle2xyz, xyz2angle
try:
from functools import cached_property
except ImportError:
# for python < 3.8
from satpy._compat import cached_property
logger = logging.getLogger(__name__)
PLATFORM_NAMES = {'S3A': 'Sentinel-3A',
'S3B': 'Sentinel-3B'}
class BitFlags(object):
"""Manipulate flags stored bitwise."""
flag_list = ['INVALID', 'WATER', 'LAND', 'CLOUD', 'SNOW_ICE',
'INLAND_WATER', 'TIDAL', 'COSMETIC', 'SUSPECT',
'HISOLZEN', 'SATURATED', 'MEGLINT', 'HIGHGLINT',
'WHITECAPS', 'ADJAC', 'WV_FAIL', 'PAR_FAIL',
'AC_FAIL', 'OC4ME_FAIL', 'OCNN_FAIL',
'Extra_1',
'KDM_FAIL',
'Extra_2',
'CLOUD_AMBIGUOUS', 'CLOUD_MARGIN', 'BPAC_ON', 'WHITE_SCATT',
'LOWRW', 'HIGHRW']
meaning = {f: i for i, f in enumerate(flag_list)}
def __init__(self, value):
"""Init the flags."""
self._value = value
def __getitem__(self, item):
"""Get the item."""
pos = self.meaning[item]
data = self._value
if isinstance(data, xr.DataArray):
data = data.data
res = ((data >> pos) % 2).astype(np.bool)
res = xr.DataArray(res, coords=self._value.coords,
attrs=self._value.attrs,
dims=self._value.dims)
else:
res = ((data >> pos) % 2).astype(np.bool)
return res
class NCOLCIBase(BaseFileHandler):
"""The OLCI reader base."""
def __init__(self, filename, filename_info, filetype_info,
engine=None):
"""Init the olci reader base."""
super(NCOLCIBase, self).__init__(filename, filename_info,
filetype_info)
self._engine = engine
self._start_time = filename_info['start_time']
self._end_time = filename_info['end_time']
# TODO: get metadata from the manifest file (xfdumanifest.xml)
self.platform_name = PLATFORM_NAMES[filename_info['mission_id']]
self.sensor = 'olci'
self.open_file = None
@cached_property
def nc(self):
"""Get the nc xr dataset."""
f_obj = open_file_or_filename(self.filename)
dataset = xr.open_dataset(f_obj,
decode_cf=True,
mask_and_scale=True,
engine=self._engine,
chunks={'columns': CHUNK_SIZE,
'rows': CHUNK_SIZE})
return dataset.rename({'columns': 'x', 'rows': 'y'})
@property
def start_time(self):
"""Start time property."""
return self._start_time
@property
def end_time(self):
"""End time property."""
return self._end_time
def get_dataset(self, key, info):
"""Load a dataset."""
logger.debug('Reading %s.', key['name'])
variable = self.nc[key['name']]
return variable
def __del__(self):
"""Close the NetCDF file that may still be open."""
with suppress(IOError, OSError, AttributeError):
self.nc.close()
class NCOLCICal(NCOLCIBase):
"""Dummy class for calibration."""
pass
class NCOLCIGeo(NCOLCIBase):
"""Dummy class for navigation."""
pass
class NCOLCIChannelBase(NCOLCIBase):
"""Base class for channel reading."""
def __init__(self, filename, filename_info, filetype_info,
engine=None):
"""Init the file handler."""
super(NCOLCIChannelBase, self).__init__(filename, filename_info,
filetype_info)
self.channel = filename_info.get('dataset_name')
class NCOLCI1B(NCOLCIChannelBase):
"""File handler for OLCI l1b."""
def __init__(self, filename, filename_info, filetype_info, cal,
engine=None):
"""Init the file handler."""
super(NCOLCI1B, self).__init__(filename, filename_info,
filetype_info)
self.cal = cal.nc
@staticmethod
def _get_items(idx, solar_flux):
"""Get items."""
return solar_flux[idx]
def _get_solar_flux(self, band):
"""Get the solar flux for the band."""
solar_flux = self.cal['solar_flux'].isel(bands=band).values
d_index = self.cal['detector_index'].fillna(0).astype(int)
return da.map_blocks(self._get_items, d_index.data,
solar_flux=solar_flux, dtype=solar_flux.dtype)
def get_dataset(self, key, info):
"""Load a dataset."""
if self.channel != key['name']:
return
logger.debug('Reading %s.', key['name'])
radiances = self.nc[self.channel + '_radiance']
if key['calibration'] == 'reflectance':
idx = int(key['name'][2:]) - 1
sflux = self._get_solar_flux(idx)
radiances = radiances / sflux * np.pi * 100
radiances.attrs['units'] = '%'
radiances.attrs['platform_name'] = self.platform_name
radiances.attrs['sensor'] = self.sensor
radiances.attrs.update(key.to_dict())
return radiances
class NCOLCI2(NCOLCIChannelBase):
"""File handler for OLCI l2."""
def get_dataset(self, key, info):
"""Load a dataset."""
if self.channel is not None and self.channel != key['name']:
return
logger.debug('Reading %s.', key['name'])
if self.channel is not None and self.channel.startswith('Oa'):
dataset = self.nc[self.channel + '_reflectance']
else:
dataset = self.nc[info['nc_key']]
if key['name'] == 'wqsf':
dataset.attrs['_FillValue'] = 1
elif key['name'] == 'mask':
dataset = self.getbitmask(dataset)
dataset.attrs['platform_name'] = self.platform_name
dataset.attrs['sensor'] = self.sensor
dataset.attrs.update(key.to_dict())
return dataset
def getbitmask(self, wqsf, items=None):
"""Get the bitmask."""
if items is None:
items = ["INVALID", "SNOW_ICE", "INLAND_WATER", "SUSPECT",
"AC_FAIL", "CLOUD", "HISOLZEN", "OCNN_FAIL",
"CLOUD_MARGIN", "CLOUD_AMBIGUOUS", "LOWRW", "LAND"]
bflags = BitFlags(wqsf)
return reduce(np.logical_or, [bflags[item] for item in items])
class NCOLCILowResData(BaseFileHandler):
"""Handler for low resolution data."""
def __init__(self, filename, filename_info, filetype_info,
engine=None):
"""Init the file handler."""
super(NCOLCILowResData, self).__init__(filename, filename_info, filetype_info)
self.nc = None
# TODO: get metadata from the manifest file (xfdumanifest.xml)
self.platform_name = PLATFORM_NAMES[filename_info['mission_id']]
self.sensor = 'olci'
self.cache = {}
self.engine = engine
def _open_dataset(self):
if self.nc is None:
self.nc = xr.open_dataset(self.filename,
decode_cf=True,
mask_and_scale=True,
engine=self.engine,
chunks={'tie_columns': CHUNK_SIZE,
'tie_rows': CHUNK_SIZE})
self.nc = self.nc.rename({'tie_columns': 'x', 'tie_rows': 'y'})
self.l_step = self.nc.attrs['al_subsampling_factor']
self.c_step = self.nc.attrs['ac_subsampling_factor']
def _do_interpolate(self, data):
if not isinstance(data, tuple):
data = (data,)
shape = data[0].shape
from geotiepoints.interpolator import Interpolator
tie_lines = np.arange(0, (shape[0] - 1) * self.l_step + 1, self.l_step)
tie_cols = np.arange(0, (shape[1] - 1) * self.c_step + 1, self.c_step)
lines = np.arange((shape[0] - 1) * self.l_step + 1)
cols = np.arange((shape[1] - 1) * self.c_step + 1)
along_track_order = 1
cross_track_order = 3
satint = Interpolator([x.values for x in data],
(tie_lines, tie_cols),
(lines, cols),
along_track_order,
cross_track_order)
int_data = satint.interpolate()
return [xr.DataArray(da.from_array(x, chunks=(CHUNK_SIZE, CHUNK_SIZE)),
dims=['y', 'x']) for x in int_data]
def _need_interpolation(self):
return (self.c_step != 1 or self.l_step != 1)
def __del__(self):
"""Close the NetCDF file that may still be open."""
try:
self.nc.close()
except (IOError, OSError, AttributeError):
pass
class NCOLCIAngles(NCOLCILowResData):
"""File handler for the OLCI angles."""
datasets = {'satellite_azimuth_angle': 'OAA',
'satellite_zenith_angle': 'OZA',
'solar_azimuth_angle': 'SAA',
'solar_zenith_angle': 'SZA'}
def get_dataset(self, key, info):
"""Load a dataset."""
if key['name'] not in self.datasets:
return
self._open_dataset()
logger.debug('Reading %s.', key['name'])
if self._need_interpolation() and self.cache.get(key['name']) is None:
if key['name'].startswith('satellite'):
zen = self.nc[self.datasets['satellite_zenith_angle']]
zattrs = zen.attrs
azi = self.nc[self.datasets['satellite_azimuth_angle']]
aattrs = azi.attrs
elif key['name'].startswith('solar'):
zen = self.nc[self.datasets['solar_zenith_angle']]
zattrs = zen.attrs
azi = self.nc[self.datasets['solar_azimuth_angle']]
aattrs = azi.attrs
else:
raise NotImplementedError("Don't know how to read " + key['name'])
x, y, z = angle2xyz(azi, zen)
x, y, z = self._do_interpolate((x, y, z))
azi, zen = xyz2angle(x, y, z)
azi.attrs = aattrs
zen.attrs = zattrs
if 'zenith' in key['name']:
values = zen
elif 'azimuth' in key['name']:
values = azi
else:
raise NotImplementedError("Don't know how to read " + key['name'])
if key['name'].startswith('satellite'):
self.cache['satellite_zenith_angle'] = zen
self.cache['satellite_azimuth_angle'] = azi
elif key['name'].startswith('solar'):
self.cache['solar_zenith_angle'] = zen
self.cache['solar_azimuth_angle'] = azi
elif key['name'] in self.cache:
values = self.cache[key['name']]
else:
values = self.nc[self.datasets[key['name']]]
values.attrs['platform_name'] = self.platform_name
values.attrs['sensor'] = self.sensor
values.attrs.update(key.to_dict())
return values
def __del__(self):
"""Close the NetCDF file that may still be open."""
try:
self.nc.close()
except (IOError, OSError, AttributeError):
pass
class NCOLCIMeteo(NCOLCILowResData):
"""File handler for the OLCI meteo data."""
datasets = ['humidity', 'sea_level_pressure', 'total_columnar_water_vapour', 'total_ozone']
# TODO: the following depends on more than columns, rows
# float atmospheric_temperature_profile(tie_rows, tie_columns, tie_pressure_levels) ;
# float horizontal_wind(tie_rows, tie_columns, wind_vectors) ;
# float reference_pressure_level(tie_pressure_levels) ;
def get_dataset(self, key, info):
"""Load a dataset."""
if key['name'] not in self.datasets:
return
self._open_dataset()
logger.debug('Reading %s.', key['name'])
if self._need_interpolation() and self.cache.get(key['name']) is None:
data = self.nc[key['name']]
values, = self._do_interpolate(data)
values.attrs = data.attrs
self.cache[key['name']] = values
elif key['name'] in self.cache:
values = self.cache[key['name']]
else:
values = self.nc[key['name']]
values.attrs['platform_name'] = self.platform_name
values.attrs['sensor'] = self.sensor
values.attrs.update(key.to_dict())
return values