def setup_class(cls): # Generate a scalar field and a corresponding EOF solution for the # standard numpy array interface. cls.sf, cls.eofs, cls.pcs = reference_solution('cdms2') cls.neofs = cls.eofs.shape[0] # Create an Eof for the scalar field. cls.eofobj = Eof(cls.sf)
def setup_class(cls): # Generate a scalar field and a corresponding EOF solution for the # cdms2 interface. try: cls.sf, cls.eofs, cls.pcs = reference_solution('cdms2') except ValueError: raise SkipTest('library component not available') # Create an Eof instance with the scalar field. cls.eofobj = Eof(cls.sf)
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np from eof2 import Eof # Read SST anomalies using the cdms2 module from CDAT. The file contains # November-March averages of SST anomaly in the central and northern Pacific. ncin = cdms2.open("../../example_data/sst_ndjfm_anom.nc") sst = ncin("sst") ncin.close() # Create an EOF solver to do the EOF analysis. Square-root of cosine of # latitude weights are applied before the computation of EOFs. solver = Eof(sst, weights="coslat") # Retrieve the leading EOF, expressed as the correlation between the leading # PC time series and the input SST anomalies at each grid point, and the # leading PC time series itself. eof1 = solver.eofsAsCorrelation(neofs=1) pc1 = solver.pcs(npcs=1, pcscaling=1) # Plot the leading EOF expressed as correlation in the Pacific domain. m = Basemap(projection="cyl", llcrnrlon=120, llcrnrlat=-20, urcrnrlon=260, urcrnrlat=60) lons, lats = eof1.getLongitude()[:], eof1.getLatitude()[:] x, y = m(*np.meshgrid(lons, lats)) clevs = np.linspace(-1, 1, 11) m.contourf(x, y, eof1(squeeze=True), clevs, cmap=plt.cm.RdBu_r) m.drawcoastlines() m.drawparallels([-20, 0, 20, 40, 60])
# Read geopotential height data using the cdms2 module from CDAT. The file # contains December-February averages of geopotential height at 500 hPa for # the European/Atlantic domain (80W-40E, 20-90N). ncin = cdms2.open('../../example_data/hgt_djf.nc', 'r') z_djf = ncin('z') ncin.close() # Compute anomalies by removing the time-mean. z_djf_mean = cdutil.averager(z_djf, axis='t') z_djf = z_djf - z_djf_mean z_djf.id = 'z' # Create an EOF solver to do the EOF analysis. Square-root of cosine of # latitude weights are applied before the computation of EOFs. solver = Eof(z_djf, weights='coslat') # Retrieve the leading EOF, expressed as the covariance between the leading PC # time series and the input SLP anomalies at each grid point. eof1 = solver.eofsAsCovariance(neofs=1) # Plot the leading EOF expressed as covariance in the European/Atlantic domain. m = Basemap(projection='ortho', lat_0=60., lon_0=-20.) lons, lats = eof1.getLongitude()[:], eof1.getLatitude()[:] x, y = m(*np.meshgrid(lons, lats)) m.contourf(x, y, eof1(squeeze=True), cmap=plt.cm.RdBu_r) m.drawcoastlines() m.drawparallels(np.arange(-80, 90, 20)) m.drawmeridians(np.arange(0, 360, 20)) plt.title('EOF1 expressed as covariance', fontsize=16)
def genEofVars(infiles, outfile, eobjf=True, latitude=(-30, 30, 'cob'), NEOF=4, season='all', year=None, **kwarg): """ """ eofobj_endname = kwarg.get('eofobj_endname', None) for name, varName, infile in infiles: if season == 'all': f = cdms2.open(infile) if year: # add the time axis year statements here in future. data = f(varName, time=year, latitude=latitude) else: data = f(varName, latitude=latitude) # end of if year: elif season == 'sum': data = timeobj.getSummerData(varName, infile, latitude=latitude, year=year) elif season == 'win': data = timeobj.getWinterData(varName, infile, latitude=latitude, year=year, cyclic=True) else: raise ValueError("arg 'season' must be either 'all/sum/win' only") # end of if season == 'all': data = data(squeeze=1) cdutil.setSlabTimeBoundsDaily(data) print "Multiplying coslat with data of %s for %s" % (name, season) lat = data.getLatitude() coslat = _coslat_weights(lat) for l in range(len(lat)): data[:, l] *= coslat[l] # end of for l in range(len(lat)): print "Doing EOF of %s for %s" % (name, season) eofobj = Eof(data, weights=None) if eobjf: # generate the eofobj binary file name and its path path = os.path.dirname(outfile) eofobj_filename = ['eofobj', 'level1', name, season] eofobj_filename = '_'.join(eofobj_filename) if eofobj_endname: eofobj_filename += '_' + eofobj_endname eofobj_filename += '.pkl' # end of if not eofobj_filename: eofobj_fpath = os.path.join(path, eofobj_filename) # store the eofobj into binary file using pickle module objf = open(eofobj_fpath, 'wb') pickle.dump(eofobj, objf, 2) comment = '' pickle.dump(comment, objf, 2) objf.close() print "Saved the eofobj in", eofobj_fpath # end of if eobjf: pcts = eofobj.pcs(pcscaling=0, npcs=2) eof_data = eofobj.eofs(neofs=NEOF, eofscaling=2) per_exp = eofobj.varianceFraction(neigs=NEOF) * 100 pcts.id = '_'.join(['pcs', name, season]) pcts.comment = '' per_exp.id = '_'.join(['per_exp', name, season]) per_exp.comment = '' eof_data.id = '_'.join(['eof', name, season]) eof_data.comment = '' out = cdms2.open(outfile, 'a') out.write(pcts) out.write(per_exp) out.write(eof_data) out.close() # make memory free del data, pcts, per_exp, eof_data, lat # for name, varName, infile in infiles: print "Saved the eof_vars_*.nc file in", outfile
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np from eof2 import Eof # Read SST anomalies using the cdms2 module from CDAT. The file contains # November-March averages of SST anomaly in the central and northern Pacific. ncin = cdms2.open('../../example_data/sst_ndjfm_anom.nc') sst = ncin('sst') ncin.close() # Create an EOF solver to do the EOF analysis. Square-root of cosine of # latitude weights are applied before the computation of EOFs. solver = Eof(sst, weights='coslat') # Retrieve the leading EOF, expressed as the correlation between the leading # PC time series and the input SST anomalies at each grid point, and the # leading PC time series itself. eof1 = solver.eofsAsCorrelation(neofs=1) pc1 = solver.pcs(npcs=1, pcscaling=1) # Plot the leading EOF expressed as correlation in the Pacific domain. m = Basemap(projection='cyl', llcrnrlon=120, llcrnrlat=-20, urcrnrlon=260, urcrnrlat=60) lons, lats = eof1.getLongitude()[:], eof1.getLatitude()[:] x, y = m(*np.meshgrid(lons, lats)) clevs = np.linspace(-1, 1, 11) m.contourf(x, y, eof1(squeeze=True), clevs, cmap=plt.cm.RdBu_r) m.drawcoastlines()