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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011, 2012.
# SMHI,
# Folkborgsvägen 1,
# Norrköping,
# Sweden
# Author(s):
# Martin Raspaud <martin.raspaud@smhi.se>
# Adam Dybbroe <adam.dybbroe@smhi.se>
# This file is part of mpop.
# mpop 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.
# mpop 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
# mpop. If not, see <http://www.gnu.org/licenses/>.
"""Very simple netcdf reader for mpop.
"""
# TODO
# - complete projection list and attribute list
# - handle other units than "m" for coordinates
# - handle units for data
# - pluginize
import warnings
from ConfigParser import NoSectionError
import numpy as np
from netCDF4 import Dataset, num2date
from mpop.instruments.visir import VisirCompositer
from mpop.satellites import GenericFactory
from mpop.satout.cfscene import TIME_UNITS
from mpop.utils import get_logger
LOG = get_logger("netcdf4/cf reader")
# To be complete, get from appendix F of cf conventions
MAPPING_ATTRIBUTES = {'grid_mapping_name': "proj",
'standard_parallel': ["lat_1", "lat_2"],
'latitude_of_projection_origin': "lat_0",
'longitude_of_projection_origin': "lon_0",
'longitude_of_central_meridian': "lon_0",
'perspective_point_height': "h",
'false_easting': "x_0",
'false_northing': "y_0",
'semi_major_axis': "a",
'semi_minor_axis': "b",
'inverse_flattening': "rf",
'ellipsoid': "ellps", # not in CF conventions...
}
# To be completed, get from appendix F of cf conventions
PROJNAME = {"vertical_perspective": "nsper",
"geostationary": "geos",
"albers_conical_equal_area": "aea",
"azimuthal_equidistant": "aeqd",
}
def _load02(filename):
"""Load data from a netcdf4 file, cf-satellite v0.2 (2012-02-03).
"""
rootgrp = Dataset(filename, 'r')
# processed variables
processed = set()
satellite_name, satellite_number = rootgrp.platform.rsplit("-", 1)
time_slot = rootgrp.variables["time"].getValue()[0]
time_slot = num2date(time_slot, TIME_UNITS)
processed |= set(["time"])
try:
service = str(rootgrp.service)
except AttributeError:
service = ""
instrument_name = str(rootgrp.instrument)
try:
orbit = str(rootgrp.orbit)
except AttributeError:
orbit = None
try:
scene = GenericFactory.create_scene(satellite_name,
satellite_number,
instrument_name,
time_slot,
orbit,
None,
service)
except NoSectionError:
scene = VisirCompositer(time_slot=time_slot)
scene.satname = satellite_name
scene.number = satellite_number
scene.service = service
dim_chart = {}
for var_name, var in rootgrp.variables.items():
varname = None
try:
varname = var.standard_name
except AttributeError:
try:
varname = var.long_name
except AttributeError:
pass
if varname in ["band_data", "Band data"]:
LOG.debug("Found some data: " + var_name)
dims = var.dimensions
for dim in dims:
dim_chart[dim] = var_name
for cnt, dim in enumerate(dims):
if dim.startswith("band"):
break
data = var
data.set_auto_maskandscale(False)
area = None
try:
area_var_name = getattr(var,"grid_mapping")
area_var = rootgrp.variables[area_var_name]
proj4_dict = {}
for attr, projattr in MAPPING_ATTRIBUTES.items():
try:
the_attr = getattr(area_var, attr)
if projattr == "proj":
proj4_dict[projattr] = PROJNAME[the_attr]
elif(isinstance(projattr, (list, tuple))):
try:
for i, subattr in enumerate(the_attr):
proj4_dict[projattr[i]] = subattr
except TypeError:
proj4_dict[projattr[0]] = the_attr
else:
proj4_dict[projattr] = the_attr
except AttributeError:
pass
y_name, x_name = dims[:cnt] + dims[cnt + 1:]
x__ = rootgrp.variables[x_name][:]
y__ = rootgrp.variables[y_name][:]
if proj4_dict["proj"] == "geos":
x__ *= proj4_dict["h"]
y__ *= proj4_dict["h"]
x_pixel_size = abs((np.diff(x__)).mean())
y_pixel_size = abs((np.diff(y__)).mean())
llx = x__[0] - x_pixel_size / 2.0
lly = y__[-1] - y_pixel_size / 2.0
urx = x__[-1] + x_pixel_size / 2.0
ury = y__[0] + y_pixel_size / 2.0
area_extent = (llx, lly, urx, ury)
try:
# create the pyresample areadef
from pyresample.geometry import AreaDefinition
area = AreaDefinition("myareaid", "myareaname",
"myprojid", proj4_dict,
len(x__), len(y__),
area_extent)
except ImportError:
LOG.warning("Pyresample not found, "
"cannot load area descrition")
processed |= set([area_var_name, x_name, y_name])
LOG.debug("Grid mapping found and used.")
except AttributeError:
LOG.debug("No grid mapping found.")
try:
area_var = getattr(var,"coordinates")
coordinates_vars = area_var.split(" ")
lons = None
lats = None
for coord_var_name in coordinates_vars:
coord_var = rootgrp.variables[coord_var_name]
units = getattr(coord_var, "units")
if(coord_var_name.lower().startswith("lon") or
units.lower().endswith("east") or
units.lower().endswith("west")):
lons = coord_var[:]
elif(coord_var_name.lower().startswith("lat") or
units.lower().endswith("north") or
units.lower().endswith("south")):
lats = coord_var[:]
if lons and lats:
try:
from pyresample.geometry import SwathDefinition
area = SwathDefinition(lons=lons, lats=lats)
except ImportError:
LOG.warning("Pyresample not found, "
"cannot load area descrition")
processed |= set(coordinates_vars)
LOG.debug("Lon/lat found and used.")
except AttributeError:
LOG.debug("No lon/lat found.")
names = rootgrp.variables[dim][:]
scales = data.scale_factor
offsets = data.add_offset
if len(names) == 1:
scales = np.array([scales])
offsets = np.array([offsets])
print scales, offsets
for nbr, name in enumerate(names):
try:
if cnt == 0:
chn_data = data[nbr, :, :].squeeze()
if cnt == 1:
chn_data = data[:, nbr, :].squeeze()
if cnt == 2:
chn_data = data[:, :, nbr].squeeze()
scene[name] = (np.ma.masked_equal(chn_data, data._FillValue)
* scales[nbr] + offsets[nbr])
scene[name].info["units"] = var.units
except KeyError:
from mpop.channel import Channel
scene.channels.append(Channel(name))
if area is not None:
scene[name].area = area
processed |= set([var_name, dim])
non_processed = set(rootgrp.variables.keys()) - processed
for var_name in non_processed:
var = rootgrp.variables[var_name]
if not (hasattr(var, "standard_name") or
hasattr(var, "long_name")):
LOG.info("Delayed processing of " + var_name)
continue
dims = var.dimensions
if len(dims) != 1:
LOG.info("Don't know what to do with " + var_name)
continue
dim = dims[0]
if var.standard_name == "radiation_wavelength":
names = rootgrp.variables[dim][:]
for nbr, name in enumerate(names):
scene[name].wavelength_range[1] = var[nbr]
try:
bnds = rootgrp.variables[var.bounds][:]
for nbr, name in enumerate(names):
scene[name].wavelength_range[0] = bnds[nbr, 0]
scene[name].wavelength_range[2] = bnds[nbr, 1]
processed |= set([var.bounds])
except AttributeError:
pass
processed |= set([var_name])
non_processed = set(rootgrp.variables.keys()) - processed
if len(non_processed) > 0:
LOG.warning("Remaining non-processed variables: " + str(non_processed))
return scene
def load_from_nc4(filename):
"""Load data from a netcdf4 file, cf-satellite v0.1
"""
rootgrp = Dataset(filename, 'r')
try:
rootgrp.satellite_number
warnings.warn("You are loading old style netcdf files...", DeprecationWarning)
except AttributeError:
return _load02(filename)
if not isinstance(rootgrp.satellite_number, str):
satellite_number = "%02d" % rootgrp.satellite_number
else:
satellite_number = str(rootgrp.satellite_number)
time_slot = rootgrp.variables["time"].getValue()[0]
time_slot = num2date(time_slot, TIME_UNITS)
service = str(rootgrp.service)
satellite_name = str(rootgrp.satellite_name)
instrument_name = str(rootgrp.instrument_name)
try:
orbit = str(rootgrp.orbit)
except AttributeError:
orbit = None
try:
scene = GenericFactory.create_scene(satellite_name,
satellite_number,
instrument_name,
time_slot,
orbit,
None,
service)
except NoSectionError:
scene = VisirCompositer(time_slot=time_slot)
scene.satname = satellite_name
scene.number = satellite_number
scene.service = service
for var_name, var in rootgrp.variables.items():
area = None
if var_name.startswith("band_data"):
resolution = var.resolution
str_res = str(int(resolution)) + "m"
names = rootgrp.variables["bandname"+str_res][:]
data = var[:, :, :].astype(var.dtype)
data = np.ma.masked_outside(data,
var.valid_range[0],
var.valid_range[1])
try:
area_var = getattr(var,"grid_mapping")
area_var = rootgrp.variables[area_var]
proj4_dict = {}
for attr, projattr in MAPPING_ATTRIBUTES.items():
try:
the_attr = getattr(area_var, attr)
if projattr == "proj":
proj4_dict[projattr] = PROJNAME[the_attr]
elif(isinstance(projattr, (list, tuple))):
try:
for i, subattr in enumerate(the_attr):
proj4_dict[projattr[i]] = subattr
except TypeError:
proj4_dict[projattr[0]] = the_attr
else:
proj4_dict[projattr] = the_attr
except AttributeError:
pass
x__ = rootgrp.variables["x"+str_res][:]
y__ = rootgrp.variables["y"+str_res][:]
x_pixel_size = abs((x__[1] - x__[0]))
y_pixel_size = abs((y__[1] - y__[0]))
llx = x__[0] - x_pixel_size / 2.0
lly = y__[-1] - y_pixel_size / 2.0
urx = x__[-1] + x_pixel_size / 2.0
ury = y__[0] + y_pixel_size / 2.0
area_extent = (llx, lly, urx, ury)
try:
# create the pyresample areadef
from pyresample.geometry import AreaDefinition
area = AreaDefinition("myareaid", "myareaname",
"myprojid", proj4_dict,
data.shape[1], data.shape[0],
area_extent)
except ImportError:
LOG.warning("Pyresample not found, "
"cannot load area descrition")
except AttributeError:
LOG.debug("No grid mapping found.")
try:
area_var = getattr(var,"coordinates")
coordinates_vars = area_var.split(" ")
lons = None
lats = None
for coord_var_name in coordinates_vars:
coord_var = rootgrp.variables[coord_var_name]
units = getattr(coord_var, "units")
if(coord_var_name.lower().startswith("lon") or
units.lower().endswith("east") or
units.lower().endswith("west")):
lons = coord_var[:]
elif(coord_var_name.lower().startswith("lat") or
units.lower().endswith("north") or
units.lower().endswith("south")):
lats = coord_var[:]
if lons and lats:
try:
from pyresample.geometry import SwathDefinition
area = SwathDefinition(lons=lons, lats=lats)
except ImportError:
LOG.warning("Pyresample not found, "
"cannot load area descrition")
except AttributeError:
LOG.debug("No lon/lat found.")
for i, name in enumerate(names):
if var.dimensions[0].startswith("band"):
chn_data = data[i, :, :]
elif var.dimensions[1].startswith("band"):
chn_data = data[:, i, :]
elif var.dimensions[2].startswith("band"):
chn_data = data[:, :, i]
else:
raise ValueError("Invalid dimension names for band data")
try:
scene[name] = (chn_data *
rootgrp.variables["scale"+str_res][i] +
rootgrp.variables["offset"+str_res][i])
#FIXME complete this
#scene[name].info
except KeyError:
# build the channel on the fly
from mpop.channel import Channel
wv_var = rootgrp.variables["nominal_wavelength"+str_res]
wb_var = rootgrp.variables[getattr(wv_var, "bounds")]
minmax = wb_var[i]
scene.channels.append(Channel(name,
resolution,
(minmax[0],
wv_var[i][0],
minmax[1])))
scene[name] = (chn_data *
rootgrp.variables["scale"+str_res][i] +
rootgrp.variables["offset"+str_res][i])
if area is not None:
scene[name].area = area
area = None
for attr in rootgrp.ncattrs():
scene.info[attr] = getattr(rootgrp, attr)
scene.add_to_history("Loaded from netcdf4/cf by mpop")
return scene
|