Ejemplo n.º 1
0
    def __init__(self,
                 fn,
                 frame=0,
                 double=False,
                 store_force=False,
                 mode='r',
                 format='NETCDF4'):
        self._fn = fn
        self._data = None
        try:
            if __have_netcdf4__:
                self._data = Dataset(fn, mode, format=format)
            else:
                if mode == 'ws':
                    mode = 'w'
                self._data = NetCDFFile(fn, mode)
        except RuntimeError as e:
            raise RuntimeError('Error opening file "{0}": {1}'.format(fn, e))

        if double:
            self._float_str = 'f8'
        else:
            self._float_str = 'f4'

        self._store_force = store_force

        self._is_amber = False

        if mode[0] == 'w':
            self._data.program = 'PyCo'
            self._data.programVersion = 'N/A'
            self._is_defined = False
        else:
            if 'nx' in self._data.dimensions and 'ny' in self._data.dimensions:
                try:
                    self._shape = (len(self._data.dimensions['nx']),
                                   len(self._data.dimensions['ny']))
                except TypeError:
                    self._shape = (self._data.dimensions['nx'],
                                   self._data.dimensions['ny'])
                self._shape2 = self._shape
            elif 'atom' in self._data.dimensions:
                n = self._data.dimensions['atom']
                nx = int(sqrt(n))
                assert nx * nx == n
                self._shape = (nx, nx)
                self._shape2 = (nx, nx)

                self._is_amber = True
            else:
                raise RuntimeError('Unknown NetCDF convention used for file '
                                   '%s.' % fn)

            self._is_defined = True

        if frame < 0:
            self._cur_frame = len(self) + frame
        else:
            self._cur_frame = frame
Ejemplo n.º 2
0
def main():
    fileName = sys.argv[1]

    ncFile = NetCDFFile(fileName, 'r')
    description = ET.Element('pointDataDescription')

    variableKeys = ncFile.variables.keys()
    variableKeys.sort()
    for variableName in variableKeys:
        if variableName in excludeVars:
            continue
        variableObject = ncFile.variables[variableName]
        varElement = ET.SubElement(description, 'parameter')
        varElement.set('name', variableName)
        typeCode = variableObject.typecode()
        numDims = len(variableObject.shape)
        if numDims > 1 and typeCode is 'c':
            typeCode = 's'
            numDims = numDims - 1
        varElement.set('type', typeMap[typeCode])
        varElement.set('numDims', str(numDims))

        if 'units' in variableObject._attributes:
            unit = variableObject._attributes['units']
            varElement.set('unit', unit)
        if '_FillValue' in variableObject._attributes:
            fillValue = variableObject._attributes['_FillValue']
            # Disabled for now:
            # if fillValue:
            #   varElement.set('fillValue',str(long(fillValue)))
    indentElement(description)
    print ET.tostring(description, 'UTF-8')
Ejemplo n.º 3
0
"""
from pupynere import NetCDFFile
import pylab as pl
from matplotlib import rcParams
try:
    import numpy
    rcParams['numerix'] = 'numpy'
except:
    raise ImportError('this example requires numpy')
import matplotlib.numerix.ma as MA
import matplotlib.numerix as N
from matplotlib.toolkits.basemap import Basemap

# read in data from netCDF file.
infile    = 'ccsm_popgrid.nc'
fpin      = NetCDFFile(infile)
tlat      = fpin.variables['TLAT'][:]
tlon      = fpin.variables['TLONG'][:]
temp      = fpin.variables['TEMP'][:]
fillvalue = fpin.variables['TEMP'].attributes['_FillValue']
fpin.close()

# make longitudes monotonically increasing.
tlon = N.where(N.greater_equal(tlon,min(tlon[:,0])),tlon-360,tlon)

# create a masked array with temperature data (continents masked).
temp = MA.masked_values(temp,fillvalue)

# stack grids side-by-side (in longitiudinal direction), so
# any range of longitudes may be plotted on a world map.
tlon = N.concatenate((tlon,tlon+360),1)
Ejemplo n.º 4
0
import matplotlib as mpl  # Descomente para não mostrar a janela em cada plot
mpl.use('Agg')            # Descomente para não mostrar a janela em cada plot
from pupynere import NetCDFFile
from PyFuncemeClimateTools import PlotMaps as pm
import numpy as np
from mpl_toolkits.basemap import shiftgrid

# y1, y2, x1, x2 = -60., 15., -90., -30.
y1, y2, x1, x2 = -90., 90., -180., 176.
ltime = 5
levs = (270., 275., 280., 285., 290., 295., 300.) #7
my_colors = ('#ffffff', '#E5E5E5', '#CBCBCB', '#B2B2B2',
             '#989898', '#7F7F7F', '#666666', '#4E4E4E') #8

# LIQIANG
f1 = NetCDFFile('/home/marcelo/Downloads/sst-test/liq/obs.sst.2013.nc', 'r')
sstliq = f1.variables['sst'][:]
lons_sstliq = f1.variables['lon'][:]
lats_sstliq = f1.variables['lat'][:]
f1.close()
sstliq, lons_sstliq = shiftgrid(180., sstliq, lons_sstliq, start=False)
sstliq_title = u'TSM LIQ'
fig_sstliq = '/home/marcelo/Downloads/sst-test/tsmliq.png'
pm.plotmap(sstliq[ltime, :, :], lats_sstliq-2.8125/2., lons_sstliq-2.8125/2., latsouthpoint=y1, latnorthpoint=y2,
           lonwestpoint=x1, loneastpoint=x2,  fig_name=fig_sstliq, barloc='bottom', maptype='fillc',
           barcolor=my_colors, barlevs=levs, fig_title=sstliq_title, barinf='max', ocean_mask=0,
           meridians=np.arange(-160., 161., 30.), parallels=np.arange(-90., 91., 20.))


# NÃO INVERTIDO USANDO A LAT DO MENOR PARA O MAIOR
# f4 = NetCDFFile('/home/marcelo/Downloads/sst-test/nc3/obs.sst.2013.nc', 'r')
Ejemplo n.º 5
0
"""
from pupynere import NetCDFFile
import pylab as pl
from matplotlib import rcParams
try:
    import numpy
    rcParams['numerix'] = 'numpy'
except:
    raise ImportError('this example requires numpy')
import matplotlib.numerix.ma as MA
import matplotlib.numerix as N
from matplotlib.toolkits.basemap import Basemap

# read in data from netCDF file.
infile = 'ccsm_popgrid.nc'
fpin = NetCDFFile(infile)
tlat = fpin.variables['TLAT'][:]
tlon = fpin.variables['TLONG'][:]
temp = fpin.variables['TEMP'][:]
fillvalue = fpin.variables['TEMP'].attributes['_FillValue']
fpin.close()

# make longitudes monotonically increasing.
tlon = N.where(N.greater_equal(tlon, min(tlon[:, 0])), tlon - 360, tlon)

# create a masked array with temperature data (continents masked).
temp = MA.masked_values(temp, fillvalue)

# stack grids side-by-side (in longitiudinal direction), so
# any range of longitudes may be plotted on a world map.
tlon = N.concatenate((tlon, tlon + 360), 1)
Ejemplo n.º 6
0
class NetCDFContainer(object):
    def __init__(self,
                 fn,
                 frame=0,
                 double=False,
                 store_force=False,
                 mode='r',
                 format='NETCDF4'):
        self._fn = fn
        self._data = None
        try:
            if __have_netcdf4__:
                self._data = Dataset(fn, mode, format=format)
            else:
                if mode == 'ws':
                    mode = 'w'
                self._data = NetCDFFile(fn, mode)
        except RuntimeError as e:
            raise RuntimeError('Error opening file "{0}": {1}'.format(fn, e))

        if double:
            self._float_str = 'f8'
        else:
            self._float_str = 'f4'

        self._store_force = store_force

        self._is_amber = False

        if mode[0] == 'w':
            self._data.program = 'PyCo'
            self._data.programVersion = 'N/A'
            self._is_defined = False
        else:
            if 'nx' in self._data.dimensions and 'ny' in self._data.dimensions:
                try:
                    self._shape = (len(self._data.dimensions['nx']),
                                   len(self._data.dimensions['ny']))
                except TypeError:
                    self._shape = (self._data.dimensions['nx'],
                                   self._data.dimensions['ny'])
                self._shape2 = self._shape
            elif 'atom' in self._data.dimensions:
                n = self._data.dimensions['atom']
                nx = int(sqrt(n))
                assert nx * nx == n
                self._shape = (nx, nx)
                self._shape2 = (nx, nx)

                self._is_amber = True
            else:
                raise RuntimeError('Unknown NetCDF convention used for file '
                                   '%s.' % fn)

            self._is_defined = True

        if frame < 0:
            self._cur_frame = len(self) + frame
        else:
            self._cur_frame = frame

    def __del__(self):
        if self._data is not None:
            self._data.close()

    def _define_file_structure(self, shape):
        # print 'defining file structure, shape = {0}'.format(shape)
        self._shape = shape

        if len(shape) == 3:
            ndof, nx, ny = shape
        else:
            ndof = 1
            nx, ny = shape

        self._shape2 = (nx, ny)

        if 'frame' not in self._data.dimensions:
            self._data.createDimension('frame', None)
        if ndof > 1 and 'ndof' not in self._data.dimensions:
            self._data.createDimension('ndof', ndof)
        if 'nx' not in self._data.dimensions:
            self._data.createDimension('nx', nx)
        if 'ny' not in self._data.dimensions:
            self._data.createDimension('ny', ny)

        self._data.sync()

        self._is_defined = True

    def set_shape(self, x, ndof=None):
        try:
            shape = x.shape
        except AttributeError:
            shape = x
        if not self._is_defined:
            if ndof is None or ndof == 1:
                self._define_file_structure(shape)
            else:
                self._define_file_structure([ndof] + list(shape))
        else:
            if ndof is None or ndof == 1:
                if not np.all(np.array(shape) == np.array(self._shape)):
                    raise RuntimeError(
                        'Shape mismatch: NetCDF file has shape '
                        '{0} x {1}, but someone is trying to '
                        'override this with shape {2} x {3}.'.format(
                            self._shape[0], self._shape[1], shape[0],
                            shape[1]))
            else:
                assert np.all(
                    np.array([ndof] + list(shape)) == np.array(self._shape))

    def __len__(self):
        try:
            length = len(self._data.dimensions['frame'])
        except TypeError:
            length = self._data.dimensions['frame']
        return length

    def close(self):
        if self._data is not None:
            self._data.close()
            self._is_defined = False
            self._data = None

    def has_h(self):
        return 'h' in self._data.variables

    def set_rigid_surface(self, h, ndof=None):
        self.set_shape(h, ndof=ndof)
        nx, ny = self._shape2
        hnx, hny = h.shape

        if 'h' not in self._data.variables:
            if hnx != nx or hny != ny:
                if 'rigid_nx' not in self._data.dimensions:
                    self._data.createDimension('rigid_nx', hnx)
                if 'rigid_ny' not in self._data.dimensions:
                    self._data.createDimension('rigid_ny', hny)
                self._data.createVariable('h', 'f8', (
                    'rigid_nx',
                    'rigid_ny',
                ))
            else:
                self._data.createVariable('h', 'f8', (
                    'nx',
                    'ny',
                ))

        self._data.variables['h'][:, :] = h

    # Backward compatibility
    set_h = set_rigid_surface

    def set_elastic_surface(self, h):
        if 'elastic_surface' not in self._data.variables:
            self._data.createVariable('elastic_surface', 'f8', (
                'nx',
                'ny',
            ))

        self._data.variables['elastic_surface'][:, :] = h

    def get_rigid_surface(self):
        return self._data.variables['h'][:, :]

    # Backward compatibility
    get_h = get_rigid_surface

    def get_elastic_surface(self):
        return self._data.variables['elastic_surface']

    def get_filename(self):
        return self._fn

    def get_next_frame(self):
        frame = NetCDFContainerFrame(self, self._cur_frame)
        self._cur_frame += 1
        return frame

    def set_cursor(self, cur_frame):
        self._cur_frame = cur_frame

    def get_cursor(self):
        return self._cur_frame

    def __getattr__(self, name):
        if name[0] == '_':
            return self.__dict__[name]

        if name in self._data.variables:
            return self._data.variables[name][...]

        return self._data.__getattr__(name)

    def __setattr__(self, name, value):
        if name[0] == '_':
            return object.__setattr__(self, name, value)

        if isinstance(value, np.ndarray) and value.shape != ():
            if name not in self._data.variables:
                if len(value.shape) == len(self._shape) and \
                        np.all(np.array(value.shape) == np.array(self._shape)):
                    self._data.createVariable(name, 'f8', (
                        'nx',
                        'ny',
                    ))
                else:
                    raise RuntimeError('Not sure how to guess NetCDF type for '
                                       'field "{0}" which is a numpy ndarray '
                                       'with type {1} and shape {2}.'.format(
                                           name, value.dtype, value.shape))

            self._data.variables[name][:, :] = value
            return

        return self._data.__setattr__(name, value)

    def __setitem__(self, i, value):
        if isinstance(i, str):
            return self.__setattr__(i, value)
        raise RuntimeError('Cannot set full frame.')

    def __getitem__(self, i):
        if isinstance(i, str):
            return self.__getattr__(i)
        if isinstance(i, slice):
            return [
                NetCDFContainerFrame(self, j)
                for j in range(*i.indices(len(self)))
            ]
        return NetCDFContainerFrame(self, i)

    def __iter__(self):
        for i in range(len(self)):
            yield NetCDFContainerFrame(self, i)

    def get_size(self):
        return self._shape

    def sync(self):
        self._data.sync()

    def __str__(self):
        return self._fn
Ejemplo n.º 7
0
from pupynere import NetCDFFile
from matplotlib.toolkits.basemap import Basemap, cm
import pylab, copy
from matplotlib import rcParams

# make tick labels smaller
rcParams['xtick.labelsize'] = 9
rcParams['ytick.labelsize'] = 9

# plot rainfall from NWS using special precipitation
# colormap used by the NWS, and included in basemap.

nc = NetCDFFile('nws_precip_conus_20061222.nc')
# data from http://www.srh.noaa.gov/rfcshare/precip_analysis_new.php
prcpvar = nc.variables['amountofprecip']
data = 0.01 * prcpvar[:]
data = pylab.clip(data, 0, 10000)
latcorners = nc.variables['lat'][:]
loncorners = -nc.variables['lon'][:]
plottitle = prcpvar.long_name + ' for period ending ' + prcpvar.dateofdata
print data.min(), data.max()
print latcorners
print loncorners
print plottitle
print data.shape
lon_0 = -nc.variables['true_lon'].getValue()
lat_0 = nc.variables['true_lat'].getValue()
# create polar stereographic Basemap instance.
m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\
            llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\
            llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\
Ejemplo n.º 8
0
# -*- coding: utf-8 -*-

from pupynere import NetCDFFile
from PyFuncemeClimateTools import CreateNetCDF

f = NetCDFFile(
    "/home/rodrigues/AmbientePython27/lib/python2.7/site-packages/PyFuncemeClimateTools/examples/pcp-daily-total-ec4amip_8908JFM.nc",
    "r",
)

myvar = f.variables["pcp"][:]
lons = f.variables["longitude"][:]
lats = f.variables["latitude"][:]

f.close()

CreateNetCDF.create_netcdf(myvar, lons, lats, varname="precip", varunits="mm", ntime=20)