def run_plots(DataDirectory, Base_file): root = DataDirectory + Base_file filenames = get_filenames(root) counter = 0 # create the plot for the initial raster initial_file = filenames[0] # read in the raster raster = IO.ReadRasterArrayBlocks(initial_file) f = mlab.figure(size=(1000, 1000), bgcolor=(0.5, 0.5, 0.5)) s = mlab.surf(raster, warp_scale=0.4, colormap='gist_earth', vmax=100) #mlab.outline(color=(0,0,0)) #mlab.axes(s, color=(1,1,1), z_axis_visibility=True, y_axis_visibility=False, xlabel='', ylabel='', zlabel='', ranges=[0,500,0,1000,0,0]) #@mlab.animate(delay=10) #def anim(): # now loop through each file and update the z values for fname in filenames: this_rast = IO.ReadRasterArrayBlocks(fname) s.mlab_source.scalars = this_rast #f.scene.render() # mlab.savefig(fname[:-4] + '_3d.png')
def PlotBasinsWithHillshade(DataDirectory, OutDirectory, fname_prefix, stream_order=1): """ Read in the basins and plot them over a hillshade coloured by their cluster ID """ df = pd.read_csv(OutDirectory + fname_prefix + '_profiles_clustered_SO{}.csv'.format(stream_order)) clusters = df.cluster_id.unique() # make a figure fig = plt.figure(1, facecolor='white') gs = plt.GridSpec(100, 100, bottom=0.15, left=0.15, right=0.9, top=0.9) ax = fig.add_subplot(gs[5:100, 5:100]) # plot the raster hs_raster = IO.ReadRasterArrayBlocks(DataDirectory + fname_prefix + '_hs.bil') extent = IO.GetRasterExtent(DataDirectory + fname_prefix + '_hs.bil') # hs_raster = IO.ReadRasterArrayBlocks(DataDirectory+'Pozo_DTM_basin_208_hs.bil') # extent = IO.GetRasterExtent(DataDirectory+'Pozo_DTM_basin_208_hs.bil') plt.imshow(hs_raster, cmap=cm.gray, extent=extent) plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.xlabel('Easting (m)') plt.ylabel('Northing (m)') means = {} for i, cl in enumerate(clusters): this_df = df[df.cluster_id == cl] # get the polygons polygons = ReadBasinPolygons( DataDirectory, OutDirectory, fname_prefix + '_basins_SO{}_CL{}'.format(stream_order, int(cl))) for p in polygons: #print(list(p.exterior.coords)) patch = PolygonPatch(p, facecolor=this_df.iloc[0]['colour'], alpha=1.0, zorder=2, lw=0.2) ax.add_patch(patch) #print(polygons) # for each plt.savefig(OutDirectory + fname_prefix + '_hs_basins_SO{}.png'.format(stream_order), FigFormat='png', dpi=500, transparent=True)
def get_terrace_areas(terrace_df, fname_prefix): """ This function takes the initial terrace dataframe and calculates the area of each terrace. Args: terrace_df: pandas dataframe with the terrace info fname_prefix: name of the DEM (to get data res) Returns: dict where key is the terrace ID and value is the terrace area in m^2 Author: FJC """ # get unique IDs terraceIDs = terrace_df.terraceID.unique() area_dict = {} for terraceID in terraceIDs: # get the n rows with this ID masked_df = terrace_df[terrace_df['terraceID'] == terraceID] n_pixels = len(masked_df.index) # get the data resolution of the DEM Cell_area = IO.GetPixelArea(fname_prefix) terrace_area = n_pixels * Cell_area area_dict[terraceID] = terrace_area return area_dict
def BoxPlotByCluster(DataDirectory, OutDirectory, fname_prefix, raster_name, stream_order=1): """ Make a boxplot of the results of the clustering compared to the raster specified by raster_name """ #df = pd.read_csv(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order)) # read in the raster raster_ext = '.bil' this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name) EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name) NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name) CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name) pts = PT.LSDMap_PointData(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order),data_type ='csv') easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string) cluster_id = pts.QueryData('cluster_id', PANDEX=True) clusters = list(set(cluster_id)) # dict for the data data = {k: [] for k in clusters} for x, (i, j) in enumerate(zip(northing, easting)): # convert to rows and cols X_coordinate_shifted_origin = j - XMin; Y_coordinate_shifted_origin = i - YMin; col_point = int(X_coordinate_shifted_origin/CellSize); row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize)); # check for data at this cell this_value = this_raster[row_point][col_point] if not np.isnan(this_value): if this_value < 10: # get the cluster id data[cluster_id[x]].append(this_value) print(data) # now make a boxplot labels, these_data = [*zip(*data.items())] # 'transpose' items to parallel key, value lists plt.boxplot(these_data) plt.xticks(range(1, len(labels) + 1), labels) plt.show()
def GetLithologyPercentages(DataDirectory, OutDirectory, fname_prefix, raster_name, stream_order=1): """ Get the percentage of the nodes in each cluster that drain each lithology """ from collections import Counter # read in the raster raster_ext = '.bil' this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name) EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name) NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name) CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name) pts = PT.LSDMap_PointData(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order),data_type ='csv') easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string) cluster_id = pts.QueryData('cluster_id', PANDEX=True) clusters = list(set(cluster_id)) # dict for the data data = {k: [] for k in clusters} for x, (i, j) in enumerate(zip(northing, easting)): # convert to rows and cols X_coordinate_shifted_origin = j - XMin; Y_coordinate_shifted_origin = i - YMin; col_point = int(X_coordinate_shifted_origin/CellSize); row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize)); # check for data at this cell this_value = this_raster[row_point][col_point] if not np.isnan(this_value): data[cluster_id[x]].append(this_value) # you have the values. now what percentage are each? for key, liths in data.items(): c = Counter(liths) n_ndv = c[0.0] print(c) [print(x,": ",vals/len(liths) * 100) for x, vals in c.items()]
def GenerateExtentShapefile(DataDirectory, RasterFile): """ This just wraps a LSDMap_GDALIO script Args: DataDirectory (str): the data directory with the basin raster RasterFile (str): the name of the raster Returns: Shapefile of the raster footprint. Has "_footprint" in filename. Author: SMM Date: 24/01/2018 """ LSDMGDAL.CreateShapefileOfRasterFootprint(DataDirectory, RasterFile)
def ReadBasinPolygons(DataDirectory, OutDirectory, raster_name): """ Read in the basin polygons """ import shapefile #ax.set_aspect('equal') # check if the shapefile exists shpfile = raster_name + '.shp' if not os.path.isfile(OutDirectory + shpfile): print("Polygonising the basin raster...") # read in the raster raster_ext = '.bil' polygons = IO.PolygoniseRaster(OutDirectory, raster_name + raster_ext, raster_name) polygons = list(polygons.values()) else: # read in the shapefile sf = shapefile.Reader(OutDirectory + shpfile) # shape = file.GetLayer(0) polygons = [] for s in list(sf.iterShapes()): nparts = len(s.parts) # total parts if nparts == 1: polygon = Polygon(s.points) polygons.append(polygon) else: # loop over parts of each shape, plot separately for ip in range(nparts): # loop over parts, plot separately i0 = s.parts[ip] if ip < nparts - 1: i1 = s.parts[ip + 1] - 1 else: i1 = len(s.points) polygon = Polygon(s.points[i0:i1 + 1]) polygons.append(polygon) return polygons
""" Created on Sat Feb 11 11:40:41 2017 @author: dav """ import LSDPlottingTools.LSDMap_GDALIO as lsdio import numpy as np import scipy as sp Zenith = 45 Azimuth = 315 ZFactor = 1 Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" BackgroundRasterName = "BoscastleElevations0.asc" File = Directory + BackgroundRasterName RasterData = lsdio.ReadRasterArrayBlocks(File) def Hillshade_Smooth(RasterData, altitude, azimuth, z_factor): """Plots a Hillshade a la LSDRaster""" zenith_rad = sp.deg2rad(altitude) azimuth_rad = sp.deg2rad(azimuth)
def MakeBoxPlotsKsnLithology(DataDirectory, fname_prefix, raster_name, theta=0.45, label_list=[]): """ Make boxplots of ksn compared to lithology raster. Lithology should have integer values for the different rock types (rock type with 0 is excluded). Pass in list of labels for the different units, which must be the same length as the number of lithology codes. If none is passed then just use the integer values for labelling. """ from scipy import stats # read in the raster raster_ext = '.bil' this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name) #EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name) EPSG_string='epsg:32611' print(EPSG_string) NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name) CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name) pts = PT.LSDMap_PointData(DataDirectory+fname_prefix+'_ksn.csv',data_type ='csv') print(pts) easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string) ksn = pts.QueryData('ksn', PANDEX=True) #print(ksn) # get the unique values in the raster raster_values = np.unique(this_raster) raster_values = raster_values[1:] # dict for the data data = {k: [] for k in raster_values} for x, (i, j) in enumerate(zip(northing, easting)): # convert to rows and cols X_coordinate_shifted_origin = j - XMin; Y_coordinate_shifted_origin = i - YMin; col_point = int(X_coordinate_shifted_origin/CellSize); row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize)); # check for data at this cell this_raster_value = this_raster[row_point][col_point] if not np.isnan(this_raster_value) and this_raster_value != 0: data[this_raster_value].append(ksn[x]) # set up a figure fig,ax = plt.subplots(nrows=1,ncols=1, figsize=(5,5), sharex=True, sharey=True) labels, dict = [*zip(*data.items())] # 'transpose' items to parallel key, value lists print(label_list) if label_list: labels = label_list print(labels) box = plt.boxplot(dict, patch_artist=True) plt.xticks(range(1, len(labels) + 1), labels) plt.ylabel('$k_{sn}$', fontsize=14) # get the medians for plotting as an upper label medians = [] print("========SOME KSN STATISTICS=========") for key, value in data.items(): print("Key {}, median ksn = {}".format(key, np.median(value))) medians.append(np.median(value)) print("Key {}, IQR = {}".format(key, stats.iqr(value))) print("========================================") pos = np.arange(len(labels)) + 1 upperLabels = [str(np.round(s, 2)) for s in medians] # change the colours for each lithology colors=['#60609fff', '#fdbb7fff', '#935353ff', '#f07b72ff'] for patch, color in zip(box['boxes'], colors): patch.set_facecolor(color) patch.set_alpha(0.9) patch.set_edgecolor('k') for cap in box['caps']: cap.set(color='k') for wh in box['whiskers']: wh.set(color='k') for med in box['medians']: med.set(color='k') for flier, color in zip(box['fliers'], colors): flier.set_markeredgecolor(color) flier.set_markerfacecolor(color) flier.set_markersize(2) # for tick, label in zip(range(len(labels)), ax.get_xticklabels()): # k = tick % 2 # ax.text(pos[tick], top - (top*0.05), upperLabels[tick], # horizontalalignment='center', color=colors[k]) ax.grid(color='0.8', linestyle='--', which='major', zorder=1) plt.title('Boxplots of $k_{sn}$ by lithology', fontsize=14) plt.savefig(DataDirectory+fname_prefix+'_boxplot_lith_ksn.png', dpi=300, transparent=True) plt.clf() # Do some stats, yo # KS test to see if we can distinguish the distributions at a confidence level of p = 0.05 # https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html # relief keys = list(data.keys()) values = list(data.values()) k=0 for i in range(len(keys)-1): for j in range(i+1, len(keys)): print("KS test between {} and {}".format(keys[i], keys[j])) d, p = stats.ks_2samp(values[i], values[j]) print(d, p) k += 1
def GenerateBasemapImage(DataDirectory, RasterFile, FigWidthInches = 4, FigHeightInches = 3, bm_width = 2000000, bm_height = 2000000, projection = 'lcc',resolution = 'l', lat_0 = 0, lon_0 = 0, lat_1 = 45,lat_2 = 55, satellite_height = 10000000, FigFormat = "png", fig_dpi = 500, out_fname_prefix = ""): """ This makes the basemap image. Args: DataDirectory (str): The directory of the raster file RasterFile (str): the name of the raster file (include extension) FigWidthInches (float): How wide you want the basemap FigHeightInches (float): How high you want your basemap bm_width (float): The width in metres of your basemap bm_height (float): The height in metres covered by your basemap projection (str): The projection of your basemap. See basemap docs for details resolution (str): Resolution. See basmap documentation. Default is "l" (for low) since higher resolution ("high" or "full") must be installed separately with basemap (and is very large) lat_0 (flt): Latitude of centre of your map lon_0 (flt): Longitude of centre of your map lat_1 (flt): See basemap documentation lon_1 (flt): See basemap documentation satellite_height (flt): The satellite height in metres for geostationary projections FigFormat (str): Figure format, can be `png`, `svg`, `pdf`, etc. fig_dpi (int): Dots per inch of your figure out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix Author: SMM Date: 24/01/2018 """ # Make sure data directory is in correct format if not DataDirectory.endswith(os.sep): print("You forgot the separator at the end of the directory, appending...") DataDirectory = DataDirectory+os.sep # Set up the figure. This is needed to both size the figure and get the axis handle for plotting polygons fig, ax = plt.subplots(figsize=(FigWidthInches, FigHeightInches)) # get some filenames RasterSplit = RasterFile.split(".") Raster_prefix = RasterSplit[0] Shape_name = DataDirectory+Raster_prefix+"_footprint" SName = "Shape" Full_Shape_name = Shape_name+".shp" # Get the name of the image if len(out_fname_prefix) == 0: FigFileName = DataDirectory+Base_file+"_basemap."+fig_format else: FigFileName = DataDirectory+out_fname_prefix+"_basemap."+fig_format # Now for the basemap # setup Lambert Conformal basemap. #m = Basemap(width=bm_width,height=bm_width,projection=projection, # resolution=resolution,lat_1=lat_1 ,lat_2=lat_2,lat_0=lat_0,lon_0=lon_0, satellite_height = satellite_height, area_thresh = 100000) # create the shapefile LSDMGDAL.CreateShapefileOfRasterFootprint(DataDirectory, RasterFile) #shape_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), facecolor='none') #ax.add_feature(shape_feature) # draw coastlines. #m.drawcoastlines(linewidth = 0.5) # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. #m.drawmapboundary(fill_color='snow') # fill continents, set lake color same as ocean color. #m.fillcontinents(color='lightgray',lake_color='snow') # draw parallels and meridians. # label parallels on right and top # meridians on bottom and left parallels = np.arange(0.,90,5.) # labels = [left,right,top,bottom] #m.drawparallels(parallels,labels=[False,True,True,False]) meridians = np.arange(10.,351.,5.) #m.drawmeridians(meridians,labels=[True,False,False,True]) #m.drawcountries() # Make a patch from the shapefile # All this stuff from: # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ df_poly = pd.DataFrame({ 'shapes': [Polygon(np.array(shape), True) for shape in m.footprint]}) #df_poly = df_poly.merge(new_areas, on='area', how='left') #cmap = plt.get_cmap('Oranges') pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5) pc.set_facecolor("crimson") ax.add_collection(pc) plt.savefig(FigFileName,format=FigFormat,dpi=fig_dpi)
def GenerateBasemapImageAutomated(DataDirectory, RasterFile, FigWidthInches = 4, FigHeightInches = 3, FigFormat = "png", fig_dpi = 500, regional_extent_multiplier = 5, label_spacing_multiplier = 0.5, out_fname_prefix = "", is_orthographic = False): """ This makes the basemap image. Uses data from the raster to size the figure and locate the centrepoint Args: DataDirectory (str): The directory of the raster file RasterFile (str): the name of the raster file (include extension) FigWidthInches (flt): How wide you want the basemap FigHeightInches (float): How high you want your basemap FigFormat (str): Figure format, can be `png`, `svg`, `pdf`, etc. fig_dpi (int): Dots per inch of your figure regional_extent_multiplier (float): How much bigger you want the extent vs the size of the raster label_spacing_multiplier (float): If the meridians and parallels are too close, increase this number. Default of 0.5 out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix Author: SMM Date: 01/02/2018 """ # Make sure data directory is in correct format if not DataDirectory.endswith(os.sep): print("You forgot the separator at the end of the directory, appending...") DataDirectory = DataDirectory+os.sep # Set up the figure. This is needed to both size the figure and get the axis handle for plotting polygons fig = plt.figure(figsize=(FigWidthInches, FigHeightInches)) print("The size is: " +str(FigWidthInches)+", "+str(FigHeightInches)) # get some filenames RasterSplit = RasterFile.split(".") Raster_prefix = RasterSplit[0] Shape_name = DataDirectory+Raster_prefix+"_footprint.shp" SName = "Shape" # Get the name of the image if len(out_fname_prefix) == 0: FigFileName = DataDirectory+Base_file+"_basemap."+FigFormat else: FigFileName = DataDirectory+out_fname_prefix+"_basemap."+FigFormat # Now we get the extents from the raster centre_lat, centre_long, extent_lat, extent_long, xproj_extent, yproj_extent = LSDMGDAL.GetCentreAndExtentOfRaster(DataDirectory, RasterFile) # Calculate the aspect ratio aspect_ratio = BasemapExtentSizer(FigWidthInches, FigHeightInches) # Figure out the longest dimension long_dimension = xproj_extent if yproj_extent > long_dimension: long_dimension = yproj_extent print("The long dimension is: "+str(long_dimension)) # Get the full extent by mulitplying the longest extent by the multiplier full_dimension = long_dimension*regional_extent_multiplier # now get the two dimensions for the extent of the figure print("The aspect ratio is: "+str(aspect_ratio)) if aspect_ratio > 1: # This is when the figure is wider than tall x_ext = full_dimension*aspect_ratio y_ext = full_dimension full_extent_long = extent_long*aspect_ratio*regional_extent_multiplier full_extent_lat = extent_long*regional_extent_multiplier else: x_ext = full_dimension y_ext = full_dimension*aspect_ratio full_extent_long = extent_lat*regional_extent_multiplier full_extent_lat = extent_lat*aspect_ratio*regional_extent_multiplier extents = [centre_long-0.5*full_extent_long, centre_long+0.5*full_extent_long, centre_lat-0.5*full_extent_lat, centre_lat+0.5*full_extent_lat] print("Extents are: ") print(extents) # Now we set up the extents and coordinate system #if (is_orthographic): # ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.Orthographic(centre_lat, #centre_long)) # # ax.add_feature(cfeature.LAND) # ax.add_feature(cfeature.OCEAN, edgecolor='black') # ax.set_global() # ax.gridlines() if(is_orthographic): ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.NearsidePerspective( central_latitude=centre_lat, central_longitude=centre_long, satellite_height=10000000.0)) ax.coastlines(resolution='110m',linewidth=0.5) borders_110m = cfeature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '110m',edgecolor='face', facecolor=cfeature.COLORS['land']) ax.add_feature(borders_110m, edgecolor='black', facecolor = "none",linewidth=0.5) ax.gridlines() else: ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.PlateCarree()) ax.set_extent([centre_long-0.5*full_extent_long, centre_long+0.5*full_extent_long, centre_lat-0.5*full_extent_lat, centre_lat+0.5*full_extent_lat], ccrs.PlateCarree()) land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor=cfeature.COLORS['land']) borders_50m = cfeature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '50m', edgecolor='face', facecolor=cfeature.COLORS['land']) ax.add_feature(land_50m, edgecolor='black', linewidth=0.5) ax.add_feature(borders_50m, edgecolor='black', facecolor = "none",linewidth=0.5) #ax.add_feature(cfeature.LAND) #ax.add_feature(cfeature.OCEAN) #ax.add_feature(cfeature.COASTLINE) #ax.add_feature(cfeature.BORDERS, linestyle='--') #ax.add_feature(cfeature.LAKES, alpha=0.5) #ax.add_feature(cfeature.RIVERS) # create the shapefile LSDMGDAL.CreateShapefileOfRasterFootprint(DataDirectory, RasterFile) ax.add_geometries( shpreader.Reader(Shape_name).geometries(), ccrs.PlateCarree(),edgecolor='black', facecolor='green', alpha=0.5, linewidth=0.5) #========================================== # draw parallels and meridians. # Calculate the spacing of the meridians and parallels # THIS IS ALL FROM BASEMAP AND NOT USED BY CARTOPY max_latlong_ext = extent_lat if extent_long < max_latlong_ext: max_latlong_ext = extent_long max_latlong_ext = max_latlong_ext*regional_extent_multiplier print("The maximum extent is:"+str(max_latlong_ext)) latlong_label_spacing = int(label_spacing_multiplier*max_latlong_ext+0.5) print("And the label spacing is: "+str(latlong_label_spacing)) start_lat = int(centre_lat - max_latlong_ext*2 - 0.5) end_lat = int(centre_lat + max_latlong_ext*2+0.5) start_long = int(centre_long - max_latlong_ext*2 -0.5) end_long = int(centre_long + max_latlong_ext*2+0.5) # label parallels on right and top # meridians on bottom and left parallels = np.arange(start_lat,end_lat,latlong_label_spacing) # labels = [left,right,top,bottom] #m.drawparallels(parallels,labels=[False,True,True,False]) meridians = np.arange(start_long,end_long,latlong_label_spacing) #m.drawmeridians(meridians,labels=[True,False,False,True]) #========================================== #========================================== # THIS IS ALL FROM BASEMAP AND NOT USED BY CARTOPY # Make a patch from the shapefile # All this stuff from: # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ #df_poly = pd.DataFrame({ # 'shapes': [Polygon(np.array(shape), True) for shape in m.footprint]}) #df_poly = df_poly.merge(new_areas, on='area', how='left') #cmap = plt.get_cmap('Oranges') #pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5) #pc.set_facecolor("crimson") #ax.add_collection(pc) #========================================== plt.savefig(FigFileName,format=FigFormat,dpi=fig_dpi)
# e.g. with a setup.py script that builds your cython extension library # This MUST come before you import the C hillshade pyx file if you are doing it # this way. #################### import pyximport pyximport.install() #################### from LSDPlottingTools import fast_hillshade as fasthill import LSDPlottingTools.LSDMap_GDALIO as LSDMap_IO import LSDPlottingTools.LSDMap_BasicPlotting as LSDMap_BP Directory = "/mnt/SCRATCH/Dev/ExampleTopoDatasets/" BackgroundRasterName = "indian_creek.bil" raster = LSDMap_IO.ReadRasterArrayBlocks(Directory + BackgroundRasterName) data_res = LSDMap_IO.GetGeoInfo(Directory + BackgroundRasterName)[3][1] try: NoDataValue = float( LSDMap_IO.getNoDataValue(Directory + BackgroundRasterName)) except TypeError: NoDataValue = -9999.0 ncols, nrows = raster.shape # LSDMappingTools hillshade #hs = LSDMap_BP.Hillshade(raster) #plt.imshow(hs, cmap="gray") #plt.show() #LSDRaster Cythonised version pf hillshade
def PlotLithologyWithClusters(DataDirectory, OutDirectory, fname_prefix, stream_order=1, shapefile_name='geol.shp', geol_field='geol'): """ Make a hillshade of the raster with the channels coloured by the cluster value. Rasterise a geology shapefile and drape on the top. Uses the LSDPlottingTools libraries. https://github.com/LSDtopotools/LSDMappingTools Args: stream_order: the stream order of the profiles that you are analysing shapefile_name: name of the lithology shapefile geol_field: the field of the shapefile that has the lithology information Author: FJC """ import LSDPlottingTools as LSDP from LSDMapFigure.PlottingRaster import MapFigure df = pd.read_csv(DataDirectory + fname_prefix + '_all_tribs.csv') cluster_df = pd.read_csv( OutDirectory + fname_prefix + '_profiles_clustered_SO{}.csv'.format(stream_order)) # set figure sizes based on format fig_width_inches = 4.92126 # some raster names raster_ext = '.bil' BackgroundRasterName = fname_prefix + raster_ext HSName = fname_prefix + '_hs' + raster_ext if not os.path.isfile(DataDirectory + HSName): print("Making a hillshade for you") # make a hillshade BM.GetHillshade(DataDirectory + BackgroundRasterName, DataDirectory + HSName) # create the map figure MF = MapFigure(HSName, DataDirectory, coord_type="UTM") res = IO.GetUTMMaxMin(DataDirectory + BackgroundRasterName)[0] #rasterise the shapefile new_shp, geol_dict = VT.geologic_maps_modify_shapefile( DataDirectory + shapefile_name, geol_field) lith_raster = VT.Rasterize_geologic_maps_pythonic(new_shp, res, geol_field) MF.add_drape_image(lith_raster, "", colourmap=plt.cm.jet, alpha=0.4, show_colourbar=False, discrete_cmap=True, cbar_type=int, mask_value=0) clusters = cluster_df.cluster_id.unique() for cl in clusters: # plot the whole channel network in black ChannelPoints = LSDP.LSDMap_PointData(df, data_type="pandas", PANDEX=True) MF.add_point_data(ChannelPoints, show_colourbar="False", unicolor='0.9', manual_size=2, zorder=1, alpha=0.5) # plot the clustered profiles in the correct colour this_df = cluster_df[cluster_df.cluster_id == cl] this_colour = str(this_df.colour.unique()[0]) ClusteredPoints = LSDP.LSDMap_PointData(this_df, data_type="pandas", PANDEX=True) MF.add_point_data(ClusteredPoints, show_colourbar="False", zorder=100, unicolor=this_colour, manual_size=3) MF.save_fig(fig_width_inches=fig_width_inches, FigFileName=OutDirectory + fname_prefix + '_lith_clusters_SO{}.png'.format(stream_order), FigFormat='png', Fig_dpi=300, fixed_cbar_characters=6, adjust_cbar_characters=False, transparent=True) # Save the figure
as a series of rasters and overlays of different data, e.g. Hillshade overlaid by erosion/deposition amounts, or water depth or d50 size, etc. @author: dav """ import LSDPlottingTools as lsdplt import LSDPlottingTools.LSDMap_GDALIO as mapio # fun trivia: this is Welsh for 'mapping'. import numpy as np """Plots a hillshade overlain with the erossion or deposition amount""" folder = "/mnt/DATA/DATA/VIRTUALBOX_SHARED/HydrogeomorphPaper/BOSCASTLE/PaperSimulations/Radar1km/TransLim/" laptop_folder = "" filename = "boscastle5m_bedrock_fill.asc" drapename = "waterdepth2400.txt" # Create the drape array from one of the Catchment model output rasters drape_array = mapio.ReadRasterArrayBlocks(folder + drapename) # Optional: A lot of the output rasters contain very small values for certain # things like water depth or elevation difference, so you can mask this below: low_values_index = drape_array < 0.005 drape_array[low_values_index] = np.nan # Alternatively you can just pass the name of a secondary drape raster instead # of an array below: The function takes either a string or a ready-extracted array. lsdplt.DrapedOverHillshade(folder + filename, drape_array, clim_val=(0,400), \ drape_cmap='Blues', colorbarlabel='Elevation in meters'\ ,ShowColorbar=True, ShowDrapeColorbar=True, drape_cbarlabel = "Water depth (m)")
#################### import pyximport pyximport.install() #################### from LSDPlottingTools import fast_hillshade as fasthill import LSDPlottingTools.LSDMap_GDALIO as LSDMap_IO import LSDPlottingTools.LSDMap_BasicPlotting as LSDMap_BP Directory = "/mnt/SCRATCH/Dev/ExampleTopoDatasets/" BackgroundRasterName = "indian_creek.bil" raster = LSDMap_IO.ReadRasterArrayBlocks(Directory + BackgroundRasterName) data_res = LSDMap_IO.GetGeoInfo(Directory + BackgroundRasterName)[3][1] try: NoDataValue = float(LSDMap_IO.getNoDataValue(Directory + BackgroundRasterName)) except TypeError: NoDataValue = -9999.0 ncols, nrows = raster.shape # LSDMappingTools hillshade #hs = LSDMap_BP.Hillshade(raster) #plt.imshow(hs, cmap="gray") #plt.show() #LSDRaster Cythonised version pf hillshade hs_nice = fasthill.Hillshade(raster, data_res, NoDataValue=NoDataValue) # I tend to comment out these two lines profiling, so you # aren't actually profiling the matplotlib rendering... #plt.imshow(hs_nice, cmap="gray")