Beispiel #1
0
    def __init__(self, axis, source_axis=None, parent=None):
        super(AxisBoundsChooser, self).__init__(parent=parent)
        if source_axis is not None:
            self.axis = source_axis
        else:
            self.axis = axis
        l = QtGui.QVBoxLayout()
        l.addWidget(header_label(axis.id))

        if source_axis is not None:
            minimum, maximum = (float(num) for num in genutil.minmax(source_axis))
            bottom, top = (float(num) for num in genutil.minmax(axis))
            for i, v in enumerate(source_axis):
                if v == bottom:
                    bot_ind = i
                if v == top:
                    top_ind = i
            self.range = RangeWidget(axis_values(source_axis), bottom=bot_ind, top=top_ind)
        else:
            minimum, maximum = (float(num) for num in genutil.minmax(axis))
            self.range = RangeWidget(axis_values(axis))

        l.addWidget(self.range)
        self.setLayout(l)

        emitter = partial(self.boundsEdited.emit, self.axis)

        self.range.boundsEdited.connect(emitter)
Beispiel #2
0
    def __init__(self, axis, source_axis=None, parent=None):
        super(AxisBoundsChooser, self).__init__(parent=parent)
        if source_axis is not None:
            self.axis = source_axis
        else:
            self.axis = axis
        l = QtGui.QVBoxLayout()
        l.addWidget(header_label(axis.id))

        if source_axis is not None:
            minimum, maximum = (float(num)
                                for num in genutil.minmax(source_axis))
            bottom, top = (float(num) for num in genutil.minmax(axis))
            for i, v in enumerate(source_axis):
                if v == bottom:
                    bot_ind = i
                if v == top:
                    top_ind = i
            self.range = RangeWidget(axis_values(source_axis),
                                     bottom=bot_ind,
                                     top=top_ind)
        else:
            minimum, maximum = (float(num) for num in genutil.minmax(axis))
            self.range = RangeWidget(axis_values(axis))

        l.addWidget(self.range)
        self.setLayout(l)

        emitter = partial(self.boundsEdited.emit, self.axis)

        self.range.boundsEdited.connect(emitter)
Beispiel #3
0
    def extrema(self):
        """ Extraction des valeurs minimum et maximum dans les champs modelises et observes """
        from genutil import minmax

        self.model.extrema = minmax(self.model)
        self.obs.extrema = minmax(self.obs)

        # Affichage du resultat
        m = str(self.model.extrema)
        o = str(self.obs.extrema)
Beispiel #4
0
    def extrema(self):
        """ Extraction des valeurs minimum et maximum dans les champs modelises et observes """
        from genutil import minmax

        self.model.extrema=minmax(self.model)
        self.obs.extrema=minmax(self.obs)

        # Affichage du resultat
        m=str(self.model.extrema)
        o=str(self.obs.extrema)
Beispiel #5
0
    def setupVariableAxes(self):
        """ Iterate through the variable's axes and create and initialize an Axis
        object for each axis.
        """
        if self.var is None:
            return
        
        if (self.axisList is None):
            if self.cdmsFile is None:
                self.axisList = self.var.getAxisList()
                self.grid=self.var.getGrid()
            else:
                try:
                    self.axisList = self.cdmsFile[self.var].getAxisList()
                    self.grid=self.cdmsFile[self.var].getGrid()
                except:
                    ## Ok this is probably a simple axis
                    self.axisList=[self.cdmsFile[self.var],]
                    self.grid=None
            self.axisOrder = range(len(self.axisList))

        self.clear()            
        self.setAxesNames()
        
        # Iterate through the variables axes & init each axis widget
        axisIndex = 0
        didVirtual=False
        for axis, axisName in zip(self.axisList, self.axesNames):
            virtual = 0
            if  isinstance(self.grid,(cdms2.hgrid.AbstractHorizontalGrid,cdms2.gengrid.AbstractHorizontalGrid)) and axis in self.grid.getLatitude().getAxisList():
                    virtual = -1
                    if didVirtual is False:
                        didVirtual=True
                        minLat,maxLat=genutil.minmax(self.grid.getLatitude())
                        minLon,maxLon=genutil.minmax(self.grid.getLongitude())
                        vLat=cdms2.createAxis(numpy.arange(numpy.floor(minLat),numpy.ceil(maxLat)+.1,.1),id="latitude")
                        vLon=cdms2.createAxis(numpy.arange(numpy.floor(minLon),numpy.ceil(maxLon)+.1,.1),id="longitude")
                        virtualLatWidget=QAxis(vLat, "latitude", axisIndex, self,virtual=1)
                        virtualLonWidget=QAxis(vLon, "longitude", axisIndex, self,virtual=2)
                        self.axisWidgets.append(virtualLatWidget)
                        self.axisWidgets.append(virtualLonWidget)
            # Create the axis widget
            # Virtual: 0: Not virtual
            #         -1: options to switch to virtual
            #          1: is latitude virtual needs option to switch back
            #          2: is longitude virtual needs option to switch back
            axisWidget = QAxis(axis, axisName, axisIndex, self,virtual=virtual)
            self.axisWidgets.append(axisWidget)
            axisIndex += 1
        self.gridLayout.setRowStretch(self.gridLayout.rowCount(), 1)
Beispiel #6
0
    def scan_rois(self, variables):
        self.rois = {}

        for var in variables:
            lat, lon = None, None
            for axis in var.getAxisList():
                if axis.isLatitude():
                    lat = axis
                elif axis.isLongitude():
                    lon = axis
            lat_range = minmax(lat)
            lon_range = minmax(lon)
            roi = (lat_range, lon_range)
            roi_vars = self.rois.get(roi, [])
            roi_vars.append(var)
            self.rois[roi] = roi_vars
Beispiel #7
0
    def scan_rois(self, variables):
        self.rois = {}

        for var in variables:
            lat, lon = None, None
            for axis in var.getAxisList():
                if axis.isLatitude():
                    lat = axis
                elif axis.isLongitude():
                    lon = axis
            lat_range = minmax(lat)
            lon_range = minmax(lon)
            roi = (lat_range, lon_range)
            roi_vars = self.rois.get(roi, [])
            roi_vars.append(var)
            self.rois[roi] = roi_vars
Beispiel #8
0
def vminmax(data, asdict=False, symetric=False):
    """Get min and max of dict, list, tuple, array"""
    if isinstance(data, dict):
        vmin, vmax  = vminmax(data.values())
    else:
        vmin, vmax = minmax(data)
    if symetric:
        vmax = min(abs(vmin), abs(vmax))
        vmin = -vmax
    if asdict:
        return dict(vmin=vmin, vmax=vmax)
    return vmin, vmax
Beispiel #9
0
C=genutil.array_indexing.extract(A,B)
print C,C.dtype.char
C=genutil.arrayindexing.get(A,B)
print C,C.dtype.char

f=cdms2.open(os.path.join(cdms2.__path__[0],'..','..','..','..','sample_data','clt.nc'))
clt=f('clt')
## clt=cdms2.MV2.average(clt,2)
print clt.shape

M=numpy.ma.maximum.reduce(clt,axis=0)
marg=numpy.ma.argmax(clt,axis=0)
M2=genutil.arrayindexing.get(clt,marg)

print M2.shape,M2.mask,genutil.minmax(M2-M)

M=numpy.ma.maximum.reduce(clt,axis=1)
marg=numpy.ma.argmax(clt,axis=1)
marg=cdms2.MV2.array(marg)
marg.setAxis(0,clt.getAxis(0))
marg.setAxis(1,clt.getAxis(2))
print clt.dtype.char,M.shape
M2=genutil.arrayindexing.get(clt,marg,axis=1)

print M2.shape,M2.mask,genutil.minmax(M2-M)

clt=cdms2.MV2.masked_greater(clt,80)
M=numpy.ma.maximum.reduce(clt,axis=1)
print M.mask,'is the mask'
marg=numpy.ma.argmax(clt,axis=1)
from cdms_utils.cdms_compat import *
import cdms_utils.var_utils as vu
import genutil as g

fin = cdms.open(
    "/disks/archive/real/prob_land_cc/grid_box_25km/2060-2089/prob_land_cc_grid_box_25km_may_2060-2089_mslp_dmean_tmean_abs.nc"
)
v = fin("cdf_mslp_dmean_tmean_abs")


def p(v):
    print v.shape
    print v.getAxisIds()


p(v)

x = vu.cleverSqueeze(v)
p(x)

y = vu.cleverSqueeze(v, ["meaning_period"])
p(y)

print "SAME?"
d = y(squeeze=1) - x
p(d)
print g.minmax(d)
Beispiel #11
0
def Es(T, method=None):
    """Computes saturated pressure in Pa given T in K, using the method:
    1: Hyland-Wexler formulation, polynomial coeff (absolute norm)
    2: Wexler formulation
    3: Hyland-Wexler formulation, polynomial coeff (relative error norm)
    4: classic Goff Gratch equation
    5: 6.112*numpy.ma.exp(17.67*tempc/(tempc+243.5))

    Default is method 1

    Note: 1 and 2 use method 3 where T is not : 173.15 < T < 473.15
    ref for 1, 2 and 3:
    Piotr Flatau and al., Journal of Applied Met., Vol 31, Dec 1992
    ( http://ams.allenpress.com/perlserv/?request=get-document&\
doi=10.1175%2F1520-0450(1992)031%3C1507%3APFTSVP%3E2.0.CO%3B2&ct=1 )
    """
    if method is None:
        method = 1

    if method == 1:
        # Put in C
        x = T - 273.15
        # Water vapor
        c0 = 0.611220713e03
        c1 = 0.443944344e02
        c2 = 0.143195336e01
        c3 = 0.263350515e-01
        c4 = 0.310636053e-03
        c5 = 0.185218710e-05
        c6 = 0.103440324e-07
        c7 = -0.468258100e-10
        c8 = 0.466533033e-13
        eswat = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * c8)))))))
        # ice
        c0 = 0.611153246e03
        c1 = 0.503261230e02
        c2 = 0.188595709e01
        c3 = 0.422115970e-01
        c4 = 0.620376691e-03
        c5 = 0.616082536e-05
        c6 = 0.405172828e-07
        c7 = 0.161492905e-09
        c8 = 0.297886454e-12
        esice = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * c8)))))))
        # Combine
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        # Overwrite values outside valid range with method 2
        mn, mx = genutil.minmax(T)
        if mn < 173.16 or mx > 473.15:
            es2 = Es(T, method=2)
            es = MV2.where(MV2.less(T, 173.16), es2, es)
            es = MV2.where(MV2.greater(T, 473.15), es2, es)
    elif method == 2:
        # over water
        g0 = -0.29912729e4
        g1 = -0.60170128e4
        g2 = 0.1887643854e2
        g3 = -0.28354721e-1
        g4 = 0.17838301e-4
        g5 = -0.84150417e-9
        g6 = 0.44412543e-12
        g7 = 0.2858487e1
        # over ice
        k0 = -0.58653696e4
        k1 = 0.2224103300e2
        k2 = 0.13749042e-1
        k3 = -0.34031775e-4
        k4 = 0.26967687e-7
        k5 = 0.6918651
        esice = (k0 + (k1 + k5 * MV2.log(T) + (k2 + (k3 + k4 * T) * T) * T) * T) / T  # over ice
        eswat = (
            g0 + (g1 + (g2 + g7 * MV2.log(T) + (g3 + (g4 + (g5 + g6 * T) * T) * T) * T) * T) * T
        ) / T ** 2  # over water
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        es = MV2.exp(es)
    elif method == 3:
        # Put in C
        x = T - 273.15
        # Water vapor
        c0 = 0.611213476e03
        c1 = 0.444007856e02
        c2 = 0.143064234e01
        c3 = 0.264461437e-01
        c4 = 0.305930558e-03
        c5 = 0.196237241e-05
        c6 = 0.892344772e-08
        c7 = -0.373208410e-10
        c8 = 0.209339997e-13
        eswat = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * c8)))))))
        # ice
        c0 = 0.611123516e03
        c1 = 0.503109514e02
        c2 = 0.1888369801e01
        c3 = 0.420547422e-01
        c4 = 0.614396778e-03
        c5 = 0.602780717e-05
        c6 = 0.387940929e-07
        c7 = 0.149436277e-09
        c8 = 0.262655803e-12
        esice = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * c8)))))))
        # Combine
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        # Overwrite values outside valid range with method 2
        mn, mx = genutil.minmax(T)
        if mn < 173.16 or mx > 473.15:
            es2 = Es(T, method=2)
            es = MV2.where(MV2.less(T, 173.16), es2, es)
            es = MV2.where(MV2.greater(T, 473.15), es2, es)
    elif method == 4:
        est = 101324.6  # Pa
        Ts = 373.16 / T
        a = -7.90298
        b = 5.02808
        c = -1.3816e-7
        d = 11.344
        f = 8.1328e-3
        h = -3.49149
        maxexp = int(numpy.log10(numpy.finfo(numpy.float).max))
        minexp = 1 - a
        es = a * (Ts - 1.0)
        es = es + b * numpy.ma.log10(Ts)
        A = d * (1.0 - Ts)
        A = numpy.ma.masked_greater(A, maxexp)
        A = numpy.ma.masked_less(A, minexp)
        es = es + c * (numpy.ma.power(10, A) - 1.0)
        A = h * (Ts - 1.0)
        A = numpy.ma.masked_greater(A, maxexp)
        A = numpy.ma.masked_less(A, minexp)
        es = es + f * (numpy.ma.power(10, A) - 1.0)
        es = est * numpy.ma.power(10, es)
    elif method == 5:
        tempc = T - 273.15
        es = 611.2 * numpy.ma.exp(17.67 * tempc / (tempc + 243.5))
    return es
Beispiel #12
0
# Adapted for numpy/ma/cdms2 by convertcdms.py
import sys
import MSU,cdms2


f=cdms2.open('../Data/ta.nc')
ta=f('ta',longitude=(0,360,'co'))
f.close()
f=cdms2.open('../Data/weights.nc')
w=f('weights')
f.close()
critw=0.5 # 50% of data required

msu=MSU.msu(ta,w,critw)

f=cdms2.open('../Data/tam2.nc')
goodtam2=f('tam2',longitude=(0,360,'co'))
f.close()
tam2=msu[...,0]
diff=tam2-goodtam2
import genutil
print genutil.minmax(diff)
if not cdms2.MV2.allclose(tam2,goodtam2):
    raise 'Error in MSU module, wrong result outputed for tam2, check if they are very different form 0, could be machine precision error'
else:
    print 'MSU seems ok, congratulations!'
from cdms_utils.cdms_compat import *
import cdms_utils.var_utils as vu
import genutil as g

fin = cdms.open("/disks/archive/real/prob_land_cc/grid_box_25km/2060-2089/prob_land_cc_grid_box_25km_may_2060-2089_mslp_dmean_tmean_abs.nc")
v = fin("cdf_mslp_dmean_tmean_abs")

def p(v):
 print v.shape
 print v.getAxisIds()

p(v)

x = vu.cleverSqueeze(v)
p(x)

y = vu.cleverSqueeze(v, ["meaning_period"])
p(y)

print "SAME?"
d = y(squeeze=1) - x
p(d)
print g.minmax(d)
Beispiel #14
0
# Adapted for numpy/ma/cdms2 by convertcdms.py
import sys
import MSU, cdms2

f = cdms2.open('../Data/ta.nc')
ta = f('ta', longitude=(0, 360, 'co'))
f.close()
f = cdms2.open('../Data/weights.nc')
w = f('weights')
f.close()
critw = 0.5  # 50% of data required

msu = MSU.msu(ta, w, critw)

f = cdms2.open('../Data/tam2.nc')
goodtam2 = f('tam2', longitude=(0, 360, 'co'))
f.close()
tam2 = msu[..., 0]
diff = tam2 - goodtam2
import genutil

print genutil.minmax(diff)
if not cdms2.MV2.allclose(tam2, goodtam2):
    raise 'Error in MSU module, wrong result outputed for tam2, check if they are very different form 0, could be machine precision error'
else:
    print 'MSU seems ok, congratulations!'
Beispiel #15
0
select = cdms2.selectors.Selector(lon=slice(0, 3), time=('1950', cdtime.comptime(1960)))
print u(equator)(select).shape
#  -> appliquez à la lecture du fichier






# Le module genutil : utilitaires generiques

# - contenu
import genutil
print dir(genutil)

# - statistics standards
print dir(genutil.statistics)
ustd = genutil.statistics.std(u, axis=0)                # testez les options
ustd.info()
print N.ma.allclose(ustd, u.std(axis=0))

# - salstat
print dir(genutil.salstat)
print genutil.salstat.kurtosis(u, axis='t')             # essayez d'autres fonctions

# - divers
_, uu = genutil.grower(u, u[0])                         # testez d'autres slices
print uu.shape
print genutil.minmax(u, u**2)
print u[:, 0, 0](genutil.picker(time=['1960-01-03', '1965-05-03'])) # testez option match
Beispiel #16
0
print C, C.dtype.char
C = genutil.arrayindexing.get(A, B)
print C, C.dtype.char

f = cdms2.open(
    os.path.join(cdms2.__path__[0], '..', '..', '..', '..', 'sample_data',
                 'clt.nc'))
clt = f('clt')
## clt=cdms2.MV2.average(clt,2)
print clt.shape

M = numpy.ma.maximum.reduce(clt, axis=0)
marg = numpy.ma.argmax(clt, axis=0)
M2 = genutil.arrayindexing.get(clt, marg)

print M2.shape, M2.mask, genutil.minmax(M2 - M)

M = numpy.ma.maximum.reduce(clt, axis=1)
marg = numpy.ma.argmax(clt, axis=1)
marg = cdms2.MV2.array(marg)
marg.setAxis(0, clt.getAxis(0))
marg.setAxis(1, clt.getAxis(2))
print clt.dtype.char, M.shape
M2 = genutil.arrayindexing.get(clt, marg, axis=1)

print M2.shape, M2.mask, genutil.minmax(M2 - M)

clt = cdms2.MV2.masked_greater(clt, 80)
M = numpy.ma.maximum.reduce(clt, axis=1)
print M.mask, 'is the mask'
marg = numpy.ma.argmax(clt, axis=1)
Beispiel #17
0
	def bwr():
		cdict = {'red': ((0.,)*3,(.5,1.,1.),(1.,1.,1.)),
			'green': ((0.,)*3,(.5,1.,1.),(1.,0.,0.)),
			'blue': ((0.,1.,1.),(.5,1.,1.),(1.,0.,0.))}
		return matplotlib.colors.LinearSegmentedColormap('bwr',cdict,256)

	figure(figsize=(8,8))
	subplot(ncol,nrow,nslice)
	for i in xrange(nslice):
		lon = composites.getLongitude()
		lat = composites.getLatitude()
		xx,yy = meshgrid(lon,lat)
		m = Basemap(resolution='l',lat_0=N.average(lat),lon_0=N.average(lon),
			llcrnrlon=min(lon),llcrnrlat=min(lat),
			urcrnrlon=max(lon),urcrnrlat=max(lat))
		levels = vcs.mkscale(genutil.minmax(composites))
		m.contourf(lon,lat,composites[i],levels=levels,cmap=bwr)
		clabel(m.contour(lon,lat,composites[i],levels=levels))
		title("Phase %i/%i" (i+1,6))
		m.drawcoastlines()
		m.drawcountries()
		m.fillcontinents(color='coral')
		m.drawparallels(vcs.mkscale(genutil.minmax(lat)),labels=[1,0,0,0])
		m.drawmeridians(vcs.mkscale(genutil.minmax(lon)),labels=[0,0,0,1])
	figtext(.5,1.,"\n%s [%s]" % ("El Nino phase composites\nSea surface temperature", composites.units))
	savefig(sys.argv[0].replace(".py",".png"))
	show()
	

# Fall back to vcs because we have it!
except:
xe_nea = interp1d(xe, new_time, method='nearest')
xe_nea.long_name = 'Nearest'
# - linear
xe_lin = interp1d(xe, new_time, method='linear')
xe_lin.long_name = 'Linear'
# - cubic
xe_cub = interp1d(xe, new_time, method='cubic')
xe_cub.long_name = 'Cubic'

# Plots
from matplotlib import rcParams ; rcParams['font.size'] = 8
import pylab as P
from vacumm.misc.plot import yhide, xscale, savefigs, hov2, curve2
from vacumm.misc.color import cmap_jets
from genutil import minmax
vmin, vmax = minmax(xe, xe_lin)
kwplot = dict(vmin=vmin, vmax=vmax, show=False)
kwhov = dict(kwplot)
kwhov.update(cmap=cmap_jets(stretch=-.4), colorbar=False, xrotation=25.)
kwcurve = dict(kwplot)
kwcurve.update(transpose=True, color='r', yhide=True)
kwplot.update(order = '-d', title=True)
kwhov['date_fmt'] = '%Hh'
# - original
#print xe.getTime().asComponentTime()
hov2(xe, subplot=421, top=.95, hspace=.45, figsize=(5.5, 8), bottom=.06, **kwhov)
axlims = P.axis()
curve2(xe[:, 15], 'o', subplot=422, **kwcurve)
xscale(1.1, keep_min=1)
# - nearest
hov2(xe_nea, subplot=423, **kwhov)
xe_nea.long_name = 'Nearest'
# - linear
xe_lin = interp1d(xe, new_time, method='linear')
xe_lin.long_name = 'Linear'
# - cubic
xe_cub = interp1d(xe, new_time, method='cubic')
xe_cub.long_name = 'Cubic'

# Plots
from matplotlib import rcParams
rcParams['font.size'] = 8
import pylab as P
from vacumm.misc.plot import yhide, xscale, savefigs, hov2, curve2
from vacumm.misc.color import cmap_jets
from genutil import minmax
vmin, vmax = minmax(xe, xe_lin)
kwplot = dict(vmin=vmin, vmax=vmax, show=False)
kwhov = dict(kwplot)
kwhov.update(cmap=cmap_jets(stretch=-.4), colorbar=False, xrotation=25.)
kwcurve = dict(kwplot)
kwcurve.update(transpose=True, color='r', yhide=True)
kwplot.update(order='-d', title=True)
kwhov['date_fmt'] = '%Hh'
# - original
#print xe.getTime().asComponentTime()
hov2(xe,
     subplot=421,
     top=.95,
     hspace=.45,
     figsize=(5.5, 8),
     bottom=.06,
Beispiel #20
0
def plot_bathy(bathy, shadow=True, contour=True, shadow_stretch=1., shadow_shapiro=False,
    show=True, shadow_alpha=1., shadow_black=.3, white_deep=False, nmax=30,m=None, alpha=1.,
    zmin=None, zmax=None, **kwargs):
    """Plot a bathymetry

    - *lon*: Longitude range.
    - *lat*: Latitude range.
    - *show*:Display the figure [default: True]
    - *pcolor*: Use pcolor instead of contour [default: False]
    - *contour*: Add line contours [default: True]
    - *shadow*:Plot south-west shadows instead of filled contours.
    - *nmax*: Max number of levels for contours [default: 30]
    - *white_deep*: Deep contours are white [default: False]
    - All other keyword are passed to :func:`~vacumm.misc.plot.map2`
    """

    # Input
    bb = bathy
    if isinstance(bathy, GriddedBathy):
        bathy = bathy.bathy()
        if shadow:
            xxs = getattr(bb, '_xxs', None)
            yys = getattr(bb, '_yys', None)
            if xxs is None:
                lon2d = bb._lon2d
                lat2d = bb._lat2d
    elif shadow:
        xxs = yys = None
        lon2d,lat2d = meshgrid(get_axis(bathy, -1).getValue(),get_axis(bathy, -2).getValue())

    # Masking
    if 'maxdep' in kwargs:
        zmin = -maxdep
    if 'maxalt' in kwargs:
        zmax = maxalt
    if zmin is not None:
        bathy[:] = MV2.masked_less(bathy, zmin)
    if zmax is not None:
        bathy[:] = MV2.masked_greater(bathy, zmax)

    # Default arguments for map
    if hasattr(bathy, 'long_name'):
        kwargs.setdefault('title',bathy.long_name)
    if 'cmap' not in kwargs:
        vmin, vmax = minmax(bathy)
#        print 'cmap topo', vmin, vmax
        kwargs['cmap'] = auto_cmap_topo((kwargs.get('vmin', vmin), kwargs.get('vmax', vmax)))
#       kwargs.setdefault('ticklabel_size','smaller')
    kwargs.setdefault('clabel_fontsize', 8)
    kwargs.setdefault('clabel_alpha',.7*alpha)
    kwargs.setdefault('clabel_glow_alpha', kwargs['clabel_alpha'])
    kwargs.setdefault('fill', 'contourf')
    kwargs['nmax'] = nmax
    kwargs['show'] = False
    kwargs['contour'] = contour
    if shadow: kwargs.setdefault('alpha',.5*alpha)
    kwargs.setdefault('projection', 'merc')
    kwargs.setdefault('fmt', BathyFormatter())
    kwargs.setdefault('colorbar_format', BathyFormatter())
    kwargs.setdefault('units', False)
    kwargs.setdefault('levels_mode','normal')
    kwargs.setdefault('bgcolor', '0.8')
    kwargs.setdefault('contour_linestyle', '-')
    savefig = kwargs.pop('savefig', None)
    kwsavefig = kwfilter(kwargs, 'savefig_')


    # White contour when dark
    if contour and white_deep:
        levels = auto_scale(bathy,nmax=nmax)
        colors = []
        nlevel = len(levels)
        for i in range(nlevel):
            if i < old_div(nlevel,2):
                colors.append('w')
            else:
                colors.append('k')
        kwargs.setdefault('contour_colors',tuple(colors))

    # Call to map
    m = map2(bathy, m=m, **kwargs)

    # Add shadow
    if shadow:

        # Filter
        data = MV.array(bathy,'f',fill_value=0.)
        if shadow_shapiro:
            data = shapiro2d(data,fast=True).shape

        # Gradient
        grd = deriv2d(data,direction=45.,fast=True,fill_value=0.).filled(0.)
        grdn = refine(grd, 3)
        grdn = norm_atan(grdn,stretch=shadow_stretch).clip(0,1.) ; del grd

        # Grid
#           im = m.map.imshow(grdn,cmap=P.get_cmap('gist_yarg'),alpha=1) # gist_yarg , YlGnBu
        if xxs is None or yys is None:
            xx, yy = m(lon2d,lat2d)
            xxr = refine(xx, 3)
            yyr = refine(yy, 3)
            xxs, yys = meshbounds(xxr, yyr)
            if isinstance(bb, GriddedBathy):
                bb._xxs = xxs
                bb._yys = yys
            del xx, yy, xxr, yyr

        # Cmap
        cmap = cmap_custom(( ((1, )*3, 0), ((shadow_black, )*3, 1) ))

        # Plot
        pp = m.map.pcolormesh(xxs, yys, grdn,cmap=cmap)#P.get_cmap('gist_yarg'))
        pp.set_zorder(.9)
        pp.set_linewidth(0)
        pp.set_alpha(shadow_alpha*N.clip(alpha*2, 0, 1))
        del grdn

    # Show it?
    if savefig:
        m.savefig(savefig, **kwsavefig)
    if show:
        P.show()
    return m
        lon_id, lon_val = find_nearest(lond, lon1[i])
        #print('lat_id = ',lat_id, lat_val, 'lon_id=',lon_id, lon_val)

        a = int(lat_id)
        b = int(lon_id)

        if deltat[a, b] != 0:
            print('-------------')
            print('i=', i, 'lat1=', lat1[i], 'lon1=', lon1[i])
            print('lat_id = ', lat_id, lat_val, 'lon_id=', lon_id, lon_val,
                  'a=', a, 'b=', b)
            print('deltat is', deltat[a, b])
            print('/////')

            for ilev in range(nlev):
                if TSOI_r[i, ilev] != 0:
                    TSOI_new1[i, ilev] = TSOI_r[i, ilev] + deltat[a, b]

                print('ilev = ', ilev, \
                        'TSOI_r = ',TSOI_r[i,ilev],\
                        'TSOI_new1 = ', TSOI_new1[i,ilev])

TSOI_new1.id = 'T_SOISNO'
TSOI_new1.setAxisList(TSOI_r.getAxisList())

diff1 = TSOI_new1 - TSOI_r
print(genutil.minmax(diff1))

f3.write(TSOI_new1)
f3.close()
Beispiel #22
0
def Es(T, method=None):
    """Computes saturated pressure in Pa given T in K, using the method:
    1: Hyland-Wexler formulation, polynomial coeff (absolute norm)
    2: Wexler formulation
    3: Hyland-Wexler formulation, polynomial coeff (relative error norm)
    4: classic Goff Gratch equation
    5: 6.112*numpy.ma.exp(17.67*tempc/(tempc+243.5))

    Default is method 1
    
    Note: 1 and 2 use method 3 where T is not : 173.15 < T < 473.15
    ref for 1, 2 and 3:
    Piotr Flatau and al., Journal of Applied Met., Vol 31, Dec 1992 ( http://ams.allenpress.com/perlserv/?request=get-document&doi=10.1175%2F1520-0450(1992)031%3C1507%3APFTSVP%3E2.0.CO%3B2&ct=1 )
    """
    if method is None:
        method = 1

    if method == 1:
        ## Put in C
        x = T - 273.15
        ## Water vapor
        c0 = 0.611220713E03
        c1 = 0.443944344E02
        c2 = 0.143195336E01
        c3 = 0.263350515E-01
        c4 = 0.310636053E-03
        c5 = 0.185218710E-05
        c6 = 0.103440324E-07
        c7 = -0.468258100E-10
        c8 = 0.466533033E-13
        eswat = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x *
                                                        (c5 + x *
                                                         (c6 + x *
                                                          (c7 + x * c8)))))))
        ## ice
        c0 = .611153246E03
        c1 = .503261230E02
        c2 = .188595709E01
        c3 = .422115970E-01
        c4 = .620376691E-03
        c5 = .616082536E-05
        c6 = .405172828E-07
        c7 = .161492905E-09
        c8 = .297886454E-12
        esice = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x *
                                                        (c5 + x *
                                                         (c6 + x *
                                                          (c7 + x * c8)))))))
        ## Combine
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        ## Overwrite values outside valid range with method 2
        mn, mx = genutil.minmax(T)
        if mn < 173.16 or mx > 473.15:
            es2 = Es(T, method=2)
            es = MV2.where(MV2.less(T, 173.16), es2, es)
            es = MV2.where(MV2.greater(T, 473.15), es2, es)
    elif method == 2:
        # over water
        g0 = -0.29912729E4
        g1 = -0.60170128E4
        g2 = 0.1887643854E2
        g3 = -0.28354721E-1
        g4 = 0.17838301E-4
        g5 = -0.84150417E-9
        g6 = 0.44412543E-12
        g7 = 0.2858487E1
        # over ice
        k0 = -0.58653696e4
        k1 = 0.2224103300E2
        k2 = 0.13749042E-1
        k3 = -0.34031775E-4
        k4 = 0.26967687E-7
        k5 = 0.6918651
        esice = (k0 + (k1 + k5 * MV2.log(T) +
                       (k2 + (k3 + k4 * T) * T) * T) * T) / T  # over ice
        eswat = (g0 + (g1 + (g2 + g7 * MV2.log(T) +
                             (g3 + (g4 + (g5 + g6 * T) * T) * T) * T) * T) *
                 T) / T**2  # over water
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        es = MV2.exp(es)
    elif method == 3:
        ## Put in C
        x = T - 273.15
        ## Water vapor
        c0 = 0.611213476E03
        c1 = 0.444007856E02
        c2 = 0.143064234E01
        c3 = 0.264461437E-01
        c4 = 0.305930558E-03
        c5 = 0.196237241E-05
        c6 = 0.892344772E-08
        c7 = -0.373208410E-10
        c8 = 0.209339997E-13
        eswat = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x *
                                                        (c5 + x *
                                                         (c6 + x *
                                                          (c7 + x * c8)))))))
        ## ice
        c0 = .611123516E03
        c1 = .503109514E02
        c2 = .1888369801E01
        c3 = .420547422E-01
        c4 = .614396778E-03
        c5 = .602780717E-05
        c6 = .387940929E-07
        c7 = .149436277E-09
        c8 = .262655803E-12
        esice = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x *
                                                        (c5 + x *
                                                         (c6 + x *
                                                          (c7 + x * c8)))))))
        ## Combine
        es = MV2.where(MV2.less(T, 273.15), esice, eswat)
        ## Overwrite values outside valid range with method 2
        mn, mx = genutil.minmax(T)
        if mn < 173.16 or mx > 473.15:
            es2 = Es(T, method=2)
            es = MV2.where(MV2.less(T, 173.16), es2, es)
            es = MV2.where(MV2.greater(T, 473.15), es2, es)
    elif method == 4:
        est = 101324.6  #Pa
        Ts = 373.16 / T
        a = -7.90298
        b = 5.02808
        c = -1.3816E-7
        d = 11.344
        f = 8.1328E-3
        h = -3.49149
        maxexp = int(numpy.log10(numpy.finfo(numpy.float).max))
        minexp = 1 - a
        es = a * (Ts - 1.)
        es = es + b * numpy.ma.log10(Ts)
        A = d * (1. - Ts)
        A = numpy.ma.masked_greater(A, maxexp)
        A = numpy.ma.masked_less(A, minexp)
        es = es + c * (numpy.ma.power(10, A) - 1.)
        A = h * (Ts - 1.)
        A = numpy.ma.masked_greater(A, maxexp)
        A = numpy.ma.masked_less(A, minexp)
        es = es + f * (numpy.ma.power(10, A) - 1.)
        es = est * numpy.ma.power(10, es)
    elif method == 5:
        tempc = T - 273.15
        es = 611.2 * numpy.ma.exp(17.67 * tempc / (tempc + 243.5))
    return es
Beispiel #23
0
        return matplotlib.colors.LinearSegmentedColormap('bwr', cdict, 256)

    figure(figsize=(8, 8))
    subplot(ncol, nrow, nslice)
    for i in xrange(nslice):
        lon = composites.getLongitude()
        lat = composites.getLatitude()
        xx, yy = meshgrid(lon, lat)
        m = Basemap(resolution='l',
                    lat_0=N.average(lat),
                    lon_0=N.average(lon),
                    llcrnrlon=min(lon),
                    llcrnrlat=min(lat),
                    urcrnrlon=max(lon),
                    urcrnrlat=max(lat))
        levels = vcs.mkscale(genutil.minmax(composites))
        m.contourf(lon, lat, composites[i], levels=levels, cmap=bwr)
        clabel(m.contour(lon, lat, composites[i], levels=levels))
        title("Phase %i/%i" (i + 1, 6))
        m.drawcoastlines()
        m.drawcountries()
        m.fillcontinents(color='coral')
        m.drawparallels(vcs.mkscale(genutil.minmax(lat)), labels=[1, 0, 0, 0])
        m.drawmeridians(vcs.mkscale(genutil.minmax(lon)), labels=[0, 0, 0, 1])
    figtext(
        .5, 1.,
        "\n%s [%s]" % ("El Nino phase composites\nSea surface temperature",
                       composites.units))
    savefig(sys.argv[0].replace(".py", ".png"))
    show()