def TestNewMappingTools_asc(): DataDirectory = "T:\\analysis_for_papers\\Beaches\\" #Filename1 = "BedThickness_050.asc" #Filename2 = "BedThickness_100.asc" Filename1 = "20m_bl.asc" ThisFile = DataDirectory + Filename1 yo = LSDP.GetRasterExtent(ThisFile) print "raster extent is: " print yo #MB = LSDP.BasicMassBalance(DataDirectory, Filename1, Filename2) #print "Mass balance between these two time steps is: " + str(MB) + " cubic metres" #Mean1 = LSDP.RasterMeanValue(DataDirectory, Filename1) #Mean2 = LSDP.RasterMeanValue(DataDirectory, Filename2) #print "The mean values of the two rasters are: " + str(Mean1) +" and "+ str(Mean2) # now try the swath plotting #axis = 0 #LSDP.SwathPlot(DataDirectory, Filename1, axis) axis = 1 LSDP.SwathPlot(DataDirectory, Filename1, axis)
def make_ticks(self): """ This function makes the tick marks and the tick labels. It has been optimised so you get nice looking ticks, so you shouldn't have to mess with them after this is called. """ if self._coord_type == "UTM": self.tick_xlocs, self.tick_ylocs, self.tick_x_labels, self.tick_y_labels = LSDP.GetTicksForUTMNoInversion( self._BaseRasterFullName, self._xmax, self._xmin, self._ymax, self._ymin, self._n_target_ticks) elif self._coord_type == "UTM_km": self.tick_xlocs, self.tick_ylocs, self.tick_x_labels, self.tick_y_labels = LSDP.GetTicksForUTMNoInversion( self._BaseRasterFullName, self._xmax, self._xmin, self._ymax, self._ymin, self._n_target_ticks) n_hacked_digits = 3 self.tick_x_labels = LSDP.TickLabelShortenizer( self.tick_x_labels, n_hacked_digits) self.tick_y_labels = LSDP.TickLabelShortenizer( self.tick_y_labels, n_hacked_digits) else: raise ValueError("Sorry, the coordinate type: ", self._coord_type, "is not yet supported") print("I made the ticks.") print("x labels are: ") print(self.tick_x_labels) print("x locations are:") print(self.tick_xlocs) print("y labels are: ") print(self.tick_y_labels) print("y locations are:") print(self.tick_ylocs)
def Correct_Raterized_GLIM_map(tifname): # And now for a hack that converts to print("The raster name is: " + tifname) [xsize, ysize, geotransform, geoproj, Z] = readFile(tifname) print("Before data check") print(Z) print("Data type is: " + str(Z.dtype)) X = Z.astype(int) # Set large negative values to -9999 X[X <= 0] = -9999 #Z[np.isnan(Z)]= -9999 print("After_data_check") print(X) #get path and filename seperately filepath = LSDPT.GetPath(tifname) #filename = LSDPT.GetFileNameNoPath(tifname) fileshortname = LSDPT.GetFilePrefix(tifname) outraster2 = filepath + fileshortname + '2.tif' writeFile(outraster2, geotransform, geoproj, X)
def make_field_sites_figure(DataDirectory): N_HSFiles = 4 NRows = 3 NCols = 2 n_target_ticks = 6 LSDP.field_sites(DataDirectory, N_HSFiles, NRows, NCols, n_target_ticks)
def geologic_maps_modify_shapefile(shapefile_name, geol_field="xx"): # The shapefile to be rasterized: print('Rasterize ' + shapefile_name) #get path and filename seperately shapefilefilepath = LSDPT.GetPath(shapefile_name) #shapefilename = LSDPT.GetFileNameNoPath(shapefile_name) shapefileshortname = LSDPT.GetFilePrefix(shapefile_name) # get the new shapefile name new_shapefile_name = shapefilefilepath + os.sep + shapefileshortname + "_new.shp" # copy the shapefile into the new shapefile--we don't wwant to mess up the original data print("The New Shapefile name is: " + new_shapefile_name) Copy_Shapefile(shapefile_name, new_shapefile_name) # New shapefile is opened for writing. dataSource = ogr.Open(new_shapefile_name, 1) daLayer = dataSource.GetLayer(0) # add a new field new_field = ogr.FieldDefn("GEOL_CODE", ogr.OFTInteger) daLayer.CreateField(new_field) # lets see what the layers are print( "Let me tell you what the names of the fields are after I added one!") layerDefinition = daLayer.GetLayerDefn() for i in range(layerDefinition.GetFieldCount()): print(layerDefinition.GetFieldDefn(i).GetName()) # Make a key for the bedrock geol_dict = dict() geol_iterator = 0 geol_field = geol_field # for feature in daLayer: GEOL = feature.GetField(geol_field) if GEOL not in geol_dict: geol_iterator = geol_iterator + 1 print("I found a new rock type, GEOL: " + str(GEOL) + " and rock type: " + str(geol_iterator)) geol_dict[GEOL] = geol_iterator # now get the geol code this_geol_code = geol_dict[GEOL] # set the feature feature.SetField("GEOL_CODE", this_geol_code) # need to update the layer daLayer.SetFeature(feature) print("The rocks are: ") print(geol_dict) print("All done") return new_shapefile_name, geol_dict
def __init__(self, RasterName, Directory): self._RasterFileName = RasterName self._RasterDirectory = Directory self._FullPathRaster = self._RasterDirectory + self._RasterFileName # I think the BaseRaster should contain a numpy array of the Raster self._RasterArray = LSDP.ReadRasterArrayBlocks(self._FullPathRaster) # Get the extents as a list self._RasterExtents = LSDP.GetRasterExtent(self._FullPathRaster)
def ResetErosionRaster(): DataDirectory = "T://analysis_for_papers//Manny_Idaho//Revised//nested//" #DataDirectory = "C://basin_data//Manny_Idaho//nested//" ConstFname = "ConstEros.bil" NewErateName = "HarringCreek_ERKnown.bil" ThisFile = DataDirectory + ConstFname NewFilename = DataDirectory + NewErateName LSDP.CheckNoData(ThisFile) # now print the constant value file constant_value = 0.0092 LSDP.SetToConstantValue(ThisFile, NewFilename, constant_value) LSDP.CheckNoData(NewFilename)
def main(argv): # If there are no arguments, send to the welcome screen if not len(sys.argv) > 1: full_paramfile = print_welcome() #sys.exit() else: # Get the arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("-pf", "--parameter_file",type=str, default="Params.param", help="The name, with extension and path, of your parameter file.") args = parser.parse_args() full_paramfile = args.parameter_file print("The full parameter file is: "+full_paramfile) # Now make a plotting driver object PD = LSDPT.LSDMap_PlottingDriver(full_paramfile) print(PD.FilePrefix) print(PD.FilePath) print("The plotting switches are: ") print(PD.plotting_switches) # Now make some plots!! PD.plot_data()
def ChiMappingToolsTest(): DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/Meghalaya/chi_analysis/" #DataDirectory = "T:\\analysis_for_papers\\Meghalaya/chi_analysis\\" #DataDirectory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\" Filename = "Mega_clip.bil" HSFilename = "Mega_clip_hs.bil" DEMname = DataDirectory+Filename HSname = DataDirectory+HSFilename FigName = DataDirectory+'TestChiFull2.png' ChiName = DataDirectory+'Mega_clip_MChiSegmented.csv' #FigFormat = 'svg' #FigFileN= 'Sorbas_chi.svg' #FigFileName= DataDirectory+FigFileN elevation_threshold = 1 #LSDP.BasicChiPlotGridPlot(DEMname,HSname,ChiName, 'gray','gray', # '$k_{sn}$',(0,0), # 0.4,FigName,'png',elevation_threshold) #FigName2 = DataDirectory+'TestChannelMap.png' #LSDP.BasicChannelPlotGridPlotCategories(DEMname,HSname,ChiName, 'gray','gray', # '$Channel$',(0,0), # 0.4,FigName2,'png',elevation_threshold,'source_key') FigName3 = DataDirectory+'ChiProfiles.png' LSDP.ChiProfiles(ChiName, FigName3,'png',elevation_threshold)
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.1,left=0.1,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 = LSDP.GetRasterExtent(DataDirectory+fname_prefix+'_hs.bil') plt.imshow(hs_raster, cmap=cm.gray, extent=extent) 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+'polygons.png', FigFormat='png', dpi=500)
def ShieldPlots_fine(): DataDirectory = "T://analysis_for_papers//Cosmo_paper//Palumbo_shield_plots//" Filename = "SpawnedBasin_07C13-fine_SH.bil" ThisFile = DataDirectory+Filename LSDP.BasicDensityPlotGridPlot(ThisFile, thiscmap='summer',colorbarlabel='Topographic shielding fine', clim_val = (0.85,1),FigFileName = 'Shield_fine.pdf', FigFormat = 'pdf')
def _render_background(self, fullpath_to_raster): """ Renders the background image that will form the drape plot, e.g. a hillshade """ if self._backgroundtype == "Hillshade": self.Hillshade = LSDP.Hillshade(self.fullpath_to_raster) self.colourmap = "gray" elif self._backgroundtype == "Terrain": self.Hillshade = LSDP.ReadRasterArrayBlocks( self.fullpath_to_raster) self.colourmap = LSDP.colours.UsefulColourmaps.niceterrain #self.colourmap = LSDP.colours.UsefulColourmaps.darkearth #self.colourmap = "terrain" else: print ("That background style is not yet supported. Currently only " \ " 'Hillshade' and 'Terrain' are supported.")
def TestNewMappingTools2(): DataDirectory = "T://analysis_for_papers//Manny_idaho//" Filename = "TestIdaho.bil" NewFilename = "TestIdaho_after2.bil" ThreshFname = "ThreshIdaho.bil" ConstFname = "ConstEros.bil" ThisFile = DataDirectory+Filename NewFilename = DataDirectory+NewFilename ThreshFname = DataDirectory+ThreshFname ConstFname = DataDirectory+ConstFname #FigFormat = 'svg' #FigFileN= 'Sorbas_chi.svg' #FigFileName= DataDirectory+FigFileN #Plot the basin over the elevation #tcmapcolorbarlabel = "Elevation (m)" #tcmap = 'jet' #tcmapcolorbarlabel='Chi' #clim_val = (50,300) #LSDP.BasicDensityPlotGridPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) #get the nodata values NData = LSDP.getNoDataValue(ThisFile) print "NoData is: " + str(NData) # get the data as an array array = LSDP.ReadRasterArrayBlocks(ThisFile) driver_name = "ENVI" LSDP.array2raster(ThisFile,NewFilename,array,driver_name, -9999) #get the nodata values NData2 = LSDP.getNoDataValue(NewFilename) #print "NoData 2 is: " + str(NData2) LSDP.SetNoDataBelowThreshold(ThisFile,ThreshFname) # now print the constant value file constant_value = 0.001 LSDP.SetToConstantValue(ThreshFname,ConstFname,constant_value)
def map_custom(): """ Testing function to plot custom maps before creating real function for mapping routines Args: Yes. returns: No. Author: BG """ ###### Parameters ###### Directory = "/home/s1675537/PhD/DataStoreBoris/GIS/Data/Carpathian/knickpoint/" # reading directory wDirectory = Directory # writing directory Base_file = "Buzau" # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata csv_file = Directory + "test_sign_m_chi.csv" # Name of your point file, add a similar line with different name if you have more than one point file DrapeRasterName = "Buzau_hs.bil" # if you want to drap a raster on your background one. Just add a similar line in case you want another raster to drap and so on wname = "sign_test" # name of your output file dpi = 500 # Quality of your output image, don't exceed 900 fig_size_inches = 7 # Figure size in Inches ##### Now we can load and plot the data BackgroundRasterName = Base_file + ".bil" # Ignore this line thisPointData = LSDP.LSDMap_PointData(csv_file, PANDEX = True) # Load the point file #1, add a similar line with different name if you have more than one point file. plt.clf() # Ignore this line MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km") # load the background raster MF.add_drape_image(DrapeRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one colourmap = "gray", # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version alpha=0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque show_colourbar = False, # Well, this one is explicit I think colorbarlabel = "Colourbar") # Name of your Colourbar, it might bug though MF.add_point_data( thisPointData, # this function plot the requested point file using the lat/long column in the csv file column_for_plotting = "m_chi_sign", # Column used to color the data this_colourmap = "cubehelix", # Colormap used, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version colorbarlabel = "Colourbar", # Label scale_points = False, # All the point will have the same size if False column_for_scaling = "None", # If scale point True, you can scale the size of your points using one of the columns scaled_data_in_log = False, # If scale point True, you can log the scaling max_point_size = 5, # max size if scale point True again min_point_size = 0.5, # You should be able to guess that one now coulor_log = False, # do you want a log scale for your colorbar ? coulor_manual_scale = [], #Do you want to manually limit the scale of your colorbar? if not let is false manual_size = 0.5, # If none of above is choosen but you want to put another value than 0.5 to scale your point alpha = 1, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque minimum_log_scale_cut_off = -10) # you probably won't need this ImageName = wDirectory+str(int(clock.time()))+wname+".png" # Ignore this ax_style = "Normal" # Ignore this MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = dpi) # Save the figure
def __init__(self, RasterName, Directory): self._RasterFileName = RasterName self._RasterDirectory = Directory self._FullPathRaster = self._RasterDirectory + self._RasterFileName # I think the BaseRaster should contain a numpy array of the Raster self._RasterArray = LSDP.ReadRasterArrayBlocks(self._FullPathRaster) # Get the extents as a list self._RasterExtents = LSDP.GetRasterExtent(self._FullPathRaster) self._RasterAspectRatio = ( self._RasterExtents[1] - self._RasterExtents[0]) / ( self._RasterExtents[3] - self._RasterExtents[2]) # set the default colourmap self._colourmap = "gray" # get the EPSG string self._EPSGString = LSDP.LSDMap_IO.GetUTMEPSG(self._FullPathRaster)
def PalumboPlots(): DataDirectory = "T://analysis_for_papers//Cosmo_paper//Palumbo_shield_plots//" Filename = "SpawnedBasin_07C13-(Q8).bil" Drapename = "SpawnedBasin_07C13-(Q8)_BASINS.bil" ThisFile = DataDirectory+Filename DrapeFile = DataDirectory+Drapename LSDP.BasicDrapedPlotGridPlot(ThisFile, DrapeFile, thiscmap='terrain',drape_cmap='gray', colorbarlabel='Elevation in meters',clim_val = (2000,5000), drape_alpha = 0.4,FigFileName = 'Basin.pdf',FigFormat = 'pdf')
def FloodThenHillshade(): DataDirectory = "M:\\students\\kunkelova\\" DEMName = "bk_10m_dem.bil" newDEMName = "bk_10m_dem_updated.bil" HillshadeName = "bk_10m_dem_HS.bil" RasterFilename = DataDirectory + DEMName NewRasterFilename = DataDirectory + newDEMName HillshadeNameFile = DataDirectory + HillshadeName LSDP.SetNoDataBelowThreshold(RasterFilename, NewRasterFilename, threshold=0, driver_name="ENVI", NoDataValue=-9999) LSDP.GetHillshade(NewRasterFilename, HillshadeNameFile, azimuth=315, angle_altitude=45, driver_name="ENVI", NoDataValue=-9999)
def FixStupidNoData(): DataDirectory = "T://analysis_for_papers//Indus//" DEMName = "indus_utm44.bil" newDEMName = "Indus_ND.bil" RasterFilename = DataDirectory + DEMName NewRasterFilename = DataDirectory + newDEMName LSDP.SetNoDataBelowThreshold(RasterFilename, NewRasterFilename, threshold=0, driver_name="ENVI", NoDataValue=-9999)
def findmaxval_multirasters(FileList): """ Loops through a list or array of rasters (np arrays) and finds the maximum single value in the set of arrays. """ overall_max_val = 0 for i in range (len(FileList)): raster_as_array = LSDP.ReadRasterArrayBlocks(FileList[i]) this_max_val = np.max(raster_as_array) if this_max_val > overall_max_val: overall_max_val = this_max_val print(overall_max_val) return overall_max_val
def TestNewMappingTools2(): DataDirectory = "T://analysis_for_papers//Manny_idaho//" Filename = "TestIdaho.bil" NewFilename = "TestIdaho_after2.bil" ThreshFname = "ThreshIdaho.bil" ConstFname = "ConstEros.bil" ThisFile = DataDirectory + Filename NewFilename = DataDirectory + NewFilename ThreshFname = DataDirectory + ThreshFname ConstFname = DataDirectory + ConstFname #FigFormat = 'svg' #FigFileN= 'Sorbas_chi.svg' #FigFileName= DataDirectory+FigFileN #Plot the basin over the elevation #tcmapcolorbarlabel = "Elevation (m)" #tcmap = 'jet' #tcmapcolorbarlabel='Chi' #clim_val = (50,300) #LSDP.BasicDensityPlotGridPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) #get the nodata values NData = LSDP.getNoDataValue(ThisFile) print "NoData is: " + str(NData) # get the data as an array array = LSDP.ReadRasterArrayBlocks(ThisFile) driver_name = "ENVI" LSDP.array2raster(ThisFile, NewFilename, array, driver_name, -9999) #get the nodata values NData2 = LSDP.getNoDataValue(NewFilename) #print "NoData 2 is: " + str(NData2) LSDP.SetNoDataBelowThreshold(ThisFile, ThreshFname) # now print the constant value file constant_value = 0.001 LSDP.SetToConstantValue(ThreshFname, ConstFname, constant_value)
def TestMappingToolsPoints(): #DataDirectory = "T://analysis_for_papers//Test_map_chi_gradient//results//" DataDirectory = "T://students//Wainwright//" #Filename = "Mandakini_OutletList.csv" Filename = "Bids_DD.csv" #ExportName = "ShapeTest" fname = DataDirectory + Filename #Exp_fname = DataDirectory+ExportName thisPointData = LSDP.LSDMap_PointData(fname) thisPointData.GetParameterNames(True) thisPointData.GetLongitude(True) print "Hey buddy, the province is: " thisPointData.QueryData("province", True) print "Hey buddy, the gma is: " thisPointData.QueryData("gma", True) thisPointData.TranslateToReducedShapefile(fname) thisPointData.TranslateToReducedGeoJSON(fname)
def ElevationSwaths(path, filename, axis, fprefix): Fileformat = 'png' # get the path to the raster file NewPath = LSDOst.AppendSepToDirectoryPath(path) FileName = NewPath+filename # get the data vectors means,medians,std_deviations,twentyfifth_percentile,seventyfifth_percentile = LSDP.SimpleSwath(path, filename, axis) print "Means shape is: " print means.shape x_vec,y_vec = LSDP.GetLocationVectors(FileName) print "X shape is: " print x_vec.shape print "Y shape is: " print y_vec.shape import matplotlib.pyplot as plt import matplotlib.lines as mpllines from mpl_toolkits.axes_grid1 import AxesGrid label_size = 20 #title_size = 30 axis_size = 28 # Set up fonts for plots rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['arial'] rcParams['font.size'] = label_size # make a figure, sized for a ppt slide fig = plt.figure(1, facecolor='white',figsize=(10,7.5)) gs = plt.GridSpec(100,75,bottom=0.1,left=0.1,right=0.9,top=1.0) ax = fig.add_subplot(gs[10:100,10:75]) if axis == 0: dir_vec = x_vec else: dir_vec = y_vec # get the distance from shore dist_from_shore = np.subtract(dir_vec[-1],dir_vec) min_sd = np.subtract(means,std_deviations) plus_sd = np.add(means,std_deviations) ax.plot(dist_from_shore,means, linewidth = 2.5, color = "black") #ax.fill_between(dist_from_shore, twentyfifth_percentile, seventyfifth_percentile, facecolor='green', alpha = 0.7, interpolate=True) ax.fill_between(dist_from_shore, min_sd, plus_sd, facecolor='blue', alpha = 0.25, interpolate=True) ax.set_xlim(dist_from_shore[0],dist_from_shore[-1]) ax.annotate('Standard deviation envelope', xy=(dist_from_shore[10],plus_sd[10]), xycoords='data', xytext=(0.1, 0.8), textcoords='axes fraction', size=label_size, # bbox=dict(boxstyle="round", fc="0.8"), arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none", connectionstyle="arc3,rad=0.3"), ) ax.spines['top'].set_linewidth(2) ax.spines['left'].set_linewidth(2) ax.spines['right'].set_linewidth(2) ax.spines['bottom'].set_linewidth(2) #ax.tick_params(axis='both', width=1) plt.xlabel('Distance from shore (m)', fontsize = axis_size) plt.ylabel('Bed elevation relative to MSL (m)', fontsize = axis_size) plt.title(fprefix) # This gets all the ticks, and pads them away from the axis so that the corners don't overlap ax.tick_params(axis='both', width=2, pad = 10) for tick in ax.xaxis.get_major_ticks(): tick.set_pad(10) #plt.show() plt.savefig(NewPath+fprefix+"_BedElev.png",format = Fileformat) plt.clf()
#DataDirectory = '/home/s0923330/DEMs_for_analysis/mid_bailey_run_10m/' #DEM_prefix = 'bailey_dem_10m' DataDirectory = 'C:\\VagrantBoxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Paper\\' DEM_prefix = 'Meghalaya' FigFormat = 'png' x_param = 'mean' #MakeRawSlopeAreaPlot(DataDirectory, DEM_prefix, FigFormat='png', size_format = 'ESURF') #MakeBinnedSlopeAreaPlot(DataDirectory, DEM_prefix, FigFormat, x_param) #MakeChannelsMap(DataDirectory, DEM_prefix, FigFormat=FigFormat) #MakeSegmentedSlopeAreaPlot(DataDirectory, DEM_prefix, FigFormat) #these_basin_keys = [0,1,2] these_basin_keys = [] #MakeSegmentedWithRawSlopeAreaPlot(DataDirectory, DEM_prefix, FigFormat, basin_keys = these_basin_keys) #MakeBinnedWithRawSlopeAreaPlot(DataDirectory, DEM_prefix, FigFormat, basin_keys = these_basin_keys) #BinnedRegressionDriver(DataDirectory, DEM_prefix, basin_keys = these_basin_keys) LSDP.SAPlotDriver(DataDirectory, DEM_prefix, FigFormat=FigFormat, show_raw=True, show_segments=False, cmap=plt.cm.Set1, n_colours=5, basin_keys=these_basin_keys) #LSDP.TestSARegression(DataDirectory, DEM_prefix) #adict = LSDP.BinnedRegressionDriver(DataDirectory, DEM_prefix, basin_keys = these_basin_keys) #from LSDPlottingTools import LSDMap_MOverNPlotting as MN #MN.CompareChiAndSAMOverN(DataDirectory, DEM_prefix, basin_list=these_basin_keys, start_movern=0.1, d_movern=0.1, n_movern=8)
def flood_maps_shapefile_zoom(DataDirectory): LSDP.flood_maps_shapefile_with_zoom(DataDirectory)
def flood_maps_with_shapefile(DataDirectory): LSDP.flood_maps_with_shapefile(DataDirectory)
def make_flood_maps(DataDirectory): LSDP.multiple_flood_maps(DataDirectory)
Created on Tue May 05 14:08:16 2015 @author: dav """ import glob as glob import os.path import numpy as np import LSDPlottingTools as LSDP import matplotlib.cm as cm #import lsdmatplotlibextensions as mplext import matplotlib.pyplot as plt from matplotlib import ticker # Get favourite plotting fonts and sizes LSDP.init_plotting_DV() # Truncate the colour map #trunc_cmap = LSDP.colours.truncate_colormap("Blues", 0.4, 1.0) # Option for getting a discrete colour map #discreet_cmap = mplext.colours.discrete_colourmap(8, "Blues") #discreet_cmap = mplext.colours.cmap_discretize(8, trunc_cmap) # Non-linear colourmap levels = [-2.5, -1.5 -0.5, -0.25, 0, 0.25, 0.5, 1.5, 2.5 ] #levels = levels[levels <= tmax] print (levels) levels.sort() print (levels) cmap_lin = cm.jet
Created on Tue May 05 14:08:16 2015 @author: dav """ import glob as glob import os.path import numpy as np import LSDPlottingTools as LSDP import matplotlib.cm as cm #import lsdmatplotlibextensions as mplext import matplotlib.pyplot as plt from matplotlib import ticker # Get favourite plotting fonts and sizes LSDP.init_plotting_DV() # Truncate the colour map #trunc_cmap = LSDP.colours.truncate_colormap("Blues", 0.4, 1.0) # Option for getting a discrete colour map #discreet_cmap = mplext.colours.discrete_colourmap(8, "Blues") #discreet_cmap = mplext.colours.cmap_discretize(8, trunc_cmap) # Non-linear colourmap levels = [-2.5, -1.5 - 0.5, -0.25, 0, 0.25, 0.5, 1.5, 2.5] #levels = levels[levels <= tmax] print(levels) levels.sort() print(levels) cmap_lin = cm.jet
def main(argv): # If there are no arguments, send to the welcome screen if not len(sys.argv) > 1: full_paramfile = print_welcome() sys.exit() # Get the arguments import argparse parser = argparse.ArgumentParser() # The location of the data files parser.add_argument( "-dir", "--base_directory", type=str, help="The base directory. If not defined, current directory.") parser.add_argument("-fname", "--fname_prefix", type=str, help="The prefix of your DEM WITHOUT EXTENSION!") parser.add_argument( "-fmt", "--FigFormat", type=str, default='png', help="Set the figure format for the plots. Default is png") args = parser.parse_args() # get the base directory if args.base_directory: DataDirectory = args.base_directory # check if you remembered a / at the end of your path_name if not DataDirectory.endswith("/"): print( "You forgot the '/' at the end of the directory, appending...") DataDirectory = this_dir + "/" else: this_dir = os.getcwd() if not args.fname_prefix: print( "WARNING! You haven't supplied your DEM name. Please specify this with the flag '-fname'" ) sys.exit() else: fname_prefix = args.fname_prefix # set to not parallel parallel = False faults = True FigFormat = args.FigFormat # check if a directory exists for the chi plots. If not then make it. raster_directory = DataDirectory + 'raster_plots/' if not os.path.isdir(raster_directory): os.makedirs(raster_directory) # Set up fonts for plots label_size = 8 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['arial'] rcParams['font.size'] = label_size # set figure sizes based on format size_format = "" if size_format == "geomorphology": fig_width_inches = 6.25 elif size_format == "big": fig_width_inches = 16 else: fig_width_inches = 4.92126 # get the basin IDs to make a discrete colourmap for each ID BasinInfoDF = Helper.ReadBasinInfoCSV(DataDirectory, fname_prefix) basin_keys = list(BasinInfoDF['basin_key']) basin_keys = [int(x) for x in basin_keys] basin_junctions = list(BasinInfoDF['outlet_junction']) basin_junctions = [int(x) for x in basin_junctions] # get a discrete colormap cmap = plt.cm.viridis # going to make the basin plots - need to have bil extensions. print( "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!" ) # get the rasters raster_ext = '.bil' BackgroundRasterName = fname_prefix + raster_ext HillshadeName = fname_prefix + '_hs' + raster_ext BasinsName = fname_prefix + '_AllBasins' + raster_ext # create the map figure MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location='none') # add the basins drape BasinsDict = dict(zip(basin_keys, basin_keys)) # MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, label_basins=False, # use_keys_not_junctions = True, show_colourbar = False, # value_dict = BasinsDict, discrete_cmap=True, n_colours=len(basin_keys), # colorbarlabel = "Basin ID", cbar_type=int, tickspacefactor=2, # colourmap = cmap, edgecolour='none', adjust_text = True, parallel=parallel) # add the channel network if not parallel: ChannelDF = Helper.ReadChiDataMapCSV(DataDirectory, fname_prefix) else: ChannelDF = Helper.AppendChiDataMapCSVs(DataDirectory) # remove chi no data values ChannelDF = ChannelDF[ChannelDF.chi != -9999] ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type="pandas", PANDEX=True) # add chi map MF.add_point_data(ChannelPoints, column_for_plotting="chi", column_for_scaling="chi", colorbarlabel="$\chi$ (m)", show_colourbar=True, this_colourmap=cmap, colourbar_location="top") # add the faults if faults: LineFileName = DataDirectory + fname_prefix + "_faults.shp" MF.add_line_data(LineFileName, linestyle="-", linewidth=1.5, zorder=99, legend=True, label="Fault Segments") # add the basin outlines ### need to parallelise if not parallel: Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName) else: Basins = LSDP.GetMultipleBasinOutlines(DataDirectory) # Find the relay basins and plot separately RelayBasinIDs = [1248, 4788, 4995, 5185, 6187, 6758, 6805] RelayBasins = { key: value for key, value in Basins.items() if key in RelayBasinIDs } # Plot all basins MF.plot_polygon_outlines(Basins, colour='k', linewidth=0.5, alpha=1, legend=True, label="Catchments") MF.plot_polygon_outlines(RelayBasins, colour='r', linewidth=0.5, alpha=1, legend=True, label="Relay Catchments") # Add the legend MF.add_legend() # Save the figure ImageName = raster_directory + fname_prefix + '_chi_map.' + FigFormat MF.save_fig(fig_width_inches=fig_width_inches, FigFileName=ImageName, FigFormat=FigFormat, Fig_dpi=300)
def PrintBasins(DataDirectory, fname_prefix, add_basin_labels=True, cmap="jet", cbar_loc="right", size_format="ESURF", fig_format="png", dpi=250, out_fname_prefix=""): """ This function makes a shaded relief plot of the DEM with the basins coloured by the basin ID. IMPORTANT: To get this to run you need to set the flags in chi mapping tool to: write_hillshade: true print_basin_raster: true print_chi_data_maps: true Args: DataDirectory (str): the data directory with the m/n csv files fname_prefix (str): The prefix for the m/n csv files add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar. cmap (str or colourmap): The colourmap to use for the plot cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation. If you want only a hillshade set to none and the cmap to "gray" size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size) fig_format (str): An image format. png, pdf, eps, svg all valid dpi (int): The dots per inch of the figure out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix Returns: Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin Author: FJC, SMM """ #import modules from LSDMapFigure.PlottingRaster import MapFigure # set figure sizes based on format if size_format == "geomorphology": fig_width_inches = 6.25 elif size_format == "big": fig_width_inches = 16 else: fig_width_inches = 4.92126 # get the basin IDs to make a discrete colourmap for each ID BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix) basin_keys = list(BasinInfoDF['basin_key']) basin_keys = [int(x) for x in basin_keys] basin_junctions = list(BasinInfoDF['outlet_junction']) basin_junctions = [float(x) for x in basin_junctions] print('Basin keys are: ') print(basin_keys) # going to make the basin plots - need to have bil extensions. print( "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!" ) # get the rasters raster_ext = '.bil' #BackgroundRasterName = fname_prefix+raster_ext HillshadeName = fname_prefix + '_hs' + raster_ext BasinsName = fname_prefix + '_AllBasins' + raster_ext print(BasinsName) Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName) # If wanted, add the labels if add_basin_labels: print("I am going to add basin labels, there will be no colourbar.") MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location="None") MF.plot_polygon_outlines(Basins, linewidth=0.8) MF.add_drape_image(BasinsName, DataDirectory, colourmap=cmap, alpha=0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar=False, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type=int) # This is used to label the basins label_dict = dict(zip(basin_junctions, basin_keys)) # this dict has the basin junction as the key and the basin_key as the value Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName) MF.add_text_annotation_from_shapely_points(Points, text_colour='k', label_dict=label_dict) else: print("I am showing the basins without text labels.") MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location=cbar_loc) MF.plot_polygon_outlines(Basins, linewidth=0.8) MF.add_drape_image(BasinsName, DataDirectory, colourmap=cmap, alpha=0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar=True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type=int) # Save the image if len(out_fname_prefix) == 0: ImageName = DataDirectory + fname_prefix + "_basins." + fig_format else: ImageName = DataDirectory + out_fname_prefix + "_basins." + fig_format MF.save_fig(fig_width_inches=fig_width_inches, FigFileName=ImageName, FigFormat=fig_format, Fig_dpi=dpi) # Save the figure
def PrintChannelsAndBasins(DataDirectory, fname_prefix, add_basin_labels=True, cmap="jet", cbar_loc="right", size_format="ESURF", fig_format="png", dpi=250, out_fname_prefix=""): """ This function prints a channel map over a hillshade. Args: DataDirectory (str): the data directory with the m/n csv files fname_prefix (str): The prefix for the m/n csv files add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar. cmap (str or colourmap): The colourmap to use for the plot cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation. If you want only a hillshade set to none and the cmap to "gray" size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size) fig_format (str): An image format. png, pdf, eps, svg all valid dpi (int): The dots per inch of the figure out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix Returns: Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin Author: SMM """ # specify the figure size and format # set figure sizes based on format if size_format == "geomorphology": fig_size_inches = 6.25 elif size_format == "big": fig_size_inches = 16 else: fig_size_inches = 4.92126 ax_style = "Normal" # get the basin IDs to make a discrete colourmap for each ID BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix) basin_keys = list(BasinInfoDF['basin_key']) basin_keys = [int(x) for x in basin_keys] basin_junctions = list(BasinInfoDF['outlet_junction']) basin_junctions = [float(x) for x in basin_junctions] print('Basin keys are: ') print(basin_keys) # going to make the basin plots - need to have bil extensions. print( "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!" ) # get the rasters raster_ext = '.bil' #BackgroundRasterName = fname_prefix+raster_ext HillshadeName = fname_prefix + '_hs' + raster_ext BasinsName = fname_prefix + '_AllBasins' + raster_ext print(BasinsName) Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName) ChannelFileName = fname_prefix + "_chi_data_map.csv" chi_csv_fname = DataDirectory + ChannelFileName thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname) # clear the plot plt.clf() # set up the base image and the map print("I am showing the basins without text labels.") MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location="None") MF.plot_polygon_outlines(Basins, linewidth=0.8) MF.add_drape_image(BasinsName, DataDirectory, colourmap=cmap, alpha=0.1, discrete_cmap=False, n_colours=len(basin_keys), show_colourbar=False, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type=int) MF.add_point_data(thisPointData, column_for_plotting="basin_key", scale_points=True, column_for_scaling="drainage_area", this_colourmap=cmap, scaled_data_in_log=True, max_point_size=3, min_point_size=1) # Save the image if len(out_fname_prefix) == 0: ImageName = DataDirectory + fname_prefix + "_channels_with_basins." + fig_format else: ImageName = DataDirectory + out_fname_prefix + "_channels_with_basins." + fig_format MF.save_fig(fig_width_inches=fig_size_inches, FigFileName=ImageName, axis_style=ax_style, FigFormat=fig_format, Fig_dpi=dpi)
""" Created on Tue May 05 14:08:16 2015 @author: dav """ import glob as glob import os.path import numpy as np import LSDPlottingTools as LSDP import lsdmatplotlibextensions as mplext import matplotlib.pyplot as plt from matplotlib import ticker # Get favourite plotting fonts and sizes LSDP.init_plotting_DV() # Truncate the colour map trunc_cmap = mplext.colours.truncate_colormap("Blues", 0.4, 1.0) # Option for getting a discrete colour map #discreet_cmap = mplext.colours.discrete_colourmap(8, "Blues") #discreet_cmap = mplext.colours.cmap_discretize(8, trunc_cmap) #def RasterDifference(OriginalRaster, FinalRaster): # """ # Subtracts FinalRaster from OriginalRaster # to create a 'DEM of difference' # """ # Raster1 = LSDP.ReadRasterArrayBlocks(OriginalRaster,raster_band=1) # Raster2 = LSDP.ReadRasterArrayBlocks(FinalRaster,raster_band=1)