def plot(self, ds=1000, unit='km', cmap='seismic_r', vmin=None, vmax=None, zsize=10): """Plot velocity model ============================================================================= Input Parameters: ds - grid spacing unit - unit vmin, vmax - vmin,vmax for colorbar ============================================================================= """ # XLength=self.xmax-self.xmin # ZLength=self.zmax-self.zmin # xsize=zsize*(XLength/ZLength) # fig = plt.figure(figsize=(xsize, zsize)) if cmap=='ses3d': cmap = colormaps.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) if self.plotflag==False: raise ValueError('No plot array!') # plt.figure(figsize=(16,13)) if self.regular==True: im=plt.pcolormesh(self.XArrPlot/ds, self.ZArrPlot/ds, self.VsArrPlot/ds, cmap=cmap, vmin=vmin, vmax=vmax) else: xi = np.linspace(self.xmin, self.xmax, self.Nx*10) zi = np.linspace(self.zmin, self.zmax, self.Nz*10) self.xi, self.zi = np.meshgrid(xi, zi) #-- Interpolating at the points in xi, yi self.vi = griddata(self.XArr, self.ZArr, self.VsArr, self.xi, self.zi, 'linear') im=plt.pcolormesh(self.xi/ds, self.zi/ds, ma.getdata(self.vi)/ds, cmap=cmap, vmin=vmin, vmax=vmax, shading='gouraud') ########################################## plt.plot(500., 1000 , 'r*', markersize=30, lw=3) # plt.plot( [0., 4000.], [1000, 1000] , 'b--', lw=3) # plt.plot( [500., 500.], [700., 1300.] , 'g-', lw=3) # plt.plot( [500., 3500.], [700., 700.] , 'g-', lw=3) # plt.plot( [500., 3500.], [1300., 1300.] , 'g-', lw=3) # plt.plot( [3500., 3500.], [700., 1300.] , 'g-', lw=3) # # plt.plot( [0., 0.], [0., 2000.] , 'k-', lw=3) # plt.plot( [0., 4000.], [0., 0.] , 'k-', lw=3) # plt.plot( [4000., 4000.], [0., 2000.] , 'k-', lw=3) # plt.plot( [0., 4000.], [2000., 2000.] , 'k-', lw=3) ########################################## plt.xlabel('x('+unit+')', fontsize=35) plt.ylabel('z('+unit+')', fontsize=35) # plt.axis([self.xmin/ds, self.xmax/ds, self.zmin/ds, self.zmax/ds]) plt.axis('scaled') cb=plt.colorbar(shrink=0.8)#, size="3%", pad='2%') cb.set_label('Vs (km/s)', fontsize=20, rotation=90) plt.yticks(fontsize=30) plt.xticks(fontsize=30) ######################## # plt.ylim([-100, 2100]) # plt.xlim([-100, 4100]) ######################## plt.show() return
def region_plot(fname, time, output_dir, julday): #print "fname = %s, day = %d\n" % (fname, time); ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20.48,10.24)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) # for mom output lats = ncfile.variables["yt_ocean"][:] lons = ncfile.variables["xt_ocean"][:] field = ncfile.variables["eta_t"][time,:,:] aveNcfile = nc.Dataset('ocean_eta_annual.nc','r') average = aveNcfile.variables["eta_t"][0,:,:] field = field - average field = ma.array(field) field = ma.masked_where(field == -1.0e10, field) field = ma.masked_where(field<= -10,field) field = ma.masked_where(field>= 100, field) field, lons = addcyclic(field, lons) #field_min = np.min(field) #field_max = np.max(field) x,y = m(*np.meshgrid(lons[:],lats[:])) colorMap = colormaps.make_colormap({0.:'#191970', 0.2:'#448BB9', 0.35:'#1e90ff', 0.5:'w', 0.6:'#F8BC4E', 0.7:'#ffa500', 0.8:'#ff8c00',0.9:'#F56D2E', 1.0:'#CC4000'}) m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(-0.8,0.8,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) #plt.show() ncfile.close()
def plot_colat_slice(self, component, colat, valmin, valmax, iteration=0, verbose=True): #- Some initialisations. ------------------------------------------------------------------ colat = np.pi * colat / 180.0 n_procs = self.setup["procs"]["px"] * self.setup["procs"]["py"] * self.setup["procs"]["pz"] vmax = float("-inf") vmin = float("inf") fig, ax = plt.subplots() #- Loop over processor boxes and check if colat falls within the volume. ------------------ for p in range(n_procs): if (colat >= self.theta[p,:].min()) & (colat <= self.theta[p,:].max()): #- Read this field and make lats & lons. ------------------------------------------ field = self.read_single_box(component,p,iteration) r, lon = np.meshgrid(self.z[p,:], self.phi[p,:]) x = r * np.cos(lon) y = r * np.sin(lon) #- Find the colat index and plot for this one box. -------------------------------- idx=min(np.where(min(np.abs(self.theta[p,:]-colat))==np.abs(self.theta[p,:]-colat))[0]) colat_effective = self.theta[p,idx]*180.0/np.pi #- Find min and max values. ------------------------------------------------------- vmax = max(vmax, field[idx,:,:].max()) vmin = min(vmin, field[idx,:,:].min()) #- Make a nice colourmap and plot. ------------------------------------------------ my_colormap=cm.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) cax = ax.pcolor(x, y, field[idx,:,:], cmap=my_colormap, vmin=valmin,vmax=valmax) #- Add colobar and title. ------------------------------------------------------------------ cbar = fig.colorbar(cax) if component in UNIT_DICT: cb.set_label(UNIT_DICT[component], fontsize="x-large", rotation=0) plt.suptitle("Vertical slice of %s at %i degree colatitude" % (component, colat_effective), size="large") plt.axis('equal') plt.show()
def plot_appV(self, projection='lambert', geopolygons=None, showfig=True, vmin=None, vmax=None): """Plot data with contour """ m=self._get_basemap(projection=projection, geopolygons=geopolygons) x, y=m(self.lonArr, self.latArr) cmap = colormaps.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) im=m.pcolormesh(x, y, self.appV, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) cb = m.colorbar(im, "right", size="3%", pad='2%') cb.ax.tick_params(labelsize=10) cb.set_label(r"$\frac{\mathrm{km}}{\mathrm{s}}$", fontsize=8, rotation=0) if showfig: plt.show() return
def plot_vel_iso(self, dataid=None, period=None, projection='lambert', fastaxis=False, geopolygons=None, showfig=True, vmin=None, vmax=None): """Plot isotropic velocity """ if dataid != None and period != None: self.get_data4plot(dataid=dataid, period=period) try: vel_iso = self.vel_iso except: print 'Specify dataid and period to get data for plotting!' return m = self._get_basemap(projection=projection, geopolygons=geopolygons) x, y = m(self.lonArr, self.latArr) cmap = colormaps.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) im = m.pcolormesh(x, y, vel_iso, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label('V' + self.datatype + ' (km/s)', fontsize=12, rotation=0) plt.title(str(self.period) + ' sec', fontsize=20) if fastaxis: try: self.plot_fast_axis(inbasemap=m) except: pass if showfig: plt.show() return
def region_plot(fname, time, output_dir, julday): ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20,10)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) # for ofam salinity lats = ncfile.variables["yt_ocean"][:] lons = ncfile.variables["xt_ocean"][:] field = ncfile.variables["salt"][time,0,:,:] aveNcfile = nc.Dataset('ocean_salt_annual.nc','r') average = aveNcfile.variables["salt"][0,0,:,:] field = field - average field = ma.array(field) field = ma.masked_where(field == -1.0e10, field) field = ma.masked_where(field<= -10,field) field = ma.masked_where(field>= 100, field) field, lons = addcyclic(field, lons) x,y = m(*np.meshgrid(lons[:],lats[:])) colorMap = colormaps.make_colormap({0.:'#010233', 0.3:'#01034B',0.4:'#02035F',0.42:'#28297B', 0.45:'#3B3D8E', 0.5:'w', 0.55:'#B32222',0.58:'#731515',0.6:'#600202',0.7:'#4B0202', 1.0:'#330101'}) # red to blue m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(-2,2,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) ncfile.close()
def plot_array(self, inarray, title='', label='', projection='lambert', fastaxis=False, geopolygons=None, showfig=True, vmin=None, vmax=None): """Plot input array """ if inarray.shape != self.lonArr.shape: raise ValueError( 'Shape of input array is not compatible with longitude/latitude array!' ) m = self._get_basemap(projection=projection, geopolygons=geopolygons) x, y = m(self.lonArr, self.latArr) cmap = colormaps.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) im = m.pcolormesh(x, y, inarray, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label(label, fontsize=12, rotation=0) plt.title(title + str(self.period) + ' sec', fontsize=20) if fastaxis: try: self.plot_fast_axis(inbasemap=m) except: pass if showfig: plt.show() return
def plot_global_map(self, period, resolution='i', inglbpfx='./MAPS/smpkolya_phv_R', geopolygons=None, showfig=True, vmin=None, vmax=None): """ Plot global phave velocity map ================================================================================================================= Input Parameters: period - input period resolution - resolution in Basemap object inglbpfx - prefix of input global velocity map files geopolygons - geopolygons for plotting showfig - show figure or not vmin/vmax - minimum/maximum value for plotting ================================================================================================================= """ inglbfname=inglbpfx+'_'+str(int(period)) inArr = np.loadtxt(inglbfname) lonArr=inArr[:,0] lonArr[lonArr>180]=lonArr[lonArr>180]-360 lonArr=lonArr.reshape(181, 360) latArr=inArr[:,1] latArr=latArr.reshape(181, 360) phvArr=inArr[:,2] phvArr=phvArr.reshape(181, 360) minlon=self.attrs['minlon'] maxlon=self.attrs['maxlon'] minlat=self.attrs['minlat'] maxlat=self.attrs['maxlat'] lat_centre = (maxlat+minlat)/2.0 lon_centre = (maxlon+minlon)/2.0 m=Basemap(projection='moll',lon_0=lon_centre, lat_0=lat_centre, resolution=resolution) x, y=m(lonArr, latArr) cmap = colormaps.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) im=m.pcolormesh(x, y, phvArr, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) m.drawcoastlines(linewidth=1.0) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label('Vph'+' (km/s)', fontsize=12, rotation=0) plt.title(str(period)+' sec', fontsize=20) # m.readshapefile('./tectonicplates/PB2002_plates', # name='tectonic_plates', # drawbounds=True, # color='red') if showfig: plt.show() return
def plot_vel_iso(self, projection='lambert', fastaxis=False, geopolygons=None, showfig=True, vmin=None, vmax=None): """Plot isotropic velocity """ m=self._get_basemap(projection=projection, geopolygons=geopolygons) x, y=m(self.lonArr, self.latArr) cmap = colormaps.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) im=m.pcolormesh(x, y, self.vel_iso, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label('V'+self.datatype+' (km/s)', fontsize=12, rotation=0) plt.title(str(self.period)+' sec', fontsize=20) if fastaxis: try: self.plot_fast_axis(inbasemap=m) except: pass if showfig: plt.show() return
def plot_array(self, inarray, title='', label='', projection='lambert', fastaxis=False, geopolygons=None, showfig=True, vmin=None, vmax=None): """Plot input array """ if inarray.shape!=self.lonArr.shape: raise ValueError('Shape of input array is not compatible with longitude/latitude array!') m=self._get_basemap(projection=projection, geopolygons=geopolygons) x, y=m(self.lonArr, self.latArr) cmap = colormaps.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) im=m.pcolormesh(x, y, inarray, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label(label, fontsize=12, rotation=0) plt.title(title+str(self.period)+' sec', fontsize=20) if fastaxis: try: self.plot_fast_axis(inbasemap=m) except: pass if showfig: plt.show() return
def plot_colat_slice(self, component, colat, valmin, valmax, iteration=0, verbose=True): #- Some initialisations. ------------------------------------------------------------------ colat = np.pi * colat / 180.0 n_procs = self.setup["procs"]["px"] * self.setup["procs"][ "py"] * self.setup["procs"]["pz"] vmax = float("-inf") vmin = float("inf") fig, ax = plt.subplots() #- Loop over processor boxes and check if colat falls within the volume. ------------------ for p in range(n_procs): if (colat >= self.theta[p, :].min()) & (colat <= self.theta[p, :].max()): #- Read this field and make lats & lons. ------------------------------------------ field = self.read_single_box(component, p, iteration) r, lon = np.meshgrid(self.z[p, :], self.phi[p, :]) x = r * np.cos(lon) y = r * np.sin(lon) #- Find the colat index and plot for this one box. -------------------------------- idx = min( np.where( min(np.abs(self.theta[p, :] - colat)) == np.abs(self.theta[p, :] - colat))[0]) colat_effective = self.theta[p, idx] * 180.0 / np.pi #- Find min and max values. ------------------------------------------------------- vmax = max(vmax, field[idx, :, :].max()) vmin = min(vmin, field[idx, :, :].min()) #- Make a nice colourmap and plot. ------------------------------------------------ my_colormap = cm.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) cax = ax.pcolor(x, y, field[idx, :, :], cmap=my_colormap, vmin=valmin, vmax=valmax) #- Add colobar and title. ------------------------------------------------------------------ cbar = fig.colorbar(cax) if component in UNIT_DICT: cb.set_label(UNIT_DICT[component], fontsize="x-large", rotation=0) plt.suptitle("Vertical slice of %s at %i degree colatitude" % (component, colat_effective), size="large") plt.axis('equal') plt.show()
def plot_global_map(self, period, resolution='i', inglbpfx='./MAPS/smpkolya_phv_R', geopolygons=None, showfig=True, vmin=None, vmax=None): """ Plot global phave velocity map ================================================================================================================= Input Parameters: period - input period resolution - resolution in Basemap object inglbpfx - prefix of input global velocity map files geopolygons - geopolygons for plotting showfig - show figure or not vmin/vmax - minimum/maximum value for plotting ================================================================================================================= """ inglbfname = inglbpfx + '_' + str(int(period)) inArr = np.loadtxt(inglbfname) lonArr = inArr[:, 0] lonArr[lonArr > 180] = lonArr[lonArr > 180] - 360 lonArr = lonArr.reshape(181, 360) latArr = inArr[:, 1] latArr = latArr.reshape(181, 360) phvArr = inArr[:, 2] phvArr = phvArr.reshape(181, 360) minlon = self.attrs['minlon'] maxlon = self.attrs['maxlon'] minlat = self.attrs['minlat'] maxlat = self.attrs['maxlat'] lat_centre = (maxlat + minlat) / 2.0 lon_centre = (maxlon + minlon) / 2.0 m = Basemap(projection='moll', lon_0=lon_centre, lat_0=lat_centre, resolution=resolution) x, y = m(lonArr, latArr) cmap = colormaps.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) im = m.pcolormesh(x, y, phvArr, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) m.drawcoastlines(linewidth=1.0) cb = m.colorbar(im, "bottom", size="3%", pad='2%') cb.set_label('Vph' + ' (km/s)', fontsize=12, rotation=0) plt.title(str(period) + ' sec', fontsize=20) # m.readshapefile('./tectonicplates/PB2002_plates', # name='tectonic_plates', # drawbounds=True, # color='red') if showfig: plt.show() return
def plot_slice(self, depth, colormap='tomo', res='i', verbose=False): """ plot horizontal slices through an ses3d model plot_slice(self,depth,colormap='tomo',res='i',verbose=False) depth=depth in km of the slice colormap='tomo','mono' res=resolution of the map, admissible values are: c, l, i, h f """ radius = 6371.0 - depth #- set up a map and colourmap ----------------------------------------- if self.global_regional == 'regional': m = Basemap(projection='merc', llcrnrlat=self.lat_min, urcrnrlat=self.lat_max, llcrnrlon=self.lon_min, urcrnrlon=self.lon_max, lat_ts=20, resolution=res) m.drawparallels(np.arange(self.lat_min, self.lat_max, self.d_lon), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(self.lon_min, self.lon_max, self.d_lat), labels=[1, 0, 0, 1]) elif self.global_regional == 'global': m = Basemap(projection='ortho', lon_0=self.lon_centre, lat_0=self.lat_centre, resolution=res) m.drawparallels(np.arange(-80.0, 80.0, 10.0), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(-170.0, 170.0, 10.0), labels=[1, 0, 0, 1]) m.drawcoastlines() m.drawcountries() m.drawmapboundary(fill_color=[1.0, 1.0, 1.0]) if colormap == 'tomo': my_colormap = cm.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) elif colormap == 'mono': my_colormap = cm.make_colormap({ 0.0: [1.0, 1.0, 1.0], 0.15: [1.0, 1.0, 1.0], 0.85: [0.0, 0.0, 0.0], 1.0: [0.0, 0.0, 0.0] }) #- loop over subvolumes to collect information ------------------------ x_list = [] y_list = [] idz_list = [] N_list = [] for k in np.arange(self.nsubvol): r = self.m[k].r #- collect subvolumes within target depth if (max(r) >= radius) & (min(r) < radius): N_list.append(k) r = r[0:len(r) - 1] idz = min( np.where(min(np.abs(r - radius)) == np.abs(r - radius))[0]) if idz == len(r): idz -= idz idz_list.append(idz) if verbose == True: print 'true plotting depth: ' + str(6371.0 - r[idz]) + ' km' x, y = m(self.m[k].lon_rot, self.m[k].lat_rot) x_list.append(x) y_list.append(y) #- make a (hopefully) intelligent colour scale ------------------------ if len(N_list) > 0: #- compute some diagnostics min_list = [] max_list = [] percentile_list = [] for k in np.arange(len(N_list)): min_list.append(np.min(self.m[N_list[k]].v[:, :, idz_list[k]])) max_list.append(np.max(self.m[N_list[k]].v[:, :, idz_list[k]])) percentile_list.append( np.percentile( np.abs(self.m[N_list[k]].v[:, :, idz_list[k]]), 99.0)) minval = np.min(min_list) maxval = np.max(max_list) percent = np.max(percentile_list) #- min and max roughly centred around zero if (minval * maxval < 0.0): max_val_plot = percent min_val_plot = -max_val_plot #- min and max not centred around zero else: max_val_plot = maxval min_val_plot = minval #- loop over subvolumes to plot --------------------------------------- for k in np.arange(len(N_list)): im = m.pcolor(x_list[k], y_list[k], self.m[N_list[k]].v[:, :, idz_list[k]], cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot) m.colorbar(im, "right", size="3%", pad='2%') plt.title(str(depth) + ' km') plt.show()
def plot_threshold(self, val, min_val_plot, max_val_plot, colormap='tomo', verbose=False): """ plot depth to a certain threshold value 'val' in an ses3d model plot_threshold(val,min_val_plot,max_val_plot,colormap='tomo',verbose=False): val=threshold value min_val_plot, max_val_plot=minimum and maximum values of the colour scale colormap='tomo','mono' """ #- set up a map and colourmap if self.global_regional == 'regional': m = Basemap(projection='merc', llcrnrlat=self.lat_min, urcrnrlat=self.lat_max, llcrnrlon=self.lon_min, urcrnrlon=self.lon_max, lat_ts=20, resolution=res) m.drawparallels(np.arange(self.lat_min, self.lat_max, self.d_lon), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(self.lon_min, self.lon_max, self.d_lat), labels=[1, 0, 0, 1]) elif self.global_regional == 'global': m = Basemap(projection='ortho', lon_0=self.lon_centre, lat_0=self.lat_centre, resolution=res) m.drawparallels(np.arange(-80.0, 80.0, 10.0), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(-170.0, 170.0, 10.0), labels=[1, 0, 0, 1]) m.drawcoastlines() m.drawcountries() m.drawmapboundary(fill_color=[1.0, 1.0, 1.0]) if colormap == 'tomo': my_colormap = cm.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) elif colormap == 'mono': my_colormap = cm.make_colormap({ 0.0: [1.0, 1.0, 1.0], 0.15: [1.0, 1.0, 1.0], 0.85: [0.0, 0.0, 0.0], 1.0: [0.0, 0.0, 0.0] }) #- loop over subvolumes for k in np.arange(self.nsubvol): depth = np.zeros(np.shape(self.m[k].v[:, :, 0])) nx = len(self.m[k].lat) ny = len(self.m[k].lon) #- find depth r = self.m[k].r r = 0.5 * (r[0:len(r) - 1] + r[1:len(r)]) for idx in np.arange(nx - 1): for idy in np.arange(ny - 1): n = self.m[k].v[idx, idy, :] >= val depth[idx, idy] = 6371.0 - np.max(r[n]) #- rotate coordinate system if necessary lon, lat = np.meshgrid(self.m[k].lon[0:ny], self.m[k].lat[0:nx]) if self.phi != 0.0: lat_rot = np.zeros(np.shape(lon), dtype=float) lon_rot = np.zeros(np.shape(lat), dtype=float) for idx in np.arange(nx): for idy in np.arange(ny): colat = 90.0 - lat[idx, idy] lat_rot[idx, idy], lon_rot[idx, idy] = rot.rotate_coordinates( self.n, -self.phi, colat, lon[idx, idy]) lat_rot[idx, idy] = 90.0 - lat_rot[idx, idy] lon = lon_rot lat = lat_rot #- convert to map coordinates and plot x, y = m(lon, lat) im = m.pcolor(x, y, depth, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot) m.colorbar(im, "right", size="3%", pad='2%') plt.title('depth to ' + str(val) + ' km/s [km]') plt.show()
def plot_depth_slice(self, component, depth, valmin, valmax, iteration=0, verbose=True, stations=True, res="i"): """ plot_depth_slice(self, component, depth, valmin, valmax, iteration=0, verbose=True, stations=True, res="i") Plot depth slices of field component at depth "depth" with colourbar ranging between "valmin" and "valmax". The resolution of the coastline is "res" (c, l, i, h, f). The currently available "components" are: Material parameters: A, B, C, mu, lambda, rhoinv, vp, vsh, vsv, rho Velocity field snapshots: vx, vy, vz Sensitivity kernels: Q_mu, Q_kappa, alpha_mu, alpha_kappa """ #- Some initialisations. ------------------------------------------------------------------ n_procs = self.setup["procs"]["px"] * self.setup["procs"]["py"] * self.setup["procs"]["pz"] radius = 1000.0 * (6371.0 - depth) vmax = float("-inf") vmin = float("inf") lat_min = 90.0 - self.setup["domain"]["theta_max"]*180.0/np.pi lat_max = 90.0 - self.setup["domain"]["theta_min"]*180.0/np.pi lon_min = self.setup["domain"]["phi_min"]*180.0/np.pi lon_max = self.setup["domain"]["phi_max"]*180.0/np.pi lat_centre = (lat_max+lat_min)/2.0 lon_centre = (lon_max+lon_min)/2.0 lat_centre,lon_centre = rot.rotate_coordinates(self.n,-self.rotangle,90.0-lat_centre,lon_centre) lat_centre = 90.0-lat_centre d_lon = np.round((lon_max-lon_min)/10.0) d_lat = np.round((lat_max-lat_min)/10.0) #- Set up the map. ------------------------------------------------------------------------ if (lat_max-lat_min) > 30.0: m = Basemap(projection='ortho', lon_0=lon_centre, lat_0=lat_centre, resolution=res) m.drawparallels(np.arange(-80.0,80.0,10.0),labels=[1,0,0,1]) m.drawmeridians(np.arange(-170.0,170.0,10.0),labels=[1,0,0,1]) else: m=Basemap(projection='merc',llcrnrlat=lat_min,urcrnrlat=lat_max,llcrnrlon=lon_min,urcrnrlon=lon_max,lat_ts=20,resolution=res) m.drawparallels(np.arange(np.round(lat_min),np.round(lat_max),d_lat),labels=[1,0,0,1]) m.drawmeridians(np.arange(np.round(lon_min),np.round(lon_max),d_lon),labels=[1,0,0,1]) m.drawcoastlines() m.fillcontinents("0.9", zorder=0) m.drawmapboundary(fill_color="white") m.drawcountries() #- Loop over processor boxes and check if depth falls within the volume. ------------------ for p in range(n_procs): if (radius >= self.z[p,:].min()) & (radius <= self.z[p,:].max()): #- Read this field and make lats & lons. ------------------------------------------ field = self.read_single_box(component,p,iteration) lats = 90.0 - self.theta[p,:] * 180.0 / np.pi lons = self.phi[p,:] * 180.0 / np.pi lon, lat = np.meshgrid(lons, lats) #- Find the depth index and plot for this one box. -------------------------------- idz=min(np.where(min(np.abs(self.z[p,:]-radius))==np.abs(self.z[p,:]-radius))[0]) r_effective = int(self.z[p,idz]/1000.0) #- Find min and max values. ------------------------------------------------------- vmax = max(vmax, field[:,:,idz].max()) vmin = min(vmin, field[:,:,idz].min()) #- Make lats and lons. ------------------------------------------------------------ lats = 90.0 - self.theta[p,:] * 180.0 / np.pi lons = self.phi[p,:] * 180.0 / np.pi lon, lat = np.meshgrid(lons, lats) #- Rotate if necessary. ----------------------------------------------------------- if self.rotangle != 0.0: lat_rot = np.zeros(np.shape(lon),dtype=float) lon_rot = np.zeros(np.shape(lat),dtype=float) for idlon in np.arange(len(lons)): for idlat in np.arange(len(lats)): lat_rot[idlat,idlon],lon_rot[idlat,idlon] = rot.rotate_coordinates(self.n,-self.rotangle,90.0-lat[idlat,idlon],lon[idlat,idlon]) lat_rot[idlat,idlon] = 90.0-lat_rot[idlat,idlon] lon = lon_rot lat = lat_rot #- Make a nice colourmap. --------------------------------------------------------- my_colormap=cm.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) x, y = m(lon, lat) im = m.pcolormesh(x, y, field[:,:,idz], cmap=my_colormap, vmin=valmin,vmax=valmax) #- Add colobar and title. ------------------------------------------------------------------ cb = m.colorbar(im, "right", size="3%", pad='2%') if component in UNIT_DICT: cb.set_label(UNIT_DICT[component], fontsize="x-large", rotation=0) plt.suptitle("Depth slice of %s at %i km" % (component, r_effective), size="large") #- Plot stations if available. ------------------------------------------------------------ if (self.stations == True) & (stations==True): x,y = m(self.stlons,self.stlats) for n in range(self.n_stations): plt.text(x[n],y[n],self.stnames[n][:4]) plt.plot(x[n],y[n],'ro') plt.show() if verbose == True: print "minimum value: "+str(vmin)+", maximum value: "+str(vmax)
def plot_topo(topoplotdata): """ Plot topo data as specified by topoplotdata. """ import os import pylab if topoplotdata.Z is None: topoplodata = read_topo(topoplotdata) x = topoplotdata.x y = topoplotdata.y topo = topoplotdata.Z X = topoplotdata.X Y = topoplotdata.Y xllcorner = x[0] yllcorner = y[0] cellsize = x[1]-x[0] fname = topoplotdata.fname topotype = topoplotdata.topotype if topoplotdata.climits: # deprecated option cmin = topoplotdata.climits[0] cmax = topoplotdata.climits[1] else: cmin = topoplotdata.cmin cmax = topoplotdata.cmax figno = topoplotdata.figno addcolorbar = topoplotdata.addcolorbar addcontour = topoplotdata.addcontour contour_levels = topoplotdata.contour_levels xlimits = topoplotdata.xlimits ylimits = topoplotdata.ylimits coarsen = topoplotdata.coarsen imshow = topoplotdata.imshow gridedges_show = topoplotdata.gridedges_show neg_cmap = topoplotdata.neg_cmap pos_cmap = topoplotdata.pos_cmap cmap = topoplotdata.cmap clf = topoplotdata.clf print_fname = topoplotdata.print_fname if neg_cmap is None: neg_cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1], -0.00001:[0.95,0.9,0.7], 0.00001:[.5,.7,0]}) if pos_cmap is None: pos_cmap = colormaps.make_colormap({ -0.00001:[0.95,0.9,0.7], 0.00001:[.5,.7,0], cmax:[.2,.5,.2]}) if cmap is None: cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1], -0.00001:[0.95,0.9,0.7], 0.00001:[.5,.7,0], cmax:[.2,.5,.2]}) #cmap = colormaps.make_colormap({-1:[0,0,1],0:[1,1,1],1:[1,0,0]}) #------------- if 0: if abs(topotype) == 1: X,Y,topo = topotools.topofile2griddata(fname, topotype) topo = pylab.flipud(topo) Y = pylab.flipud(Y) x = X[0,:] y = Y[:,0] xllcorner = x[0] yllcorner = y[0] cellsize = x[1]-x[0] elif abs(topotype) == 3: file = open(fname, 'r') lines = file.readlines() ncols = int(lines[0].split()[0]) nrows = int(lines[1].split()[0]) xllcorner = float(lines[2].split()[0]) yllcorner = float(lines[3].split()[0]) cellsize = float(lines[4].split()[0]) NODATA_value = int(lines[5].split()[0]) print "Loading file ",fname print " nrows = %i, ncols = %i" % (nrows,ncols) topo = pylab.loadtxt(fname,skiprows=6,dtype=float) print " Done loading" if 0: topo = [] for i in range(nrows): topo.append(pylab.array(lines[6+i],)) print '+++ topo = ',topo topo = pylab.array(topo) topo = pylab.flipud(topo) x = pylab.linspace(xllcorner, xllcorner+ncols*cellsize, ncols) y = pylab.linspace(yllcorner, yllcorner+nrows*cellsize, nrows) print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape else: raise Exception("*** Only topotypes 1 and 3 supported so far") if topotype < 0: topo = -topo #------------------ ncols,nrows = topo.shape #import pdb; pdb.set_trace() if coarsen > 1: topo = topo[slice(0,nrows,coarsen), slice(0,ncols,coarsen)] X = X[slice(0,nrows,coarsen), slice(0,ncols,coarsen)] Y = Y[slice(0,nrows,coarsen), slice(0,ncols,coarsen)] x = x[slice(0,ncols,coarsen)] y = y[slice(0,nrows,coarsen)] print "Shapes after coarsening: ", x.shape, y.shape, topo.shape if figno: pylab.figure(figno) if clf: pylab.clf() if topoplotdata.imshow: color_norm = Normalize(cmin,cmax,clip=True) xylimits = (x[0],x[-1],y[0],y[-1]) #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \ pylab.imshow(topo, extent=xylimits, \ cmap=cmap, interpolation='nearest', \ norm=color_norm) #pylab.clim([cmin,cmax]) if addcolorbar: pylab.colorbar(shrink=0.5) else: neg_topo = ma.masked_where(topo>0., topo) all_masked = (ma.count(neg_topo) == 0) if not all_masked: pylab.pcolormesh(X,Y,neg_topo,cmap=neg_cmap) pylab.clim([cmin,0]) if addcolorbar: pylab.colorbar(shrink=0.5) pos_topo = ma.masked_where(topo<0., topo) all_masked = (ma.count(pos_topo) == 0) if not all_masked: pylab.pcolormesh(X,Y,pos_topo,cmap=pos_cmap) pylab.clim([0,cmax]) if addcolorbar: pylab.colorbar(shrink=0.5) pylab.axis('scaled') if addcontour: pylab.contour(X,Y,topo,levels=contour_levels,colors='k') patchedges_show = True if patchedges_show: pylab.plot([x[0],x[-1]],[y[0],y[0]],'k') pylab.plot([x[0],x[-1]],[y[-1],y[-1]],'k') pylab.plot([x[0],x[0]],[y[0],y[-1]],'k') pylab.plot([x[-1],x[-1]],[y[0],y[-1]],'k') if print_fname: fname2 = os.path.splitext(fname)[0] pylab.text(xllcorner+cellsize, yllcorner+cellsize, fname2, color='m') topodata = object() topodata.x = x topodata.y = y topodata.topo = topo return topodata
def plot_slice(self,depth,colormap='tomo',res='i',verbose=False): """ plot horizontal slices through an ses3d model plot_slice(self,depth,colormap='tomo',res='i',verbose=False) depth=depth in km of the slice colormap='tomo','mono' res=resolution of the map, admissible values are: c, l, i, h f """ radius=6371.0-depth #- set up a map and colourmap ----------------------------------------- if self.global_regional=='regional': m=Basemap(projection='merc',llcrnrlat=self.lat_min,urcrnrlat=self.lat_max,llcrnrlon=self.lon_min,urcrnrlon=self.lon_max,lat_ts=20,resolution=res) m.drawparallels(np.arange(self.lat_min,self.lat_max,self.d_lon),labels=[1,0,0,1]) m.drawmeridians(np.arange(self.lon_min,self.lon_max,self.d_lat),labels=[1,0,0,1]) elif self.global_regional=='global': m=Basemap(projection='ortho',lon_0=self.lon_centre,lat_0=self.lat_centre,resolution=res) m.drawparallels(np.arange(-80.0,80.0,10.0),labels=[1,0,0,1]) m.drawmeridians(np.arange(-170.0,170.0,10.0),labels=[1,0,0,1]) m.drawcoastlines() m.drawcountries() m.drawmapboundary(fill_color=[1.0,1.0,1.0]) if colormap=='tomo': my_colormap=cm.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) elif colormap=='mono': my_colormap=cm.make_colormap({0.0:[1.0,1.0,1.0], 0.15:[1.0,1.0,1.0], 0.85:[0.0,0.0,0.0], 1.0:[0.0,0.0,0.0]}) #- loop over subvolumes to collect information ------------------------ x_list=[] y_list=[] idz_list=[] N_list=[] for k in np.arange(self.nsubvol): r=self.m[k].r #- collect subvolumes within target depth if (max(r)>=radius) & (min(r)<radius): N_list.append(k) r=r[0:len(r)-1] idz=min(np.where(min(np.abs(r-radius))==np.abs(r-radius))[0]) if idz==len(r): idz-=idz idz_list.append(idz) if verbose==True: print 'true plotting depth: '+str(6371.0-r[idz])+' km' x,y=m(self.m[k].lon_rot,self.m[k].lat_rot) x_list.append(x) y_list.append(y) #- make a (hopefully) intelligent colour scale ------------------------ if len(N_list)>0: #- compute some diagnostics min_list=[] max_list=[] percentile_list=[] for k in np.arange(len(N_list)): min_list.append(np.min(self.m[N_list[k]].v[:,:,idz_list[k]])) max_list.append(np.max(self.m[N_list[k]].v[:,:,idz_list[k]])) percentile_list.append(np.percentile(np.abs(self.m[N_list[k]].v[:,:,idz_list[k]]),99.0)) minval=np.min(min_list) maxval=np.max(max_list) percent=np.max(percentile_list) #- min and max roughly centred around zero if (minval*maxval<0.0): max_val_plot=percent min_val_plot=-max_val_plot #- min and max not centred around zero else: max_val_plot=maxval min_val_plot=minval #- loop over subvolumes to plot --------------------------------------- for k in np.arange(len(N_list)): im=m.pcolor(x_list[k],y_list[k],self.m[N_list[k]].v[:,:,idz_list[k]],cmap=my_colormap,vmin=min_val_plot,vmax=max_val_plot) m.colorbar(im,"right", size="3%", pad='2%') plt.title(str(depth)+' km') plt.show()
def plot(self, ds=1000, unit='km', cmap='seismic_r', vmin=None, vmax=None, zsize=10): """Plot velocity model ============================================================================= Input Parameters: ds - grid spacing unit - unit vmin, vmax - vmin,vmax for colorbar ============================================================================= """ # XLength=self.xmax-self.xmin # ZLength=self.zmax-self.zmin # xsize=zsize*(XLength/ZLength) # fig = plt.figure(figsize=(xsize, zsize)) if cmap == 'ses3d': cmap = colormaps.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) if self.plotflag == False: raise ValueError('No plot array!') # plt.figure(figsize=(16,13)) if self.regular == True: im = plt.pcolormesh(self.XArrPlot / ds, self.ZArrPlot / ds, self.VsArrPlot / ds, cmap=cmap, vmin=vmin, vmax=vmax) else: xi = np.linspace(self.xmin, self.xmax, self.Nx * 10) zi = np.linspace(self.zmin, self.zmax, self.Nz * 10) self.xi, self.zi = np.meshgrid(xi, zi) #-- Interpolating at the points in xi, yi self.vi = griddata(self.XArr, self.ZArr, self.VsArr, self.xi, self.zi, 'linear') im = plt.pcolormesh(self.xi / ds, self.zi / ds, ma.getdata(self.vi) / ds, cmap=cmap, vmin=vmin, vmax=vmax, shading='gouraud') ########################################## plt.plot(500., 1000, 'r*', markersize=30, lw=3) # plt.plot( [0., 4000.], [1000, 1000] , 'b--', lw=3) # plt.plot( [500., 500.], [700., 1300.] , 'g-', lw=3) # plt.plot( [500., 3500.], [700., 700.] , 'g-', lw=3) # plt.plot( [500., 3500.], [1300., 1300.] , 'g-', lw=3) # plt.plot( [3500., 3500.], [700., 1300.] , 'g-', lw=3) # # plt.plot( [0., 0.], [0., 2000.] , 'k-', lw=3) # plt.plot( [0., 4000.], [0., 0.] , 'k-', lw=3) # plt.plot( [4000., 4000.], [0., 2000.] , 'k-', lw=3) # plt.plot( [0., 4000.], [2000., 2000.] , 'k-', lw=3) ########################################## plt.xlabel('x(' + unit + ')', fontsize=35) plt.ylabel('z(' + unit + ')', fontsize=35) # plt.axis([self.xmin/ds, self.xmax/ds, self.zmin/ds, self.zmax/ds]) plt.axis('scaled') cb = plt.colorbar(shrink=0.8) #, size="3%", pad='2%') cb.set_label('Vs (km/s)', fontsize=20, rotation=90) plt.yticks(fontsize=30) plt.xticks(fontsize=30) ######################## # plt.ylim([-100, 2100]) # plt.xlim([-100, 4100]) ######################## plt.show() return
def plot_threshold(self,val,min_val_plot,max_val_plot,colormap='tomo',verbose=False): """ plot depth to a certain threshold value 'val' in an ses3d model plot_threshold(val,min_val_plot,max_val_plot,colormap='tomo',verbose=False): val=threshold value min_val_plot, max_val_plot=minimum and maximum values of the colour scale colormap='tomo','mono' """ #- set up a map and colourmap if self.global_regional=='regional': m=Basemap(projection='merc',llcrnrlat=self.lat_min,urcrnrlat=self.lat_max,llcrnrlon=self.lon_min,urcrnrlon=self.lon_max,lat_ts=20,resolution=res) m.drawparallels(np.arange(self.lat_min,self.lat_max,self.d_lon),labels=[1,0,0,1]) m.drawmeridians(np.arange(self.lon_min,self.lon_max,self.d_lat),labels=[1,0,0,1]) elif self.global_regional=='global': m=Basemap(projection='ortho',lon_0=self.lon_centre,lat_0=self.lat_centre,resolution=res) m.drawparallels(np.arange(-80.0,80.0,10.0),labels=[1,0,0,1]) m.drawmeridians(np.arange(-170.0,170.0,10.0),labels=[1,0,0,1]) m.drawcoastlines() m.drawcountries() m.drawmapboundary(fill_color=[1.0,1.0,1.0]) if colormap=='tomo': my_colormap=cm.make_colormap({0.0:[0.1,0.0,0.0], 0.2:[0.8,0.0,0.0], 0.3:[1.0,0.7,0.0],0.48:[0.92,0.92,0.92], 0.5:[0.92,0.92,0.92], 0.52:[0.92,0.92,0.92], 0.7:[0.0,0.6,0.7], 0.8:[0.0,0.0,0.8], 1.0:[0.0,0.0,0.1]}) elif colormap=='mono': my_colormap=cm.make_colormap({0.0:[1.0,1.0,1.0], 0.15:[1.0,1.0,1.0], 0.85:[0.0,0.0,0.0], 1.0:[0.0,0.0,0.0]}) #- loop over subvolumes for k in np.arange(self.nsubvol): depth=np.zeros(np.shape(self.m[k].v[:,:,0])) nx=len(self.m[k].lat) ny=len(self.m[k].lon) #- find depth r=self.m[k].r r=0.5*(r[0:len(r)-1]+r[1:len(r)]) for idx in np.arange(nx-1): for idy in np.arange(ny-1): n=self.m[k].v[idx,idy,:]>=val depth[idx,idy]=6371.0-np.max(r[n]) #- rotate coordinate system if necessary lon,lat=np.meshgrid(self.m[k].lon[0:ny],self.m[k].lat[0:nx]) if self.phi!=0.0: lat_rot=np.zeros(np.shape(lon),dtype=float) lon_rot=np.zeros(np.shape(lat),dtype=float) for idx in np.arange(nx): for idy in np.arange(ny): colat=90.0-lat[idx,idy] lat_rot[idx,idy],lon_rot[idx,idy]=rot.rotate_coordinates(self.n,-self.phi,colat,lon[idx,idy]) lat_rot[idx,idy]=90.0-lat_rot[idx,idy] lon=lon_rot lat=lat_rot #- convert to map coordinates and plot x,y=m(lon,lat) im=m.pcolor(x,y,depth,cmap=my_colormap,vmin=min_val_plot,vmax=max_val_plot) m.colorbar(im,"right", size="3%", pad='2%') plt.title('depth to '+str(val)+' km/s [km]') plt.show()
def plot_depth_slice(self, component, depth, valmin, valmax, iteration=0, verbose=True, stations=True, res="i"): """ plot_depth_slice(self, component, depth, valmin, valmax, iteration=0, verbose=True, stations=True, res="i") Plot depth slices of field component at depth "depth" with colourbar ranging between "valmin" and "valmax". The resolution of the coastline is "res" (c, l, i, h, f). The currently available "components" are: Material parameters: A, B, C, mu, lambda, rhoinv, vp, vsh, vsv, rho Velocity field snapshots: vx, vy, vz Sensitivity kernels: Q_mu, Q_kappa, alpha_mu, alpha_kappa """ #- Some initialisations. ------------------------------------------------------------------ n_procs = self.setup["procs"]["px"] * self.setup["procs"][ "py"] * self.setup["procs"]["pz"] radius = 1000.0 * (6371.0 - depth) vmax = float("-inf") vmin = float("inf") lat_min = 90.0 - self.setup["domain"]["theta_max"] * 180.0 / np.pi lat_max = 90.0 - self.setup["domain"]["theta_min"] * 180.0 / np.pi lon_min = self.setup["domain"]["phi_min"] * 180.0 / np.pi lon_max = self.setup["domain"]["phi_max"] * 180.0 / np.pi lat_centre = (lat_max + lat_min) / 2.0 lon_centre = (lon_max + lon_min) / 2.0 lat_centre, lon_centre = rot.rotate_coordinates( self.n, -self.rotangle, 90.0 - lat_centre, lon_centre) lat_centre = 90.0 - lat_centre d_lon = np.round((lon_max - lon_min) / 10.0) d_lat = np.round((lat_max - lat_min) / 10.0) #- Set up the map. ------------------------------------------------------------------------ if (lat_max - lat_min) > 30.0: m = Basemap(projection='ortho', lon_0=lon_centre, lat_0=lat_centre, resolution=res) m.drawparallels(np.arange(-80.0, 80.0, 10.0), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(-170.0, 170.0, 10.0), labels=[1, 0, 0, 1]) else: m = Basemap(projection='merc', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_ts=20, resolution=res) m.drawparallels(np.arange(np.round(lat_min), np.round(lat_max), d_lat), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(np.round(lon_min), np.round(lon_max), d_lon), labels=[1, 0, 0, 1]) m.drawcoastlines() m.fillcontinents("0.9", zorder=0) m.drawmapboundary(fill_color="white") m.drawcountries() #- Loop over processor boxes and check if depth falls within the volume. ------------------ for p in range(n_procs): if (radius >= self.z[p, :].min()) & (radius <= self.z[p, :].max()): #- Read this field and make lats & lons. ------------------------------------------ field = self.read_single_box(component, p, iteration) lats = 90.0 - self.theta[p, :] * 180.0 / np.pi lons = self.phi[p, :] * 180.0 / np.pi lon, lat = np.meshgrid(lons, lats) #- Find the depth index and plot for this one box. -------------------------------- idz = min( np.where( min(np.abs(self.z[p, :] - radius)) == np.abs(self.z[p, :] - radius))[0]) r_effective = int(self.z[p, idz] / 1000.0) #- Find min and max values. ------------------------------------------------------- vmax = max(vmax, field[:, :, idz].max()) vmin = min(vmin, field[:, :, idz].min()) #- Make lats and lons. ------------------------------------------------------------ lats = 90.0 - self.theta[p, :] * 180.0 / np.pi lons = self.phi[p, :] * 180.0 / np.pi lon, lat = np.meshgrid(lons, lats) #- Rotate if necessary. ----------------------------------------------------------- if self.rotangle != 0.0: lat_rot = np.zeros(np.shape(lon), dtype=float) lon_rot = np.zeros(np.shape(lat), dtype=float) for idlon in np.arange(len(lons)): for idlat in np.arange(len(lats)): lat_rot[idlat, idlon], lon_rot[ idlat, idlon] = rot.rotate_coordinates( self.n, -self.rotangle, 90.0 - lat[idlat, idlon], lon[idlat, idlon]) lat_rot[idlat, idlon] = 90.0 - lat_rot[idlat, idlon] lon = lon_rot lat = lat_rot #- Make a nice colourmap. --------------------------------------------------------- my_colormap = cm.make_colormap({ 0.0: [0.1, 0.0, 0.0], 0.2: [0.8, 0.0, 0.0], 0.3: [1.0, 0.7, 0.0], 0.48: [0.92, 0.92, 0.92], 0.5: [0.92, 0.92, 0.92], 0.52: [0.92, 0.92, 0.92], 0.7: [0.0, 0.6, 0.7], 0.8: [0.0, 0.0, 0.8], 1.0: [0.0, 0.0, 0.1] }) x, y = m(lon, lat) im = m.pcolormesh(x, y, field[:, :, idz], cmap=my_colormap, vmin=valmin, vmax=valmax) #- Add colobar and title. ------------------------------------------------------------------ cb = m.colorbar(im, "right", size="3%", pad='2%') if component in UNIT_DICT: cb.set_label(UNIT_DICT[component], fontsize="x-large", rotation=0) plt.suptitle("Depth slice of %s at %i km" % (component, r_effective), size="large") #- Plot stations if available. ------------------------------------------------------------ if (self.stations == True) & (stations == True): x, y = m(self.stlons, self.stlats) for n in range(self.n_stations): plt.text(x[n], y[n], self.stnames[n][:4]) plt.plot(x[n], y[n], 'ro') plt.show() if verbose == True: print "minimum value: " + str(vmin) + ", maximum value: " + str( vmax)