def get_era_winds(m, rawdatapath, start_year, end_year, start_month, end_month, xyres): wind_data = Dataset(rawdatapath+'/WINDS/ERA/DATA/ERAI_WINDS_MONTHLY_1979-2014.nc', 'r') lats = wind_data.variables['latitude'][::-1] lons = wind_data.variables['longitude'][:] time = wind_data.variables['time'][:]/(24.*30.) time = time-time[0] time=time.reshape(time.shape[0]/12,12) u10 = wind_data.variables['u10'][:, ::-1, :] v10 = wind_data.variables['v10'][:, ::-1, :] u10=u10.reshape(u10.shape[0]/12, 12,u10.shape[1],u10.shape[2]) v10=v10.reshape(v10.shape[0]/12, 12, v10.shape[1],v10.shape[2]) u10_winter_mean= np.mean(u10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2))) v10_winter_mean= np.mean(v10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2))) u10_winter_meanS, lonsS = shiftgrid(180.,u10_winter_mean,lons,start=False) v10_winter_meanS, lonsS = shiftgrid(180.,v10_winter_mean,lons,start=False) u10_winter_meanSC, lonsSC = addcyclic(u10_winter_meanS, lonsS) v10_winter_meanSC, lonsSC = addcyclic(v10_winter_meanS, lonsS) xyres=100 xvel,yvel,xptsW,yptsW = m.transform_vector(u10_winter_meanSC,v10_winter_meanSC,lonsSC,lats,xyres,xyres,returnxy=True,masked=True) wind_speed = sqrt((xvel**2) + (yvel**2)) wind_speed = sqrt((xvel**2) + (yvel**2)) return xptsW, yptsW, xvel, yvel, wind_speed
def vars(self, index): var_array1 = self.f_u.variables[self.varname1][index,::-1, ::] var_array2 = self.f_v.variables[self.varname2][index,::-1, ::] var_temp1, lons_temp = shiftgrid(180.,var_array1,self.lons0,start=False) var_temp2, lons_temp = shiftgrid(180.,var_array2,self.lons0,start=False) return var_temp1, var_temp2
def updatefig(nt): global CS1,CS2,Q date = dates[nt] for c in CS1.collections: c.remove() CS1 = m.contour(x,y,slp[nt,:,:],clevs,linewidths=0.5,colors='k') for c in CS2.collections: c.remove() CS2 = m.contourf(x,y,slp[nt,:,:],clevs,cmap=plt.cm.RdBu_r) ugrid,newlons = shiftgrid(180.,u[nt,:,:],longitudes,start=False) vgrid,newlons = shiftgrid(180.,v[nt,:,:],longitudes,start=False) urot,vrot,xx,yy = m.transform_vector(ugrid,vgrid,newlons,latitudes,51,51,returnxy=True,masked=True) txt.set_text('SLP and Wind Vectors '+str(date)) Q.set_UVC(urot,vrot)
def transform(bm, args): from numpy import meshgrid, ndarray from mpl_toolkits.basemap import shiftgrid from warnings import warn # X, Y, U, V if len(args) == 4: X, Y, U, V = args U, newX = shiftgrid(180, U, X, start=False) V, newX = shiftgrid(180, V, X, start=False) #newX, Y = meshgrid(newX, Y) #UP, VP, XX, YY = bm.transform_vector(U, V, newX, Y, 31, 31, returnxy=True) UP, VP, XX, YY = bm.rotate_vector(U, V, newX, Y, returnxy=True) return XX, YY, UP, VP #TODO: finish the rest of the cases warn("Don't know what to do for the coordinate transformation") return args
def dummy_plot(ldata, lats, lons, tit, fname): plt.figure(figsize=(20,10)) m = Basemap(projection = 'robin', lon_0 = 0) data = np.zeros((ldata.shape[0],ldata.shape[1]+1)) data[:,:-1] = ldata data[:,-1] = data[:,0] llons = lons.tolist() llons.append(360) lons = np.array(llons) lat_ndx = np.argsort(lats) lats = lats[lat_ndx] data = data[lat_ndx, :] data, lons = basemap.shiftgrid(180.,data,lons,start=False) m.fillcontinents(color = "#ECF0F3", lake_color = "#A9E5FF", zorder = 0) m.drawmapboundary(fill_color = "#A9E5FF") m.drawcoastlines(linewidth = 2, color = "#333333") m.drawcountries(linewidth = 1.5, color = "#333333") m.drawparallels(np.arange(-90, 120, 30), linewidth = 1.2, labels = [1,0,0,0], color = "#222222", size = 15) m.drawmeridians(np.arange(-180, 180, 60), linewidth = 1.2, labels = [0,0,0,1], color = "#222222", size = 15) x, y = m(*np.meshgrid(lons, lats)) cs = m.contourf(x, y, data, 20, cmap = plt.get_cmap('CMRmap_r')) plt.colorbar(cs) plt.title(tit, size = 25) if fname is not None: plt.savefig(fname, bbox_inches='tight') else: plt.show()
def doplot(nc_file=None,varname=None,vmin=None,vmax=None, title=None): lons=nc_file.variables['lon'][...] lats=nc_file.variables['lat'][...] vals=nc_file.variables[varname] vals.set_auto_maskandscale(True) vals=vals[...] vals,lons=shiftgrid(180.,vals,lons,start=False) vals,lons=addcyclic(vals,lons) fig,ax = plt.subplots(1,1) ax.cla() cmap=cm.RdBu_r cmap.set_over('y') cmap.set_under('k') the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False) params=dict(projection='moll',lon_0= 0,resolution='c') m = Basemap(**params) x, y = m(*np.meshgrid(lons, lats)) im=m.pcolormesh(x,y,vals,cmap=cmap,norm=the_norm,ax=ax) cb=m.colorbar(im,extend='both',location='bottom') m.drawcoastlines() m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,420.,60.)) ax.set_title(title) return fig,m,ax,vals,lons
def plot_2Ddata_with_underlay(data_array, lons=None, lats=None): """ Plot of a 2D array on top of coast lines and country lines. """ figure() # Create the basemap instance and draw the continents # Basemap kw args: llcrnrlon = lower left corner longitude, and so on m = Basemap(llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, projection="mill") m.drawcoastlines(linewidth=1.25) m.drawcountries(linewidth=0.5) # m.fillcontinents(color='0.8') m.drawparallels(np.arange(-90, 91, 20), labels=[1, 1, 0, 0]) m.drawmeridians(np.arange(-180, 180, 60), labels=[0, 0, 0, 1]) # Shift the data by 180 in longitude to center the map on longitude=0 data_array, lon_out = shiftgrid(180, data_array, lons) # Add the data, and place origin in upper left since the origin of the numpy # array corresponds tolat = 90 and long = 0 m.imshow(data_array, origin="upper") # More complex version that involves interpolation on a grid of points in # map coordinates. # nx = int((m.xmax-m.xmin)/500.)+1; ny = int((m.ymax-m.ymin)/500.)+1 # dat_array = m.transform_scalar(data_array, lons,lats,nx,ny) # m.imshow(dat_array, origin = 'upper') # figure() # m = Basemap(projection='ortho',lon_0=-105,lat_0=40) # m.drawcoastlines(linewidth=1.25) # m.drawcountries(linewidth=0.5) # dat_transformed = m.transform_scalar(data_array, return
def __init__(self, filepath, varname): self.f = Dataset(filepath, 'r') self.varname = varname self.var_array = self.f.variables[varname][0,::-1, ::] self.lats = self.f.variables['latitude'][::-1] self.lons0 = self.f.variables['longitude'][:] var_temp, self.lons_s = shiftgrid(180.,self.var_array,self.lons0,start=False)
def apply(self): from mpl_toolkits.basemap import shiftgrid, cm common.ShowQuestion display = self.VpyartDisplay.value if (isinstance(display, pyart.graph.RadarMapDisplay) or isinstance(display, pyart.graph.GridMapDisplay)): pass elif (isinstance(display, pyart.graph.RadarDisplay) or isinstance(display, pyart.graph.AirborneRadarDisplay)): common.ShowWarning( "Topography require a MapDisplay, be sure to " "check the 'use MapDisplay' box in the 'Display Options' Menu") return else: common.ShowWarning( "Need a pyart display instance, be sure to " "link this components (%s), to a radar or grid display" % self.name) return filename = str(self.lineEdit.text()) if filename != self.current_open: if filename.startswith("http"): resp = common.ShowQuestion( "Loading a file from the internet may take long." + " Are you sure you want to continue?") if resp != QtWidgets.QMessageBox.Ok: return self.etopodata = Dataset(filename) self.current_open = filename topoin = np.maximum(0, self.etopodata.variables['ROSE'][:]) lons = self.etopodata.variables['ETOPO05_X'][:] lats = self.etopodata.variables['ETOPO05_Y'][:] # shift data so lons go from -180 to 180 instead of 20 to 380. topoin, lons = shiftgrid(180., topoin, lons, start=False) # plot topography/bathymetry as an image. # create the figure and axes instances. # setup of basemap ('lcc' = lambert conformal conic). # use major and minor sphere radii from WGS84 ellipsoid. m = self.VpyartDisplay.value.basemap # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin)/500.) + 1 ny = int((m.ymax - m.ymin)/500.) + 1 topodat = m.transform_scalar(topoin, lons, lats, nx, ny) # plot image over map with imshow. # draw coastlines and political boundaries. ls = LightSource(azdeg=90, altdeg=20) # convert data to rgb array including shading from light source. # (must specify color map) rgb = ls.shade(topodat, cm.GMT_relief) im = m.imshow(rgb) self.VpyartDisplay.update(strong=False)
def render_component_oneframe(gf, templ): with open(FILE_NAME_COMPS, 'r') as f: d = cPickle.load(f) mn = d['mean'] Nc = mn.shape[1] mn_mask = (np.abs(mn) > 1.0 / mn.shape[0]**0.5) mn_thr = mn * mn_mask zero_mask = np.all(mn_mask == False, axis = 1) cid = np.argmax(np.abs(mn) * mn_mask, axis = 1)[:, np.newaxis] + 1 cid[zero_mask, :] = 0 mnd = gf.reshape_flat_field(cid) # in case lats are not in ascending order, fix this lat_ndx = np.argsort(gf.lats) lats_s = gf.lats[lat_ndx] # shift the grid by 180 degs and remap lons to -180, 180 Cout, lons_s = basemap.shiftgrid(180, mnd[0, :, :], gf.lons) lons_s -= 360 fig = plt.figure() # construct the projection from the remapped data m = basemap.Basemap(projection='mill', llcrnrlat=lats_s[0], urcrnrlat=lats_s[-1], llcrnrlon=lons_s[0], urcrnrlon=lons_s[-1], resolution='c') m.drawcoastlines() m.drawparallels(np.arange(-90.,91.,30.), labels=[1,0,0,1]) m.drawmeridians(np.arange(-120., 121.,60.), labels=[1,0,0,1]) nx = int((m.xmax-m.xmin) / 20000) + 1 ny = int((m.ymax-m.ymin) / 20000) + 1 f = m.transform_scalar(Cout[lat_ndx, :], lons_s, lats_s, nx, ny, order = 0) plt.title('Components [%s]' % METHOD_NAME) imgplt = m.imshow(f, alpha = 0.8, cmap = plt.get_cmap('Paired')) fig.savefig('figs/%s_component_clusters.pdf' % templ, bbox_inches = 'tight', pad_inches = 0.5, transparent = True) print('Uncovered area: %d grid points' % (np.sum(cid==0))) c_size = np.zeros((Nc+1,)) for i in range(Nc+1): c_size[i] = np.sum(cid == i) f = plt.figure() plt.title('Cluster sizes') plt.bar(np.arange(Nc) - 0.3 + 1, c_size[1:], 0.6) plt.xlabel('Cluster id') plt.ylabel('Grid points in cluster') f.savefig('figs/%s_cluster_sizes.pdf' % templ)
def normalize_lat_lon_values(lats, lons, values): ''' Normalize lat/lon values Ensure that lat/lon values are within [-180, 180)/[-90, 90) as well as sorted. If the values are off the grid they are shifted into the expected range. :param lats: A 1D numpy array of sorted lat values. :type lats: :class:`numpy.ndarray` :param lons: A 1D numpy array of sorted lon values. :type lons: :class:`numpy.ndarray` :param values: A 3D array of data values. :returns: A :func:`tuple` of the form (adjust_lats, adjusted_lons, adjusted_values) :raises ValueError: If the lat/lon values are not sorted. ''' if lats.ndim ==1 and lons.ndim ==1: # Avoid unnecessary shifting if all lons are higher than 180 if lons.min() > 180: lons-=360 # Make sure lats and lons are monotonically increasing lats_decreasing = np.diff(lats) < 0 lons_decreasing = np.diff(lons) < 0 # If all values are decreasing then they just need to be reversed lats_reversed, lons_reversed = lats_decreasing.all(), lons_decreasing.all() # If the lat values are unsorted then raise an exception if not lats_reversed and lats_decreasing.any(): raise ValueError('Latitudes must be sorted.') # Perform same checks now for lons if not lons_reversed and lons_decreasing.any(): raise ValueError('Longitudes must be sorted.') # Also check if lons go from [0, 360), and convert to [-180, 180) # if necessary lons_shifted = lons.max() > 180 lats_out, lons_out, data_out = lats[:], lons[:], values[:] # Now correct data if latlon grid needs to be shifted if lats_reversed: lats_out = lats_out[::-1] data_out = data_out[..., ::-1, :] if lons_reversed: lons_out = lons_out[::-1] data_out = data_out[..., ::-1] if lons_shifted: data_out, lons_out = shiftgrid(180, data_out, lons_out, start=False) return lats_out, lons_out, data_out else: lons[lons > 180] = lons[lons > 180] - 360. return lats, lons, values
def load(self): c = client.open_url(self.url) lon = c.ugrdtrop.lon[:] #lon[lon > 180] -= 360 # Basemap runs from -180 to +180 lat = c.ugrdtrop.lat[:] u_component = c.ugrdtrop.ugrdtrop[0][0] # units m/s v_component = c.vgrdtrop.vgrdtrop[0][0] # units m/s windspeed = 3.6 * np.sqrt(u_component**2, v_component**2) # units km/h # Shift grid from 0 to 360 => -180 to 180 windspeed, lon = basemap.shiftgrid(180, windspeed, lon, start=False) self.lon, self.lat, self.windspeed = lon, lat, windspeed
def imshowmap( lat, lon, indata, ax=None, projection="cyl", mapbound="all", gridstep=(30, 30), shift=False, colorbar=True, colorbarlabel=None, *args, **kwargs ): """ Purpose: plot a map on cyl projection. Arguments: ax --> An axes instance lat,lon --> geographic coordinate variables; mapbound --> tuple containing (lat1,lat2,lon1,lon2); lat1 --> lower parallel; lat2 --> upper parallel; lon1 --> left meridian; lon2 --> right meridian; default 'all' means plot the extent of input lat, lon coordinate variables; gridstep --> the step for parallel and meridian grid for the map, tuple containing (parallel_step, meridian_step). vmin,vmax --> as in plt.imshow function indata --> numpy array with dimension of len(lat)Xlen(lon) shift --> boolean value. False for longtitude data ranging [-180,180]; for longtitude data ranging [0,360] set shift to True if a 180 east shift is desired. """ print "Deprecate Warning! imshowmap replaced by mapimshow" # handle the case ax==None: if ax == None: fig, axt = g.Create_1Axes() else: axt = ax if shift == True: indata, lon = bmp.shiftgrid(180, indata, lon, start=False) # make the map and use mapbound to cut the data m, lonpro, latpro, latind, lonind = makemap(axt, projection, mapbound, lat, lon, gridstep) pdata = indata[latind[0] : latind[-1] + 1, lonind[0] : lonind[-1] + 1] cs = m.imshow(pdata, origin="upper", *args, **kwargs) if colorbar == True: cbar = m.colorbar(cs) if colorbarlabel != None: cbar.set_label(colorbarlabel) else: cbar = None return m, cs, cbar
def etopo5(self,file='data/etopo5.nc'): """ read in etopo5 topography/bathymetry. """ etopodata = Dataset(file) self.topoin = etopodata.variables['bath'][:] self.elons = etopodata.variables['X'][:] self.elats = etopodata.variables['Y'][:] etopodata.close() self.topoin,self.elons = shiftgrid(0.,self.topoin,self.elons,start=False) # -360 -> 0
def hammer_plot(NetworkF,Theta,Phi,theta,phi): from mpl_toolkits.basemap import Basemap, shiftgrid fig,ax = plt.subplots() RAD = 180/np.pi m = Basemap(projection='hammer',lon_0=0,resolution='c') Phi, NetworkF = shiftgrid(180,Phi,NetworkF) m.contourf(Phi*RAD, Theta*RAD, NetworkF, 100, cmap=plt.cm.jet,latlon=True) plt.plot(phi,theta,'go',markersize=5) plt.xlabel(r'$\phi$'' (radians)') plt.ylabel(r'$\theta$'' (radians)') plt.savefig('hammer.png') return plt.show()
def read_ncep2_mask(filepath): #READ IN NCEP 2 LAND MASK #SHIFT GRID FROM 0-360 to -180-180 filepath_m = filepath+'/land_sfc_gauss.nc' f = Dataset(filepath_m, 'r') mask_array = f.variables['land'][0,::-1, ::][60:-1, :] lats = f.variables['lat'][::-1][60:-1] lons0 = f.variables['lon'][:] mask_shift, lons_s = shiftgrid(180.,mask_array,lons0,start=False) return mask_shift
def load(self): data = netCDF4.Dataset('era-december-averages.nc') #times = netCDF4.num2date(data.variables['time'], #data.variables['time'].units) #print(times[self.year - 1979]) lon = data.variables['longitude'][:] lat = data.variables['latitude'][:] windspeed = 3.6 * np.sqrt(data.variables['u'][:]**2 + data.variables['v'][:]**2) windspeed = windspeed[self.year - 1979] # Shift grid from 0 to 360 => -180 to 180 windspeed, lon = basemap.shiftgrid(180, windspeed, lon, start=False) self.lon, self.lat, self.windspeed = lon, lat, windspeed
def shade_coord(xin,yin,datain=None,lon0=None): from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic from mcmath import edges # invert lat coords if they are descending instead of ascending if yin[-1] < yin[0]: yin = yin[::-1] if datain is not None: ydimloc = np.where(yin.size == np.array(datain.shape))[0] if len(ydimloc) == 0: raise MCPlotError("no dimension in 'datain' matches length of 'yin'") y_ind = [] for i in xrange(datain.ndim): y_ind.append(slice(None)) y_ind[ydimloc[0]] = slice(None,None,-1) datain = datain[y_ind] yedg = edges(yin) # convert xin to -180:180 range; roll and addcyclic as needed to have lon0 as central lon xedg = edges(xin) xspan = xedg[-1] - xedg[0] if ((xspan < 365.) & (xspan > 355.)): xin = np.where(xin >= 180,xin-360,xin) roll_ind = np.where(xin < np.roll(xin,1))[0] if len(roll_ind) == 0: raise MCPlotError("can't find pivot between +180 and -180 in xin") xin = np.roll(xin,-roll_ind) if datain is not None: xdimloc = np.where(xin.size == np.array(datain.shape))[-1] if len(xdimloc) == 0: raise MCPlotError("no dimension in 'datain' matches length of 'xin'") datain = np.roll(datain,-roll_ind,axis=xdimloc) if (lon0 is not None): (datain,xin) = addcyclic(datain,xin) (datain,xin) = shiftgrid(lon0-180,datain,xin) xedg = edges(xin) ## Fix for keeping the squares near the edges of global maps filled just to the edge (map boundary) if (lon0 is not None): if xedg[0] < (lon0-180): xedg[0] = lon0-180 if xedg[-1] > (lon0+180): xedg[-1] = lon0+180 return [xedg,yedg,datain,xin,yin] else: xedg = edges(xin) return [xedg,yedg,datain,xin,yin]
def __init__(self, year): filepath_u = '/Users/apetty/NOAA/DATA/WINDS/NCEP/DATA/REANAL1/uwnd.sig995.'+str(year)+'.nc' filepath_v = '/Users/apetty/NOAA/DATA/WINDS/NCEP/DATA/REANAL1/vwnd.sig995.'+str(year)+'.nc' self.f_u = Dataset(filepath_u, 'r') self.f_v = Dataset(filepath_v, 'r') self.varname1 = 'uwnd' self.varname2 = 'vwnd' self.lats = self.f_u.variables['lat'][::-1] self.lons0 = self.f_u.variables['lon'][:] var_array_t = self.f_u.variables['uwnd'][0, ::-1, ::] var_temp, self.lons_s = shiftgrid(180.,var_array_t,self.lons0,start=False)
def __init__(self, year, filepath): filepath_u = filepath+'/uwnd.10m.gauss.'+str(year)+'.nc' filepath_v = filepath+'/vwnd.10m.gauss.'+str(year)+'.nc' self.f_u = Dataset(filepath_u, 'r') self.f_v = Dataset(filepath_v, 'r') self.varname1 = 'uwnd' self.varname2 = 'vwnd' #AS ARRAYS ARE QUITE BIG - ONLY USE DATA FROM AROUND 25 DEG NORTH self.lats = self.f_u.variables['lat'][::-1][60:-1] self.lons0 = self.f_u.variables['lon'][:] var_array_t = self.f_u.variables['uwnd'][0,0, ::-1, ::][60:-1, :] var_temp, self.lons_s = shiftgrid(180.,var_array_t,self.lons0,start=False)
def etopo5_data(): """ read in etopo5 topography/bathymetry. """ file = 'data/etopo5.nc' etopodata = Dataset(file) topoin = etopodata.variables['bath'][:] lons = etopodata.variables['X'][:] lats = etopodata.variables['Y'][:] etopodata.close() topoin,lons = shiftgrid(0.,topoin,lons,start=False) # -360 -> 0 #lons, lats = np.meshgrid(lons, lats) return(topoin, lats, lons)
def __init__(self, year, filepath): filepath_u = glob(filepath+'/anl_surf125.033_ugrd.'+str(year)+'*.nc') #print filepath_u filepath_v = glob(filepath+'/anl_surf125.034_vgrd.'+str(year)+'*.nc') self.f_u = Dataset(filepath_u[0], 'r') self.f_v = Dataset(filepath_v[0], 'r') self.varname1 = 'UGRD_GDS0_HTGL' self.varname2 = 'VGRD_GDS0_HTGL' #AS ARRAYS ARE QUITE BIG - ONLY USE DATA FROM AROUND 25 DEG NORTH self.lats = self.f_u.variables['g0_lat_1'][::-1] self.lons0 = self.f_u.variables['g0_lon_2'][:] var_array_t = self.f_u.variables['UGRD_GDS0_HTGL'][0, ::-1, ::] var_temp, self.lons_s = shiftgrid(180.,var_array_t,self.lons0,start=False)
def etopo5_data(filein='/Users/bell/in_and_outbox/Ongoing_Analysis/MapGrids/etopo5.nc'): """ read in etopo5 topography/bathymetry. """ etopodata = Dataset(filein) topoin = etopodata.variables['bath'][:] lons = etopodata.variables['X'][:] lats = etopodata.variables['Y'][:] etopodata.close() topoin,lons = shiftgrid(0.,topoin,lons,start=False) # -360 -> 0 #lons, lats = np.meshgrid(lons, lats) return(topoin, lats, lons)
def etopo5_data(): """ read in etopo5 topography/bathymetry. """ #file = '/Users/bell/Data_Local/MapGrids/etopo5.nc' ncdata = '/Users/bell/Programs/Python/AtSeaPrograms/data/etopo5.nc' etopodata = Dataset(ncdata) topoin = etopodata.variables['bath'][:] lons = etopodata.variables['X'][:] lats = etopodata.variables['Y'][:] etopodata.close() topoin,lons = shiftgrid(0.,topoin,lons,start=False) # -360 -> 0 lons, lats = np.meshgrid(lons, lats) return(topoin, lats, lons)
def expand_longitude( test_lon,orig_lon,orig_data): """ Makes a cyclic array using basemap and expands the longitudes to give the buffer aroud the edge needed for the area weighted re-gridding. """ import numpy as np from mpl_toolkits.basemap import addcyclic, shiftgrid import copy # shift the grid of the emissions so it fits with the test longitude grid # first, find the value of the orig long grid nearest to the test long grid if len(orig_data.shape) != 2: raise Exception, 'Data array must be two-dimensional' idx = (np.abs(orig_lon-test_lon[0])).argmin() start = orig_lon[idx] orig_data_temp,orig_lon_temp=addcyclic(orig_data,orig_lon) orig_data_temp,orig_lon_temp=shiftgrid(start,orig_data_temp,orig_lon_temp) test_dlon = test_lon[1] - test_lon[0] orig_dlon = orig_lon[1] - orig_lon[0] extra_cells=np.int(test_dlon/orig_dlon)+2 # NOTE: DATA AND LOGITUDE HAVE BEEN MADE CYCLIC, ORIGIN IS THAT CLOSEST IN ORIG TO THE START OF TEST new_lon = np.linspace(orig_lon_temp[0] - extra_cells*orig_dlon,\ orig_lon_temp[-2]+(extra_cells)*orig_dlon,\ len(orig_lon)+2*extra_cells) lon_index = np.arange(-1*extra_cells,len(new_lon)-extra_cells,1,dtype=np.int) new_data = np.zeros((orig_data.shape[0],len(new_lon))) i = 0 while i < len(new_lon): # ignore cyclic grid here for length, since orig_data_temp[0] == orig_data_temp[1], but # we don't want to replicate that new_data[:,i] = copy.deepcopy(orig_data_temp[:,lon_index[i]%orig_data.shape[1]]) i+=1 del idx del i del start del orig_data_temp del orig_lon_temp del test_dlon del orig_dlon del test_lon del orig_lon del orig_data del extra_cells del lon_index return new_lon,new_data
def maskpoly(x2d,y2d,poly,s=0): """ x2d(ny,nx), y2d(ny,nx), poly(npoints, 2) example: indian = np.array([ [80,0],[80,217],[113,267],[160,320],[883,320],[883,0],[80,0]]) x2d,y2d=np.meshgrid(np.arange(2160),np.arange(320)) ma_ip = maskpoly(x2d,y2d,indian) output: masked array (ny,nx) ; True for points inside the polygon """ import numpy as np from matplotlib import path from mpl_toolkits.basemap import shiftgrid ny,nx=x2d.shape if s !=0: x2ds, tmp = shiftgrid(x2d[1,s], x2d, x2d[1,:], start=False) x2d=x2ds points=np.c_[x2d.reshape(-1,1),y2d.reshape(-1,1)] mask = path.Path(poly).contains_points(points).reshape(ny,nx) return mask
def render_component_single(C, lats, lons, clims = None, fname = None, plt_name = None, cmap = None, cbar = True, cbticks = None): """ Render a single component on a plot. """ # we either accept prescribed if clims == 'symm': rmax = max(np.amax(C), np.amax(-C)) clims = (-rmax, rmax) if plt_name == None: plt_name = 'Component' # in case lats are not in ascending order, fix this lat_ndx = np.argsort(lats) lats_s = lats[lat_ndx] # shift the grid by 180 degs and remap lons to -180, 180 Cout, lons_s = basemap.shiftgrid(180, C, lons) lons_s -= 360 # construct the projection from the remapped data m = Basemap(projection='mill', llcrnrlat=lats_s[0], urcrnrlat=lats_s[-1], llcrnrlon=lons_s[0], urcrnrlon=lons_s[-1], resolution='c') f = plt.figure() if cbar: plt.subplots_adjust(left = 0.1, bottom = 0.05, right = 0.95, top = 0.95) else: plt.subplots_adjust(left = 0.1, bottom = 0.05, right = 1.0, top = 1.0) plt.subplot(1, 1, 1) render_component(m, Cout[lat_ndx, :], lats_s, lons_s, clims, plt_name, cmap, cbar, cbticks) if fname: plt.savefig(fname) plt.close(f) else: return f
def mapwithtopo(p,ax=[],cutdepth=[],aspect=2.5,cmap=[],dlon=30,dlat=10,smooth=False): import popy,os from netCDF4 import Dataset from mpl_toolkits.basemap import shiftgrid from matplotlib.colors import LightSource import pylab as plt import numpy as np etopofn='/net/mazdata2/jinbo/mdata5-jinbo/obs/ETOPO/ETOPO1_Bed_g_gmt4.grd' etopo = Dataset(etopofn,'r').variables x,y,z=etopo['x'][1:],etopo['y'][1:],etopo['z'][1:,1:] dx,dy=5,5 x=x.reshape(-1,dx).mean(axis=-1) y=y.reshape(-1,dx).mean(axis=-1) z=z.reshape(y.size,dx,x.size,dx).mean(axis=-1).mean(axis=1) if smooth: z=popy.utils.smooth2d(z,window_len=3) if cutdepth!=[]: z[z<cutdepth]=cutdepth if ax==[]: fig=plt.figure() ax=fig.add_subplot() if cmap==[]: cmap=plt.cm.Greys z,x = shiftgrid(p[0],z,x,start=True) lon,lat,z = popy.utils.subtractsubdomain(x,y,p,z) m = setmap(p=p,dlon=dlon,dlat=dlat) x, y = m(*np.meshgrid(lon, lat)) ls = LightSource(azdeg=90, altdeg=45) rgb = ls.shade(z, cmap=cmap) m.imshow(rgb, aspect=aspect) plt.savefig('/tmp/tmp.png') os.popen('eog /tmp/tmp.png') return etopo
def plot_clusters_with_centers_and_links(gf, clusts, c_lons, c_lats, links = []): # in case lats are not in ascending order, fix this lat_ndx = np.argsort(gf.lats) lats_s = gf.lats[lat_ndx] # shift the grid by 180 degs and remap lons to -180, 180 Cout, lons_s = basemap.shiftgrid(180, clusts, gf.lons) lons_s -= 360 plt.figure() plt.title('NH Extratropical Components [%s]' % METH_NAME) # construct the projection from the remapped data m = basemap.Basemap(projection='mill', llcrnrlat=lats_s[0], urcrnrlat=lats_s[-1], llcrnrlon=lons_s[0], urcrnrlon=lons_s[-1], resolution='c') m.drawcoastlines() m.drawparallels(np.arange(-90.,91.,30.), labels = [1,0,0,1]) m.drawmeridians(np.arange(-120., 121.,60.), labels = [1,0,0,1]) nx = int((m.xmax-m.xmin) / 20000) + 1 ny = int((m.ymax-m.ymin) / 20000) + 1 f = m.transform_scalar(Cout[lat_ndx, :], lons_s, lats_s, nx, ny, order = 0) imgplt = m.imshow(f, alpha = 0.9, cmap = plt.get_cmap('Paired')) # plot the centers of the components x, y = m(c_lons, c_lats) plt.plot(x, y, 'ko', markersize = 6) # plot the links, if any for n1, n2, c in links: plt.plot([x[n1-1], x[n2-1]], [y[n1-1], y[n2-1]], '%s-' % c, alpha = 0.8) plt.savefig('figs/slp_nh_component_clusters_with_centers.pdf', bbox_inches = 'tight', pad_inches = 0.5)
def _generate_map_prepare_data( data=None, lat=None, lon=None, projection="cyl", mapbound="all", gridstep=(30, 30), shift=False, map_threshold=None, levels=None, cmap=None, smartlevel=None, data_transform=False, gmapkw={}, ax=None, ): """ This function makes the map, and transform data for ready use of m.contourf or m.imshow """ if shift == True: data, lon = bmp.shiftgrid(180, data, lon, start=False) mgmap = gmap(ax, projection, mapbound, lat, lon, gridstep, **gmapkw) m, lonpro, latpro, latind, lonind = (mgmap.m, mgmap.lonpro, mgmap.latpro, mgmap.latind, mgmap.lonind) pdata = data[latind[0] : latind[-1] + 1, lonind[0] : lonind[-1] + 1] # mask by map_threshold pdata = mathex.ndarray_mask_by_threshold(pdata, map_threshold) # generate the smartlevel if smartlevel == True: if levels != None: raise ValueError("levels must be None when smartlevel is True!") else: levels = _generate_smartlevel(pdata) data_transform = True # prepare the data for contourf pdata, plotlev, plotlab, extend, trans_base_list = _transform_data(pdata, levels, data_transform) return (mgmap, pdata, plotlev, plotlab, extend, trans_base_list, data_transform)
lat = nc.variables['lat'][:] lon = nc.variables['lon'][:] m = mapformat() array = np.empty((180,360)) array[:] = np.NAN; x = np.arange(0.5, 360.5, 1.0) y = np.arange(-90, 91, 1.0) for i in range(0, lat.size): ilat = int(lat[i] + 90.0) ilon = int(lon[i] - 0.5) array[ilat, ilon] = tasmax[i, ilat, ilon] if ilon < 179 or ilon > 181: # HACK: to avoid date-line wraparound problem array[ilat,ilon] = tasmax[i] array, x = shiftgrid(180, array, x) array_mask = np.ma.masked_invalid(array) x,y = np.meshgrid(x,y) x,y = m(x,y) # rbb = np.loadtxt('cmaps/runoff-brownblue.txt')/255; # rbb = mpl.colors.ListedColormap(rbb) m.pcolormesh(x,y,array_mask, rasterized=False, edgecolor='0.6', linewidth=0) cbar = m.colorbar() cbar.solids.set_edgecolor("face") # cbar.set_ticks([0,100]) plt.title("Max temperaturre") plt.show()
lat = f.variables['lat'][:] lon = f.variables['lon'][:] puptake = f.variables['NUPTAKE'] unit = puptake.units long_name = puptake.long_name nfix = f.variables['NFIX'][:] pnonmyc = f.variables['NNONMYC'][:] pactive = f.variables['NACTIVE'][:] pretrans = f.variables['NRETRANS'][:] pam = f.variables['NAM'][:] pecm = f.variables['NECM'][:] puptake, lon = shiftgrid(180., puptake, lon, start=False) lon = f.variables['lon'][:] pnonmyc, lon = shiftgrid(180., pnonmyc, lon, start=False) lon = f.variables['lon'][:] pactive, lon = shiftgrid(180., pactive, lon, start=False) lon = f.variables['lon'][:] pretrans, lon = shiftgrid(180., pretrans, lon, start=False) lon = f.variables['lon'][:] pam, lon = shiftgrid(180., pam, lon, start=False) lon = f.variables['lon'][:] pecm, lon = shiftgrid(180., pecm, lon, start=False) lon = f.variables['lon'][:] nfix, lon = shiftgrid(180., nfix, lon, start=False) #Function to calculate the weights of latitude radius = 6367449
import scipy.signal from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1 import make_axes_locatable mai = NetCDFFile('outputnew_noinund.nc', 'r') maiir = mai.variables['totalyield'][:, :, :] mai1 = NetCDFFile('outputnew_noinund.nc', 'r') mai = mai1.variables['totalyield'][:, :, :] maiir = ma.masked_where(maiir <= 0.0, maiir) mai = ma.masked_where(mai <= 0.0, mai) region = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/Ctry_halfdeg.nc', 'r') cou = region.variables['MASK_Country'][:, :] lonab1 = region.variables['Lon'][:] cou, lonab = shiftgrid(0.5, cou, lonab1, start=True) region = NetCDFFile( '/global/project/projectdirs/m1602/datasets4.full/arbit_init_state_05x05.nc', 'r') ind = region.variables['REGION_MASK'][:, :] lona = region.variables['lon'][:] lata = region.variables['lat'][:] isam1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/luh2area_850_2015_corrcrop.nc', 'r') meareaisam1 = isam1.variables['fmai_tt'][1150, :, :] #2000 meareaisam1 = ma.masked_where(meareaisam1 <= 500.0, meareaisam1) x = 38 meareaisam = N.zeros((x, 360, 720))
eiyield6ynew= ma.masked_where(iyield6ynew<=0.,eiyield6ynew) iyield1ynewe= ma.masked_where(iyield1ynewe<=0.,iyield1ynewe) iyield2ynewe= ma.masked_where(iyield2ynewe<=0.,iyield2ynewe) iyield3ynewe= ma.masked_where(iyield3ynewe<=0.,iyield3ynewe) iyield4ynewe= ma.masked_where(iyield4ynewe<=0.,iyield4ynewe) iyield5ynewe= ma.masked_where(iyield5ynewe<=0.,iyield5ynewe) eiyield1ynewe= ma.masked_where(iyield1ynewe<=0.,eiyield1ynewe) eiyield2ynewe= ma.masked_where(iyield2ynewe<=0.,eiyield2ynewe) eiyield3ynewe= ma.masked_where(iyield3ynewe<=0.,eiyield3ynewe) eiyield4ynewe= ma.masked_where(iyield4ynewe<=0.,eiyield4ynewe) eiyield5ynewe= ma.masked_where(iyield5ynewe<=0.,eiyield5ynewe) maizeto1,lonisam2=shiftgrid(0.5,maizeto,lonisam1,start=True) maizeto1i,lonisam2=shiftgrid(0.5,maitropi,lonisam1,start=True) maizeto1r,lonisam2=shiftgrid(0.5,maitrop,lonisam1,start=True) maizete1i,lonisam2=shiftgrid(0.5,maitempi,lonisam1,start=True) maizete1r,lonisam2=shiftgrid(0.5,maitemp,lonisam1,start=True) landfrac1,lonisam2=shiftgrid(0.5,landfrac,lonisam1,start=True) #gridarea1,lonisam2=shiftgrid(0.5,gridarea,lonisam1,start=True) iyield1ynew=ma.filled(iyield1ynew, fill_value=0.) iyield2ynew=ma.filled(iyield2ynew, fill_value=0.) iyield3ynew=ma.filled(iyield3ynew, fill_value=0.) iyield4ynew=ma.filled(iyield4ynew, fill_value=0.) iyield5ynew=ma.filled(iyield5ynew, fill_value=0.) iyield6ynew=ma.filled(iyield6ynew, fill_value=0.) iyield1ynew= ma.masked_where(iyield1ynew<=0.,iyield1ynew)
yield_clmtf = clmtropf + clmtempf yield_clmtf = ma.masked_where(yield_clmtf <= 0, yield_clmtf) #yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf ) yield_clmtf = ma.filled(yield_clmtf, fill_value=0.) yield_clmtfi = clmtropfi + clmtempfi yield_clmtfi = ma.masked_where(yield_clmtfi <= 0, yield_clmtfi) #yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi) yield_clmtfi = ma.filled(yield_clmtfi, fill_value=0.) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'][:, :] gridlon = area.variables['lon'][:] gridarea, gridlon = shiftgrid(180.5, gridarea, gridlon, start=False) nclu = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/maize_AreaYieldProduction.nc', 'r') ncvar_maize = nclu.variables['maizeData'][:] latnc = nclu.variables['latitude'][:] znc = nclu.variables['level'][:] lonnc = nclu.variables['longitude'][:] timenc = nclu.variables['time'][:] yieldfi = N.zeros((100, 360, 720)) yieldf2i = N.zeros((100, 360, 720)) yieldf = N.zeros((100, 360, 720)) yieldf2 = N.zeros((100, 360, 720))
def yieldout(year): bb = year - 2015 bb1 = year - 2015 isam1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/mirca_isam.nc', 'r') maitrop1 = isam1.variables['amai_rf'][:, :] #mirca2000 maitropi1 = isam1.variables['amai_irr'][:, :] #mirca2000 maitrop1 = ma.masked_where(maitrop1 <= 0, maitrop1) maitrop1 = ma.filled(maitrop1, fill_value=0.) maitropi1 = ma.masked_where(maitropi1 <= 0, maitropi1) maitropi1 = ma.filled(maitropi1, fill_value=0.) lonisam = isam1.variables['lon'][:] maitrop, lonisam1 = shiftgrid(180.5, maitrop1, lonisam, start=False) maitropi, lonisam1 = shiftgrid(180.5, maitropi1, lonisam, start=False) maizetor = maitrop maizetoi = maitropi maizetrop = maitrop + maitropi maizeto = maitrop + maitropi isam = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/rcp45new/mai_fert/output/mai_fert.nc', 'r') clmtropf = isam.variables['g_ET'][bb, 0, :, :] clm2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/rcp45new/mai_irr_fert/output/mai_irr_fert.nc', 'r') clmtropfi = clm2.variables['g_ET'][bb, 0, :, :] lonisam = clm2.variables['lon'][:] clmtropf, lonisam1 = shiftgrid(180.5, clmtropf, lonisam, start=False) clmtropfi, lonisam1 = shiftgrid(180.5, clmtropfi, lonisam, start=False) print lonisam1 clmtropf = ma.masked_where(maitrop <= 0, clmtropf) clmtropf = ma.filled(clmtropf, fill_value=0.) clmtropfi = ma.masked_where(maitropi <= 0, clmtropfi) clmtropfi = ma.filled(clmtropfi, fill_value=0.) yield_clmtf = clmtropf yield_clmtf = ma.masked_where(yield_clmtf <= 0, yield_clmtf) yield_clmtf = ma.filled(yield_clmtf, fill_value=0.) yield_clmtfi = clmtropfi yield_clmtfi = ma.masked_where(yield_clmtfi <= 0, yield_clmtfi) yield_clmtfi = ma.filled(yield_clmtfi, fill_value=0.) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf_isam.nc', 'r') gridarea = area.variables['cell_area'][:, :] gridlon = area.variables['lon'][:] gridlat = area.variables['lat'][:] gridarea, gridlon = shiftgrid(180.5, gridarea, gridlon, start=False) lon2, lat2 = N.meshgrid(gridlon, gridlat) map = Basemap(projection='cyl', llcrnrlat=-65, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') x, y = map(lon2, lat2) yield_clmtf = maskoceans(x, y, yield_clmtf) yield_clmtf = ma.masked_where(maizeto <= 0, yield_clmtf) yield_clmtfi = maskoceans(x, y, yield_clmtfi) yield_clmtfi = ma.masked_where(maizeto <= 0, yield_clmtfi) clmy = ((yield_clmtf * maizetor) + (yield_clmtfi * maizetoi)) / ((maizetoi) + (maizetor)) areall = (maizetoi) + (maizetor) clmall = ((yield_clmtf * maizetor) + (yield_clmtfi * maizetoi)) return clmy, areall, clmall
for i, year1 in enumerate(years2): # base2 = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/model/global/isam_future/rcp45am/output/rcp45am.bgp-yearly_crop_{0}.nc".format(year1), mode='r') # base2 = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/model/global/isam_future/rcp45bm/output/rcp45bm.bgp-yearly_crop_{0}.nc".format(year1), mode='r') base2 = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/model/global/isam_future/rcp45cm/output/rcp45cm.bgp-yearly_crop_{0}.nc".format(year1), mode='r') base2a = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/model/global/isam_future/rcp45dm/output/rcp45dm.bgp-yearly_crop_{0}.nc".format(year1), mode='r') yield2 = base2.variables["g_Temp"][7,0,:,:] yieldf2[i, :, :] = yield2 yield21 = base2a.variables["g_Temp"][7,0,:,:] yieldf21[i, :, :] = yield21 yielda=N.average(yieldf,axis=0) yielda2=N.average(yieldf2,axis=0) yield_new,lona11 = shiftgrid(180.5,yielda,lona1,start=False) yield_new2,lona11 = shiftgrid(180.5,yielda2,lona1,start=False) yielda1=N.average(yieldf1,axis=0) yielda21=N.average(yieldf21,axis=0) yield_new1,lona11 = shiftgrid(180.5,yielda1,lona1,start=False) yield_new21,lona11 = shiftgrid(180.5,yielda21,lona1,start=False) lon2,lat2 = N.meshgrid(lona11,lata1) yield_new= ma.masked_where( clmhis[:,:]<=0,yield_new) yield_new2=ma.masked_where( clmfuture[:,:]<=0,yield_new2)
yieldf2a[i, :, :] = yield2a yield2ay = base2a.variables["yield"][0, :, :] yieldf2ay[i, :, :] = yield2ay yield2ay1 = base2ay.variables["yield"][0, :, :] yieldf2ay1[i, :, :] = yield2ay1 yielda = N.average(yieldf, axis=0) yielda2 = N.average(yieldf2, axis=0) yielday = N.average(yieldfy, axis=0) yielda2y = N.average(yieldf2y, axis=0) yielday1 = N.average(yieldfy1, axis=0) yielda2y1 = N.average(yieldf2y1, axis=0) yield_new, lona11 = shiftgrid(180.5, yielda, lona1, start=False) yield_new2, lona11 = shiftgrid(180.5, yielda2, lona1, start=False) yield_newy, lona11 = shiftgrid(180.5, yielday, lona1, start=False) yield_new2y, lona11 = shiftgrid(180.5, yielda2y, lona1, start=False) yield_newy1, lona11 = shiftgrid(180.5, yielday1, lona1, start=False) yield_new2y1, lona11 = shiftgrid(180.5, yielda2y1, lona1, start=False) yieldaa = N.average(yieldfa, axis=0) yielda2a = N.average(yieldf2a, axis=0) yield_newa, lona11 = shiftgrid(180.5, yieldaa, lona1, start=False) yield_new2a, lona11 = shiftgrid(180.5, yielda2a, lona1, start=False) yieldaay = N.average(yieldfay, axis=0)
map = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=70, llcrnrlon=-40, urcrnrlon=70, resolution='l', ax=ax) map.drawcountries(color='black', linewidth=2.5, ax=ax) map.drawcoastlines(color='k', linewidth=2.5, ax=ax) map.drawmapboundary(color='k', linewidth=2.5, ax=ax) map.drawparallels(np.arange(-90, 90, 10), labels=[1, 0, 0, 0], **csfont) map.drawmeridians(np.arange(-180, 180, 10), labels=[0, 0, 0, 1], **csfont) ax.set_ylabel("Latitude ", **csfont, labelpad=70) ax.set_xlabel("Longitude", **csfont, labelpad=40) pv, lns = shiftgrid(180., pv, ln, start=False) llons, llats = np.meshgrid(lns, lt) x, y = map(llons, llats) data = (pv[i, :, :]) data = data / 0.000001 cmap = c.ListedColormap(my_color) cmap.set_under('#f5bc42') bounds = np.linspace(0, 10, 100, endpoint=True) norm = c.BoundaryNorm(bounds, ncolors=cmap.N) cs = plt.contourf(x, y, data, cmap=cmap, norm=norm, levels=bounds, extend='both',
def annualyield(year, couna, counb): if year <= 2005: bb = year - 1901 aa = year - 1901 else: bb = 104 aa = year - 1901 region1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalGLM_crop_150901.nc', 'r') lonlon = region1.variables['lon'][:] maitrop = region1.variables['maize_trop'][bb, :, :] maitemp = region1.variables['maize_temp'][bb, :, :] maitropi = region1.variables['maize_trop_irrig'][bb, :, :] maitempi = region1.variables['maize_temp_irrig'][bb, :, :] gridarea = region1.variables['area'][:, :] maitrop = ma.masked_where(maitrop <= 0, maitrop) maitrop = ma.filled(maitrop, fill_value=0.) maitemp = ma.masked_where(maitemp <= 0, maitemp) maitemp = ma.filled(maitemp, fill_value=0.) maitropi = ma.masked_where(maitropi <= 0, maitropi) maitropi = ma.filled(maitropi, fill_value=0.) maitempi = ma.masked_where(maitempi <= 0, maitempi) maitempi = ma.filled(maitempi, fill_value=0.) maizetor = maitrop + maitemp maizetoi = maitropi + maitempi maizeto = maitrop + maitemp + maitropi + maitempi maizeto, lon1 = shiftgrid(0.5, maizeto, lonlon, start=True) # print lon1 clm = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_rf_fert_0.5x0.5.nc', 'r') clmtropf = clm.variables['totalyield'][bb, :, :] clmtropf = ma.masked_where(clmtropf <= 0, clmtropf) clmtropf = ma.filled(clmtropf, fill_value=0.) clm2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_irrig_fert_0.5x0.5.nc', 'r') clmtropf1 = clm2.variables['totalyield'][bb, :, :] clmtropf1 = ma.masked_where(clmtropf1 <= 0, clmtropf1) clmtropf1 = ma.filled(clmtropf1, fill_value=0.) clm3n = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_rf_nofert_0.5x0.5.nc', 'r') isammai = clm3n.variables['totalyield'][bb, :, :] isammai = ma.masked_where(isammai <= 0, isammai) isammai = ma.filled(isammai, fill_value=0.) clm3n1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_irrig_fert_var_0.5x0.5.nc', 'r') isamcrumai = clm3n1.variables['totalyield'][bb, :, :] isamcrumai = ma.masked_where(isamcrumai <= 0, isamcrumai) isamcrumai = ma.filled(isamcrumai, fill_value=0.) clm3n2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_irrig_nofert_0.5x0.5.nc', 'r') isamcrumai2 = clm3n2.variables['totalyield'][aa, :, :] isamcrumai2 = ma.masked_where(isamcrumai2 <= 0, isamcrumai2) isamcrumai2 = ma.filled(isamcrumai2, fill_value=0.) clm3n3 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical_cru/heat/fertfao/fixedirr_new1/maizetemp_historical_co2_irrig_nofert_var_0.5x0.5.nc', 'r') isamcrumai3 = clm3n3.variables['totalyield'][bb, :, :] isamcrumai3 = ma.masked_where(isamcrumai3 <= 0, isamcrumai3) isamcrumai3 = ma.filled(isamcrumai3, fill_value=0.) yieldclm1 = 0 yieldclm = 0. yieldisam = 0. yieldisamc = 0. yieldisamc2 = 0. yieldisamc3 = 0. a = 0 harea = 0 yieldc1 = 0 yieldc = 0. yieldi = 0. yieldic = 0. yieldic2 = 0. yieldic3 = 0. #USA 11501~11550 for xx in range(0, 360): for yy in range(0, 720): if coun[xx, yy] >= couna and coun[xx, yy] <= counb: harea = maizeto[xx, yy] * gridarea[xx, yy] + harea yieldclm1 = (clmtropf1[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldclm1 yieldclm = (clmtropf[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldclm yieldisam = (isammai[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldisam yieldisamc = (isamcrumai[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldisamc yieldisamc2 = (isamcrumai2[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldisamc2 yieldisamc3 = (isamcrumai3[xx, yy] * maizeto[xx, yy] * gridarea[xx, yy]) + yieldisamc3 a = a + 1 yieldc1 = N.average(clmtropf1, weights=maizeto) yieldc = N.average(clmtropf, weights=maizeto) yieldi = N.average(isammai, weights=maizeto) yieldic = N.average(isamcrumai, weights=maizeto) yieldic2 = N.average(isamcrumai2, weights=maizeto) yieldic3 = N.average(isamcrumai3, weights=maizeto) return harea, yieldc, yieldi, yieldic, yieldclm, yieldisam, yieldisamc, yieldic2, yieldic3, yieldisamc2, yieldisamc3, yieldc1
iyield4ynew = ma.masked_where(iyield4ynew <= 0., iyield4ynew) iyield5ynew = ma.masked_where(iyield5ynew <= 0., iyield5ynew) iyield6ynew = ma.masked_where(iyield6ynew <= 0., iyield6ynew) eiyield1ynew = ma.masked_where(eiyield1ynew <= 0., eiyield1ynew) eiyield2ynew = ma.masked_where(eiyield2ynew <= 0., eiyield2ynew) eiyield3ynew = ma.masked_where(eiyield3ynew <= 0., eiyield3ynew) eiyield4ynew = ma.masked_where(eiyield4ynew <= 0., eiyield4ynew) eiyield5ynew = ma.masked_where(eiyield5ynew <= 0., eiyield5ynew) maizeto1 = N.zeros((10, 360, 720)) maizeto1r = N.zeros((10, 360, 720)) for i in range(0, 10): maizeto1[i, :, :], lonisam2 = shiftgrid(0.5, maizeto[i, :, :], lonisam1, start=True) maizeto1r[i, :, :], lonisam2 = shiftgrid(0.5, maitrop[i, :, :], lonisam1, start=True) iyield1ynew = ma.filled(iyield1ynew, fill_value=0.) iyield2ynew = ma.filled(iyield2ynew, fill_value=0.) iyield3ynew = ma.filled(iyield3ynew, fill_value=0.) iyield4ynew = ma.filled(iyield4ynew, fill_value=0.) iyield5ynew = ma.filled(iyield5ynew, fill_value=0.) iyield6ynew = ma.filled(iyield6ynew, fill_value=0.) iyield1ynew = ma.masked_where(iyield1ynew <= 0., iyield1ynew) iyield2ynew = ma.masked_where(iyield2ynew <= 0., iyield2ynew)
fig = plt.figure(1, figsize=(8, 4)) ax = plt.subplot(2, 2, 2) m = Basemap(projection='cyl', llcrnrlat=-60.0, llcrnrlon=30.0, urcrnrlat=60.0, urcrnrlon=290.0) m.drawcoastlines() m.drawparallels(np.array([-60, -30, 0, 30, 60]), labels=[1, 0, 0, 0], fontsize=8) m.drawmeridians(np.array([30, 95, 160, 225, 290]), labels=[0, 0, 0, 1], fontsize=8) corrtnn, lon = shiftgrid(0., corrtnn, lon, start=True) ss_tnn, lon = shiftgrid(0., ss_tnn, lon1, start=True) lons, lats = np.meshgrid(lon, lat) xi, yi = m(lons, lats) v = np.linspace(-0.6, 0.6, 13, endpoint=True) #define colourbar ticks from -0.6 to 0.6 mymap = m.contourf(xi, yi, corrtnn, v, cmap='bwr') ss = m.contourf(xi, yi, ss_tnn, v, hatches=['...'], cmap='bwr') #plot ss ontop of correlations plt.title('DJF TNn', fontsize=10) ax = plt.subplot(2, 2, 1) m = Basemap(projection='cyl', llcrnrlat=-60.0, llcrnrlon=30.0, urcrnrlat=60.0,
linscale=0.1, vmin=-clim, vmax=clim) im = mp.pcolor(x, y, 10000 * np.transpose(pToPlot) / maxAbs, cmap='RdBu_r', norm=norm) if i == firstFrame + rank: plt.colorbar(im) title = figure.suptitle('t = %.4f' % output['t'][0]) else: title.set_text('t = %.4f' % output['t'][0]) vph, newlon = shiftgrid(180., output['vph'].T, np.degrees(lon), start=False) vth, newlon = shiftgrid(180., output['vth'].T, np.degrees(lon), start=False) uproj, vproj, xx, yy = mp.transform_vector(vph[::-1], vth[::-1], newlon, np.degrees(lat[::-1]), 81, 81, returnxy=True, masked=True)
plt.rc('legend', fontsize=SIZE) # legend fontsize plt.rc('figure', titlesize=SIZE) # # size of the figure title plt.rcParams["font.family"] = "sans-serif" # # font f = Dataset('time_average_h0.nc', 'r') lat = f.variables['lat'][:] lon = f.variables['lon'][:] gpp = f.variables['GPP'][:] pactive = f.variables['PACTIVE'][:] # shifting grid to run from -180 to 180 rather than 0-360 #clump,lon = shiftgrid(180., clump, lon, start=False) #lon = f.variables['lon'][:] pactive, lon = shiftgrid(180., pactive, lon, start=False) m = Basemap(projection='robin', lon_0=0., resolution='l') x, y = np.meshgrid(lon, lat) X, Y = m(x, y) v = pactive[:, :] * 365 * 24 * 60 * 60 #x2 = np.linspace(x[0][0],x[0][-1],x.shape[1]*20) #y2 = np.linspace(y[0][0],y[-1][0],y.shape[0]*30) x2 = np.linspace(x[0][0], x[0][-1], x.shape[1] * 40) y2 = np.linspace(y[0][0], y[-1][0], y.shape[0] * 60) x2, y2 = np.meshgrid(x2, y2)
#ncvar_len = nclu.variables['growing_season_length'][0,:,:] ##irrigated ncvar_har = nclu.variables['harvest_day'][1, :, :] ncvar_plt = nclu.variables['planting_day'][1, :, :] ncvar_len = nclu.variables['growing_season_length'][1, :, :] latnc = nclu.variables['lat'][:] lonnc = nclu.variables['lon'][:] #lon,lat = N.meshgrid(lonnc,latnc) lat_new = N.flipud(latnc) ncvar_har = N.flipud(ncvar_har) ncvar_plt = N.flipud(ncvar_plt) ncvar_len = N.flipud(ncvar_len) maskus, lona11 = shiftgrid(180.5, maskregion, lonmask, start=False) lon, lat = N.meshgrid(lonnc, lat_new) nclu = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/rice_AreaYieldProduction.nc', 'r') ncvar_m = nclu.variables['riceData'][0, 0, :, :] ncvar_y = nclu.variables['riceData'][0, 1, :, :] ncvar_a = nclu.variables['riceData'][0, 4, :, :] ncvar_p = nclu.variables['riceData'][0, 5, :, :] latnc = nclu.variables['latitude'][:] znc = nclu.variables['level'][:] lonnc = nclu.variables['longitude'][:] timenc = nclu.variables['time'][:] lat_new = N.flipud(latnc)
def yieldout(year): bb = year - 1900 region1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalGLM_crop_150901.nc', 'r') maitrop = region1.variables['maize_trop'][bb - 1, :, :] maitemp = region1.variables['maize_temp'][bb - 1, :, :] maitropi = region1.variables['maize_trop_irrig'][bb - 1, :, :] maitempi = region1.variables['maize_temp_irrig'][bb - 1, :, :] gridarea = region1.variables['area'][:, :] maitrop = ma.masked_where(maitrop <= 0, maitrop) maitrop = ma.filled(maitrop, fill_value=0.) maitemp = ma.masked_where(maitemp <= 0, maitemp) maitemp = ma.filled(maitemp, fill_value=0.) maitropi = ma.masked_where(maitropi <= 0, maitropi) maitropi = ma.filled(maitropi, fill_value=0.) maitempi = ma.masked_where(maitempi <= 0, maitempi) maitempi = ma.filled(maitempi, fill_value=0.) maizetor = maitrop + maitemp maizetoi = maitropi + maitempi maizetrop = maitrop + maitropi maizetemp = maitemp + maitempi maizeto = maitrop + maitemp + maitropi + maitempi ff = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalFertilizer.nc', 'r') fert_maitrop = ff.variables['maize_trop_fert'][bb - 1, :, :] fert_maitemp = ff.variables['maize_temp_fert'][bb - 1, :, :] clm = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_rf_fert_0.5x0.5.nc', 'r') # clmtropf = clm.variables['yield'][bb,:,:] clmtropfer = clm.variables['fertilizer'][bb - 1, :, :] clm1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_rf_fert_0.5x0.5.nc', 'r') # clmtempf = clm1.variables['yield'][bb,:,:] clmtempfer = clm1.variables['fertilizer'][bb - 1, :, :] isam = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetrop_historical_co2_rf_fert_0.5x0.5.nc', 'r') clmtropf = isam.variables['totalyield'][bb, :, :] isam1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetemp_historical_co2_rf_fert_0.5x0.5.nc', 'r') clmtempf = isam1.variables['totalyield'][bb, :, :] clm2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetrop_historical_co2_irrig_fert_0.5x0.5.nc', 'r') clmtropfi = clm2.variables['totalyield'][bb, :, :] clm3 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetemp_historical_co2_irrig_fert_0.5x0.5.nc', 'r') clmtempfi = clm3.variables['totalyield'][bb, :, :] clma = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetrop_historical_co2_rf_nofert_0.5x0.5.nc', 'r') clmtropfno = clma.variables['totalyield'][bb, :, :] clm1a = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetemp_historical_co2_rf_nofert_0.5x0.5.nc', 'r') clmtempfno = clm1a.variables['totalyield'][bb, :, :] clm2a = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetrop_historical_co2_irrig_nofert_0.5x0.5.nc', 'r') clmtropfnoi = clm2a.variables['totalyield'][bb, :, :] clm3a = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamhistorical/heat/maizetemp_historical_co2_irrig_nofert_0.5x0.5.nc', 'r') clmtempfnoi = clm3a.variables['totalyield'][bb, :, :] lonisam = clm3a.variables['lon'][:] clmtempfnoi, lonisam1 = shiftgrid(180.5, clmtempfnoi, lonisam, start=False) clmtropfnoi, lonisam1 = shiftgrid(180.5, clmtropfnoi, lonisam, start=False) clmtempfno, lonisam1 = shiftgrid(180.5, clmtempfno, lonisam, start=False) clmtropfno, lonisam1 = shiftgrid(180.5, clmtropfno, lonisam, start=False) clmtempf, lonisam1 = shiftgrid(180.5, clmtempf, lonisam, start=False) clmtropf, lonisam1 = shiftgrid(180.5, clmtropf, lonisam, start=False) clmtempfi, lonisam1 = shiftgrid(180.5, clmtempfi, lonisam, start=False) clmtropfi, lonisam1 = shiftgrid(180.5, clmtropfi, lonisam, start=False) #print lonisam1 clmtropfer = N.flipud(clmtropfer) clmtempfer = N.flipud(clmtempfer) clmtropf = ma.masked_where(maitrop <= 0, clmtropf) clmtempf = ma.masked_where(maitemp <= 0, clmtempf) clmtropf = ma.filled(clmtropf, fill_value=0.) clmtempf = ma.filled(clmtempf, fill_value=0.) clmtropfi = ma.masked_where(maitropi <= 0, clmtropfi) clmtempfi = ma.masked_where(maitempi <= 0, clmtempfi) clmtropfi = ma.filled(clmtropfi, fill_value=0.) clmtempfi = ma.filled(clmtempfi, fill_value=0.) clmtropfno = ma.masked_where(maitrop <= 0, clmtropfno) clmtempfno = ma.masked_where(maitemp <= 0, clmtempfno) clmtropfno = ma.filled(clmtropfno, fill_value=0.) clmtempfno = ma.filled(clmtempfno, fill_value=0.) clmtropfnoi = ma.masked_where(maitropi <= 0, clmtropfnoi) clmtempfnoi = ma.masked_where(maitempi <= 0, clmtempfnoi) clmtropfnoi = ma.filled(clmtropfnoi, fill_value=0.) clmtempfnoi = ma.filled(clmtempfnoi, fill_value=0.) fertfractiontrop = N.zeros((360, 720)) nofertfractiontrop = N.zeros((360, 720)) fertfractiontemp = N.zeros((360, 720)) nofertfractiontemp = N.zeros((360, 720)) for x in range(0, 360): for y in range(0, 720): if clmtropfer[x, y] > 0.0: fertfractiontrop[x, y] = min( 1.0, fert_maitrop[x, y] / clmtropfer[x, y]) nofertfractiontrop[x, y] = 1.0 - fertfractiontrop[x, y] else: fertfractiontrop[x, y] = 0.0 nofertfractiontrop[x, y] = 1.0 for x in range(0, 360): for y in range(0, 720): if clmtempfer[x, y] > 0.0: fertfractiontemp[x, y] = min( 1.0, fert_maitemp[x, y] / clmtempfer[x, y]) nofertfractiontemp[x, y] = 1.0 - fertfractiontemp[x, y] else: fertfractiontemp[x, y] = 0.0 nofertfractiontemp[x, y] = 1.0 clmtropfnew = N.zeros((360, 720)) clmtempfnew = N.zeros((360, 720)) clmtropfinew = N.zeros((360, 720)) clmtempfinew = N.zeros((360, 720)) for x in range(0, 360): for y in range(0, 720): clmtropfnew[x, y] = (nofertfractiontrop[x, y] * clmtropfno[x, y]) + ( fertfractiontrop[x, y] * clmtropf[x, y]) clmtempfnew[x, y] = (nofertfractiontemp[x, y] * clmtempfno[x, y]) + ( fertfractiontemp[x, y] * clmtempf[x, y]) clmtropfinew[x, y] = (nofertfractiontrop[x, y] * clmtropfnoi[x, y] ) + (fertfractiontrop[x, y] * clmtropfi[x, y]) clmtempfinew[x, y] = (nofertfractiontemp[x, y] * clmtempfnoi[x, y] ) + (fertfractiontemp[x, y] * clmtempfi[x, y]) yield_clmtf = clmtropf + clmtempf yield_clmtf = ma.masked_where(yield_clmtf <= 0, yield_clmtf) #yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf ) yield_clmtf = ma.filled(yield_clmtf, fill_value=0.) yield_clmtfi = clmtropfi + clmtempfi yield_clmtfi = ma.masked_where(yield_clmtfi <= 0, yield_clmtfi) #yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi) yield_clmtfi = ma.filled(yield_clmtfi, fill_value=0.) yield_clmtfnew = clmtropfnew + clmtempfnew yield_clmtfnew = ma.masked_where(yield_clmtfnew <= 0, yield_clmtfnew) #yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf ) yield_clmtfnew = ma.filled(yield_clmtfnew, fill_value=0.) yield_clmtfinew = clmtropfinew + clmtempfinew yield_clmtfinew = ma.masked_where(yield_clmtfinew <= 0, yield_clmtfinew) #yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi) yield_clmtfinew = ma.filled(yield_clmtfinew, fill_value=0.) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'][:, :] gridlon = area.variables['lon'][:] gridlat = area.variables['lat'][:] gridarea, gridlon = shiftgrid(180.5, gridarea, gridlon, start=False) lon2, lat2 = N.meshgrid(gridlon, gridlat) map = Basemap(projection='cyl', llcrnrlat=-65, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') x, y = map(lon2, lat2) yield_clmtf = maskoceans(x, y, yield_clmtf) yield_clmtf = ma.masked_where(maizeto <= 0, yield_clmtf) yield_clmtfi = maskoceans(x, y, yield_clmtfi) yield_clmtfi = ma.masked_where(maizeto <= 0, yield_clmtfi) clmy = ((yield_clmtf * maizetor * gridarea) + (yield_clmtfi * maizetoi * gridarea)) / ((maizetoi * gridarea) + (maizetor * gridarea)) yield_clmtfnew = maskoceans(x, y, yield_clmtfnew) yield_clmtfnew = ma.masked_where(maizeto <= 0, yield_clmtfnew) yield_clmtfinew = maskoceans(x, y, yield_clmtfinew) yield_clmtfinew = ma.masked_where(maizeto <= 0, yield_clmtfinew) clmynew = ((yield_clmtfnew * maizetor * gridarea) + (yield_clmtfinew * maizetoi * gridarea)) / ( (maizetoi * gridarea) + (maizetor * gridarea)) return clmynew
dat3=NetCDFFile('/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/his_cru/new/soy_irr/output/soy_irr.nc','r') iyield3ynew = dat3.variables['totalyield'][0:115,:,:] dat4=NetCDFFile('/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/his_cru/new/soy_co2/output/soy_co2.nc','r') iyield4ynew = dat4.variables['totalyield'][0:115,:,:] dat5=NetCDFFile('/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/his_cru/new/soy_cli/output/soy_cli.nc','r') iyield5ynew = dat5.variables['totalyield'][0:115,:,:] iyield6ynew=N.zeros((115,360,720)) dat6=NetCDFFile('/scratch2/scratchdirs/tslin2/isam/maisoy_cheyenne/code/isamhiscru_soy_mirca.nc','r') lonisam1=dat6.variables['lon'][:] for z in range(0,115): aa= dat6.variables['yield'][z,:,:] maizeto1r,lonisam2=shiftgrid(0.5,aa,lonisam1,start=True) iyield6ynew[z,:,:] = maizeto1r iyield1ynew= ma.masked_where(iyield1ynew<=0.,iyield1ynew) iyield2ynew= ma.masked_where(iyield2ynew<=0.,iyield2ynew) iyield3ynew= ma.masked_where(iyield3ynew<=0.,iyield3ynew) iyield4ynew= ma.masked_where(iyield4ynew<=0.,iyield4ynew) iyield5ynew= ma.masked_where(iyield5ynew<=0.,iyield5ynew) iyield6ynew= ma.masked_where(iyield6ynew<=0.,iyield6ynew) eiyield1ynew= ma.masked_where(eiyield1ynew<=0.,eiyield1ynew) eiyield2ynew= ma.masked_where(eiyield2ynew<=0.,eiyield2ynew) eiyield3ynew= ma.masked_where(eiyield3ynew<=0.,eiyield3ynew)
mask = NetCDFFile('india_mask.nc', 'r') ind = mask.variables['MASK'][:, :] ind = ma.masked_where(ind <= 0.0, ind) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'] isam = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/rice_cheyenne/his_cru/ric_irr_fert/output/ric_irr_fert.nc', 'r') lonisam1 = isam.variables['lon'][:] ric_i_f = isam.variables['totalyield'][96:103, :, :] riceb = N.average(ric_i_f, axis=0) riceb, lona11 = shiftgrid(180.5, riceb, lonisam1, start=False) nclu = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/rice_AreaYieldProduction.nc', 'r') ncvar_m = nclu.variables['riceData'][0, 0, :, :] ncvar_y = nclu.variables['riceData'][0, 1, :, :] ncvar_a = nclu.variables['riceData'][0, 4, :, :] ncvar_p = nclu.variables['riceData'][0, 5, :, :] latnc = nclu.variables['latitude'][:] znc = nclu.variables['level'][:] lonnc = nclu.variables['longitude'][:] timenc = nclu.variables['time'][:] lat_new = N.flipud(latnc)
def annualyield(year,couna,counb): bb=year-2006 region1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/RCP85_crop_150901.nc','r') maitrop = region1.variables['soy_trop'][bb,:,:] maitemp = region1.variables['soy_temp'][bb,:,:] maitropi=region1.variables['soy_trop_irrig'][bb,:,:] maitempi=region1.variables['soy_temp_irrig'][bb,:,:] gridarea = region1.variables['area'][:,:] maitrop=ma.masked_where(maitrop<=0,maitrop) maitrop=ma.filled(maitrop, fill_value=0.) maitemp=ma.masked_where(maitemp<=0,maitemp) maitemp=ma.filled(maitemp, fill_value=0.) maitropi=ma.masked_where(maitropi<=0,maitropi) maitropi=ma.filled(maitropi, fill_value=0.) maitempi=ma.masked_where(maitempi<=0,maitempi) maitempi=ma.filled(maitempi, fill_value=0.) maizetro=maitrop+maitropi maizetem=maitemp+maitempi maizetor=maitrop+maitemp maizetoi=maitropi+maitempi maizeto = maitrop+maitemp+maitropi+maitempi clm=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytrop_rcp85_constco2_rf_nofert_0.5x0.5.nc','r') clmtropf = clm.variables['yield'][bb,:,:] clm1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytemp_rcp85_constco2_rf_nofert_0.5x0.5.nc','r') clmtempf = clm1.variables['yield'][bb,:,:] clm2=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytrop_rcp85_co2_rf_nofert_0.5x0.5.nc','r') clmtropfi = clm2.variables['yield'][bb,:,:] clm3=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytemp_rcp85_co2_rf_nofert_0.5x0.5.nc','r') clmtempfi = clm3.variables['yield'][bb,:,:] clmtropf=N.flipud(clmtropf) clmtempf=N.flipud(clmtempf) clmtropfi=N.flipud(clmtropfi) clmtempfi=N.flipud(clmtempfi) clmtropf= ma.masked_where(maizetro<=0,clmtropf) clmtempf= ma.masked_where(maizetem<=0,clmtempf) clmtropf=ma.filled(clmtropf, fill_value=0.) clmtempf=ma.filled(clmtempf, fill_value=0.) clmtropfi= ma.masked_where(maizetro<=0,clmtropfi) clmtempfi= ma.masked_where(maizetem<=0,clmtempfi) clmtropfi=ma.filled(clmtropfi, fill_value=0.) clmtempfi=ma.filled(clmtempfi, fill_value=0.) yield_clmtf=clmtropf+clmtempf yield_clmtf = ma.masked_where(yield_clmtf<=0,yield_clmtf) yield_clmtf = ma.masked_where(maizeto<=0,yield_clmtf ) yield_clmtf=ma.filled(yield_clmtf, fill_value=0.) yield_clmtfi=clmtropfi+clmtempfi yield_clmtfi = ma.masked_where(yield_clmtfi<=0,yield_clmtfi) yield_clmtfi = ma.masked_where(maizeto<=0,yield_clmtfi) yield_clmtfi=ma.filled(yield_clmtfi, fill_value=0.) clmn=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytrop_rcp85_co2_rf_fert_0.5x0.5.nc','r') clmtropfn = clmn.variables['yield'][bb,:,:] clm1n=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytemp_rcp85_co2_rf_fert_0.5x0.5.nc','r') clmtempfn = clm1n.variables['yield'][bb,:,:] clm2n=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytrop_rcp85_co2_irrig_fert_0.5x0.5.nc','r') clmtropfin = clm2n.variables['yield'][bb,:,:] clm3n=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45rcp85/soytemp_rcp85_co2_irrig_fert_0.5x0.5.nc','r') clmtempfin = clm3n.variables['yield'][bb,:,:] clmtropfn=N.flipud(clmtropfn) clmtempfn=N.flipud(clmtempfn) clmtropfin=N.flipud(clmtropfin) clmtempfin=N.flipud(clmtempfin) clmtropfn= ma.masked_where(maizetro<=0,clmtropfn) clmtempfn= ma.masked_where(maizetem<=0,clmtempfn) clmtropfn=ma.filled(clmtropfn, fill_value=0.) clmtempfn=ma.filled(clmtempfn, fill_value=0.) clmtropfin= ma.masked_where(maizetro<=0,clmtropfin) clmtempfin= ma.masked_where(maizetem<=0,clmtempfin) clmtropfin=ma.filled(clmtropfin, fill_value=0.) clmtempfin=ma.filled(clmtempfin, fill_value=0.) yield_clmtfn=clmtropfn+clmtempfn yield_clmtfn = ma.masked_where(yield_clmtfn<=0,yield_clmtfn) yield_clmtfn = ma.masked_where(maizeto<=0,yield_clmtfn ) yield_clmtfn=ma.filled(yield_clmtfn, fill_value=0.) yield_clmtfin=clmtropfin+clmtempfin yield_clmtfin = ma.masked_where(yield_clmtfin<=0,yield_clmtfin) yield_clmtfin = ma.masked_where(maizeto<=0,yield_clmtfin) yield_clmtfin=ma.filled(yield_clmtfin, fill_value=0.) base = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytemp_rcp85_constco2_rf_nofert_0.5x0.5.nc", mode='r') base2 = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytemp_rcp85_co2_rf_nofert_0.5x0.5.nc", mode='r') lona1 = base.variables["lon"][:] lata1 = base.variables["lat"][:] yieldf = base.variables["totalyield"][bb,:,:] yieldfa = base2.variables["totalyield"][bb,:,:] basei = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytemp_rcp85_co2_rf_fert_0.5x0.5.nc", mode='r') base2i = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytemp_rcp85_co2_irrig_fert_0.5x0.5.nc", mode='r') yieldfi = basei.variables["totalyield"][bb,:,:] yieldfai = base2i.variables["totalyield"][bb,:,:] baseif = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytrop_rcp85_co2_rf_fert_0.5x0.5.nc", mode='r') base2if = NetCDFFile ("/scratch2/scratchdirs/tslin2/isam/cheyenne/yieldout/isamrcp85/heat/new1/soytrop_rcp85_co2_irrig_fert_0.5x0.5.nc", mode='r') yieldfitr = baseif.variables["totalyield"][bb,:,:] yieldfaitr = base2if.variables["totalyield"][bb,:,:] yielda=yieldf yield_new,lona11 = shiftgrid(180.5,yielda,lona1,start=False) yieldb=yieldfa yield_new1,lona11 = shiftgrid(180.5,yieldb,lona1,start=False) yieldai=yieldfi yield_newi,lona11 = shiftgrid(180.5,yieldai,lona1,start=False) yieldbi=yieldfai yield_new1i,lona11 = shiftgrid(180.5,yieldbi,lona1,start=False) yieldaitr=yieldfitr yield_newitr,lona11 = shiftgrid(180.5,yieldaitr,lona1,start=False) yieldbitr=yieldfaitr yield_new1itr,lona11 = shiftgrid(180.5,yieldbitr,lona1,start=False) yield_new[N.isnan(yield_new)] = -9999 yield_new = ma.masked_where(yield_new<=0,yield_new) yield_new = ma.masked_where(maizeto<=0,yield_new) yield_new=ma.filled(yield_new, fill_value=0.) yield_new1[N.isnan(yield_new1)] = -9999 yield_new1 = ma.masked_where(yield_new1<=0,yield_new1) yield_new1 = ma.masked_where(maizeto<=0,yield_new1) yield_new1=ma.filled(yield_new1, fill_value=0.) yield_newi[N.isnan(yield_newi)] = -9999 yield_newi = ma.masked_where(yield_newi<=0,yield_newi) yield_newi = ma.masked_where(maizetem<=0,yield_newi) yield_newi=ma.filled(yield_newi, fill_value=0.) yield_new1i[N.isnan(yield_new1i)] = -9999 yield_new1i = ma.masked_where(yield_new1i<=0,yield_new1i) yield_new1i = ma.masked_where(maizetem<=0,yield_new1i) yield_new1i=ma.filled(yield_new1i, fill_value=0.) yield_newitr[N.isnan(yield_newitr)] = -9999 yield_newitr = ma.masked_where(yield_newitr<=0,yield_newitr) yield_newitr = ma.masked_where(maizetro<=0,yield_newitr) yield_newitr=ma.filled(yield_newitr, fill_value=0.) yield_new1itr[N.isnan(yield_new1i)] = -9999 yield_new1itr = ma.masked_where(yield_new1itr<=0,yield_new1itr) yield_new1itr = ma.masked_where(maizetro<=0,yield_new1itr) yield_new1itr=ma.filled(yield_new1itr, fill_value=0.) yield_newi=yield_newi+yield_newitr yield_new1i=yield_new1i+yield_new1itr yieldagf=0. yieldg=0. harea=0. a=0 yieldgid=0. yieldgia=0. yieldgib=0. yieldgic=0. yieldgca=0. yieldgcb=0. yieldgcc=0. yieldgcd=0. yieldagfa=0. yieldagfb=0. yieldagfc=0. yieldagfd=0. yieldagfa1=0. yieldagfb1=0. yieldagfc1=0. yieldagfd1=0. yieldagfa=yield_new yieldagfb=yield_new1 yieldagfc=yield_newi yieldagfd=yield_new1i yieldagfa1=yield_clmtf yieldagfb1=yield_clmtfi yieldagfc1=yield_clmtfn yieldagfd1=yield_clmtfin yieldagfa = ma.masked_where(yieldagfa<=0,yieldagfa) yieldagfb = ma.masked_where(yieldagfb<=0,yieldagfb) yieldagfc = ma.masked_where(yieldagfc<=0,yieldagfc) yieldagfd = ma.masked_where(yieldagfd<=0,yieldagfd) yieldagfa1 = ma.masked_where(yieldagfa1<=0,yieldagfa1) yieldagfb1 = ma.masked_where(yieldagfb1<=0,yieldagfb1) yieldagfc1 = ma.masked_where(yieldagfc1<=0,yieldagfc1) yieldagfd1 = ma.masked_where(yieldagfd1<=0,yieldagfd1) maizeto = ma.masked_where(maizeto<=0,maizeto) return yieldagfa,yieldagfa1,yieldagfb,yieldagfb1,yieldagfc,yieldagfc1,yieldagfd,yieldagfd1,maizeto
base = NetCDFFile( "/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cruhis/output/cruhis.bgp-yearly_crop_{0}.nc" .format(year), mode='r') lona1 = base.variables["lon"][:] lata1 = base.variables["lat"][:] yield1 = base.variables["yield"][0, :, :] yieldf[i, :, :] = yield1 #yield2 = base2.variables["totalyield"][:] #yieldf2[i, :, :] = yield2 yielda = N.average(yieldf, axis=0) #yielda2=N.average(yieldf2,axis=0) yield_new, lona11 = shiftgrid(180.5, yielda, lona1, start=False) #yield_new2,lona11 = shiftgrid(180.,yielda2,lona1,start=False) lon2, lat2 = N.meshgrid(lona11, lata1) #print lon2.shape #ncvar_maize2 = interp(ncvar_maizea,lonnc,lat_new,lon,lat,order=1) #yield_smooth = interp(maize_new, lonnc,lat_new, lons_sub,lats_sub , order=1) yield_fine = interp(yield_new, lona11, lata1, lon, lat, order=1) #yield_fine2 = interp(yield_new2, lona11,lata1,lon,lat , order=1) yield_clmtro = interp(clmtropf, lona11, lata1, lon, lat, order=1) yield_clmtep = interp(clmtempf, lona11, lata1, lon, lat, order=1) mask_clm = interp(maizeto, lona11, lata1, lon, lat, order=1)
dat = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/his_cru/noheat/maihis/output/maihis.nc', 'r') iyield1 = dat.variables['totalyield'][99, :, :] dat2 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/his_cru/noheat/maihis_fert/output/maihis_fert.nc', 'r') iyield2 = dat2.variables['totalyield'][99, :, :] dat3 = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/cheyenne/his_cru/noheat/maihis_fertall/output/maihis_fertall.nc', 'r') iyield3 = dat3.variables['totalyield'][99, :, :] gridlon = dat3.variables['lon'][:] gridlat1 = dat3.variables['lat'][:] iyield1f, gridlon1 = shiftgrid(180.5, iyield1, gridlon, start=False) iyield2f, gridlon1 = shiftgrid(180.5, iyield2, gridlon, start=False) iyield3f, gridlon1 = shiftgrid(180.5, iyield3, gridlon, start=False) fig = plt.figure(figsize=(20, 15)) ax2 = fig.add_subplot(421) ax2.set_title("CLM Maize Yield (t/ha)", fontsize=20) map = Basemap(projection='cyl', llcrnrlat=-65, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') x, y = map(gridlon1, gridlat1) #iyield1c=maskoceans(x,y,iyield1c) iyield1c = ma.masked_where(iyield1c <= 0, iyield1c)
### Set limits for contours and colorbars limit85 = np.arange(-0.08, 0.081, 0.001) barlim85 = np.arange(-0.08, 0.081, 0.08) limit15 = np.arange(-0.008, 0.0081, 0.0001) barlim15 = np.arange(-0.008, 0.0081, 0.008) fig = plt.figure() ax1 = plt.subplot(2, 2, 1) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(data[0], lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvar, lons_cyclic = addcyclic(pval[0], lon) pvar, lons_cyclic = shiftgrid(180., pvar, lons_cyclic, start=False) m.drawmapboundary(fill_color='white', color='dimgray', linewidth=0.7) cs85 = m.contourf(x, y, var, limit85, extend='both') cs85q = m.contourf(x, y, pvar, colors='None', hatches=['....'], linewidths=0.4) m.drawcoastlines(color='dimgray', linewidth=0.8) cmap = cmocean.cm.balance cs85.set_cmap(cmap)
### Set limits for contours and colorbars limit = np.arange(-10, 10.1, 1) barlim = np.arange(-10, 11, 5) ### Begin figure fig = plt.figure() ax1 = plt.subplot(131) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(diff_on, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvalue_onq, lons_cyclic = addcyclic(pvalue_on, lon) pvalue_onq, lons_cyclic = shiftgrid(180., pvalue_onq, lons_cyclic, start=False) m.drawmapboundary(fill_color='white', color='dimgray', linewidth=0.7) m.drawcoastlines(color='dimgray', linewidth=0.8) parallels = np.arange(-90, 90, 45) meridians = np.arange(-180, 180, 60) #m.drawparallels(parallels,labels=[True,True,True,True], # linewidth=0.6,color='dimgray',fontsize=6) #m.drawmeridians(meridians,labels=[True,True,True,True], # linewidth=0.6,color='dimgray',fontsize=6) #m.drawlsmask(land_color='dimgray',ocean_color='mintcream')
iyield6ynew = dat6.variables['totalyield'][95:105, :, :] iyield1ynew = ma.masked_where(iyield1ynew <= 0., iyield1ynew) iyield2ynew = ma.masked_where(iyield2ynew <= 0., iyield2ynew) iyield3ynew = ma.masked_where(iyield3ynew <= 0., iyield3ynew) iyield4ynew = ma.masked_where(iyield4ynew <= 0., iyield4ynew) iyield5ynew = ma.masked_where(iyield5ynew <= 0., iyield5ynew) iyield6ynew = ma.masked_where(iyield6ynew <= 0., iyield6ynew) eiyield1ynew = ma.masked_where(eiyield1ynew <= 0., eiyield1ynew) eiyield2ynew = ma.masked_where(eiyield2ynew <= 0., eiyield2ynew) eiyield3ynew = ma.masked_where(eiyield3ynew <= 0., eiyield3ynew) eiyield4ynew = ma.masked_where(eiyield4ynew <= 0., eiyield4ynew) eiyield5ynew = ma.masked_where(eiyield5ynew <= 0., eiyield5ynew) maizeto1, lonisam2 = shiftgrid(0.5, maizeto, lonisam1, start=True) maizeto1r, lonisam2 = shiftgrid(0.5, maitrop, lonisam1, start=True) iyield1ynew = ma.filled(iyield1ynew, fill_value=0.) iyield2ynew = ma.filled(iyield2ynew, fill_value=0.) iyield3ynew = ma.filled(iyield3ynew, fill_value=0.) iyield4ynew = ma.filled(iyield4ynew, fill_value=0.) iyield5ynew = ma.filled(iyield5ynew, fill_value=0.) iyield6ynew = ma.filled(iyield6ynew, fill_value=0.) iyield1ynew = ma.masked_where(iyield1ynew <= 0., iyield1ynew) iyield2ynew = ma.masked_where(iyield2ynew <= 0., iyield2ynew) iyield3ynew = ma.masked_where(iyield3ynew <= 0., iyield3ynew) iyield4ynew = ma.masked_where(iyield4ynew <= 0., iyield4ynew) iyield5ynew = ma.masked_where(iyield5ynew <= 0., iyield5ynew) iyield6ynew = ma.masked_where(iyield6ynew <= 0., iyield6ynew)
import numpy as N import matplotlib.pyplot as plt import glob import numpy.ma as ma from scipy.interpolate import griddata import matplotlib.colors as colors from statsmodels.stats.weightstats import DescrStatsW from scipy.stats import ttest_ind from matplotlib.markers import TICKDOWN import matplotlib.patches as mpatches area=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf_isam.nc','r') gridarea = area.variables['cell_area'][:,:] gridlon = area.variables['lon'][:] gridlat=area.variables['lat'][:] gridarea,gridlon = shiftgrid(180.5,gridarea,gridlon,start=False) #print gridlon nclu=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/soybean_AreaYieldProduction.nc','r') ncvar_maize = nclu.variables['soybeanData'][:] latnc = nclu.variables['latitude'][:] znc = nclu.variables['level'][:] lonnc = nclu.variables['longitude'][:] timenc = nclu.variables['time'][:] latnc=N.flipud(latnc) ncvar_maizef= N.zeros((2160, 4320)) ncvar_maizef=ncvar_maize[0,1,:,:] ncvar_maize1=ncvar_maize[0,4,:,:] ncvar_mask= N.zeros((2160, 4320)) ncvar_mask=ncvar_maize[0,0,:,:]
import matplotlib.pyplot as plt import numpy.ma as ma mask = NetCDFFile('india_mask.nc', 'r') ind = mask.variables['MASK'][:, :] ind = ma.masked_where(ind <= 0.0, ind) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'] isam = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/rice_cheyenne/his_cru/egu_new/ric_irr_fert/output/ric_irr_fert.nc', 'r') lonisam1 = isam.variables['lon'][:] ind, lona11 = shiftgrid(180.5, ind, lonisam1, start=False) ric_i_f = isam.variables['totalyield'][79:109, :, :] ric_i_f, lona11 = shiftgrid(180.5, ric_i_f, lonisam1, start=False) ric_i_f = ma.masked_where(ric_i_f <= 0.0, ric_i_f) ric_i_f = ma.filled(ric_i_f, fill_value=0.) isam = NetCDFFile( '/scratch2/scratchdirs/tslin2/isam/rice_cheyenne/his_cru/egu_new/ric_fert/output/ric_fert.nc', 'r') ric_f = isam.variables['totalyield'][79:109, :, :] ric_f, lona11 = shiftgrid(180.5, ric_f, lonisam1, start=False) ric_f = ma.masked_where(ric_f <= 0.0, ric_f) ric_f = ma.filled(ric_f, fill_value=0.)
rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=50.,lon_0=-107.,ax=ax1) map.drawcoastlines(linewidth=2, color='#444444', zorder=6) map.drawcountries(linewidth=1, color='#444444', zorder=5) map.drawstates(linewidth=0.66, color='#444444', zorder=4) map.drawmapboundary x,y = map(X,Y) cf = map.contour(x,y,temperature_plot,levels=clevs, extend='both',zorder=1,linewidths=2) plt.clabel(cf, inline=1, fontsize=10) # plot wind vectors on projection grid. # first, shift grid so it goes from -180 to 180 (instead of 0 to 360 # in longitude). Otherwise, interpolation is messed up. ugrid,newlons = shiftgrid(180.,u_plot,lons,start=False) vgrid,newlons = shiftgrid(180.,v_plot,lons,start=False) # transform vectors to projection grid and plot windbarbs. uproj,vproj, xx, yy = map.transform_vector(ugrid,vgrid,newlons,lats,41,41,returnxy=True) barbs = map.barbs(xx,yy,uproj,vproj,length=5,barbcolor='k',flagcolor='r',linewidth=0.5) # Title ax1.set_title(str(levelh)+' hPa temperature and wind barbs') # <codecell> # Temperature advection plot cbar_min = -0.0001 cbar_max = 0.0001 cfint = 0.00001 cflevs = np.arange(cbar_min,cbar_max+cfint-(cfint/2),cfint) ncolors = np.size(cflevs)-1
yief = N.zeros((86, 360, 720)) years = range(2015, 2101) for i, yeara in enumerate(years): yie = yieldout(yeara) yief[i, :, :] = yie[0] areaa[i, :, :] = yie[1] yiep[i, :, :] = yie[2] area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf_isam.nc', 'r') gridarea = area.variables['cell_area'][:, :] gridlon = area.variables['lon'][:] gridlat = area.variables['lat'][:] gridarea, gridlon = shiftgrid(180.5, gridarea, gridlon, start=False) #print gridlon gg = N.zeros((86, 360, 720)) for i in range(0, 86): gg[i, :, :] = gridarea[:, :] yiey = yiep / (gg * 0.0001) ncfile = NetCDFFile('isamhiscru_mai_mircarcp45new_evp.nc', 'w', format='NETCDF3_64BIT_OFFSET') ncfile.createDimension('lat', 360) ncfile.createDimension('lon', 720) ncfile.createDimension('time', 86) times = ncfile.createVariable('time', 'f8', ('time', )) latitudes = ncfile.createVariable('lat', 'f8', ('lat', ))
import glob import numpy.ma as ma from scipy.interpolate import griddata import matplotlib.colors as colors from statsmodels.stats.weightstats import DescrStatsW from scipy.stats import ttest_ind from matplotlib.markers import TICKDOWN import datetime from matplotlib.dates import DateFormatter area=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf_isam.nc','r') gridarea = area.variables['cell_area'][:,:] gridlon = area.variables['lon'][:] gridlat=area.variables['lat'][:] gridarea,gridlon = shiftgrid(180.5,gridarea,gridlon,start=False) #print gridlon nclu=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/maize_AreaYieldProduction.nc','r') ncvar_maize = nclu.variables['maizeData'][:] latnc = nclu.variables['latitude'][:] znc = nclu.variables['level'][:] lonnc = nclu.variables['longitude'][:] timenc = nclu.variables['time'][:] latnc=N.flipud(latnc) ncvar_maizef= N.zeros((2160, 4320)) ncvar_maizef=ncvar_maize[0,1,:,:] ncvar_maize1=ncvar_maize[0,4,:,:] ncvar_mask= N.zeros((2160, 4320)) ncvar_mask=ncvar_maize[0,0,:,:]
from mpl_toolkits.basemap import Basemap, cm, shiftgrid, interp, maskoceans from netCDF4 import Dataset as NetCDFFile import numpy as N import matplotlib.pyplot as plt import numpy.ma as ma from statsmodels.stats.weightstats import DescrStatsW import matplotlib.colors as colors region = NetCDFFile( '/global/project/projectdirs/m1602/datasets4.full/arbit_init_state_05x05.nc', 'r') ind = region.variables['REGION_MASK'][:, :] lonisam1 = region.variables['lon'][:] ind, lona11 = shiftgrid(180.5, ind, lonisam1, start=False) area = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc', 'r') gridarea = area.variables['cell_area'][:, :] nclu = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/maize_AreaYieldProduction.nc', 'r') ncvar_m = nclu.variables['maizeData'][0, 0, :, :] ncvar_y = nclu.variables['maizeData'][0, 1, :, :] ncvar_a = nclu.variables['maizeData'][0, 4, :, :] ncvar_p = nclu.variables['maizeData'][0, 5, :, :] nclu1 = NetCDFFile( '/scratch2/scratchdirs/tslin2/plot/globalcrop/data/soybean_AreaYieldProduction.nc', 'r') ncvar_ms = nclu1.variables['soybeanData'][0, 0, :, :] ncvar_ys = nclu1.variables['soybeanData'][0, 1, :, :]