├── .gitattributes ├── .gitignore ├── 3d_elev_animations.py ├── AUTODOCS.md ├── ArchiveTestScripts ├── BGTestArtist.py ├── ChannelProfiles.py ├── EGU2017_Emma.py ├── EGU2017_Emma_1_side.py ├── EGU2017_Emma_knickpoints.py ├── ExampleNonLinearColourbar_DV.py ├── ExampleRainfallMapDrape.py ├── ExampleSingleDrape.py ├── FJCTestArtist2.py ├── FloodMaps_Continuous_colourbar_DV.py ├── FloodMaps_Discrete_colourmap_DV.py ├── PalumboPlots_MappingTools.py ├── RasterDifference.py ├── SMMTestArtist.py ├── SMMTestArtist2.py ├── SMMTestArtist3.py ├── SMMTestArtist4.py ├── SlopeAreaPlot.py ├── TestAxisLocation.py ├── TestDrapeMasked.py ├── TestMappingTools.py ├── TestMappingTools2.py ├── TestMappingToolsPoint.py ├── TestNewMappingTools.py ├── TestNewMappingTools2.py ├── TestNewMapping_asc.py ├── TestSubplots.py ├── crop2image.py ├── custom_colormap_test.py ├── raster_plotter_2d_ascii_chanfile_version.py └── test_multiple_basins.py ├── BUILD_HILLSHADE.md ├── Basemap_test.py ├── BasinAverage.py ├── ChiMappingExamples.py ├── ChiMappingTest.py ├── Coastal_plotting.py ├── Create_hillshade_series_in_directory.py ├── Data_sorting.py ├── Dev_script_for_knickpoints.py ├── Elevation_from_swath.py ├── ExampleLongitudinalSwathPlot.py ├── HillshadeComparison.py ├── LICENSE ├── LSDBasemapTools ├── LSDMap_BasemapTools.py └── __init__.py ├── LSDChiMappingExamples ├── ChiVisualisation_Example01.py └── __init__.py ├── LSDGDALBatchProcessing.py ├── LSDMapArtist ├── README.md ├── __init__.py ├── drapeplot.py └── unittests.py ├── LSDMapFigure ├── PlottingHelpers.py ├── PlottingRaster.py ├── README.asc └── __init__.py ├── LSDMapWrappers ├── LSDMapWrappers_BasicPlotting.py ├── LSDMapWrappers_ChiPlotting.py └── __init__.py ├── LSDMappingTools.py ├── LSDPlottingTools ├── LSDMap_BasicManipulation.py ├── LSDMap_BasicMaps.py ├── LSDMap_BasicPlotting.py ├── LSDMap_ChiPlotting.py ├── LSDMap_DrainageCapture.py ├── LSDMap_GDALIO.py ├── LSDMap_HillslopeMorphology.py ├── LSDMap_KnickpointPlotting.py ├── LSDMap_KnickpointPlotting_old.py ├── LSDMap_LithoPlotting.py ├── LSDMap_MOverNPlotting.py ├── LSDMap_OSystemTools.py ├── LSDMap_PlottingDriver.py ├── LSDMap_PointTools.py ├── LSDMap_SAPlotting.py ├── LSDMap_Subplots.py ├── LSDMap_SwathPlotting.py ├── LSDMap_TerracePlotting.py ├── LSDMap_VectorTools.py ├── __init__.py ├── adjust_text.py ├── colours.py ├── cubehelix.py ├── dimension.py ├── fast_hillshade.pyx ├── inundation.py ├── joyplot.py ├── labels.py ├── locationmap.py ├── scalebar.py ├── setup_cython.py ├── smoothhillshade.py └── statsutilities.py ├── LSD_GeologyTools.py ├── LithoCHILD_to_Raster.py ├── LocationMapCartopy.py ├── MLESensitivity.py ├── MappingDriver.py ├── Mapping_tools_plan.asc ├── Other └── box_whisker.py ├── PlotBasicRasters.py ├── PlotChiAnalysis.py ├── PlotDrainageCaptureMetrics.py ├── PlotHillslopeMorphology.py ├── PlotKnickpointAnalysis.py ├── PlotLithoInfo.py ├── PlotMOverNAnalysis.py ├── PlotMendocinoAnalysis.py ├── PlotTerraceLongProfiles.py ├── Rasterization.py ├── Sieve_from_field.py ├── TUTO_Mapping_Tool.py ├── TestGDALBatch.py ├── Tests ├── LSDMappingTools_test.py ├── WA.bil ├── WA.hdr ├── WA_AllBasins.bil ├── WA_AllBasins.hdr ├── WA_AllBasinsInfo.csv ├── WA_chi_data_map.csv ├── WA_hs.bil └── WA_hs.hdr ├── analyse_knickpoints.py ├── conda_environments ├── LSDMT_version_0.2.1.txt ├── LSDMT_version_0.2.2.txt ├── LSDMT_version_0.2.3.txt ├── conda_environment_notes.asc ├── environment_linux32.yml ├── environment_linux64.yml ├── environment_linux64_fixed_but_large.yml └── python3_environment.yml ├── continuous_cbar_floodmap.png ├── discrete_cbar_floodmap.png ├── docs ├── LSDPlottingTools.rst ├── Makefile ├── conf.py ├── index.rst ├── make.bat ├── requirements.txt └── rtfd-requirements.txt ├── gdal_polygonize.py ├── plot_evia_chi_map.py ├── plot_evia_movern.py ├── plot_hillslope_morphology.py ├── plot_hillslope_traces.py ├── plot_swath_profile.py ├── plotting-examples.ipynb ├── pythonic_rasterizer.py ├── readme.asc ├── rotated_mapping_tools.py ├── test_ingest_geology.py └── tuto1.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly declare text files you want to always be normalized and converted 5 | # to native line endings on checkout. 6 | *.py text 7 | *.h text 8 | *.c text 9 | *.cpp text 10 | *.hpp text 11 | 12 | # Declare files that will always have CRLF line endings on checkout. 13 | *.sln text eol=crlf 14 | 15 | # Denote all files that are truly binary and should not be modified. 16 | *.png binary 17 | *.jpg binary 18 | *.pyc binary 19 | 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # dotenv 80 | .env 81 | 82 | # virtualenv 83 | .venv/ 84 | venv/ 85 | ENV/ 86 | 87 | # Spyder project settings 88 | .spyderproject 89 | 90 | # Rope project settings 91 | .ropeproject 92 | 93 | .bak 94 | 95 | -------------------------------------------------------------------------------- /3d_elev_animations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create 3d elevation plots of model runs and then animate them 3 | """ 4 | 5 | 6 | from LSDPlottingTools import LSDMap_GDALIO as IO 7 | import matplotlib.pyplot as plt 8 | from mayavi import mlab 9 | from mayavi.modules.grid_plane import GridPlane 10 | from matplotlib import cm 11 | import numpy as np 12 | import os 13 | from sys import platform 14 | import sys 15 | from glob import glob 16 | 17 | 18 | def get_filenames(root): 19 | # Create and empty list for the filenames 20 | these_filenames = [] 21 | for filename in glob(root+'*.bil'): 22 | if not 'hs' in filename: 23 | if not 'Raster' in filename: 24 | these_filenames.append(filename) 25 | 26 | these_filenames.sort() 27 | print(these_filenames) 28 | return these_filenames 29 | 30 | def run_plots(DataDirectory,Base_file): 31 | 32 | root = DataDirectory+Base_file 33 | filenames = get_filenames(root) 34 | counter = 0 35 | 36 | # create the plot for the initial raster 37 | initial_file = filenames[0] 38 | 39 | # read in the raster 40 | raster = IO.ReadRasterArrayBlocks(initial_file) 41 | 42 | f = mlab.figure(size=(1000,1000), bgcolor=(0.5,0.5,0.5)) 43 | s = mlab.surf(raster, warp_scale=0.4, colormap='gist_earth', vmax=100) 44 | #mlab.outline(color=(0,0,0)) 45 | 46 | #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]) 47 | 48 | #@mlab.animate(delay=10) 49 | #def anim(): 50 | # now loop through each file and update the z values 51 | for fname in filenames: 52 | this_rast = IO.ReadRasterArrayBlocks(fname) 53 | s.mlab_source.scalars = this_rast 54 | #f.scene.render() 55 | # 56 | mlab.savefig(fname[:-4]+'_3d.png') 57 | #mlab.clf() 58 | 59 | # for (x, y, z) in zip(xs, ys, zs): 60 | # print('Updating scene...') 61 | # plt.mlab_source.set(x=x, y=y, z=z) 62 | # yield 63 | 64 | 65 | 66 | def animate_plots(base_directory, fname_prefix): 67 | """ 68 | This function creates a movie of the plots using ffmpeg 69 | 70 | Args: 71 | base_directory (str): the directory with the plots. 72 | fname_prefix (str): the filename for the model run 73 | 74 | Returns: 75 | none but creates mp4 from pngs in base directory 76 | 77 | Author: FJC 78 | """ 79 | import subprocess 80 | 81 | # animate the pngs using ffmpeg 82 | system_call = "ffmpeg -framerate 5 -pattern_type glob -i '"+base_directory+"*.png' -vcodec libx264 -s 1000x1000 -pix_fmt yuv420p "+base_directory+fname_prefix+"_movie.mp4" 83 | print(system_call) 84 | subprocess.call(system_call, shell=True) 85 | 86 | #============================================================================= 87 | # This is just a welcome screen that is displayed if no arguments are provided. 88 | #============================================================================= 89 | def print_welcome(): 90 | 91 | print("\n\n=======================================================================") 92 | print("Hello! I'm going to plot a series of hillshades for you.") 93 | print("You will need to tell me the directory and the base file name.") 94 | print("Use the -dir flag to define the working directory.") 95 | print("If you don't do this I will assume the data is in the same directory as this script.") 96 | print("Use the -fname flag to define the base file name.") 97 | print("For help type:") 98 | print(" python PlotMOverNAnalysis.py -h\n") 99 | print("=======================================================================\n\n ") 100 | 101 | #============================================================================= 102 | # This is the main function that runs the whole thing 103 | #============================================================================= 104 | def main(argv): 105 | 106 | """ 107 | This is just a few lines for keeping track of how long the program is taking. 108 | You can ignore it. 109 | """ 110 | import time 111 | tic = time.clock() 112 | 113 | # If there are no arguments, send to the welcome screen 114 | if not len(sys.argv) > 1: 115 | full_paramfile = print_welcome() 116 | sys.exit() 117 | 118 | # Get the arguments 119 | import argparse 120 | parser = argparse.ArgumentParser() 121 | # The location of the data files 122 | parser.add_argument("-dir", "--base_directory", type=str, help="The base directory with the hillshades. If this isn't defined I'll assume it's the same as the current directory.") 123 | parser.add_argument("-fname", "--fname_prefix", type=str, help="The base file name of the hillshades.") 124 | parser.add_argument("-animate", "--animate", type=bool, default=False, help="If this is true I'll create a movie of the model run.") 125 | parser.add_argument("-zmax", "--maximum_elevation_for_plotting", type=float, default = 400, help="This is the maximum elevation in the colourbar of the landscape plot.") 126 | args = parser.parse_args() 127 | 128 | run_plots(args.base_directory,args.fname_prefix) 129 | 130 | if (args.animate): 131 | animate_plots(args.base_directory, args.fname_prefix) 132 | 133 | toc = time.clock() 134 | print("This took: "+str(toc - tic)+" units of time") 135 | 136 | 137 | #============================================================================= 138 | if __name__ == "__main__": 139 | main(sys.argv[1:]) 140 | -------------------------------------------------------------------------------- /AUTODOCS.md: -------------------------------------------------------------------------------- 1 | # Automated documentation using ReadTheDocs and docstrings 2 | 3 | The basic documentation for this project is built using the www.readthedocs.org site. It builds documentation from document strings found in the class and function definitions within the LSDPlottingTools package and its submodules. 4 | 5 | We use the Google Dosctrings style: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html 6 | 7 | ## Some annoying things to watch out for when maintaining the docs 8 | 9 | ### Module names within LSDPlottingTools 10 | If you change the module names, you must change them in the LSDPlottingTools.rst file, same goes if you add a new module too, it must be either added manually to this file (or you can rebuild with sphinx but I think just adding the module name is easier.) 11 | 12 | ### External module names 13 | If you have external modules (gdal, cartopy etc) these have to go in the `'MagicMock'` class sys function in `conf.py`. There is a big list of module names that are from external modules that we use in LSDPlottingTools. ReadTheDocs does not have all of these modules installed in the virtualenv it creates so the MagickMock thing tricks it into thinking the modules exist. 14 | 15 | The weird thing is that they have to be listed in hierarchical order: e.g. `['gdal', gdal.gdal_array', 'gdal.gdal_array.someothesubmodule']`. 16 | 17 | Also weirdly, if you use a 3rd level submodule, but not the second level one e.g. `'cartopy.mpl.patch'` but not `'cartopy.mpl'`, you still have to add `'cartopy.mpl'` to the list and in the correct order (biggest to smallest) 18 | 19 | Isn't it so simple and automated...! 20 | -------------------------------------------------------------------------------- /ArchiveTestScripts/BGTestArtist.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 10 16:57:22 2017 4 | 5 | @author: smudd 6 | """ 7 | import matplotlib 8 | matplotlib.use('Agg') 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | # Force matplotlib to not use any Xwindows backend. 13 | 14 | 15 | from matplotlib import rcParams 16 | import matplotlib.cm as cm 17 | from LSDMapFigure.PlottingRaster import MapFigure 18 | from LSDMapFigure.PlottingRaster import BaseRaster 19 | 20 | from LSDPlottingTools import colours as lsdcolours 21 | from LSDPlottingTools import init_plotting_DV 22 | import sys 23 | 24 | #sys.path.append("PATH/TO/LSDPlottingTools/") 25 | # 26 | #init_plotting_DV() 27 | 28 | label_size = 12 29 | #rcParams['font.family'] = 'sans-serif' 30 | #rcParams['font.sans-serif'] = ['Liberation Sans'] 31 | #rcParams['font.size'] = label_size 32 | #rcParams['lines.linewidth'] = 1.5 33 | 34 | 35 | Directory = "/home/s1675537/PhD/DataStoreBoris/GIS/Data/Side_Project/m_Chi_knickpoint/Test_area/" 36 | wDirectory = "/home/s1675537/PhD/DataStoreBoris/GIS/Data/Side_Project/m_Chi_knickpoint/Test_area/LSDMT/" 37 | Base_file = "area" 38 | 39 | 40 | BackgroundRasterName = Base_file+".bil" 41 | DrapeRasterName = Base_file+"_hs.bil" 42 | ChiRasterName = Base_file+"_curvature.bil" 43 | 44 | #BR = BaseRaster(BackgroundRasterName, Directory) 45 | #BR.set_raster_type("Terrain") 46 | #print(BR._colourmap) 47 | #BR.show_raster() 48 | 49 | #BR.set_colourmap("RdYlGn") 50 | #BR.show_raster() 51 | 52 | 53 | 54 | 55 | plt.clf() 56 | MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km") 57 | MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4) 58 | MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True) 59 | #MF.show_plot() 60 | ImageName = Directory+"boris.png" 61 | fig_size_inches = 6 62 | ax_style = "Madhouse" 63 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style) 64 | 65 | 66 | 67 | # Customise the DrapePlot 68 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 69 | #dp.set_fig_axis_labels() 70 | 71 | #dp.show_plot() 72 | -------------------------------------------------------------------------------- /ArchiveTestScripts/ChannelProfiles.py: -------------------------------------------------------------------------------- 1 | # quick script for plotting channel profiles 2 | 3 | import LSDPlottingTools as LSDP 4 | 5 | DataDirectory = '/home/s0923330/DEMs_for_analysis/muddpile_test/runs_for_analysis/movern_0p5/n_is_one/' 6 | fname = 'movern_0p5_n_is_one200' 7 | 8 | LSDP.LSDMap_ChiPlotting.ChannelProfilePlot(DataDirectory,fname,FigFormat='png') 9 | -------------------------------------------------------------------------------- /ArchiveTestScripts/EGU2017_Emma.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created. 4 | 5 | @author: Boris 6 | """ 7 | #import matplotlib 8 | #matplotlib.use('Agg') 9 | import matplotlib.pyplot as plt 10 | import time as clock 11 | from matplotlib import rcParams 12 | import matplotlib.cm as cm 13 | from LSDMapFigure.PlottingRaster import MapFigure 14 | from LSDMapFigure.PlottingRaster import BaseRaster 15 | 16 | from LSDPlottingTools import colours as lsdcolours 17 | from LSDPlottingTools import init_plotting_DV 18 | import LSDPlottingTools as LSDP 19 | import sys 20 | 21 | #rcParams['font.family'] = 'sans-serif' 22 | #rcParams['font.sans-serif'] = ['Liberation Sans'] 23 | #rcParams['font.size'] = label_size 24 | #rcParams['lines.linewidth'] = 1.5 25 | 26 | ###### Parameters ###### 27 | Directory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # reading directory (if it is on windows, the path is something like C://windows/Users/blablalba/) 28 | wDirectory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # writing directory (if it is on windows, the path is something like C://windows/Users/blablalba/) 29 | Base_file = "Betics_UTM30clip_PP" # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata 30 | csv_file = Directory + "new.csv" # Name of your point file, add a similar line with different name if you have more than one point file 31 | DrapeRasterName = "Betics_UTM30clip_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 32 | wname = "output" # name of your output file 33 | dpi = 900 # Quality of your output image, don't exceed 900 34 | fig_size_inches = 24 # Figure size in Inches 35 | 36 | ##### Now we can load and plot the data 37 | 38 | BackgroundRasterName = Base_file + ".bil" # Ignore this line 39 | 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. 40 | 41 | plt.clf() # Ignore this line 42 | 43 | MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km", NFF_opti = True) # load the background raster 44 | 45 | MF.add_drape_image(DrapeRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one 46 | 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 47 | alpha=0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque 48 | show_colourbar = False, # Well, this one is explicit I think 49 | colorbarlabel = "Colourbar", # Name of your Colourbar, it might bug though 50 | NFF_opti = True) 51 | 52 | 53 | 54 | MF.add_point_data( thisPointData, # this function plot the requested point file using the lat/long column in the csv file 55 | column_for_plotting = "chi", # Column used to color the data 56 | 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 57 | colorbarlabel = "Colourbar", # Label 58 | scale_points = False, # All the point will have the same size if False 59 | column_for_scaling = "None", # If scale point True, you can scale the size of your points using one of the columns 60 | scaled_data_in_log = False, # If scale point True, you can log the scaling 61 | max_point_size = 5, # max size if scale point True again 62 | min_point_size = 0.5, # You should be able to guess that one now 63 | colour_log = False, # do you want a log scale for your colorbar ? 64 | colour_manual_scale = [], #Do you want to manually limit the scale of your colorbar? if not let is false 65 | manual_size = 0, # If none of above is choosen but you want to put another value than 0.5 to scale your point 66 | alpha = 1, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque 67 | minimum_log_scale_cut_off = -10) # you probably won't need this 68 | 69 | 70 | ImageName = wDirectory+str(int(clock.time()))+wname+".png" # Ignore this 71 | ax_style = "Normal" # Ignore this 72 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = dpi) # Save the figure 73 | -------------------------------------------------------------------------------- /ArchiveTestScripts/EGU2017_Emma_knickpoints.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 10 16:57:22 2017 4 | 5 | @author: Yes 6 | """ 7 | import matplotlib 8 | matplotlib.use('Agg') 9 | import matplotlib.pyplot as plt 10 | import time as clock 11 | 12 | # Force matplotlib to not use any Xwindows backend. 13 | 14 | 15 | from matplotlib import rcParams 16 | import matplotlib.cm as cm 17 | from LSDMapFigure.PlottingRaster import MapFigure 18 | from LSDMapFigure.PlottingRaster import BaseRaster 19 | 20 | from LSDPlottingTools import colours as lsdcolours 21 | from LSDPlottingTools import init_plotting_DV 22 | import LSDPlottingTools as LSDP 23 | import sys 24 | #import pandas as bamboo_bears 25 | 26 | #sys.path.append("PATH/TO/LSDPlottingTools/") 27 | # 28 | #init_plotting_DV() 29 | 30 | label_size = 12 31 | #rcParams['font.family'] = 'sans-serif' 32 | #rcParams['font.sans-serif'] = ['Liberation Sans'] 33 | #rcParams['font.size'] = label_size 34 | #rcParams['lines.linewidth'] = 1.5 35 | 36 | 37 | Directory = "/home/s1675537/PhD/DataStoreBoris/Emma/" 38 | wDirectory = "/home/s1675537/PhD/DataStoreBoris/Emma/" 39 | Base_file = "Betics_UTM30clip_PP" 40 | 41 | #df = bamboo_bears.read_csv(rDirectory2 + fname2, sep=",") 42 | csv_file = "/home/s1675537/PhD/DataStoreBoris/Emma/new.csv" 43 | BackgroundRasterName = Base_file + ".bil" 44 | DrapeRasterName = "Betics_UTM30clip_hs.bil" 45 | 46 | #BlackRasterD = "/home/s1675537/PhD/DataStoreBoris/GIS/Data/Carpathian/Best_DEM/" 47 | #BlackRaster = "black_35.bil" 48 | 49 | alpha_black = 1 50 | #CurveRasterName = Base_file+"_curvature.bil" 51 | 52 | #BR = BaseRaster(BackgroundRasterName, Directory) 53 | #BR.set_raster_type("Terrain") 54 | #print(BR._colourmap) 55 | #BR.show_raster() 56 | 57 | #BR.set_colourmap("RdYlGn") 58 | #BR.show_raster() 59 | thisPointData = LSDP.LSDMap_PointData(csv_file) 60 | river_network = LSDP.LSDMap_PointData("/home/s1675537/PhD/DataStoreBoris/Emma/rv.csv") 61 | 62 | #names = ['cubehelix','CMRmap','RdBu'] 63 | #names = ['spring_r', 'autumn_r','YlOrRd','YlOrRd_r'] 64 | names = ['autumn_r'] 65 | for nami in names: 66 | plt.clf() 67 | MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km", alpha = 1) 68 | MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.5) 69 | #MF.add_drape_image(BlackRaster, BlackRasterD, alpha = alpha_black) 70 | MF.add_point_data(river_network,scale_points = True, max_point_size = 1, min_point_size = 0.1, column_for_scaling ="drainage area", scaled_data_in_log = True) 71 | MF.add_point_data( thisPointData,column_for_plotting = "elevation", 72 | this_colourmap = nami, colorbarlabel = "knickpoint sign", scale_points = True, max_point_size = 100, min_point_size = 0, column_for_scaling ="knickpoints", scaled_data_in_log = True, minimum_log_scale_cut_off = 2 ) 73 | 74 | 75 | #MF.add_drape_image(CurveRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True, colorbarlabel= "Colourbar") 76 | #MF.show_plot() 77 | ImageName = wDirectory+str(int(clock.time()))+nami+".png" 78 | fig_size_inches = 12 79 | ax_style = "Normal" 80 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 500) 81 | 82 | 83 | 84 | # Customise the DrapePlot 85 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 86 | #dp.set_fig_axis_labels() 87 | 88 | #dp.show_plot() 89 | -------------------------------------------------------------------------------- /ArchiveTestScripts/ExampleNonLinearColourbar_DV.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: dav 9 | """ 10 | import glob as glob 11 | import os.path 12 | import numpy as np 13 | import LSDPlottingTools as LSDP 14 | import matplotlib.cm as cm 15 | #import lsdmatplotlibextensions as mplext 16 | 17 | import matplotlib.pyplot as plt 18 | from matplotlib import ticker 19 | 20 | # Get favourite plotting fonts and sizes 21 | LSDP.init_plotting_DV() 22 | 23 | # Truncate the colour map 24 | #trunc_cmap = LSDP.colours.truncate_colormap("Blues", 0.4, 1.0) 25 | 26 | # Option for getting a discrete colour map 27 | #discreet_cmap = mplext.colours.discrete_colourmap(8, "Blues") 28 | #discreet_cmap = mplext.colours.cmap_discretize(8, trunc_cmap) 29 | 30 | # Non-linear colourmap 31 | levels = [-2.5, -1.5 -0.5, -0.25, 0, 0.25, 0.5, 1.5, 2.5 ] 32 | #levels = levels[levels <= tmax] 33 | print (levels) 34 | levels.sort() 35 | print (levels) 36 | cmap_lin = cm.jet 37 | 38 | nonlincmap = LSDP.colours.nonlinear_colourmap(cmap_lin, levels) 39 | print (type(nonlincmap)) 40 | 41 | #DataDirectory = "/run/media/dav/SHETLAND/Analyses/Ryedale_storms_simulation/Gridded/DetachLim/" 42 | #DataDirectory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/peak_flood_maps/boscastle/erode_diff/" 43 | DataDirectory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" 44 | #DataDirectory = "/run/media/dav/SHETLAND/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" 45 | 46 | LSDP.MultiDrapeErodeDiffMaps(DataDirectory, "BoscastleElevations0.asc", "Boscastle*.bil", 47 | cmap=cmap_lin, 48 | drape_min_threshold= -2.5, 49 | drape_max_threshold= 2.5, 50 | cbar_label = "DEM difference (m)", 51 | middle_mask_range = (-0.01, 0.01) 52 | ) 53 | -------------------------------------------------------------------------------- /ArchiveTestScripts/ExampleRainfallMapDrape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jan 31 11:47:22 2017 5 | 6 | An example of using the LSDMapArtist to create drape plots 7 | 8 | @author: dav 9 | """ 10 | 11 | import matplotlib.cm as cm 12 | from LSDMapArtist.drapeplot import DrapeAxes 13 | from LSDPlottingTools import colours as lsdcolours 14 | from LSDPlottingTools import init_plotting_DV 15 | 16 | init_plotting_DV() 17 | #Directory = "/mnt/SCRATCH/Dev/LSDMappingTools/test_rasters/peak_flow_rasters/" 18 | Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/rainfall_maps/" 19 | #Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/Difference_UNIFORM_GRIDDED/" 20 | #Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" 21 | BackgroundRasterName = "BoscastleElevations0.asc" 22 | #DrapeRasterName = "BoscastleElevDiff_UNIFORM_TLIM.bil" 23 | DrapeRasterName = "rainfall_totals_boscastle_downscaled.asc" 24 | 25 | # Standard colourmap 26 | Colourmap = "Blues" 27 | 28 | #Non-linear colourmap 29 | ##ColourLevels = lsdcolours.nonlinear_colourmap.create_levels(-3.0, 3.0, -0.2, 0.2, -0.5, 0.5) 30 | ##Colourmap = lsdcolours.nonlinear_colourmap("seismic", ColourLevels) 31 | 32 | # Transformed colourmap 33 | #c = lsdcolours.TransformedColourmap(lambda x: x/2+0.5, cm.jet) 34 | 35 | drape_min_threshold = None 36 | drape_max_threshold = None 37 | colourbar_label = "Total accumulated rainfall (mm)" 38 | 39 | #raster = BaseRaster(RasterName, DataDirectory) 40 | dp = DrapeAxes(DrapeRasterName, BackgroundRasterName, Directory, 41 | Colourmap, background_type="Hillshade", 42 | show_background_colourbar=False, 43 | colourbar_label=colourbar_label, drape_alpha=0.8 44 | ) 45 | #colourbar_norm_type="SymLogNorm") 46 | dp.set_subplot_labels("") 47 | 48 | # Customise the DrapePlot 49 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 50 | #dp.set_fig_axis_labels() 51 | 52 | dp.show_plot() -------------------------------------------------------------------------------- /ArchiveTestScripts/ExampleSingleDrape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jan 31 11:47:22 2017 5 | 6 | An example of using the LSDMapArtist to create drape plots 7 | 8 | @author: dav 9 | """ 10 | 11 | import matplotlib.cm as cm 12 | from LSDMapArtist.drapeplot import DrapeAxes 13 | from LSDPlottingTools import colours as lsdcolours 14 | from LSDPlottingTools import init_plotting_DV 15 | 16 | init_plotting_DV() 17 | #Directory = "/mnt/SCRATCH/Dev/LSDMappingTools/test_rasters/peak_flow_rasters/" 18 | #Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/Difference_UNIFORM_GRIDDED/" 19 | #Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/Difference_UNIFORM_GRIDDED/" 20 | #Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" 21 | Directory = '/run/media/dav/SHETLAND/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/' 22 | BackgroundRasterName = "RyedaleElevations0.asc" 23 | DrapeRasterName = "RyedaleElevDiff_GRIDDED_DLIM.bil" 24 | #DrapeRasterName = "BoscastleErodeDiff_GRID_UNI_TLIMM.bil" 25 | 26 | # Standard colourmap 27 | Colourmap = "RdYlGn" 28 | 29 | #Non-linear colourmap 30 | ##ColourLevels = lsdcolours.nonlinear_colourmap.create_levels(-3.0, 3.0, -0.2, 0.2, -0.5, 0.5) 31 | ##Colourmap = lsdcolours.nonlinear_colourmap("seismic", ColourLevels) 32 | 33 | # Transformed colourmap 34 | #c = lsdcolours.TransformedColourmap(lambda x: x/2+0.5, cm.jet) 35 | 36 | drape_min_threshold = None 37 | drape_max_threshold = None 38 | colourbar_label = "Erosion/Deposition (m)" 39 | 40 | #raster = BaseRaster(RasterName, DataDirectory) 41 | dp = DrapeAxes(DrapeRasterName, BackgroundRasterName, Directory, 42 | Colourmap, background_type="Terrain", 43 | show_background_colourbar=True,) 44 | # colourbar_label=colourbar_label, 45 | # vmin=-4, vmax=4, middle_mask_range=(-0.02,0.02), 46 | # colourbar_norm_type="SymLogNorm") 47 | 48 | 49 | # Customise the DrapePlot 50 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 51 | #dp.set_fig_axis_labels() 52 | 53 | dp.show_plot() -------------------------------------------------------------------------------- /ArchiveTestScripts/FJCTestArtist2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 10 16:57:22 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | # -*- coding: utf-8 -*- 9 | """ 10 | Created on Fri Feb 10 12:55:23 2017 11 | 12 | @author: smudd 13 | """ 14 | import matplotlib 15 | matplotlib.use('Agg') 16 | 17 | import matplotlib.cm as cm 18 | from LSDMapFigure.PlottingRaster import MapFigure 19 | from LSDMapFigure.PlottingRaster import BaseRaster 20 | import matplotlib.pyplot as plt 21 | from LSDPlottingTools import colours as lsdcolours 22 | from LSDPlottingTools import init_plotting_DV 23 | import sys 24 | from LSDPlottingTools import LSDMap_VectorTools as LSDMap_VT 25 | 26 | # Generate random colormap 27 | def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True): 28 | """ 29 | Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks 30 | :param nlabels: Number of labels (size of colormap) 31 | :param type: 'bright' for strong colors, 'soft' for pastel colors 32 | :param first_color_black: Option to use first color as black, True or False 33 | :param last_color_black: Option to use last color as black, True or False 34 | :param verbose: Prints the number of labels and shows the colormap. True or False 35 | :return: colormap for matplotlib 36 | """ 37 | from matplotlib.colors import LinearSegmentedColormap 38 | import colorsys 39 | import numpy as np 40 | 41 | if type not in ('bright', 'soft'): 42 | print ('Please choose "bright" or "soft" for type') 43 | return 44 | 45 | if verbose: 46 | print('Number of labels: ' + str(nlabels)) 47 | 48 | # Generate color map for bright colors, based on hsv 49 | if type == 'bright': 50 | randHSVcolors = [(np.random.uniform(low=0.0, high=1), 51 | np.random.uniform(low=0.2, high=1), 52 | np.random.uniform(low=0.9, high=1)) for i in xrange(nlabels)] 53 | 54 | # Convert HSV list to RGB 55 | randRGBcolors = [] 56 | for HSVcolor in randHSVcolors: 57 | randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2])) 58 | 59 | if first_color_black: 60 | randRGBcolors[0] = [0, 0, 0] 61 | 62 | if last_color_black: 63 | randRGBcolors[-1] = [0, 0, 0] 64 | 65 | random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) 66 | 67 | # Generate soft pastel colors, by limiting the RGB spectrum 68 | if type == 'soft': 69 | low = 0.6 70 | high = 0.95 71 | randRGBcolors = [(np.random.uniform(low=low, high=high), 72 | np.random.uniform(low=low, high=high), 73 | np.random.uniform(low=low, high=high)) for i in xrange(nlabels)] 74 | 75 | if first_color_black: 76 | randRGBcolors[0] = [0, 0, 0] 77 | 78 | if last_color_black: 79 | randRGBcolors[-1] = [0, 0, 0] 80 | random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) 81 | 82 | # Display colorbar 83 | if verbose: 84 | from matplotlib import colors, colorbar 85 | from matplotlib import pyplot as plt 86 | fig, ax = plt.subplots(1, 1, figsize=(15, 0.5)) 87 | 88 | bounds = np.linspace(0, nlabels, nlabels + 1) 89 | norm = colors.BoundaryNorm(bounds, nlabels) 90 | 91 | cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None, 92 | boundaries=bounds, format='%1i', orientation=u'horizontal') 93 | 94 | return random_colormap 95 | 96 | #sys.path.append("PATH/TO/LSDPlottingTools/") 97 | # 98 | #init_plotting_DV() 99 | 100 | Directory = "/media/fionaclubb/terrace_lidar/Mendocino_TJ/mendocino/coastal_california/" 101 | #Directory = "T:\\analysis_for_papers\\Meghalaya\\divide_migration\\" 102 | Base_file = "California_clip" 103 | 104 | #BackgroundRasterName = Base_file+".bil" 105 | DrapeRasterName = Base_file+"_hs.bil" 106 | BasinsName = Base_file+"_basins.bil" 107 | 108 | #BR = BaseRaster(BackgroundRasterName, Directory) 109 | #BR.set_raster_type("Terrain") 110 | #print(BR._colourmap) 111 | #BR.show_raster() 112 | 113 | #BR.set_colourmap("RdYlGn") 114 | #BR.show_raster() 115 | 116 | #label_size = 100 117 | #rcParams['font.family'] = 'sans-serif' 118 | #rcParams['font.sans-serif'] = ['Liberation Sans'] 119 | #rcParams['font.size'] = label_size 120 | #rcParams['lines.linewidth'] = 1.5 121 | 122 | plt.clf() 123 | MF = MapFigure(DrapeRasterName, Directory,coord_type="UTM_km",colourbar_location='None') 124 | # add the basins drape 125 | cmap = cm.Set1 126 | MF.add_drape_image(BasinsName, Directory, colourmap = cmap, alpha = 0.5, colorbarlabel='Basin ID', show_colourbar = False) 127 | # add the basin outlines 128 | Basins = LSDMap_VT.GetBasinOutlines(Directory, BasinsName) 129 | MF.plot_polygon_outlines(Basins, linewidth=0.8) 130 | #MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True) 131 | #MF.show_plot() 132 | MF.save_fig(fig_width_inches = 12, FigFileName=Directory+Base_file+'.png', FigFormat='png', Fig_dpi=300, transparent=True) 133 | 134 | # Customise the DrapePlot 135 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 136 | #dp.set_fig_axis_labels() 137 | 138 | #dp.show_plot() 139 | -------------------------------------------------------------------------------- /ArchiveTestScripts/PalumboPlots_MappingTools.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | 14 | def PalumboPlots(): 15 | DataDirectory = "T://analysis_for_papers//Cosmo_paper//Palumbo_shield_plots//" 16 | Filename = "SpawnedBasin_07C13-(Q8).bil" 17 | Drapename = "SpawnedBasin_07C13-(Q8)_BASINS.bil" 18 | 19 | ThisFile = DataDirectory+Filename 20 | DrapeFile = DataDirectory+Drapename 21 | 22 | LSDP.BasicDrapedPlotGridPlot(ThisFile, DrapeFile, thiscmap='terrain',drape_cmap='gray', 23 | colorbarlabel='Elevation in meters',clim_val = (2000,5000), 24 | drape_alpha = 0.4,FigFileName = 'Basin.pdf',FigFormat = 'pdf') 25 | 26 | def ShieldPlots_coarse(): 27 | DataDirectory = "T://analysis_for_papers//Cosmo_paper//Palumbo_shield_plots//" 28 | Filename = "SpawnedBasin_07C13-coarse_SH.bil" 29 | 30 | ThisFile = DataDirectory+Filename 31 | 32 | LSDP.BasicDensityPlotGridPlot(ThisFile, thiscmap='summer',colorbarlabel='Topographic shielding coarse', 33 | clim_val = (0.85,1),FigFileName = 'Shield_coarse.pdf', FigFormat = 'pdf') 34 | 35 | def ShieldPlots_fine(): 36 | DataDirectory = "T://analysis_for_papers//Cosmo_paper//Palumbo_shield_plots//" 37 | Filename = "SpawnedBasin_07C13-fine_SH.bil" 38 | 39 | ThisFile = DataDirectory+Filename 40 | 41 | LSDP.BasicDensityPlotGridPlot(ThisFile, thiscmap='summer',colorbarlabel='Topographic shielding fine', 42 | clim_val = (0.85,1),FigFileName = 'Shield_fine.pdf', FigFormat = 'pdf') 43 | 44 | 45 | if __name__ == "__main__": 46 | #fit_weibull_from_file(sys.argv[1]) 47 | #TestNewMappingTools2() 48 | #ResetErosionRaster() 49 | PalumboPlots() 50 | ShieldPlots_coarse() 51 | ShieldPlots_fine() 52 | -------------------------------------------------------------------------------- /ArchiveTestScripts/RasterDifference.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | """ 6 | Raster/DEM differencer 7 | 8 | For when you've fucked up your C++ code and have to 9 | do the DEM-differencing by hand in Python... 10 | 11 | 12 | Created on Sun Jan 15 16:18:35 2017 13 | 14 | @author: dav 15 | 16 | """ 17 | import LSDPlottingTools as LSDP 18 | 19 | DataDirectory = "/run/media/dav/SHETLAND/Analyses/HydrogeomorphPaper/erode_diff/Difference_UNIFORM_GRIDDED/" 20 | 21 | 22 | LSDP.RasterDifference(DataDirectory + "RyedaleElevDiff_GRIDDED_TLIM.bil", 23 | DataDirectory + "RyedaleElevDiff_UNIFORM_TLIM.bil", 24 | raster_band=1, 25 | OutFileName="RyedaleErodeDiff_GRID_UNI_TLIMM.bil", 26 | OutFileType="ENVI") 27 | 28 | -------------------------------------------------------------------------------- /ArchiveTestScripts/SMMTestArtist.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 10 12:55:23 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | 9 | import matplotlib.cm as cm 10 | from LSDMapArtist.drapeplot_experimental import DrapeAxes 11 | 12 | from LSDPlottingTools import colours as lsdcolours 13 | from LSDPlottingTools import init_plotting_DV 14 | import sys 15 | 16 | #sys.path.append("PATH/TO/LSDPlottingTools/") 17 | # 18 | #init_plotting_DV() 19 | 20 | Directory = "T:\\analysis_for_papers\\Meghalaya\\divide_migration\\" 21 | Base_file = "Mega_divide" 22 | BackgroundRasterName = Base_file+".bil" 23 | DrapeRasterName = Base_file+"_hs.bil" 24 | #DrapeRasterName = "BoscastleErodeDiff_GRID_UNI_TLIMM.bil" 25 | 26 | 27 | 28 | 29 | 30 | # Standard colourmap 31 | Colourmap = "RdYlGn" 32 | 33 | #Non-linear colourmap 34 | ##ColourLevels = lsdcolours.nonlinear_colourmap.create_levels(-3.0, 3.0, -0.2, 0.2, -0.5, 0.5) 35 | ##Colourmap = lsdcolours.nonlinear_colourmap("seismic", ColourLevels) 36 | 37 | # Transformed colourmap 38 | #c = lsdcolours.TransformedColourmap(lambda x: x/2+0.5, cm.jet) 39 | 40 | drape_min_threshold = None 41 | drape_max_threshold = None 42 | colourbar_label = "Yo (m)" 43 | 44 | #raster = BaseRaster(RasterName, DataDirectory) 45 | dp = DrapeAxes(DrapeRasterName, BackgroundRasterName, Directory, 46 | Colourmap, background_type="Hillshade", 47 | show_background_colourbar=False, 48 | show_drape = True, 49 | colourbar_label=colourbar_label) 50 | 51 | 52 | 53 | # Customise the DrapePlot 54 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 55 | #dp.set_fig_axis_labels() 56 | 57 | dp.show_plot() -------------------------------------------------------------------------------- /ArchiveTestScripts/SMMTestArtist2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 10 16:57:22 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | # -*- coding: utf-8 -*- 9 | """ 10 | Created on Fri Feb 10 12:55:23 2017 11 | 12 | @author: smudd 13 | """ 14 | 15 | import matplotlib 16 | 17 | # Force matplotlib to not use any Xwindows backend. 18 | matplotlib.use('Agg') 19 | 20 | 21 | import matplotlib.pyplot as plt 22 | import matplotlib 23 | from matplotlib import rcParams 24 | import matplotlib.cm as cm 25 | from LSDMapFigure.PlottingRaster import MapFigure 26 | from LSDMapFigure.PlottingRaster import BaseRaster 27 | 28 | from LSDPlottingTools import colours as lsdcolours 29 | from LSDPlottingTools import init_plotting_DV 30 | from LSDPlottingTools import LSDMap_PointTools 31 | import sys 32 | 33 | #sys.path.append("PATH/TO/LSDPlottingTools/") 34 | # 35 | #init_plotting_DV() 36 | 37 | #label_size = 100 38 | rcParams['font.family'] = 'sans-serif' 39 | rcParams['font.sans-serif'] = ['Liberation Sans'] 40 | #rcParams['font.size'] = label_size 41 | #rcParams['lines.linewidth'] = 1.5 42 | 43 | 44 | #DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/Meghalaya/chi_analysis/" 45 | #Directory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Divides\\" 46 | #Directory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\test_segments\\" 47 | Directory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\" 48 | #DataDirectory = "T:\\analysis_for_papers\\Meghalaya/chi_analysis\\" 49 | #Base_file = "Mega_divide_segments" 50 | Base_file= "Mega_clip" 51 | 52 | #Directory = "/home/s1563094/Datastore/DATA/UK/LiDAR_DTM_1m/HIN/" 53 | #Base_file = "HIN_" 54 | 55 | BackgroundRasterName = Base_file+".bil" 56 | DrapeRasterName = Base_file+"_hs.bil" 57 | ChiRasterName = Base_file+"_chi_coord.bil" 58 | 59 | 60 | #BR = BaseRaster(BackgroundRasterName, Directory) 61 | #BR.set_raster_type("Terrain") 62 | #print(BR._colourmap) 63 | #BR.show_raster() 64 | 65 | #BR.set_colourmap("RdYlGn") 66 | #BR.show_raster() 67 | 68 | #PD_file = Base_file+"_chi_coord_basins.csv" 69 | PD_file = Base_file+"_MChiSegmented.csv" 70 | PointData = LSDMap_PointTools.LSDMap_PointData(Directory+PD_file) 71 | 72 | plt.clf() 73 | cbar_loc = "Bottom" 74 | MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km",colourbar_location = cbar_loc) 75 | MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4) 76 | #MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4) 77 | MF.add_point_data(PointData,column_for_plotting = "source_key",colorbarlabel = "I am point data", 78 | scale_points = True,column_for_scaling = "drainage area", 79 | scaled_data_in_log = False) 80 | #MF.show_plot() 81 | ImageName = Directory+"TestNewArtist.png" 82 | fig_size_inches = 6 83 | ax_style = "Normal" 84 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250) 85 | 86 | 87 | 88 | # Customise the DrapePlot 89 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 90 | #dp.set_fig_axis_labels() 91 | 92 | #dp.show_plot() -------------------------------------------------------------------------------- /ArchiveTestScripts/SMMTestArtist3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Mar 07 12:49:18 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | # -*- coding: utf-8 -*- 9 | """ 10 | Created on Fri Feb 10 16:57:22 2017 11 | 12 | @author: smudd 13 | """ 14 | 15 | # -*- coding: utf-8 -*- 16 | """ 17 | Created on Fri Feb 10 12:55:23 2017 18 | 19 | @author: smudd 20 | """ 21 | 22 | import matplotlib 23 | 24 | # Force matplotlib to not use any Xwindows backend. 25 | matplotlib.use('Agg') 26 | 27 | 28 | import matplotlib.pyplot as plt 29 | import matplotlib 30 | from matplotlib import rcParams 31 | import matplotlib.cm as cm 32 | from LSDMapFigure.PlottingRaster import MapFigure 33 | from LSDMapFigure.PlottingRaster import BaseRaster 34 | 35 | from LSDPlottingTools import colours as lsdcolours 36 | from LSDPlottingTools import init_plotting_DV 37 | from LSDPlottingTools import LSDMap_PointTools 38 | import sys 39 | 40 | #sys.path.append("PATH/TO/LSDPlottingTools/") 41 | # 42 | #init_plotting_DV() 43 | 44 | #label_size = 100 45 | rcParams['font.family'] = 'sans-serif' 46 | rcParams['font.sans-serif'] = ['Liberation Sans'] 47 | #rcParams['font.size'] = label_size 48 | #rcParams['lines.linewidth'] = 1.5 49 | 50 | 51 | DataDirectory = "/home/smudd/LSDTopoData/TanDemX_data/Nepal/" 52 | 53 | #DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/Meghalaya/chi_analysis/" 54 | #Directory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Divides\\" 55 | #DataDirectory = "T:\\analysis_for_papers\\Meghalaya/chi_analysis\\" 56 | Base_file = "HS" 57 | 58 | #Directory = "/home/s1563094/Datastore/DATA/UK/LiDAR_DTM_1m/HIN/" 59 | #Base_file = "HIN_" 60 | 61 | #BackgroundRasterName = Base_file+".bil" 62 | BackgroundRasterName = Base_file+".tif" 63 | #DrapeRasterName = Base_file+"_hs.bil" 64 | #ChiRasterName = Base_file+"_chi_coord.bil" 65 | 66 | 67 | #BR = BaseRaster(BackgroundRasterName, Directory) 68 | #BR.set_raster_type("Terrain") 69 | #print(BR._colourmap) 70 | #BR.show_raster() 71 | 72 | #BR.set_colourmap("RdYlGn") 73 | #BR.show_raster() 74 | 75 | #PD_file = Base_file+"_chi_coord_basins.csv" 76 | #PointData = LSDMap_PointTools.LSDMap_PointData(Directory+PD_file) 77 | 78 | plt.clf() 79 | cbar_loc = "bottom" 80 | MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc) 81 | #MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4) 82 | #MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4) 83 | #MF.add_point_data(PointData) 84 | #MF.show_plot() 85 | ImageName = DataDirectory+"TestNewArtist.png" 86 | fig_size_inches = 12 87 | ax_style = "Normal" 88 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250) 89 | 90 | 91 | 92 | # Customise the DrapePlot 93 | #dp.make_drape_colourbar(cbar_label=colourbar_label) 94 | #dp.set_fig_axis_labels() 95 | 96 | #dp.show_plot() -------------------------------------------------------------------------------- /ArchiveTestScripts/SMMTestArtist4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jun 05 12:28:29 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | 9 | import matplotlib 10 | 11 | # Force matplotlib to not use any Xwindows backend. 12 | matplotlib.use('Agg') 13 | 14 | 15 | import matplotlib.pyplot as plt 16 | import matplotlib 17 | from matplotlib import rcParams 18 | from LSDMapFigure.PlottingRaster import MapFigure 19 | 20 | 21 | #label_size = 100 22 | rcParams['font.family'] = 'sans-serif' 23 | rcParams['font.sans-serif'] = ['Liberation Sans'] 24 | #rcParams['font.size'] = label_size 25 | #rcParams['lines.linewidth'] = 1.5 26 | 27 | 28 | DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/movern_testing/" 29 | Base_file = "Irian_Jaya_PP" 30 | 31 | #Directory = "/home/s1563094/Datastore/DATA/UK/LiDAR_DTM_1m/HIN/" 32 | #Base_file = "HIN_" 33 | 34 | #BackgroundRasterName = Base_file+".bil" 35 | BackgroundRasterName = Base_file+".bil" 36 | DrapeRasterName = Base_file+"_hs.bil" 37 | BasinRasterName = Base_file+"_AllBasins.bil" 38 | DischargeRasterName= Base_file+"_Q.bil" 39 | 40 | 41 | 42 | plt.clf() 43 | cbar_loc = "right" 44 | MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc) 45 | #MF.add_drape_image(BackgroundRasterName,DataDirectory,alpha = 1) 46 | MF.add_drape_image(DischargeRasterName,DataDirectory,colourmap = "cubehelix", alpha = 0.6) 47 | ImageName = DataDirectory+"TestNewArtist.png" 48 | fig_size_inches = 12 49 | ax_style = "Normal" 50 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250) 51 | -------------------------------------------------------------------------------- /ArchiveTestScripts/TestAxisLocation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 06 08:42:57 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | import LSDPlottingTools as LSDP 9 | import matplotlib.pyplot as plt 10 | from matplotlib import rcParams 11 | 12 | def TestAxisLocation(): 13 | 14 | tick_label_size = 10 15 | text_size = 12 16 | 17 | # Set up fonts for plots 18 | rcParams['font.family'] = 'sans-serif' 19 | rcParams['font.sans-serif'] = ['Liberation Sans'] 20 | rcParams['font.size'] = text_size 21 | rcParams['xtick.labelsize'] = tick_label_size 22 | rcParams['ytick.labelsize'] = tick_label_size 23 | 24 | DataDirectory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Divides\\" 25 | #DataDirectory = "T:\\analysis_for_papers\\Meghalaya\\divide_migration\\" 26 | Base_file = "Mega_divide" 27 | 28 | bil = ".bil" 29 | 30 | #Filename = "Mega_clip.bil" 31 | #HSFilename = "Mega_clip_hs.bil" 32 | #BasinFilename = "Mega_clip_AllBasins.bil" 33 | 34 | DEMname = DataDirectory+Base_file+bil 35 | FigFileName = DataDirectory+Base_file+"Picture.png" 36 | FigFormat = "png" 37 | 38 | # get the data 39 | #raster = LSDP.ReadRasterArrayBlocks(DEMname) 40 | 41 | 42 | # now get the extent 43 | extent_raster = LSDP.GetRasterExtent(DEMname) 44 | 45 | x_min = extent_raster[0] 46 | x_max = extent_raster[1] 47 | y_min = extent_raster[2] 48 | y_max = extent_raster[3] 49 | 50 | print(extent_raster) 51 | 52 | fig = plt.figure(1, facecolor='white',figsize=(10,10)) 53 | 54 | # Add an axis. This will be used to check how high the text is. 55 | ax2 = fig.add_axes([0.1,0.1,0.7,0.7],zorder = -1) 56 | 57 | # turn off the ticks 58 | ax2.tick_params( 59 | axis='x', # changes apply to the x-axis 60 | which='both', # both major and minor ticks are affected 61 | bottom='off', # ticks along the bottom edge are off 62 | top='off', # ticks along the top edge are off 63 | labelbottom='off') # labels along the bottom edge are off 64 | 65 | ax2.tick_params( 66 | axis='y', # changes apply to the x-axis 67 | which='both', # both major and minor ticks are affected 68 | left='off', # ticks along the bottom edge are off 69 | right='off', # ticks along the top edge are off 70 | labelleft='off') # labels along the bottom edge are off 71 | 72 | ax1 = fig.add_axes([0.0,0.09,0.85,0.85]) 73 | #ax1.set(alpha=0.25) 74 | ax1.text(0.1,0.1, 75 | "x: Tick 10pt, Font 12pt need 0.9 inches.\n", 76 | transform=ax1.transAxes,) 77 | 78 | #im = ax1.imshow(raster[::-1], "jet", extent = extent_raster, interpolation="nearest") 79 | 80 | 81 | n_target_tics = 5 82 | xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(DEMname,x_max,x_min,y_max,y_min,n_target_tics) 83 | 84 | ax1.set_xticks(xlocs) 85 | ax1.set_yticks(ylocs) 86 | ax1.set_xticklabels(new_x_labels,rotation=60) 87 | ax1.set_yticklabels(new_y_labels) 88 | 89 | # This gets all the ticks, and pads them away from the axis so that the corners don't overlap 90 | ax1.tick_params(axis='both', width=1, pad = 2) 91 | for tick in ax1.xaxis.get_major_ticks(): 92 | tick.set_pad(2) 93 | 94 | 95 | 96 | # This affects all axes because we set share_all = True. 97 | ax1.set_xlim(x_min,x_max) 98 | ax1.set_ylim(y_max,y_min) 99 | ax1.set_xlabel("YumYumDonuts") 100 | ax1.set_ylabel("Bigmama") 101 | 102 | #ax3 = fig.add_axes([0.0,0.5,0.5,0.5]) 103 | #ax1.text(0,0,"Hello",fontsize = 94) 104 | plt.savefig(FigFileName,format=FigFormat,dpi=100) 105 | 106 | yo= 284/3 107 | print(yo) 108 | 109 | # So in every inch there are 94 points of text 110 | # The bottom 111 | 112 | plt.show() 113 | 114 | 115 | 116 | 117 | if __name__ == "__main__": 118 | TestAxisLocation() -------------------------------------------------------------------------------- /ArchiveTestScripts/TestDrapeMasked.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | import lsdmatplotlibextensions as mplext 14 | 15 | 16 | #fit_weibull_from_file(sys.argv[1]) 17 | #TestNewMappingTools2() 18 | #ResetErosionRaster() 19 | #FloodThenHillshade() 20 | #FixStupidNoData() 21 | 22 | DataDirectory = "/run/media/dav/SHETLAND/Analyses/Ryedale_storms_simulation/Gridded/DetachLim/" 23 | filename = DataDirectory + "Elevations0.asc" 24 | drapename = DataDirectory + "WaterDepths2880.asc" 25 | 26 | # Create the drape array from one of the Catchment model output rasters 27 | drape_array = LSDP.ReadRasterArrayBlocks(drapename) 28 | # Optional: A lot of the output rasters contain very small values for certain 29 | # things like water depth or elevation difference, so you can mask this below: 30 | low_values_index = drape_array < 0.005 31 | drape_array[low_values_index] = np.nan 32 | 33 | #cmap = plt.get_cmap("Blues") 34 | 35 | trunc_cmap = mplext.colours.truncate_colormap("Blues", 0.4, 1.0) 36 | 37 | LSDP.DrapedOverHillshade(filename,drape_array,clim_val=(0,400), \ 38 | drape_cmap=trunc_cmap, colorbarlabel='Elevation in meters',\ 39 | ShowColorbar=True, ShowDrapeColorbar=True, 40 | drape_cbarlabel = "Water depth (m)", 41 | drape_alpha=1.0) 42 | -------------------------------------------------------------------------------- /ArchiveTestScripts/TestMappingTools.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDMappingTools as LSDmt 13 | 14 | def TestMappingTools(): 15 | #DataDirectory = "C://basin_data//Chile//lat26p0//" 16 | #Filename = "Site_lat26p0_UTM19_DEM_FILL.bil" 17 | DataDirectory = "C://basin_data//Model_results//June2015_Results//HighK//" 18 | Filename = "InitialForCRN.asc" 19 | #Filename = "CRNvariable_long_0_0_1var128.asc" 20 | DrapeFileName = "CRNvariable_long_0_0_1var128_erosion.asc" 21 | ThisFile = DataDirectory+Filename 22 | DrapeFile =DataDirectory+DrapeFileName 23 | 24 | #data = LSDmt.ReadRasterArrayBlocks(ThisFile) 25 | #print "Data is: " 26 | #print data 27 | 28 | #print data.shape 29 | 30 | NDV, xsize, ysize, GeoT, Projection, DataType = LSDmt.GetGeoInfo(ThisFile) 31 | print "NDV: " + str(NDV) 32 | print "xsize: " + str(xsize) 33 | print "ysize: " + str(ysize) 34 | print "GeoT: " + str(GeoT) 35 | print "Projection: " + str(Projection) 36 | print "DataType: " + str(DataType) 37 | 38 | CellSize,XMin,XMax,YMin,YMax = LSDmt.GetUTMMaxMin(ThisFile) 39 | print "CellSize: " + str(CellSize) 40 | print "XMin: " + str(XMin) 41 | print "XMax: " + str(XMax) 42 | print "YMin: " + str(YMin) 43 | print "YMax: " + str(YMax) 44 | 45 | 46 | tcmap = 'bone' 47 | tcmapcolorbarlabel='Elevation in meters' 48 | clim_val = (0,40) 49 | LSDmt.BasicDensityPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) 50 | #LSDmt.DrapedPlot(ThisFile,DrapeFile) 51 | 52 | if __name__ == "__main__": 53 | #fit_weibull_from_file(sys.argv[1]) 54 | TestMappingTools() -------------------------------------------------------------------------------- /ArchiveTestScripts/TestMappingTools2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Oct 28 17:32:40 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | #============================================================================== 9 | # These are some scripts for testing the functionality of LSDMappingTools 10 | #============================================================================== 11 | # -*- coding: utf-8 -*- 12 | """ 13 | Created on Tue May 05 14:08:16 2015 14 | 15 | @author: smudd 16 | """ 17 | 18 | import numpy as np 19 | import LSDMappingTools as LSDmt 20 | 21 | def TestMappingTools(): 22 | #DataDirectory = "C://basin_data//Chile//lat26p0//" 23 | #Filename = "Site_lat26p0_UTM19_DEM_FILL.bil" 24 | #DataDirectory = "C://basin_data//Model_results//June2015_Results//HighK//" 25 | #Filename = "InitialForCRN.asc" 26 | #Filename = "CRNvariable_long_0_0_1var128.asc" 27 | #DataDirectory = "C://basin_data//Babault2//" 28 | #Filename = "Julien_DEM_HS.bil" 29 | #Filename = "Julien_DEM_Q.bil" 30 | 31 | #DrapeFileName = "Julien_DEM_Q.bil" 32 | 33 | DataDirectory = "T://analysis_for_papers//Cosmo_paper//Tibet//for_plotting//" 34 | #Filename = "SanBern.bil" 35 | Filename = "SpawnedBasin_07C13-(Q8)_SH.bil" 36 | #Filename = "CRNvariable_long_0_0_1var128.asc" 37 | #DrapeFileName = "CRNvariable_long_0_0_1var128_erosion.asc" 38 | DrapeFileName = "SpawnedBasin_07C13-(Q8)_BASINS.bil" 39 | 40 | 41 | ThisFile = DataDirectory+Filename 42 | DrapeFile =DataDirectory+DrapeFileName 43 | 44 | #data = LSDmt.ReadRasterArrayBlocks(ThisFile) 45 | #print "Data is: " 46 | #print data 47 | 48 | #print data.shape 49 | 50 | NDV, xsize, ysize, GeoT, Projection, DataType = LSDmt.GetGeoInfo(ThisFile) 51 | print "NDV: " + str(NDV) 52 | print "xsize: " + str(xsize) 53 | print "ysize: " + str(ysize) 54 | print "GeoT: " + str(GeoT) 55 | print "Projection: " + str(Projection) 56 | print "DataType: " + str(DataType) 57 | 58 | CellSize,XMin,XMax,YMin,YMax = LSDmt.GetUTMMaxMin(ThisFile) 59 | print "CellSize: " + str(CellSize) 60 | print "XMin: " + str(XMin) 61 | print "XMax: " + str(XMax) 62 | print "YMin: " + str(YMin) 63 | print "YMax: " + str(YMax) 64 | 65 | 66 | tcmap = 'autumn' 67 | tcmapcolorbarlabel='Discharge in $m^3$ per year' 68 | clim_val = (0,0) 69 | LSDmt.BasicDensityPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) 70 | #LSDmt.LogStretchDensityPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) 71 | 72 | LSDmt.DrapedPlot(ThisFile,DrapeFile) 73 | 74 | if __name__ == "__main__": 75 | #fit_weibull_from_file(sys.argv[1]) 76 | TestMappingTools() -------------------------------------------------------------------------------- /ArchiveTestScripts/TestMappingToolsPoint.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Mon May 22 14:08:16 2016 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | 14 | def TestMappingToolsPoints(): 15 | #DataDirectory = "T://analysis_for_papers//Test_map_chi_gradient//results//" 16 | DataDirectory = "T://students//Wainwright//" 17 | #Filename = "Mandakini_OutletList.csv" 18 | Filename = "Bids_DD.csv" 19 | 20 | #ExportName = "ShapeTest" 21 | 22 | fname = DataDirectory+Filename 23 | #Exp_fname = DataDirectory+ExportName 24 | 25 | thisPointData = LSDP.LSDMap_PointData(fname) 26 | 27 | thisPointData.GetParameterNames(True) 28 | thisPointData.GetLongitude(True) 29 | 30 | print "Hey buddy, the province is: " 31 | thisPointData.QueryData("province",True) 32 | 33 | print "Hey buddy, the gma is: " 34 | thisPointData.QueryData("gma",True) 35 | 36 | thisPointData.TranslateToReducedShapefile(fname) 37 | thisPointData.TranslateToReducedGeoJSON(fname) 38 | 39 | def TestMappingToolsLassoCSV(): 40 | 41 | #DataDirectory = "T://analysis_for_papers//Test_map_chi_gradient//results//" 42 | DataDirectory = "T://analysis_for_papers//Indus//NewChi//" 43 | LSDP.ConvertAllCSVToGeoJSON(DataDirectory) 44 | 45 | 46 | 47 | 48 | if __name__ == "__main__": 49 | #TestMappingToolsPoints() 50 | TestMappingToolsLassoCSV() 51 | -------------------------------------------------------------------------------- /ArchiveTestScripts/TestNewMappingTools.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | 14 | def TestNewMappingTools(): 15 | #DataDirectory = "C://basin_data//Chile//lat26p0//" 16 | #Filename = "Site_lat26p0_UTM19_DEM_FILL.bil" 17 | #DataDirectory = "C://basin_data//Model_results//June2015_Results//HighK//" 18 | #DataDirectory = "T://test_clone//topodata//" 19 | #DataDirectory = "T://analysis_for_papers//Cosmo_paper//Tibet//for_plotting//" 20 | #DataDirectory = "C://basin_data//CosmoPaper//DEMs//" 21 | DataDirectory = "M://papers//Mudd_SOS//Betics//" 22 | #Filename = "SanBern.bil" 23 | Filename = "betics_chi_TA3000_clip_UTM30.bil" 24 | #Filename = "SpawnedBasin_07C13-(Q8)_SH.bil" 25 | #Filename = "CRNvariable_long_0_0_1var128.asc" 26 | #DrapeFileName = "CRNvariable_long_0_0_1var128_erosion.asc" 27 | DrapeFileName = "SpawnedBasin_07C13-(Q8)_BASINS.bil" 28 | DEMName = "SpawnedBasin_07C13-(Q8).bil" 29 | ThisFile = DataDirectory+Filename 30 | #DrapeFile =DataDirectory+DrapeFileName 31 | #DEMFile = DataDirectory+DEMName 32 | #Shield2 = DataDirectory+"SpawnedBasin_Q8_phi30.bil" 33 | 34 | FigFormat = 'svg' 35 | FigFileN= 'Sorbas_chi.svg' 36 | FigFileName= DataDirectory+FigFileN 37 | 38 | #ShieldFigName = DataDirectory+'Shielding.svg' 39 | 40 | 41 | NDV, xsize, ysize, GeoT, Projection, DataType = LSDP.GetGeoInfo(ThisFile) 42 | print "NDV: " + str(NDV) 43 | print "xsize: " + str(xsize) 44 | print "ysize: " + str(ysize) 45 | print "GeoT: " + str(GeoT) 46 | print "Projection: " + str(Projection) 47 | print "DataType: " + str(DataType) 48 | 49 | CellSize,XMin,XMax,YMin,YMax = LSDP.GetUTMMaxMin(ThisFile) 50 | print "CellSize: " + str(CellSize) 51 | print "XMin: " + str(XMin) 52 | print "XMax: " + str(XMax) 53 | print "YMin: " + str(YMin) 54 | print "YMax: " + str(YMax) 55 | 56 | 57 | tcmap = 'jet' 58 | drape_cmap = 'gray' 59 | shield_map = 'summer' 60 | drape_alpha = 0.4 61 | tcmapcolorbarlabel='Chi' 62 | clim_val = (50,300) 63 | auto_clim = (1000,4500) 64 | #LSDP.BasicDensityPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) 65 | #LSDP.DrapedPlot(ThisFile,DrapeFile) 66 | 67 | #LSDP.BasicDensityPlotGridPlot(ThisFile,tcmap,tcmapcolorbarlabel) 68 | 69 | #Plot the basin over the elevation 70 | cmap_label = "Elevation (m)" 71 | #LSDP.BasicDrapedPlotGridPlot(DEMFile,DrapeFile,tcmap,drape_cmap, cmap_label, 72 | # auto_clim,drape_alpha,FigFileName,FigFormat) 73 | 74 | # Now plot the two shielding rasters 75 | LSDP.BasicDensityPlotGridPlot(ThisFile,shield_map,tcmapcolorbarlabel,clim_val, 76 | FigFileName,FigFormat) 77 | 78 | #FigFormat = 'svg' 79 | #SNFileN= 'Shield30.svg' 80 | #ShieldFigName2= DataDirectory+SNFileN 81 | # Now plot the two shielding rasters 82 | #LSDP.BasicDensityPlotGridPlot( Shield2,shield_map,tcmapcolorbarlabel,clim_val, 83 | # ShieldFigName2,FigFormat) 84 | 85 | 86 | if __name__ == "__main__": 87 | #fit_weibull_from_file(sys.argv[1]) 88 | TestNewMappingTools() -------------------------------------------------------------------------------- /ArchiveTestScripts/TestNewMappingTools2.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on Tue May 05 14:08:16 2015 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | 14 | def TestNewMappingTools2(): 15 | DataDirectory = "T://analysis_for_papers//Manny_idaho//" 16 | Filename = "TestIdaho.bil" 17 | NewFilename = "TestIdaho_after2.bil" 18 | ThreshFname = "ThreshIdaho.bil" 19 | ConstFname = "ConstEros.bil" 20 | ThisFile = DataDirectory+Filename 21 | NewFilename = DataDirectory+NewFilename 22 | ThreshFname = DataDirectory+ThreshFname 23 | ConstFname = DataDirectory+ConstFname 24 | 25 | #FigFormat = 'svg' 26 | #FigFileN= 'Sorbas_chi.svg' 27 | #FigFileName= DataDirectory+FigFileN 28 | 29 | 30 | #Plot the basin over the elevation 31 | #tcmapcolorbarlabel = "Elevation (m)" 32 | #tcmap = 'jet' 33 | #tcmapcolorbarlabel='Chi' 34 | #clim_val = (50,300) 35 | #LSDP.BasicDensityPlotGridPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val) 36 | 37 | #get the nodata values 38 | NData = LSDP.getNoDataValue(ThisFile) 39 | 40 | print "NoData is: " + str(NData) 41 | 42 | # get the data as an array 43 | array = LSDP.ReadRasterArrayBlocks(ThisFile) 44 | 45 | driver_name = "ENVI" 46 | LSDP.array2raster(ThisFile,NewFilename,array,driver_name, -9999) 47 | 48 | #get the nodata values 49 | NData2 = LSDP.getNoDataValue(NewFilename) 50 | 51 | #print "NoData 2 is: " + str(NData2) 52 | 53 | LSDP.SetNoDataBelowThreshold(ThisFile,ThreshFname) 54 | 55 | # now print the constant value file 56 | constant_value = 0.001 57 | LSDP.SetToConstantValue(ThreshFname,ConstFname,constant_value) 58 | 59 | 60 | def ResetErosionRaster(): 61 | DataDirectory = "T://analysis_for_papers//Manny_Idaho//Revised//nested//" 62 | #DataDirectory = "C://basin_data//Manny_Idaho//nested//" 63 | ConstFname = "ConstEros.bil" 64 | NewErateName = "HarringCreek_ERKnown.bil" 65 | ThisFile = DataDirectory+ConstFname 66 | NewFilename = DataDirectory+NewErateName 67 | 68 | LSDP.CheckNoData(ThisFile) 69 | 70 | # now print the constant value file 71 | constant_value = 0.0092 72 | LSDP.SetToConstantValue(ThisFile,NewFilename,constant_value) 73 | 74 | LSDP.CheckNoData(NewFilename) 75 | 76 | 77 | def FloodThenHillshade(): 78 | DataDirectory = "M:\\students\\kunkelova\\" 79 | DEMName = "bk_10m_dem.bil" 80 | newDEMName = "bk_10m_dem_updated.bil" 81 | HillshadeName = "bk_10m_dem_HS.bil" 82 | 83 | RasterFilename = DataDirectory+DEMName 84 | NewRasterFilename = DataDirectory+newDEMName 85 | HillshadeNameFile = DataDirectory+HillshadeName 86 | 87 | LSDP.SetNoDataBelowThreshold(RasterFilename,NewRasterFilename, threshold = 0, driver_name = "ENVI", NoDataValue = -9999) 88 | LSDP.GetHillshade(NewRasterFilename, HillshadeNameFile, azimuth = 315, angle_altitude = 45, driver_name = "ENVI", NoDataValue = -9999) 89 | 90 | 91 | def FixStupidNoData(): 92 | DataDirectory = "T://analysis_for_papers//Indus//" 93 | DEMName = "indus_utm44.bil" 94 | newDEMName = "Indus_ND.bil" 95 | 96 | RasterFilename = DataDirectory+DEMName 97 | NewRasterFilename = DataDirectory+newDEMName 98 | 99 | LSDP.SetNoDataBelowThreshold(RasterFilename,NewRasterFilename, threshold = 0, driver_name = "ENVI", NoDataValue = -9999) 100 | 101 | if __name__ == "__main__": 102 | #fit_weibull_from_file(sys.argv[1]) 103 | #TestNewMappingTools2() 104 | ResetErosionRaster() 105 | #FloodThenHillshade() 106 | #FixStupidNoData() 107 | -------------------------------------------------------------------------------- /ArchiveTestScripts/TestNewMapping_asc.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # These are some scripts for testing the functionality of LSDMappingTools 3 | #============================================================================== 4 | # -*- coding: utf-8 -*- 5 | """ 6 | Created on August 18th 2016 7 | 8 | @author: smudd 9 | """ 10 | 11 | import numpy as np 12 | import LSDPlottingTools as LSDP 13 | 14 | def TestNewMappingTools_asc(): 15 | DataDirectory = "T:\\analysis_for_papers\\Beaches\\" 16 | #Filename1 = "BedThickness_050.asc" 17 | #Filename2 = "BedThickness_100.asc" 18 | Filename1 = "20m_bl.asc" 19 | 20 | ThisFile = DataDirectory+Filename1 21 | 22 | 23 | yo = LSDP.GetRasterExtent(ThisFile) 24 | 25 | print "raster extent is: " 26 | print yo 27 | 28 | 29 | 30 | 31 | #MB = LSDP.BasicMassBalance(DataDirectory, Filename1, Filename2) 32 | #print "Mass balance between these two time steps is: " + str(MB) + " cubic metres" 33 | 34 | #Mean1 = LSDP.RasterMeanValue(DataDirectory, Filename1) 35 | #Mean2 = LSDP.RasterMeanValue(DataDirectory, Filename2) 36 | 37 | #print "The mean values of the two rasters are: " + str(Mean1) +" and "+ str(Mean2) 38 | 39 | # now try the swath plotting 40 | #axis = 0 41 | #LSDP.SwathPlot(DataDirectory, Filename1, axis) 42 | 43 | axis = 1 44 | LSDP.SwathPlot(DataDirectory, Filename1, axis) 45 | 46 | if __name__ == "__main__": 47 | #fit_weibull_from_file(sys.argv[1]) 48 | #TestNewMappingTools2() 49 | TestNewMappingTools_asc() 50 | #FloodThenHillshade() 51 | #FixStupidNoData() 52 | -------------------------------------------------------------------------------- /ArchiveTestScripts/TestSubplots.py: -------------------------------------------------------------------------------- 1 | #============================================================================== 2 | # Make a publication ready field sites figure of all the hillshades in a folder 3 | # Will also read in any map images in EPS format and create subplots to show the 4 | # location of the field sites. 5 | 6 | # FJC 22/12/16 7 | #============================================================================== 8 | import matplotlib 9 | matplotlib.use('Agg') 10 | import LSDPlottingTools as LSDP 11 | 12 | def make_field_sites_figure(DataDirectory): 13 | N_HSFiles = 4 14 | NRows = 3 15 | NCols = 2 16 | n_target_ticks = 6 17 | 18 | LSDP.field_sites(DataDirectory, N_HSFiles, NRows, NCols, n_target_ticks) 19 | 20 | def make_flood_maps(DataDirectory): 21 | LSDP.multiple_flood_maps(DataDirectory) 22 | 23 | def flood_maps_with_shapefile(DataDirectory): 24 | LSDP.flood_maps_with_shapefile(DataDirectory) 25 | 26 | def flood_maps_shapefile_zoom(DataDirectory): 27 | LSDP.flood_maps_shapefile_with_zoom(DataDirectory) 28 | 29 | if __name__ == "__main__": 30 | DataDirectory = "/home/s0923330/Datastore/Python/floodplain_initiation/results_comparison/field_data/" 31 | #make_field_sites_figure(DataDirectory) 32 | #make_flood_maps(DataDirectory) 33 | flood_maps_with_shapefile(DataDirectory) 34 | #flood_maps_shapefile_zoom(DataDirectory) 35 | -------------------------------------------------------------------------------- /ArchiveTestScripts/crop2image.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf-8 3 | 4 | """ 5 | Description : Crop and project an image in the same grid as a reference image 6 | 7 | Author : Amaury Dehecq 8 | """ 9 | 10 | #Python libraries 11 | from osgeo import gdal, osr 12 | import sys, os 13 | 14 | # ============================================================================= 15 | def Usage(): 16 | print '*** Crop and project an image in the same grid as a reference image ***' 17 | print 18 | print 'Usage : crop2image.py im_ref im2crop outfile' 19 | print 20 | print 'input parameters :' 21 | print ' im_ref : str, path to the reference image' 22 | print ' im2crop : str, path to the image to crop' 23 | print ' outfile : str, name of the output file' 24 | print 25 | # ============================================================================= 26 | 27 | # example of command line : 28 | #------------------------- 29 | # python crop2image.py /exports/csce/datastore/geos/users/mharel/Topo_Data/general/Old_zone_ref/zone69/zone69.flt /exports/csce/datastore/geos/users/mharel/World_data/seism_globe.flt /exports/csce/datastore/geos/users/mharel/Topo_Data/general/Old_zone_ref/zone69/seism_zone69.flt 30 | 31 | if len(sys.argv)<4: 32 | Usage() 33 | sys.exit(1) 34 | 35 | 36 | #Read arguments 37 | im_ref = sys.argv[1] 38 | im2crop = sys.argv[2] 39 | outfile = sys.argv[3] 40 | 41 | 42 | #Read reference image spatial reference system 43 | ds = gdal.Open(im_ref) 44 | srs_dest=osr.SpatialReference() 45 | wkt = ds.GetProjectionRef() 46 | srs_dest.ImportFromWkt(wkt) 47 | proj=srs_dest.ExportToProj4() 48 | 49 | 50 | #Read reference image size and corners coordinates 51 | trans = ds.GetGeoTransform() 52 | pixelWidth = trans[1] 53 | pixelHeight = trans[5] 54 | xmin = trans[0] 55 | xmax = trans[0] + ds.RasterXSize*trans[1] + ds.RasterYSize*trans[2] 56 | ymin = trans[3] + ds.RasterXSize*trans[4] + ds.RasterYSize*trans[5] 57 | ymax = trans[3] 58 | 59 | #Crop and reproject 60 | cmd = "gdalwarp -te %.8f %.8f %.8f %.8f -tr %.8f %.8f -t_srs '%s' %s %s -overwrite" %(xmin,ymin,xmax,ymax,pixelWidth,pixelHeight,proj,im2crop,outfile) 61 | print cmd; os.system(cmd) 62 | -------------------------------------------------------------------------------- /ArchiveTestScripts/custom_colormap_test.py: -------------------------------------------------------------------------------- 1 | # This is a test script that aim to bring a better understanding of the colormap in MatPlotLib to the world. # 2 | # Nobody reads the headers of python files anyway. Cunt. 3 | # Boris 4 | # the 21th day of September of 2017 5 | 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | from matplotlib.colors import LinearSegmentedColormap 9 | import random 10 | 11 | 12 | # Parameters 13 | discrete_values = range(10) 14 | colors = [] 15 | 16 | # Assigning the random color values 17 | for i in range(len(discrete_values)): 18 | colorTemp = "#" 19 | for j in range(6): 20 | colorTemp = colorTemp + (random.choice('0123456789ABCDEF')) 21 | colors.append(colorTemp) 22 | 23 | print colors 24 | 25 | #Creating the colormaps 26 | cm = LinearSegmentedColormap.from_list("LithoColorMap", colors, N=len(discrete_values)-1) 27 | 28 | #Test set 29 | imtest = [[0,1,2,3,4,5,6,7,8,9],[9,8,7,6,5,4,3,2,1,0],[5,4,6,7,9,8,3,1,2,0],[0,0,0,0,0,0,0,0,0,0]] 30 | 31 | plt.imshow(imtest, interpolation = "none", cmap = cm) 32 | plt.colorbar() 33 | 34 | plt.show() -------------------------------------------------------------------------------- /ArchiveTestScripts/test_multiple_basins.py: -------------------------------------------------------------------------------- 1 | #from __future__ import print_function 2 | import sys 3 | import os 4 | from LSDPlottingTools import LSDMap_MOverNPlotting as MN 5 | from LSDPlottingTools import LSDMap_SAPlotting as SA 6 | from LSDMapFigure import PlottingHelpers as Helper 7 | 8 | #let's test the basin appenders 9 | DataDirectory = '/home/mhurst/movern_analysis/Sierras/' 10 | 11 | # Helper.AppendBasinCSVs(DataDirectory) 12 | Helper.AppendChiResidualsCSVs(DataDirectory) 13 | 14 | -------------------------------------------------------------------------------- /BUILD_HILLSHADE.md: -------------------------------------------------------------------------------- 1 | ## Fast hillshade module (LSDPlottingTools/fast_hillshade.pyx) 2 | 3 | To build the cython hillshade extension, go into the LSDPlottingTools folder and run: 4 | 5 | `python setup_cython.py build_ext --inplace` 6 | 7 | You will get a fast_hillshade.so file. 8 | 9 | Nothing else should be needed to be done and you can import the hillshade module in the usual way, e.g: 10 | 11 | `import fast_hillshade as fhill` 12 | -------------------------------------------------------------------------------- /Basemap_test.py: -------------------------------------------------------------------------------- 1 | import matplotlib 2 | matplotlib.use('Agg') 3 | 4 | 5 | from mpl_toolkits.basemap import Basemap 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | import pandas as pd 9 | 10 | import matplotlib.cm 11 | 12 | from matplotlib.patches import Polygon 13 | from matplotlib.collections import PatchCollection 14 | from matplotlib.colors import Normalize 15 | 16 | 17 | def FullGlobePerspective(): 18 | 19 | fig, ax = plt.subplots(figsize=(12, 10)) 20 | 21 | # setup Lambert Conformal basemap. 22 | m = Basemap(width=1800000,height=1500000,projection='nsper',area_thresh = 100000, 23 | resolution='h',lat_1=45.,lat_2=55,lat_0=25.7,lon_0=91.5, satellite_height = 10000000) 24 | # draw coastlines. 25 | m.drawcoastlines() 26 | # draw a boundary around the map, fill the background. 27 | # this background will end up being the ocean color, since 28 | # the continents will be drawn on top. 29 | m.drawmapboundary(fill_color='aqua') 30 | # fill continents, set lake color same as ocean color. 31 | m.fillcontinents(color='peru',lake_color='aqua') 32 | # draw parallels and meridians. 33 | # label parallels on right and top 34 | # meridians on bottom and left 35 | parallels = np.arange(0.,81,5.) 36 | # labels = [left,right,top,bottom] 37 | m.drawparallels(parallels,labels=[False,True,True,False]) 38 | meridians = np.arange(10.,351.,5.) 39 | m.drawmeridians(meridians,labels=[True,False,False,True]) 40 | m.drawcountries() 41 | m.readshapefile('Mega_divide_footprint', 'MDF') 42 | 43 | # All this stuff from: 44 | # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ 45 | df_poly = pd.DataFrame({ 46 | 'shapes': [Polygon(np.array(shape), True) for shape in m.MDF]}) 47 | 48 | print(df_poly) 49 | 50 | #df_poly = df_poly.merge(new_areas, on='area', how='left') 51 | cmap = plt.get_cmap('Oranges') 52 | pc = PatchCollection(df_poly.shapes, zorder=2) 53 | pc.set_facecolor(cmap(1)) 54 | ax.add_collection(pc) 55 | 56 | FigFileName = "Test.png" 57 | FigFormat = "png" 58 | 59 | plt.savefig(FigFileName,format=FigFormat,dpi=200) 60 | 61 | def ZoomPerspective(): 62 | 63 | fig, ax = plt.subplots(figsize=(6, 5)) 64 | 65 | # setup Lambert Conformal basemap. 66 | print("I am trying to get rid of these bloody lakes") 67 | m = Basemap(width=1800000,height=1500000,projection='lcc',area_thresh=10000000., 68 | resolution='l',lat_1=45.,lat_2=55,lat_0=25.7,lon_0=91.5) 69 | # draw coastlines. 70 | m.drawcoastlines() 71 | # draw a boundary around the map, fill the background. 72 | # this background will end up being the ocean color, since 73 | # the continents will be drawn on top. 74 | m.drawmapboundary(fill_color='aqua') 75 | # fill continents, set lake color same as ocean color. 76 | m.fillcontinents(color='peru',lake_color='aqua') 77 | # draw parallels and meridians. 78 | # label parallels on right and top 79 | # meridians on bottom and left 80 | parallels = np.arange(0.,81,5.) 81 | # labels = [left,right,top,bottom] 82 | m.drawparallels(parallels,labels=[False,True,True,False]) 83 | meridians = np.arange(10.,351.,5.) 84 | m.drawmeridians(meridians,labels=[True,False,False,True]) 85 | m.drawcountries() 86 | m.readshapefile('Mega_divide_footprint', 'MDF') 87 | 88 | # All this stuff from: 89 | # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ 90 | df_poly = pd.DataFrame({ 91 | 'shapes': [Polygon(np.array(shape), True) for shape in m.MDF]}) 92 | 93 | print(df_poly) 94 | 95 | #df_poly = df_poly.merge(new_areas, on='area', how='left') 96 | cmap = plt.get_cmap('Oranges') 97 | pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5) 98 | pc.set_facecolor("r") 99 | ax.add_collection(pc) 100 | 101 | FigFileName = "Test.png" 102 | FigFormat = "png" 103 | 104 | plt.savefig(FigFileName,format=FigFormat,dpi=200) 105 | 106 | 107 | def ZoomPerspectiveEtopo(): 108 | 109 | fig, ax = plt.subplots(figsize=(3, 2.5)) 110 | 111 | # setup Lambert Conformal basemap. 112 | print("I am trying to get rid of these bloody lakes") 113 | m = Basemap(width=1800000,height=1500000,projection='lcc',area_thresh=10000000., 114 | resolution='h',lat_1=45.,lat_2=55,lat_0=25.7,lon_0=91.5) 115 | # draw coastlines. 116 | #m.drawrivers() 117 | m.drawcoastlines() 118 | # draw a boundary around the map, fill the background. 119 | # this background will end up being the ocean color, since 120 | # the continents will be drawn on top. 121 | m.drawmapboundary(fill_color='aqua') 122 | # fill continents, set lake color same as ocean color. 123 | m.fillcontinents(color='peru',lake_color='white') 124 | # draw parallels and meridians. 125 | # label parallels on right and top 126 | # meridians on bottom and left 127 | parallels = np.arange(0.,81,5.) 128 | # labels = [left,right,top,bottom] 129 | m.drawparallels(parallels,labels=[False,True,True,False]) 130 | meridians = np.arange(10.,351.,5.) 131 | m.drawmeridians(meridians,labels=[True,False,False,True]) 132 | m.drawcountries() 133 | m.readshapefile('Mega_divide_footprint', 'MDF') 134 | 135 | # All this stuff from: 136 | # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ 137 | df_poly = pd.DataFrame({ 138 | 'shapes': [Polygon(np.array(shape), True) for shape in m.MDF]}) 139 | 140 | print(df_poly) 141 | 142 | #df_poly = df_poly.merge(new_areas, on='area', how='left') 143 | cmap = plt.get_cmap('Oranges') 144 | pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5) 145 | pc.set_facecolor("gray") 146 | ax.add_collection(pc) 147 | 148 | FigFileName = "Test.svg" 149 | FigFormat = "svg" 150 | 151 | plt.savefig(FigFileName,format=FigFormat,dpi=200) 152 | 153 | 154 | if __name__ == "__main__": 155 | ZoomPerspectiveEtopo() 156 | -------------------------------------------------------------------------------- /BasinAverage.py: -------------------------------------------------------------------------------- 1 | # ================================== 2 | # Extracting basin-averaged values from a raster (.flt) given the junction number at the outlet of the basin (shape file). 3 | # Creates a csv file with the values. 4 | # Configured to manipulate the zone directories and files for the global denudation rates compilation carried out by Marie-Alice Harel 5 | # ***** DO NOT LAUNCH THIS WITH SPYDER ! ***** 6 | # *** USE A COMMAND LINE IN A TERMINAL INSTEAD *** 7 | # ================================== 8 | 9 | """ 10 | Created on Thu Mar 26 17:07:35 2015 11 | 12 | @author: mharel 13 | """ 14 | 15 | #!/usr/bin/python 16 | import gdal, ogr, osr, numpy 17 | import csv 18 | import pandas 19 | #from shapely.wkb import loads 20 | #from shapely.ops import cascaded_union 21 | 22 | #-------------------------------------------------------------------------- 23 | # Enter zone number : 24 | zonenb = 67 25 | newzonenb = 67 # New zone number if zone name belongs to older referencing 26 | 27 | # Choose a parameter to be averaged over the zone basins : 28 | paramch = 'seism' 29 | # vege 30 | # seism 31 | #-------------------------------------------------------------------------- 32 | 33 | DataDirectory ="/exports/csce/datastore/geos/users/mharel/Topo_Data/general/New_zone_ref/zone"+str(zonenb)+"/" 34 | print DataDirectory 35 | 36 | def proc(): 37 | 38 | # Each process needs its own pointer. 39 | shape = ogr.Open(input_zone_polygon) 40 | lyr = shape.GetLayer() 41 | raster = gdal.Open(input_value_raster) 42 | xmin, xmax, ymin, ymax = lyr.GetExtent() 43 | #print "Extent : ", lyr.GetExtent() 44 | # # Get extent of feat 45 | # geom = feat.GetGeometryRef() 46 | # if (geom.GetGeometryName() == 'MULTIPOLYGON'): 47 | # count = 0 48 | # pointsX = []; pointsY = [] 49 | # for polygon in geom: 50 | # geomInner = geom.GetGeometryRef(count) 51 | # ring = geomInner.GetGeometryRef(0) 52 | # numpoints = ring.GetPointCount() 53 | # for p in range(numpoints): 54 | # lon, lat, z = ring.GetPoint(p) 55 | # pointsX.append(lon) 56 | # pointsY.append(lat) 57 | # count += 1 58 | # elif (geom.GetGeometryName() == 'POLYGON'): 59 | # ring = geom.GetGeometryRef(0) 60 | # numpoints = ring.GetPointCount() 61 | # pointsX = []; pointsY = [] 62 | # for p in range(numpoints): 63 | # lon, lat, z = ring.GetPoint(p) 64 | # pointsX.append(lon) 65 | # pointsY.append(lat) 66 | # else: 67 | # sys.exit() 68 | # 69 | # xmin = min(pointsX) 70 | # xmax = max(pointsX) 71 | # ymin = min(pointsY) 72 | # ymax = max(pointsY) 73 | 74 | # print geom.GetGeometryName() 75 | # Specify offset and rows and columns to read 76 | xoff = int((xmin - xOrigin)/pixelWidth) 77 | yoff = int((yOrigin - ymax)/pixelWidth) 78 | xcount = int((xmax - xmin)/pixelWidth)+1 79 | ycount = int((ymax - ymin)/pixelWidth)+1 80 | 81 | # Create memory target raster 82 | target_ds = gdal.GetDriverByName('MEM').Create('', xcount, ycount, gdal.GDT_Byte) 83 | target_ds.SetGeoTransform(( 84 | xmin, pixelWidth, 0, 85 | ymax, 0, pixelHeight, 86 | )) 87 | # Create for target raster the same projection as for the value raster 88 | raster_srs = osr.SpatialReference() 89 | raster_srs.ImportFromWkt(raster.GetProjectionRef()) 90 | target_ds.SetProjection(raster_srs.ExportToWkt()) 91 | 92 | # Rasterize zone polygon to raster 93 | gdal.RasterizeLayer(target_ds, [1], lyr, burn_values=[1]) 94 | # Read raster as arrays 95 | banddataraster = raster.GetRasterBand(1) 96 | # error here 97 | dataraster = banddataraster.ReadAsArray(xoff, yoff, xcount, ycount).astype(numpy.float) 98 | bandmask = target_ds.GetRasterBand(1) 99 | datamask = bandmask.ReadAsArray(0, 0, xcount, ycount).astype(numpy.float) 100 | 101 | # Mask zone of raster 102 | zoneraster = numpy.ma.masked_array(dataraster, numpy.logical_not(datamask)) 103 | 104 | # Calculate statistics of zonal raster 105 | value = numpy.mean(zoneraster) 106 | 107 | print value 108 | return value 109 | 110 | 111 | resu = [] # Empty list to store the results 112 | # Extract junction numbers for this zone 113 | #data = pandas.read_csv('/home/mharel/LSDVisu_work/compil-data-MAH.csv') 114 | data = pandas.read_csv('compil-data-MAH.csv') 115 | datazon = data[(data.zone == newzonenb)].copy() 116 | #lenzon = len(datazon['Junction']) 117 | 118 | for junct in datazon['Junction']: 119 | junction = int(junct) 120 | print "Junctin is " +str(junction) 121 | 122 | # Raster dataset 123 | if paramch == 'eleva': 124 | input_value_raster = DataDirectory+"zone"+str(zonenb)+".flt" 125 | else: 126 | input_value_raster = DataDirectory+paramch+"_zone"+str(zonenb)+".flt" 127 | 128 | # Vector dataset(zones) 129 | input_zone_polygon = DataDirectory+"shape_"+str(junction)+".shp" 130 | 131 | # Open data 132 | rast = gdal.Open(input_value_raster) 133 | print rast.RasterXSize, rast.RasterYSize 134 | shp = ogr.Open(input_zone_polygon) 135 | 136 | if shp is None: 137 | raise IOError('Could not open file ' + str(input_zone_polygon)) 138 | 139 | # Get raster georeference info 140 | transform = rast.GetGeoTransform() 141 | xOrigin = transform[0] 142 | yOrigin = transform[3] 143 | pixelWidth = transform[1] 144 | pixelHeight = transform[5] 145 | 146 | # Start the processes 147 | layer = shp.GetLayer() 148 | featList = range(layer.GetFeatureCount()) 149 | #print "Number of features = " +str(featList) 150 | 151 | #pool = Pool(processes=24) 152 | #value = pool.map(proc,0,8) 153 | value = proc() 154 | resu.append([value]) 155 | print "value = " +str(value) 156 | 157 | with open ('/exports/csce/datastore/geos/users/mharel/Topo_Data/general/'+'zone'+str(newzonenb)+'_resufile_'+paramch+'.csv', 'w') as csvfile: 158 | g = csv.writer(csvfile, delimiter = ',') 159 | g.writerows(resu) 160 | 161 | print "Done." 162 | -------------------------------------------------------------------------------- /ChiMappingExamples.py: -------------------------------------------------------------------------------- 1 | """ 2 | This function drives the Chi mapping examples that are used with our documentation. 3 | The website is: https://lsdtopotools.github.io/LSDTopoTools_ChiMudd2014/ 4 | 5 | Written by Simon Mudd and Fiona Clubb 6 | June 2017 7 | git 8 | GPL3 9 | """ 10 | 11 | 12 | import LSDChiMappingExamples as CME 13 | import LSDMapWrappers as MW 14 | 15 | if __name__ == "__main__": 16 | 17 | """ 18 | This is just a few lines for keeping track of how long the program is taking. 19 | You can ignore it. 20 | """ 21 | import time 22 | tic = time.clock() 23 | 24 | """ 25 | These lines tell the example functions where your files are. If you are using 26 | the recommended file setup you won't need to modify these lines. 27 | 28 | If you have set up your own directory structure you will need to modify 29 | the directory names. 30 | 31 | IMPORTANT: To get this to work properly, in the chi mapping tool, 32 | you need these flags: 33 | write_hillshade: true 34 | print_chi_data_maps: true 35 | print_basin_raster: true 36 | 37 | Instructions for the chi mapping tool are here: 38 | https://lsdtopotools.github.io/LSDTopoTools_ChiMudd2014/ 39 | """ 40 | #DataDirectory = "S:\\movern_analysis\hokkaido\\" 41 | #Base_file = "hokkaido_points" 42 | #DataDirectory = "T:\\analysis_for_papers\\Xian\\" 43 | #DataDirectory = 'C:\\VagrantBoxes\\LSDTopoTools\\Topographic_projects\\LSDTT_chi_examples\\' 44 | #Base_file = 'Xian2' 45 | #DataDirectory = 'C:\\VagrantBoxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Paper\\' 46 | DataDirectory = 'T:\\analysis_for_papers\\Meghalaya\\Full_landscape\\' 47 | Base_file = 'Mega_select_south' 48 | 49 | """ 50 | These lines are used to run the examples. Each line calls a function in the directory 51 | ../LSDChiMappingExamples/ 52 | 53 | The individual examples are different python scripts which you can inspect at your 54 | lesiure. By playing with these scripts you can learn how to use our plotting tools. 55 | 56 | To run the examples simply comment or uncomment these lines by adding or 57 | removing the comment symbol, #, below. 58 | """ 59 | 60 | #MW.SimpleHillshade(DataDirectory,Base_file,cmap = "terrain", dpi = 250) 61 | #MW.PrintBasins(DataDirectory,Base_file) 62 | #MW.PrintBasins_Complex(DataDirectory,Base_file,Remove_Basins = [6], Rename_Basins = {3:"A",4:"B",8:"C",10:"D",12:"E"}) 63 | #MW.PrintChannels(DataDirectory,Base_file) 64 | MW.PrintChannelsAndBasins(DataDirectory,Base_file, dpi = 300) 65 | 66 | #CME.ExampleOne_PartOne_SimpleHillshade(DataDirectory,Base_file) 67 | #CME.ExampleOne_PartTwo_PrintBasins(DataDirectory,Base_file) 68 | #CME.ExampleOne_PartThree_PrintBasinsWithLabels(DataDirectory,Base_file) 69 | #CME.ExampleOne_PartFour_MaskBasins(DataDirectory,Base_file) 70 | #CME.ExampleOne_PartFive_MaskBasinsMF(DataDirectory,Base_file) 71 | 72 | toc = time.clock() 73 | print("This took: "+str(toc - tic)+" units of time") 74 | -------------------------------------------------------------------------------- /Create_hillshade_series_in_directory.py: -------------------------------------------------------------------------------- 1 | """ 2 | This function reads hillshades and elevation files in a directory 3 | 4 | 5 | INSTRUCTIONS FOR ffmpeg 6 | This will produce a series of images that you can convert to a movie using ffmpeg 7 | 8 | Here is a typical command line 9 | ffmpeg -framerate 5 -pattern_type glob -i '*.png' -vcodec libx264 -s 1230x566 -pix_fmt yuv420p movie7.mp4 10 | 11 | Some gotchas: 12 | The -framerate flag must come after ffmpeg (I think) 13 | You can be more specific about the pattern but this seems to work 14 | For the -s flag you must have pixel sizes that are divisible by 2. 15 | 16 | Written by Simon Mudd 17 | June 2017 18 | git 19 | GPL3 20 | """ 21 | 22 | 23 | import LSDChiMappingExamples as CME 24 | import LSDMapWrappers as MW 25 | import os 26 | from sys import platform 27 | import sys 28 | from glob import glob 29 | 30 | 31 | def get_filenames(root): 32 | # Create and empty list for the filenames 33 | these_filenames = [] 34 | for filename in glob(root+'*.bil'): 35 | if not 'hs' in filename: 36 | if not 'Raster' in filename: 37 | these_filenames.append(filename) 38 | 39 | these_filenames.sort() 40 | print these_filenames 41 | return these_filenames 42 | 43 | def run_plots(DataDirectory,Base_file, cbar_min_max = [0,400]): 44 | 45 | root = DataDirectory+Base_file 46 | filenames = get_filenames(root) 47 | counter = 0 48 | for fname in filenames: 49 | 50 | counter = counter+1 51 | # remove the extension form the files 52 | this_base_file = fname[:-4] 53 | if "win" in platform: 54 | split_file = this_base_file.split("\\") 55 | elif "linux" in platform: 56 | split_file = this_base_file.split("/") 57 | print("Split file is: ") 58 | print split_file 59 | this_base_file = split_file[-1] 60 | print("This base file is: "+ this_base_file) 61 | 62 | print("I am getting figures for the animation.") 63 | MW.SimpleHillshadeForAnimation(DataDirectory,this_base_file,cmap = "terrain", dpi = 250, imgnumber=counter, full_basefile = root,custom_cbar_min_max = cbar_min_max,coord_type='UTM_km', hide_ticklabels=True) 64 | 65 | def animate_plots(base_directory, fname_prefix): 66 | """ 67 | This function creates a movie of the plots using ffmpeg 68 | 69 | Args: 70 | base_directory (str): the directory with the plots. 71 | fname_prefix (str): the filename for the model run 72 | 73 | Returns: 74 | none but creates mp4 from pngs in base directory 75 | 76 | Author: FJC 77 | """ 78 | import subprocess 79 | 80 | # animate the pngs using ffmpeg 81 | system_call = "ffmpeg -framerate 5 -pattern_type glob -i '"+base_directory+"*.png' -vcodec libx264 -s 1230x566 -pix_fmt yuv420p "+base_directory+fname_prefix+"_movie.mp4" 82 | print system_call 83 | subprocess.call(system_call, shell=True) 84 | 85 | #============================================================================= 86 | # This is just a welcome screen that is displayed if no arguments are provided. 87 | #============================================================================= 88 | def print_welcome(): 89 | 90 | print("\n\n=======================================================================") 91 | print("Hello! I'm going to plot a series of hillshades for you.") 92 | print("You will need to tell me the directory and the base file name.") 93 | print("Use the -dir flag to define the working directory.") 94 | print("If you don't do this I will assume the data is in the same directory as this script.") 95 | print("Use the -fname flag to define the base file name.") 96 | print("For help type:") 97 | print(" python PlotMOverNAnalysis.py -h\n") 98 | print("=======================================================================\n\n ") 99 | 100 | #============================================================================= 101 | # This is the main function that runs the whole thing 102 | #============================================================================= 103 | def main(argv): 104 | 105 | """ 106 | This is just a few lines for keeping track of how long the program is taking. 107 | You can ignore it. 108 | """ 109 | import time 110 | tic = time.clock() 111 | 112 | # If there are no arguments, send to the welcome screen 113 | if not len(sys.argv) > 1: 114 | full_paramfile = print_welcome() 115 | sys.exit() 116 | 117 | # Get the arguments 118 | import argparse 119 | parser = argparse.ArgumentParser() 120 | # The location of the data files 121 | parser.add_argument("-dir", "--base_directory", type=str, help="The base directory with the hillshades. If this isn't defined I'll assume it's the same as the current directory.") 122 | parser.add_argument("-fname", "--fname_prefix", type=str, help="The base file name of the hillshades.") 123 | parser.add_argument("-animate", "--animate", type=bool, default=False, help="If this is true I'll create a movie of the model run.") 124 | parser.add_argument("-zmax", "--maximum_elevation_for_plotting", type=float, default = 400, help="This is the maximum elevation in the colourbar of the landscape plot.") 125 | args = parser.parse_args() 126 | 127 | cbar_min_max = [0,args.maximum_elevation_for_plotting] 128 | 129 | run_plots(args.base_directory,args.fname_prefix,cbar_min_max) 130 | 131 | if (args.animate): 132 | animate_plots(args.base_directory, args.fname_prefix) 133 | 134 | toc = time.clock() 135 | print("This took: "+str(toc - tic)+" units of time") 136 | 137 | 138 | #============================================================================= 139 | if __name__ == "__main__": 140 | main(sys.argv[1:]) 141 | -------------------------------------------------------------------------------- /Dev_script_for_knickpoints.py: -------------------------------------------------------------------------------- 1 | # Knickpoint plotting stuffs - B.G. if you need help 2 | import matplotlib 3 | matplotlib.use("Agg") 4 | from LSDPlottingTools import LSDMap_KnickpointPlotting as KP 5 | import pandas as pd 6 | from matplotlib import pyplot as plt 7 | 8 | 9 | # # print("This is the example test script for the development version of the knickpoint plotting tools") 10 | 11 | # # Smugglers = KP.KP_dev("/home/s1675537/PhD/LSDTopoData/knickpoint/model/movern_0p65_n_is_one94/", "movern_0p65_n_is_one94",binning = "source_key",min_chi_dist_for_kp = 0.0001, sources = [], bd_KDE = "scott", first_min_coeff =0.001, max_coeff = 0.5) #[30,0,11,16,20,25,27,30,69] 12 | 13 | # # Smugglers.plot_KDE( method = "deriv_ksn", group = "basin_key") 14 | # # Smugglers.map_of_knickpoint(method = "deriv_ksn", color_extent_Mx = [],color_extent_kp = [], cut_off = 0) 15 | # # Smugglers.plot_mchi_segments(method = "deriv_ksn", group = "basin_key") 16 | # # Smugglers.plot_chi_profiles( method = "deriv_ksn", group = "basin_key") 17 | # # Smugglers.plot_KDE( method = "deriv_ksn", group = "source_key") 18 | # # Smugglers.map_of_knickpoint(method = "deriv_ksn", color_extent_Mx = [],color_extent_kp = [], cut_off = 0) 19 | # # Smugglers.plot_mchi_segments(method = "deriv_ksn", group = "source_key") 20 | # # Smugglers.plot_chi_profiles( method = "deriv_ksn", group = "source_key") 21 | 22 | # # print("done") 23 | 24 | # df = pd.read_csv("/home/s1675537/PhD/LSDTopoData/knickpoint/model/movern_0p65_n_is_one94/movern_0p65_n_is_one94_MChiSegmented_Ks.csv") 25 | # df = df[df["chi"]>=0] 26 | # for source in df["source_key"].unique(): 27 | # print("source %s out of %s"%(source,df["source_key"].unique().shape[0] )) 28 | # this_df = df[df["source_key"] == source] 29 | # plt.plot(this_df["chi"], this_df["elevation"], c = "b") 30 | # plt.plot(this_df["chi"], this_df["segmented_elevation"], c = "r") 31 | # plt.savefig("/home/s1675537/PhD/LSDTopoData/knickpoint/model/movern_0p65_n_is_one94/source_%s.png"%source) 32 | # plt.clf() 33 | 34 | 35 | path = "/home/s1675537/PhD/LSDTopoData/knickpoint/puerto_rico/" 36 | prefix = "puerto_rico" 37 | 38 | Jaguar = KP.KP_dev_v2(path,prefix, min_length = 20000) 39 | 40 | # Jaguar.DEBUG_print_ksn_filters() 41 | # Jaguar.DEBUG_print_KDE() 42 | Jaguar.DEBUG_print_ksn_outliers() 43 | # Jaguar.DEBUG_print_ksn_dksndchi() 44 | 45 | Jaguar.DEBUG_print_ksn_comparison() -------------------------------------------------------------------------------- /Elevation_from_swath.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script plots (or will hopefully plot) Max/Mean/Min Elevation vs distance 3 | from the Swath(s) driver of LSDTopoTools. 4 | It takes the csv files generated from the driver and and the original raster. 5 | Written By B.Gailleton and F.J.Clubb 6 | """ 7 | 8 | #import modules 9 | import numpy as np, matplotlib.pyplot as plt 10 | from matplotlib import rcParams 11 | import matplotlib.cm as cmx 12 | #import seaborn as sns 13 | import matplotlib.colors as colors 14 | #from rand_cmap import rand_cmap 15 | from matplotlib import gridspec 16 | #from adjustText import adjust_text 17 | from scipy.interpolate import spline, UnivariateSpline 18 | 19 | # Go to the end of this script to enter your parameters 20 | # 21 | # 22 | # 23 | ################### Development part ############################ 24 | ######### Do not change these parameters unless you want to ##### 25 | ################################################################# 26 | def cm2inch(value): 27 | return value/2.54 28 | 29 | def read_all_data(DataDirectory,DEM_prefix, info_file, data_file): 30 | """ 31 | Read in the data with all the points 32 | """ 33 | 34 | # read in the file 35 | FileName = DataDirectory + data_file+'.csv' 36 | data = np.loadtxt(FileName, skiprows = 1, delimiter = ",") # Distance,Mean,Min,Max 37 | no_lines = data.size 38 | print "Number of lines: ", no_lines 39 | # Set up the arrays 40 | distance = data[:,0] 41 | MeanValues = data[:,1] 42 | MinValues = data[:,2] 43 | MaxValues = data[:,3] 44 | 45 | FileName = DataDirectory + info_file+'.csv' 46 | data2 = np.loadtxt(FileName, skiprows = 1, delimiter = ",") # latitudeA,longitudeA,latitudeB,longitudeB,general_mean_elevation,general_min_elevation,general_max_elevation,Xmin,Ymin 47 | 48 | return distance, MeanValues, MinValues, MaxValues, no_lines, data2 49 | 50 | def make_elevation_plots(DataDirectory, DEM_prefix, DEM_swathed,info_file, data_file, field_site, smoothing, OutputFigureName): 51 | """ 52 | Make nice plots of the elevations along the swath 53 | """ 54 | 55 | # Set up fonts 56 | rcParams['font.family'] = 'sans-serif' 57 | rcParams['font.sans-serif'] = ['Liberation Sans'] 58 | rcParams['font.size'] = 14 59 | 60 | distance, MeanValues, MinValues, MaxValues, Nlines, info = read_all_data(DataDirectory, DEM_prefix,info_file, data_file) 61 | 62 | # add the XY Plot 63 | fig = plt.figure(1, figsize=(cm2inch(25),cm2inch(15))) 64 | # set ratios for subplots 65 | ax = fig.add_subplot(111) 66 | 67 | 68 | distance = np.array(distance) 69 | if(smoothing): 70 | 71 | MeanValues = np.array(MeanValues) 72 | MinValues = np.array(MinValues) 73 | MaxValues = np.array(MaxValues) 74 | smooth_k = 0.7 75 | 76 | 77 | distance_interpolate = np.linspace(distance.min(),distance.max(),num = Nlines * smooth_k) 78 | MeanValues_smooth = spline(distance,MeanValues,distance_interpolate,order = 1) 79 | MinValues_smooth = spline(distance,MinValues,distance_interpolate,order = 1) 80 | MaxValues_smooth = spline(distance,MaxValues,distance_interpolate,order = 1) 81 | 82 | ax.plot(distance_interpolate, MeanValues_smooth, 'k-', lw=0.75, label = "Mean") 83 | ax.plot(distance_interpolate, MinValues_smooth, '-',c = 'gray', lw=0, label = "Max/min") 84 | ax.plot(distance_interpolate, MaxValues_smooth, '-',c = 'gray', lw=0,) 85 | ax.fill_between(distance_interpolate, MaxValues_smooth, MinValues_smooth, color = '#D5D5D5') 86 | plt.xlabel('Distance along swath (m)') 87 | plt.ylabel('Elevation (m)') 88 | else: 89 | ax.plot(distance, MeanValues, 'k-', lw=0.75, label = "Mean") 90 | ax.plot(distance, MinValues, '-',c = 'gray', lw=0, label = "Max/min") 91 | ax.plot(distance, MaxValues, '-',c = 'gray', lw=0,) 92 | ax.fill_between(distance, MaxValues, MinValues, color = '#D5D5D5') 93 | plt.xlabel('Distance along swath (m)') 94 | plt.ylabel('Elevation (m)') 95 | 96 | 97 | temp = np.array(MinValues) 98 | temp2 = np.array(MaxValues) 99 | 100 | print('I am plotting the data, the minimum altitude is %s and the maximum is %s.' %(temp.min(),temp2.max())) 101 | 102 | plt.ylim(temp.min() - temp.min()/20 ,temp2.max() + temp2.max()/20) 103 | plt.xlim(0,distance.max()) 104 | plt.title(field_site) 105 | plt.legend(loc='upper right') 106 | 107 | # Save figure 108 | OutputFigureFormat = 'png' 109 | plt.savefig(DataDirectory + OutputFigureName + '.' + OutputFigureFormat, format=OutputFigureFormat, dpi=1000) 110 | #plt.tight_layout() 111 | plt.close() 112 | 113 | ############################################################################################################# 114 | ######################################## Parameters to change ############################################### 115 | ############################################################################################################# 116 | 117 | if __name__ == "__main__": 118 | 119 | DEM_prefix = 'SRTM90_final_PP' # The original DEM 120 | DEM_swathed = DEM_prefix + "_swath_raster_0" # the swath raster produce by the driver, change it if you manually change the outpu file 121 | info_file = DEM_prefix + "_swath_genInfo_0" # the information file, change it if you manually change the outpu file 122 | data_file = DEM_prefix + "_swath_elevations_0" # the data file, change it if you manually change the outpu file 123 | field_site = "Swath profile" # Title of the figure 124 | smoothing = False # if true, slightly smooth the curve 125 | #DataDirectory = 'Z:\\DEMs_for_analysis\\eel_river\\' 126 | DataDirectory = '/home/s1675537/PhD/DataStoreBoris/GIS/Data/Carpathian/Best_DEM/' 127 | OutputFigureName = DEM_prefix+'_elevation_plots' 128 | make_elevation_plots(DataDirectory, DEM_prefix, DEM_swathed,info_file, data_file, field_site, smoothing, OutputFigureName) 129 | -------------------------------------------------------------------------------- /ExampleLongitudinalSwathPlot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 6 20:53:58 2017 4 | 5 | Example of how to use the Swath profile plotter 6 | to plot longitudinal swaths along channels 7 | from LSDSwathTools. 8 | 9 | @author: dav 10 | """ 11 | 12 | import matplotlib.pyplot as plt 13 | from LSDPlottingTools.LSDMap_BasicPlotting \ 14 | import MultiLongitudinalSwathAnalysisPlot, init_plotting_DV 15 | 16 | init_plotting_DV() 17 | 18 | #data_dir = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/SwathProfile/Swath_secondVisit/Ryedale/" 19 | data_dir = "/run/media/dav/SHETLAND/Analyses/HydrogeomorphPaper/SwathProfile/Swath_secondVisit/Ryedale/" 20 | 21 | file_single = "RyedaleElevDiff_GRIDDED_TLIM_long_profile.txt" 22 | file_wildcard = "*ElevDiff_*_TLIM_long_profile.txt" 23 | 24 | #plot_swath_profile(file_single + data_dir) 25 | plt.rcParams['lines.linewidth'] = 1.5 26 | 27 | # Returns the objects now 28 | # Cycles through input swath files in alphabetical order. 29 | fig, ax = MultiLongitudinalSwathAnalysisPlot(data_dir, file_wildcard, maximum=45000) 30 | 31 | # Check these corespond to the correct line. 32 | ax.legend(['Key label 1','Key label 2'],loc='best') 33 | 34 | -------------------------------------------------------------------------------- /HillshadeComparison.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Jan 31 11:47:22 2017 4 | 5 | An example of using the cython version of the hillshade 6 | algorithm from LSDTopoTools/LSDRaster, compared to the pure python 7 | module in LSDMappingTools. 8 | 9 | (This test version dos on-the-fly-compilation to C and then a C-lib 10 | but you could bundle a compiled c-object with the code for speed/convenience) 11 | 12 | @author: dav 13 | """ 14 | import matplotlib.pyplot as plt 15 | # For on the fly compilation - remove if you are pre-compiling the Cython-library 16 | # e.g. with a setup.py script that builds your cython extension library 17 | # This MUST come before you import the C hillshade pyx file if you are doing it 18 | # this way. 19 | #################### 20 | import pyximport 21 | pyximport.install() 22 | #################### 23 | 24 | from LSDPlottingTools import fast_hillshade as fasthill 25 | import LSDPlottingTools.LSDMap_GDALIO as LSDMap_IO 26 | import LSDPlottingTools.LSDMap_BasicPlotting as LSDMap_BP 27 | 28 | Directory = "/mnt/SCRATCH/Dev/ExampleTopoDatasets/" 29 | BackgroundRasterName = "indian_creek.bil" 30 | 31 | raster = LSDMap_IO.ReadRasterArrayBlocks(Directory + BackgroundRasterName) 32 | data_res = LSDMap_IO.GetGeoInfo(Directory + BackgroundRasterName)[3][1] 33 | try: 34 | NoDataValue = float(LSDMap_IO.getNoDataValue(Directory + BackgroundRasterName)) 35 | except TypeError: 36 | NoDataValue = -9999.0 37 | 38 | ncols, nrows = raster.shape 39 | 40 | # LSDMappingTools hillshade 41 | #hs = LSDMap_BP.Hillshade(raster) 42 | #plt.imshow(hs, cmap="gray") 43 | #plt.show() 44 | 45 | #LSDRaster Cythonised version pf hillshade 46 | hs_nice = fasthill.Hillshade(raster, data_res, NoDataValue=NoDataValue) 47 | # I tend to comment out these two lines profiling, so you 48 | # aren't actually profiling the matplotlib rendering... 49 | #plt.imshow(hs_nice, cmap="gray") 50 | #plt.show() 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Edinburgh Land Surface Dynamics Topographic Tools 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LSDBasemapTools/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Oct 30 10:37:16 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | from __future__ import absolute_import, division, print_function 9 | 10 | from .LSDMap_BasemapTools import * 11 | 12 | -------------------------------------------------------------------------------- /LSDChiMappingExamples/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Oct 30 10:37:16 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | from __future__ import absolute_import, division, print_function, unicode_literals 9 | 10 | from .ChiVisualisation_Example01 import * 11 | 12 | -------------------------------------------------------------------------------- /LSDGDALBatchProcessing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Sep 09 16:52:27 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | import numpy as np 9 | from glob import glob 10 | import LSDOSystemTools as LSDost 11 | import os 12 | import shutil 13 | import subprocess 14 | 15 | # This function looks for all the files of a certain format in a directory and 16 | # then translates them into a new format into a subdirectory named 17 | # after the target format. 18 | def GDALBatchConvert(DataDirectory,raster_format,target_format): 19 | 20 | NewDataDirectory = LSDost.ReformatSeperators(DataDirectory) 21 | DataDirectory = LSDost.AppendSepToDirectoryPath(NewDataDirectory) 22 | 23 | # Check the target format 24 | if target_format == "ENVI": 25 | target_extension = ".bil" 26 | elif target_format == "EHdr": 27 | target_extension = ".bil" 28 | elif target_format == "GTiff": 29 | target_extension = ".tiff" 30 | else: 31 | print "You have not selcted a valid raster format!" 32 | print "Options are ENVI, EHdr and GTiff" 33 | target_extension = "NULL" 34 | 35 | # now make a directory 36 | if target_extension != "NULL": 37 | 38 | target_directory = DataDirectory+target_format 39 | 40 | if not os.access(target_directory,os.F_OK): 41 | print "Making path: " 42 | os.mkdir(target_directory) 43 | print "I made a directory: " + target_directory 44 | else: 45 | print "Path: " +target_directory+" already exists." 46 | 47 | # Now check the source format 48 | if raster_format == "ENVI": 49 | raster_extension = ".bil" 50 | elif raster_format == "EHdr": 51 | raster_extension = ".bil" 52 | elif raster_format == "GTiff": 53 | raster_extension = ".tif" 54 | else: 55 | print "You have not selcted a valid raster format!" 56 | print "Options are ENVI, EHdr and GTiff" 57 | raster_extension = "NULL" 58 | 59 | # find all the dataset of the source format 60 | print "The data directory is: " + DataDirectory 61 | print "The raster extension is: " + raster_extension 62 | if raster_extension != "NULL": 63 | for FileName in glob(DataDirectory+"*"+raster_extension): 64 | print "found file: " + FileName 65 | subprocess.call(['gdalinfo',FileName]) 66 | 67 | def GDALBatchMerge(DataDirectory,merge_subfolder_name,merge_filename,raster_format,target_format): 68 | 69 | NewDataDirectory = LSDost.ReformatSeperators(DataDirectory) 70 | DataDirectory = LSDost.AppendSepToDirectoryPath(NewDataDirectory) 71 | 72 | # get the name of the data directory into which the file should be merged 73 | merge_DataDirectory = DataDirectory+merge_subfolder_name 74 | mDataDriectory = LSDost.AppendSepToDirectoryPath(merge_DataDirectory) 75 | 76 | # make the directory 77 | if not os.access(mDataDriectory,os.F_OK): 78 | print "Making path: " 79 | os.mkdir(mDataDriectory) 80 | print "I made a directory: " + mDataDriectory 81 | else: 82 | print "Path: " +mDataDriectory+" already exists." 83 | 84 | # Check the source format 85 | if raster_format == "ENVI": 86 | raster_extension = ".bil" 87 | elif raster_format == "EHdr": 88 | raster_extension = ".bil" 89 | elif raster_format == "GTiff": 90 | raster_extension = ".tif" 91 | else: 92 | print "You have not selcted a valid raster format!" 93 | print "Options are ENVI, EHdr and GTiff" 94 | raster_extension = "NULL" 95 | 96 | # Check the target format. Default is geotiff 97 | if target_format == "ENVI": 98 | target_extension = ".bil" 99 | elif target_format == "EHdr": 100 | target_extension = ".bil" 101 | elif target_format == "GTiff": 102 | target_extension = ".tif" 103 | else: 104 | print "You have not selcted a valid raster format!" 105 | print "Defaulting to GTiff" 106 | target_format == "GTiff" 107 | target_extension = ".tif" 108 | 109 | # set the name of the target file 110 | target_FileName = mDataDriectory+merge_filename+target_extension 111 | 112 | # find all the dataset of the source format 113 | print "The data directory is: " + DataDirectory 114 | print "The raster extension is: " + raster_extension 115 | if raster_extension != "NULL": 116 | 117 | # Set up the list for holding command prompt commands 118 | command_prompt = [] 119 | command_prompt.append("gdal_merge.py") 120 | command_prompt.append("-of") 121 | command_prompt.append(target_format) 122 | command_prompt.append("-o") 123 | command_prompt.append(target_FileName) 124 | 125 | 126 | for FileName in glob(DataDirectory+"*"+raster_extension): 127 | print "found file: " + FileName 128 | command_prompt.append(FileName) 129 | 130 | print "The subprocess call is: " 131 | print command_prompt 132 | subprocess.call(command_prompt) 133 | -------------------------------------------------------------------------------- /LSDMapArtist/README.md: -------------------------------------------------------------------------------- 1 | # LSDMapArtist 2 | An experimental python package for plotting LSDTopoTools output and world domination. (But mainly LSDTopoTools output) 3 | 4 | This does not affect the other modules in LSDPlottingTools. LSDPlottingTools is blissfully unaware of LSDMapArtist's existence. LSDMapArtist imports from LSDPlottingTools, but not the other way round so as not to break people's code. 5 | 6 | __Note: to use this, you must have LSDPlottingTools in your PYTHONPATH, either by setting it in bash or by using:__ 7 | 8 | ```python 9 | 10 | import sys 11 | 12 | sys.path.append("PATH/TO/LSDPlottingTools/") 13 | ``` 14 | 15 | ## Overview 16 | An object-oriented plotting module for constructing 17 | drape maps in a reusable, generic way. 18 | 19 | Experimental. Use at your own risk. Subject to rapid change. 20 | 21 | If it ever works I'll transfer it to @LSDTopoTools -- done! 22 | 23 | This software is realsed under the Artistic Licence v2.0 24 | 25 | ## Example use: 26 | (subject to change and open to suggestions) 27 | 28 | ``` 29 | import lsdmapartist as lsdmap 30 | 31 | myDrapePlot = lsdmap.DrapePlot(RasterName, BackgroundRasterName, 32 | Directory, "Blues", drape_min_threshold=0.05) 33 | 34 | myDrapePlot.set_drape_min_threshold(0.1) 35 | myDrapePlot.set_colourmap("jet") 36 | myDrapePlot.set_backgroundtype("Hillsahde") 37 | myDrapePlot.set_backgroundtype("TerrainColours") 38 | 39 | myDrapePlot.save_fig("png", "ESurfDyn") 40 | 41 | ``` 42 | And so on... 43 | 44 | ## Suggestions 45 | 46 | ## Todo 47 | -------------------------------------------------------------------------------- /LSDMapArtist/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/LSDMapArtist/__init__.py -------------------------------------------------------------------------------- /LSDMapArtist/unittests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import lsdmapartist 3 | 4 | class TestLSDMapArtist(unittest.TestCase): 5 | 6 | def test_BaseRaster(self): 7 | self.assertIsInstance(lsdmapartist.BaseRaster) 8 | 9 | 10 | -------------------------------------------------------------------------------- /LSDMapFigure/README.asc: -------------------------------------------------------------------------------- 1 | = This is an object-based plotting library for raster plotting 2 | 3 | The objects in this folder are similar to Declan's MapArtist objects but are slightly differnet mainly because I (SMM) couldn't get Declan's thing to do what I wanted. 4 | 5 | Until we write proper documentation, the best way to see how it works is to go down a folder level (into https://github.com/LSDtopotools/LSDMappingTools[the main LSDMappingTools repo]) and look at the functions that call these objects. 6 | 7 | They are: 8 | 9 | * https://github.com/LSDtopotools/LSDMappingTools/blob/master/FJCTestArtist2.py[FJCTestArtist2.py] 10 | * https://github.com/LSDtopotools/LSDMappingTools/blob/master/SMMTestArtist2.py[SMMTestArtist2.py] 11 | * https://github.com/LSDtopotools/LSDMappingTools/blob/master/BGTestArtist.py[BGTestArtist.py] -------------------------------------------------------------------------------- /LSDMapFigure/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/LSDMapFigure/__init__.py -------------------------------------------------------------------------------- /LSDMapWrappers/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Oct 30 10:37:16 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | from __future__ import absolute_import, division, print_function, unicode_literals 9 | 10 | from .LSDMapWrappers_BasicPlotting import * 11 | from .LSDMapWrappers_ChiPlotting import * 12 | 13 | -------------------------------------------------------------------------------- /LSDPlottingTools/LSDMap_DrainageCapture.py: -------------------------------------------------------------------------------- 1 | #============================================================================= 2 | # These functions create figures for visualising the data from the drainage 3 | # capture metrics 4 | # 5 | # It creates separate plots for each basin in the DEM. 6 | # 7 | # Authors: 8 | # Simon M. Mudd 9 | # Fiona J. Clubb 10 | #============================================================================= 11 | #============================================================================= 12 | # IMPORT MODULES 13 | #============================================================================= 14 | import numpy as np 15 | import LSDPlottingTools as LSDP 16 | import matplotlib.pyplot as plt 17 | from matplotlib import rcParams 18 | import matplotlib.ticker as ticker 19 | import pandas as pd 20 | import os 21 | 22 | from LSDMapFigure import PlottingHelpers as Helper 23 | 24 | #============================================================================= 25 | # PLOTTING FUNCTIONS 26 | #============================================================================= 27 | def PlotBasinPerimeter(DataDirectory, fname_prefix, size_format='ESURF', FigFormat='png'): 28 | """ 29 | Make a plot of the basin perimeter ordered by the outlet 30 | 31 | Args: 32 | DataDirectory (str): the data directory 33 | fname_prefix (str): filename of the DEM without extension 34 | size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf). 35 | FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command. 36 | 37 | Author: FJC 38 | """ 39 | # check if a directory exists for the perimeter plots. If not then make it. 40 | this_dir = DataDirectory+'basin_perimeters/' 41 | if not os.path.isdir(this_dir): 42 | os.makedirs(this_dir) 43 | 44 | # Set up fonts for plots 45 | label_size = 10 46 | rcParams['font.family'] = 'sans-serif' 47 | rcParams['font.sans-serif'] = ['Liberation Sans'] 48 | rcParams['font.size'] = label_size 49 | 50 | # make a figure 51 | if size_format == "geomorphology": 52 | fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) 53 | #l_pad = -40 54 | elif size_format == "big": 55 | fig = plt.figure(1, facecolor='white',figsize=(16,9)) 56 | #l_pad = -50 57 | else: 58 | fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2)) 59 | #l_pad = -35 60 | 61 | PerimeterDF = Helper.ReadPerimeterCSV(DataDirectory, fname_prefix) 62 | 63 | gs = plt.GridSpec(100,100,bottom=0.15,left=0.05,right=0.95,top=0.95) 64 | ax = fig.add_subplot(gs[5:100,10:95]) 65 | 66 | # plot the data 67 | ax.plot(PerimeterDF['node_key'],PerimeterDF['elevation']) 68 | 69 | # set the axis labels 70 | ax.set_xlabel('Perimeter node ordered from outlet') 71 | ax.set_ylabel('Node elevation') 72 | 73 | newFilename = this_dir+fname_prefix+"_basin_perimeter."+FigFormat 74 | plt.savefig(newFilename,format=FigFormat,dpi=300) 75 | ax.cla() 76 | plt.close(fig) 77 | -------------------------------------------------------------------------------- /LSDPlottingTools/LSDMap_SwathPlotting.py: -------------------------------------------------------------------------------- 1 | ## LSDMap_SwathPlotting.py 2 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 3 | ## These functions are tools to deal with plotting swaths 4 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 5 | ## SMM 6 | ## 20/02/2018 7 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 8 | from __future__ import absolute_import, division, print_function 9 | 10 | import numpy as np 11 | import os 12 | from . import cubehelix 13 | import matplotlib.pyplot as plt 14 | import matplotlib as mpl 15 | from matplotlib import rcParams 16 | from matplotlib import colors 17 | import LSDPlottingTools.LSDMap_GDALIO as LSDMap_IO 18 | import LSDPlottingTools.LSDMap_BasicPlotting as LSDMap_BP 19 | import LSDPlottingTools.LSDMap_PointTools as LSDMap_PD 20 | from LSDMapFigure.PlottingRaster import MapFigure 21 | from LSDMapFigure.PlottingRaster import BaseRaster 22 | from LSDMapFigure import PlottingHelpers as Helper 23 | 24 | def PlotSwath(swath_csv_name, FigFileName = 'Image.png', size_format = "geomorphology", fig_format = "png", dpi = 500, aspect_ratio = 2): 25 | """ 26 | This plots a swath profile 27 | 28 | Args: 29 | swath_csv_name (str): the name of the csv file (with path!) 30 | 31 | Author: SMM 32 | 33 | Date 20/02/2018 34 | """ 35 | 36 | print("STARTING swath plot.") 37 | 38 | # Set up fonts for plots 39 | label_size = 12 40 | rcParams['font.family'] = 'sans-serif' 41 | rcParams['font.sans-serif'] = ['Liberation Sans'] 42 | rcParams['font.size'] = label_size 43 | 44 | # make a figure, 45 | if size_format == "geomorphology": 46 | fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) 47 | fig_size_inches = 6.25 48 | l_pad = -40 49 | elif size_format == "big": 50 | fig = plt.figure(1, facecolor='white',figsize=(16,9)) 51 | fig_size_inches = 16 52 | l_pad = -50 53 | else: 54 | fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5)) 55 | fig_size_inches = 4.92126 56 | l_pad = -35 57 | 58 | # Note all the below parameters are overwritten by the figure sizer routine 59 | gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) 60 | ax = fig.add_subplot(gs[25:100,10:95]) 61 | 62 | print("Getting data from the file: "+swath_csv_name) 63 | thisPointData = LSDMap_PD.LSDMap_PointData(swath_csv_name) 64 | 65 | distance = thisPointData.QueryData('Distance').values 66 | mean_val = thisPointData.QueryData('Mean').values 67 | min_val = thisPointData.QueryData('Min').values 68 | max_val = thisPointData.QueryData('Max').values 69 | 70 | # Get the minimum and maximum distances 71 | X_axis_min = 0 72 | X_axis_max = distance[-1] 73 | n_target_tics = 5 74 | xlocs,new_x_labels = LSDMap_BP.TickConverter(X_axis_min,X_axis_max,n_target_tics) 75 | 76 | ax.fill_between(distance, min_val, max_val, facecolor='orange', alpha = 0.5, interpolate=True) 77 | ax.plot(distance, mean_val,"b", linewidth = 1) 78 | ax.plot(distance, min_val,"k",distance,max_val,"k",linewidth = 1) 79 | 80 | ax.spines['top'].set_linewidth(1) 81 | ax.spines['left'].set_linewidth(1) 82 | ax.spines['right'].set_linewidth(1) 83 | ax.spines['bottom'].set_linewidth(1) 84 | 85 | ax.set_ylabel("Elevation (m)") 86 | ax.set_xlabel("Distance along swath (km)") 87 | 88 | ax.set_xticks(xlocs) 89 | ax.set_xticklabels(new_x_labels,rotation=60) 90 | 91 | # This gets all the ticks, and pads them away from the axis so that the corners don't overlap 92 | ax.tick_params(axis='both', width=1, pad = 2) 93 | for tick in ax.xaxis.get_major_ticks(): 94 | tick.set_pad(2) 95 | 96 | 97 | # Lets try to size the figure 98 | cbar_L = "None" 99 | [fig_size_inches,map_axes,cbar_axes] = Helper.MapFigureSizer(fig_size_inches,aspect_ratio, cbar_loc = cbar_L, title = "None") 100 | 101 | fig.set_size_inches(fig_size_inches[0], fig_size_inches[1]) 102 | ax.set_position(map_axes) 103 | 104 | FigFormat = fig_format 105 | print("The figure format is: " + FigFormat) 106 | if FigFormat == 'show': 107 | plt.show() 108 | elif FigFormat == 'return': 109 | return fig 110 | else: 111 | plt.savefig(FigFileName,format=FigFormat,dpi=dpi) 112 | fig.clf() 113 | 114 | -------------------------------------------------------------------------------- /LSDPlottingTools/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Oct 30 10:37:16 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | from __future__ import absolute_import, division, print_function, unicode_literals 9 | 10 | from .LSDMap_BasicPlotting import * 11 | from .LSDMap_GDALIO import * 12 | from .LSDMap_BasicManipulation import * 13 | from .LSDMap_PointTools import * 14 | from .LSDMap_ChiPlotting import * 15 | from .LSDMap_SAPlotting import * 16 | from .LSDMap_Subplots import * 17 | from .LSDMap_OSystemTools import * 18 | from .LSDMap_PlottingDriver import * 19 | from .LSDMap_VectorTools import * 20 | from .LSDMap_SwathPlotting import * 21 | from .adjust_text import * 22 | 23 | from . import colours as lsdcolours 24 | from . import labels as lsdlabels 25 | from . import scalebar as lsdscalebar 26 | from . import statsutilities as lsdstatsutilities 27 | 28 | -------------------------------------------------------------------------------- /LSDPlottingTools/cubehelix.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, division, print_function, unicode_literals 3 | 4 | from matplotlib.colors import LinearSegmentedColormap as LSC 5 | from math import pi 6 | import numpy as np 7 | 8 | 9 | def cmap(start=0.5, rot=-1.5, gamma=1.0, reverse=False, nlev=256., 10 | minSat=1.2, maxSat=1.2, minLight=0., maxLight=1., 11 | **kwargs): 12 | """ 13 | A full implementation of Dave Green's "cubehelix" for Matplotlib. 14 | Based on the FORTRAN 77 code provided in 15 | D.A. Green, 2011, BASI, 39, 289. 16 | 17 | http://adsabs.harvard.edu/abs/2011arXiv1108.5083G 18 | 19 | User can adjust all parameters of the cubehelix algorithm. 20 | This enables much greater flexibility in choosing color maps, while 21 | always ensuring the color map scales in intensity from black 22 | to white. A few simple examples: 23 | 24 | Default color map settings produce the standard "cubehelix". 25 | 26 | Create color map in only blues by setting rot=0 and start=0. 27 | 28 | Create reverse (white to black) backwards through the rainbow once 29 | by setting rot=1 and reverse=True. 30 | 31 | Parameters 32 | ---------- 33 | start : scalar, optional 34 | Sets the starting position in the color space. 0=blue, 1=red, 35 | 2=green. Defaults to 0.5. 36 | rot : scalar, optional 37 | The number of rotations through the rainbow. Can be positive 38 | or negative, indicating direction of rainbow. Negative values 39 | correspond to Blue->Red direction. Defaults to -1.5 40 | gamma : scalar, optional 41 | The gamma correction for intensity. Defaults to 1.0 42 | reverse : boolean, optional 43 | Set to True to reverse the color map. Will go from black to 44 | white. Good for density plots where shade~density. Defaults to False 45 | nlev : scalar, optional 46 | Defines the number of discrete levels to render colors at. 47 | Defaults to 256. 48 | sat : scalar, optional 49 | The saturation intensity factor. Defaults to 1.2 50 | NOTE: this was formerly known as "hue" parameter 51 | minSat : scalar, optional 52 | Sets the minimum-level saturation. Defaults to 1.2 53 | maxSat : scalar, optional 54 | Sets the maximum-level saturation. Defaults to 1.2 55 | startHue : scalar, optional 56 | Sets the starting color, ranging from [0, 360], as in 57 | D3 version by @mbostock 58 | NOTE: overrides values in start parameter 59 | endHue : scalar, optional 60 | Sets the ending color, ranging from [0, 360], as in 61 | D3 version by @mbostock 62 | NOTE: overrides values in rot parameter 63 | minLight : scalar, optional 64 | Sets the minimum lightness value. Defaults to 0. 65 | maxLight : scalar, optional 66 | Sets the maximum lightness value. Defaults to 1. 67 | 68 | Returns 69 | ------- 70 | matplotlib.colors.LinearSegmentedColormap object 71 | 72 | Example 73 | ------- 74 | >>> import cubehelix 75 | >>> import matplotlib.pyplot as plt 76 | >>> import numpy as np 77 | >>> x = np.random.randn(1000) 78 | >>> y = np.random.randn(1000) 79 | >>> cx = cubehelix.cmap(start=0., rot=-0.5) 80 | >>> plt.hexbin(x, y, gridsize=50, cmap=cx) 81 | 82 | Revisions 83 | --------- 84 | 2014-04 (@jradavenport) Ported from IDL version 85 | 2014-04 (@jradavenport) Added kwargs to enable similar to D3 version, 86 | changed name of "hue" parameter to "sat" 87 | """ 88 | 89 | # override start and rot if startHue and endHue are set 90 | if kwargs is not None: 91 | if 'startHue' in kwargs: 92 | start = (kwargs.get('startHue') / 360. - 1.) * 3. 93 | if 'endHue' in kwargs: 94 | rot = kwargs.get('endHue') / 360. - start / 3. - 1. 95 | if 'sat' in kwargs: 96 | minSat = kwargs.get('sat') 97 | maxSat = kwargs.get('sat') 98 | 99 | # set up the parameters 100 | fract = np.linspace(minLight, maxLight, nlev) 101 | angle = 2.0 * pi * (start / 3.0 + rot * fract + 1.) 102 | fract = fract**gamma 103 | 104 | satar = np.linspace(minSat, maxSat, nlev) 105 | amp = satar * fract * (1. - fract) / 2. 106 | 107 | # compute the RGB vectors according to main equations 108 | red = fract + amp * (-0.14861 * np.cos(angle) + 1.78277 * np.sin(angle)) 109 | grn = fract + amp * (-0.29227 * np.cos(angle) - 0.90649 * np.sin(angle)) 110 | blu = fract + amp * (1.97294 * np.cos(angle)) 111 | 112 | # find where RBB are outside the range [0,1], clip 113 | red[np.where((red > 1.))] = 1. 114 | grn[np.where((grn > 1.))] = 1. 115 | blu[np.where((blu > 1.))] = 1. 116 | 117 | red[np.where((red < 0.))] = 0. 118 | grn[np.where((grn < 0.))] = 0. 119 | blu[np.where((blu < 0.))] = 0. 120 | 121 | # optional color reverse 122 | if reverse is True: 123 | red = red[::-1] 124 | blu = blu[::-1] 125 | grn = grn[::-1] 126 | 127 | # put in to tuple & dictionary structures needed 128 | rr = [] 129 | bb = [] 130 | gg = [] 131 | for k in range(0, int(nlev)): 132 | rr.append((float(k) / (nlev - 1.), red[k], red[k])) 133 | bb.append((float(k) / (nlev - 1.), blu[k], blu[k])) 134 | gg.append((float(k) / (nlev - 1.), grn[k], grn[k])) 135 | 136 | cdict = {'red': rr, 'blue': bb, 'green': gg} 137 | return LSC('cubehelix_map', cdict) 138 | -------------------------------------------------------------------------------- /LSDPlottingTools/dimension.py: -------------------------------------------------------------------------------- 1 | """""" 2 | 3 | # Standard library modules. 4 | from __future__ import absolute_import, division, print_function, unicode_literals 5 | from operator import itemgetter 6 | import bisect 7 | 8 | # Third party modules. 9 | 10 | # Local modules. 11 | 12 | # Globals and constants variables. 13 | _PREFIXES_FACTORS = {'Y': 1e24, 'Z': 1e21, 'E': 1e18, 'P': 1e15, 'T': 1e12, 14 | 'G': 1e9, 'M': 1e6, 'k': 1e3, 'd': 1e-1, 'c': 1e-2, 15 | 'm': 1e-3, u'\u00b5': 1e-6, 16 | 'u': 1e-6, 'n': 1e-9, 'p': 1e-12, 'f': 1e-15, 'a': 1e-18, 17 | 'z': 1e-21, 'y': 1e-24} 18 | 19 | class _Dimension(object): 20 | 21 | def __init__(self, base_units, latexrepr=None): 22 | self._base_units = base_units 23 | self._units = {base_units: 1.0} 24 | if latexrepr is None: 25 | latexrepr = base_units 26 | self._latexrepr = {base_units: latexrepr} 27 | 28 | def add_units(self, units, factor, latexrepr=None): 29 | """ 30 | Add new possible units. 31 | 32 | :arg units: units 33 | :type units: :class:`str` 34 | 35 | :arg factor: multiplication factor to convert new units into base units 36 | :type factor: :class:`float` 37 | 38 | :arg latexrepr: LaTeX representation of units (if ``None``, use *units) 39 | :type latexrepr: :class:`str` 40 | """ 41 | if units in self._units: 42 | raise ValueError('%s already defined' % units) 43 | if factor == 1: 44 | raise ValueError('Factor cannot be equal to 1') 45 | if latexrepr is None: 46 | latexrepr = units 47 | 48 | self._units[units] = factor 49 | self._latexrepr[units] = latexrepr 50 | 51 | def is_valid_units(self, units): 52 | return units in self._units and units in self._latexrepr 53 | 54 | def calculate_preferred(self, value, units): 55 | if units not in self._units: 56 | raise ValueError('Unknown units: %s' % units) 57 | base_value = value * self._units[units] 58 | 59 | units_factor = sorted(self._units.items(), key=itemgetter(1)) 60 | factors = [item[1] for item in units_factor] 61 | index = bisect.bisect_right(factors, base_value) 62 | newunits, factor = units_factor[index - 1] 63 | 64 | return base_value / factor, newunits 65 | 66 | def to_latex(self, units): 67 | if units not in self._latexrepr: 68 | raise ValueError('Unknown units: %s' % units) 69 | return self._latexrepr[units] 70 | 71 | @property 72 | def base_units(self): 73 | return self._base_units 74 | 75 | class SILengthDimension(_Dimension): 76 | 77 | def __init__(self): 78 | super(SILengthDimension, self).__init__('m') 79 | for prefix, factor in _PREFIXES_FACTORS.items(): 80 | latexrepr = None 81 | if prefix == u'\u00b5': 82 | latexrepr = '$\\mu$m' 83 | self.add_units(prefix + 'm', factor, latexrepr) 84 | 85 | class SILengthReciprocalDimension(_Dimension): 86 | 87 | def __init__(self): 88 | super(SILengthReciprocalDimension, self).__init__('1/m', 'm$^{-1}$') 89 | for prefix, factor in _PREFIXES_FACTORS.items(): 90 | latexrepr = '{0}m$^{{-1}}$'.format(prefix) 91 | if prefix == u'\u00b5': 92 | latexrepr = '$\\mu$m$^{-1}$' 93 | self.add_units('1/{0}m'.format(prefix), factor, latexrepr) 94 | 95 | class ImperialLengthDimension(_Dimension): 96 | 97 | def __init__(self): 98 | super(ImperialLengthDimension, self).__init__('ft') 99 | self.add_units('th', 1 / 12000) 100 | self.add_units('in', 1 / 12) 101 | self.add_units('yd', 3) 102 | self.add_units('ch', 66) 103 | self.add_units('fur', 660) 104 | self.add_units('mi', 5280) 105 | self.add_units('lea', 15840) 106 | 107 | 108 | -------------------------------------------------------------------------------- /LSDPlottingTools/fast_hillshade.pyx: -------------------------------------------------------------------------------- 1 | #fast_hillshade.pyx 2 | """ 3 | This is a cython version of the nicer looking hillshade function in the 4 | LSDTopoTools core C++ libraries. 5 | 6 | @author dav 7 | """ 8 | 9 | # Cython rule of thumb no 1. If there are equivalent C-libraries for 10 | # numpy stuff, use them. (E.g. math functions) 11 | # Let's use the native C-libraries for math functions. 12 | from libc.math cimport sin, cos, sqrt, M_PI, atan, atan2 13 | 14 | import cython 15 | cimport cython 16 | 17 | from cython.parallel import prange, parallel 18 | 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | # Find out how many cores/CPUs we have available 23 | import multiprocessing 24 | cdef int num_threads_use = multiprocessing.cpu_count() 25 | print(num_threads_use) 26 | 27 | # Fix a data type for our arrays. 28 | DTYPE = np.float64 29 | # Define a compile type to DTYPE_t 30 | ctypedef np.float64_t DTYPE_t 31 | 32 | # Best to turn off these decorators if you are debugging 33 | # (Segfaults etc.) 34 | @cython.boundscheck(False) 35 | @cython.wraparound(False) 36 | @cython.nonecheck(False) 37 | @cython.cdivision(True) 38 | def Hillshade(np.ndarray[DTYPE_t, ndim=2] terrain_array, 39 | float DataResolution, float azimuth = 315, 40 | float angle_altitude = 45, 41 | float NoDataValue = -9999, float z_factor = 1): 42 | """Creates a hillshade raster 43 | 44 | Args: 45 | raster_array (numpy array): A numpy raster of your terrain 46 | e.g generated by LSDMap_GDALIO.ReadRasterArrayBlocks 47 | azimuth (float): Azimuth of sunlight 48 | angle_altitude (float): Angle altitude of sun 49 | z_factor (float): z_factor 50 | NoDataValue (float): The nodata value of the raster 51 | 52 | Returns: 53 | HSArray (numpy.array): The hillshade array 54 | 55 | Author: 56 | DAV, SWDG, SMM 57 | 58 | """ 59 | cdef unsigned int ncols = terrain_array.shape[1] 60 | cdef unsigned int nrows = terrain_array.shape[0] 61 | 62 | # Ndarray best choice? Will revisit later... 63 | cdef np.ndarray[DTYPE_t, ndim=2] HSarray = np.empty((ncols,nrows)) 64 | HSarray.fill(np.nan) 65 | 66 | cdef float zenith_rad = (90 - angle_altitude) * M_PI / 180.0 67 | cdef float azimuth_math = 360-azimuth + 90 68 | if (azimuth_math >= 360.0): 69 | azimuth_math = azimuth_math - 360 70 | cdef float azimuth_rad = azimuth_math * M_PI / 180.0 71 | 72 | cdef float slope_rad = 0 73 | cdef float aspect_rad = 0 74 | cdef float dzdx = 0 75 | cdef float dzdy = 0 76 | cdef int i = 0, j = 0 77 | 78 | # We can safely turn off the Python Global Interpreter lock for these for loops 79 | with nogil, parallel(num_threads=num_threads_use): 80 | # OpenMP threads created for the outer loop. 81 | for i in prange(nrows): 82 | for j in range(ncols): 83 | if terrain_array[i, j] != NoDataValue: 84 | dzdx = (((terrain_array[i, j+1] + 2*terrain_array[i+1, j] + terrain_array[i+1, j+1]) - 85 | (terrain_array[i-1, j-1] + 2*terrain_array[i-1, j] + terrain_array[i-1, j+1])) 86 | / (8 * DataResolution)) 87 | dzdy = (((terrain_array[i-1, j+1] + 2*terrain_array[i, j+1] + terrain_array[i+1, j+1]) - 88 | (terrain_array[i-1, j-1] + 2*terrain_array[i, j-1] + terrain_array[i+1, j-1])) 89 | / (8 * DataResolution)) 90 | 91 | slope_rad = atan(z_factor * sqrt((dzdx * dzdx) + (dzdy * dzdy))) 92 | 93 | if (dzdx != 0): 94 | aspect_rad = atan2(dzdy, (dzdx*-1)) 95 | if (aspect_rad < 0): 96 | aspect_rad = 2 * M_PI + aspect_rad 97 | 98 | else: 99 | if (dzdy > 0): 100 | aspect_rad = M_PI / 2 101 | elif (dzdy < 0): 102 | aspect_rad = 2 * M_PI - M_PI / 2 103 | else: 104 | aspect_rad = aspect_rad 105 | 106 | HSarray[i, j] = 255.0 * ((cos(zenith_rad) * cos(slope_rad)) + 107 | (sin(zenith_rad) * sin(slope_rad) * 108 | cos(azimuth_rad - aspect_rad))) 109 | # Necessary? 110 | if (HSarray[i, j] < 0): 111 | HSarray[i, j] = 0 112 | 113 | return HSarray 114 | -------------------------------------------------------------------------------- /LSDPlottingTools/labels.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Oct 10 16:09:29 2016 4 | 5 | A series of functions to provide extra functionality to matplotlib 6 | involving the creation of labels for plots. 7 | 8 | Author: DAV 9 | @stackoverflow: http://stackoverflow.com/questions/16992038/inline-labels-in-matplotlib 10 | """ 11 | from __future__ import absolute_import, division, print_function, unicode_literals 12 | 13 | from math import atan2 as _atan2, degrees as _degrees 14 | import numpy as _np 15 | import re as _re 16 | 17 | #Label line with line2D label data 18 | def labelLine(line,x,label=None,align=True,**kwargs): 19 | """Places a label on a line plot and orients it to run parallel with the line. 20 | 21 | Given a matplotlib Line instance and x-coordinate, places `label` at the x-coord 22 | on the given line and orientates it parallel to the line. 23 | 24 | Author: http://stackoverflow.com/questions/16992038/inline-labels-in-matplotlib 25 | 26 | Arguments: 27 | line: Matplotlib Line instance 28 | x: x-coordinate on the line at which the label will be positioned. 29 | label (str): The label to be added to the line. 30 | align (bool): whether or not to align the label parallel to the line 31 | 32 | """ 33 | 34 | ax = line.get_axes() 35 | xdata = line.get_xdata() 36 | ydata = line.get_ydata() 37 | 38 | if (x < xdata[0]) or (x > xdata[-1]): 39 | print('x label location is outside data range!') 40 | return 41 | 42 | #Find corresponding y co-ordinate and angle of the 43 | ip = 1 44 | for i in range(len(xdata)): 45 | if x < xdata[i]: 46 | ip = i 47 | break 48 | 49 | y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1]) 50 | 51 | if not label: 52 | label = line.get_label() 53 | 54 | if align: 55 | #Compute the slope 56 | dx = xdata[ip] - xdata[ip-1] 57 | dy = ydata[ip] - ydata[ip-1] 58 | ang = _degrees(_atan2(dy,dx)) 59 | 60 | #Transform to screen co-ordinates 61 | pt = _np.array([x,y]).reshape((1,2)) 62 | trans_angle = ax.transData.transform_angles(_np.array((ang,)),pt)[0] 63 | 64 | else: 65 | trans_angle = 0 66 | 67 | #Set a bunch of keyword arguments 68 | if 'color' not in kwargs: 69 | kwargs['color'] = line.get_color() 70 | 71 | if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs): 72 | kwargs['ha'] = 'center' 73 | 74 | if ('verticalalignment' not in kwargs) and ('va' not in kwargs): 75 | kwargs['va'] = 'center' 76 | 77 | if 'backgroundcolor' not in kwargs: 78 | kwargs['backgroundcolor'] = ax.get_axis_bgcolor() 79 | 80 | if 'clip_on' not in kwargs: 81 | kwargs['clip_on'] = True 82 | 83 | if 'zorder' not in kwargs: 84 | kwargs['zorder'] = 2.5 85 | 86 | ax.text(x,y,label,rotation=trans_angle,**kwargs) 87 | 88 | def labelLines(lines,align=True,xvals=None,**kwargs): 89 | """Version of labelLine that assigns labels for all lines 90 | in a plot. 91 | 92 | Similar to labelLine, except a list of lines is passed. 93 | 94 | Argumnets: 95 | lines (list): A list of the lines to be labeled. 96 | xvals: A list of x-coordinates where the labels should be anchored. 97 | """ 98 | 99 | 100 | 101 | ax = lines[0].get_axes() 102 | labLines = [] 103 | labels = [] 104 | 105 | #Take only the lines which have labels other than the default ones 106 | for line in lines: 107 | label = line.get_label() 108 | if "_line" not in label: 109 | labLines.append(line) 110 | labels.append(label) 111 | 112 | if xvals is None: 113 | xmin,xmax = ax.get_xlim() 114 | xvals = _np.linspace(xmin,xmax,len(labLines)+2)[1:-1] 115 | 116 | for line,x,label in zip(labLines,xvals,labels): 117 | labelLine(line,x,label,align,**kwargs) 118 | 119 | def make_line_label(fname): 120 | """Makes a string (label) by splitting a file name. 121 | 122 | Warning: 123 | A lot of this is hard coded to split according to certain filenaming 124 | conventions, separated by underscored. e.g. MyFile_part1_part2_part3.file 125 | So you should modify this to fit your own file naming 126 | convention. 127 | 128 | Todo: Rewrite this as a more generic function. 129 | 130 | Arguments: 131 | fname (str): Filename to create labels from. 132 | 133 | Author: DAV 134 | 135 | """ 136 | parts = [] 137 | # Passing a list of delimiters to the re.split function 138 | try: 139 | part1 = _re.split("[_.]", fname)[0] 140 | print(part1) 141 | parts.append(part1) 142 | except: 143 | print("Unable to extract file name parts as strings by splitting \ 144 | after first underscore") 145 | part1 = None 146 | 147 | try: 148 | part2 = _re.split("[_.]", fname)[1] 149 | print(part2) 150 | parts.append(part2) 151 | except: 152 | print("Unable to extract file name parts as strings by splitting \ 153 | after second underscore") 154 | part2 = None 155 | 156 | try: 157 | part3 = _re.split("[_.]", fname)[2] 158 | print(part3) 159 | parts.append(part3) 160 | except: 161 | print("Unable to extract file name parts as strings by splitting \ 162 | after third underscore") 163 | part3 = None 164 | 165 | print(parts) 166 | label = '_'.join(parts[1:]) 167 | 168 | print("FIGURE LABEL IS:", label) 169 | return label 170 | -------------------------------------------------------------------------------- /LSDPlottingTools/locationmap.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Location map. 4 | 5 | Plots a location map using the Cartopy package 6 | 7 | Install cartopy first for this to work. 8 | 9 | http://scitools.org.uk/cartopy/docs/v0.13/index.html 10 | 11 | Add annotations for locations using their lon/lats. 12 | 13 | Author: DAV 14 | 15 | """ 16 | 17 | import cartopy.feature as cfeature 18 | import cartopy.crs as ccrs 19 | import matplotlib.pyplot as plt 20 | import matplotlib.patches as patches 21 | 22 | 23 | from shapely.geometry.polygon import LinearRing 24 | from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter 25 | 26 | def location_map(extent, gazetter, offset=0.): 27 | """Plots a series of points marking towns/sample sites/locations etc 28 | given a dictionary of places and lat/lons. 29 | 30 | Arguments: 31 | extent (list): A list of the cooridinates of the bounding extent of the 32 | location map in format: [West, East, South, North] e.g.: 33 | [lonW, lonE, latS, latN] 34 | 35 | gazetter (dict): A dictionary of arbitrary length of the format: 36 | { 'Placename1' : (LATITUDE, LONGITUDE), 37 | 'Placename2' : (LATITUDE, LONGITUDE). 38 | and so on...} 39 | 40 | offset (float): Offset of the text label to the marker points, 41 | in degrees. 42 | 43 | Todo: Greying out the landmass appears to block out the marker points 44 | (weird...) so this has been commented out and you just get an 45 | outline map for now. 46 | 47 | Author: DAV 48 | 49 | """ 50 | ax = plt.axes(projection=ccrs.PlateCarree()) 51 | 52 | # Put a background image on for nice sea rendering. 53 | 54 | ax.coastlines('50m') 55 | # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth 56 | # DAV - 50m scale not enough for UK 57 | # Using '10m' works but too many boundaries as it defaults to unitary authorities 58 | # in England and Council areas in Wales/Scotland so appears way too cluttered. 59 | states_provinces = cfeature.NaturalEarthFeature( 60 | category='cultural', 61 | name='admin_1_states_provinces_lines', 62 | scale='50m', 63 | facecolor='none') 64 | 65 | # Add grey for the land 66 | land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m', 67 | edgecolor='face', 68 | facecolor=cfeature.COLORS['land']) 69 | 70 | ax.add_feature(states_provinces, edgecolor='gray') 71 | #ax.xaxis.set_visible(True) 72 | #ax.yaxis.set_visible(True) 73 | 74 | ax.set_yticks([50,54,58], crs=ccrs.PlateCarree()) 75 | ax.set_xticks([-6, -4, -2, 0], crs=ccrs.PlateCarree()) 76 | 77 | lon_formatter = LongitudeFormatter(zero_direction_label=True) 78 | lat_formatter = LatitudeFormatter() 79 | 80 | ax.xaxis.set_major_formatter(lon_formatter) 81 | ax.yaxis.set_major_formatter(lat_formatter) 82 | 83 | #ax.add_feature(land_50m, edgecolor='gray') 84 | 85 | for location in gazetter: 86 | plt.text(gazetter[location][1] - offset, gazetter[location][0] + offset, location, 87 | horizontalalignment='right', 88 | transform=ccrs.PlateCarree()) 89 | 90 | plt.scatter(gazetter[location][1], gazetter[location][0], 91 | color='black', marker='o', 92 | transform=ccrs.PlateCarree()) 93 | 94 | """ 95 | plt.text(boscastle_lon - 0.1, boscastle_lat + 0.1, 'Boscastle', 96 | horizontalalignment='right', 97 | transform=ccrs.PlateCarree()) 98 | 99 | plt.text(ryedale_lon + 0.3, ryedale_lat + 0.3, 'Helmsley', 100 | horizontalalignment='left', 101 | transform=ccrs.PlateCarree()) 102 | 103 | # Bug to fix. Markers do not appear when add_feature used above?? 104 | plt.scatter(boscastle_lon, boscastle_lat, 105 | color='black', marker='o', 106 | transform=ccrs.PlateCarree(), 107 | ) 108 | 109 | plt.scatter(ryedale_lon, ryedale_lat, 110 | color='black', marker='o', 111 | transform=ccrs.PlateCarree(), 112 | ) 113 | """ 114 | # Set the longitude and latitude extents [West, East, South, North] 115 | ax.set_extent(extent) 116 | 117 | # Draw a bounding box square 118 | """ 119 | lons = [-5.8, -5.8, -5.5, -5.5] 120 | lats = [50.27, 50.48, 50.48, 50.27] 121 | ring = LinearRing(list(zip(lons, lats))) 122 | ax.add_geometries([ring], ccrs.PlateCarree(), facecolor='none', edgecolor='blue') 123 | """ 124 | 125 | """This method didn't work 126 | # Add location rectangle 127 | rect = patches.Rectangle((-4,1),2,2,linewidth=1,edgecolor='r',facecolor='none') 128 | ax.add_patch(patches.Rectangle(xy=[1, 1], width=2, height=2, 129 | facecolor='blue', 130 | alpha=0.2, 131 | transform=ccrs.Robinson())) 132 | """ 133 | 134 | plt.show() 135 | -------------------------------------------------------------------------------- /LSDPlottingTools/setup_cython.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from distutils.extension import Extension 3 | from Cython.Build import cythonize 4 | 5 | ext_modules = [ 6 | Extension( 7 | "fast_hillshade", 8 | ["fast_hillshade.pyx"], 9 | extra_compile_args=['-fopenmp'], 10 | extra_link_args=['-fopenmp'], 11 | ) 12 | ] 13 | 14 | setup( 15 | name='fast_hillshade', 16 | ext_modules=cythonize(ext_modules), 17 | ) 18 | # build with python setup_cython.py build_ext --inplace 19 | -------------------------------------------------------------------------------- /LSDPlottingTools/smoothhillshade.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Feb 11 11:40:41 2017 5 | 6 | @author: dav 7 | """ 8 | 9 | import LSDPlottingTools.LSDMap_GDALIO as lsdio 10 | 11 | import numpy as np 12 | import scipy as sp 13 | 14 | 15 | Zenith = 45 16 | Azimuth = 315 17 | ZFactor = 1 18 | 19 | Directory = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/erode_diff/test_raster_diff_func/" 20 | BackgroundRasterName = "BoscastleElevations0.asc" 21 | 22 | File = Directory + BackgroundRasterName 23 | 24 | RasterData = lsdio.ReadRasterArrayBlocks(File) 25 | 26 | def Hillshade_Smooth(RasterData, altitude, azimuth, z_factor): 27 | """Plots a Hillshade a la LSDRaster""" 28 | 29 | zenith_rad = sp.deg2rad(altitude) 30 | azimuth_rad = sp.deg2rad(azimuth) 31 | 32 | 33 | -------------------------------------------------------------------------------- /LithoCHILD_to_Raster.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | """ 3 | Script that take the xyz output of Lithochild (Ask Emma for more info) and convert it to BIL raster. 4 | 5 | Created Today 6 | @author: Boris 7 | """ 8 | import pandas 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from scipy.interpolate import griddata 12 | import gdal, ogr, os, osr 13 | 14 | 15 | ########## Ignore this ######## 16 | def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array, nodata, EPSG): 17 | """This function take a regular array to create a raster with it""" 18 | print("I am dealing with nodata values") 19 | array[np.isnan(array)] = nodata # Dealing with Nodata values 20 | print("I am writing the raster") 21 | cols = array.shape[1] 22 | rows = array.shape[0] 23 | 24 | originX = rasterOrigin[0] 25 | originY = rasterOrigin[1] 26 | 27 | driver = gdal.GetDriverByName('ENVI') 28 | outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Float64) 29 | outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight)) 30 | outband = outRaster.GetRasterBand(1) 31 | #outband.SetNoDataValue(nodata) 32 | outband.WriteArray(array) 33 | #outband.SetNoDataValue(nodata) 34 | 35 | outRasterSRS = osr.SpatialReference() 36 | outRasterSRS.ImportFromEPSG(EPSG) 37 | 38 | outRaster.SetProjection(outRasterSRS.ExportToWkt()) 39 | 40 | outband.FlushCache() 41 | 42 | def adapatSeaLevel(arr,nodata): 43 | minimum_raster = np.nanmin(arr) 44 | if(minimum_raster<0 and minimum_raster != nodata): 45 | arr[arr[:,:]!=nodata] += -minimum_raster 46 | print("I Uplifted your raster to make the lowest value the new sea level. It works only if your raster reach the sea level. Deactivate me in the code if you don't want it") 47 | else: 48 | print("I didn't change your raster, are you sure it required a sea level rise???") 49 | return arr 50 | ############################################################## 51 | 52 | 53 | 54 | if __name__ == "__main__": # Ignore this line 55 | 56 | ########## Parameters ######## 57 | # Parameters I need 58 | 59 | print(" This script should take the output of lithochild and convert it to a bil ENVI raster ready for use with LSDTopoTools/MappingTool") 60 | 61 | Directory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # needed if the file is not in the same directory as the script 62 | csv_file = "beticstest5_ts11_xyz.txt" # name of the test file containing the data 63 | separator = ", " # string that separate the data /!\ in case, tabulation is \t /!\ 64 | raster_name = "Final.bil" 65 | EPSG = 32630 # EPSG code of your projection 66 | write_Directory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # the path were you want the file to be placed 67 | Sea_Level_rise = True # Adapt the sea level if True 68 | 69 | 70 | Xres = 10 # resolution on the X axis 71 | Yres = 10 # resolution for the Y axis (I haven't tested it yet on a non-square matrix) 72 | Xmin = 560488 # Xmin of your raster 73 | Xmax = 605518 # Xmax of your raster 74 | Ymin = 4086007 # Ymin of your raster 75 | Ymax = 4120537 # Ymax of your raster 76 | nodata = -1 # No data value 77 | 78 | ########## Python code, no more parameters to set ######## 79 | rasterOrigin = (Xmin, Ymax) # The origin of the raster is the upper left corner 80 | raster_output = write_Directory+raster_name 81 | hdr_name = raster_name[:-4]+".hdr" # Needed to deal with no data 82 | 83 | 84 | # Importing the files 85 | 86 | print("I am importing the data from csv with Pandas, ignore the warning if there is any") 87 | df = pandas.read_csv(Directory + csv_file, sep=separator) # Pandas is impressively fast 88 | print("I am done, I am now converting it into workable array") 89 | X = np.linspace(0,Xmax-Xmin,(Xmax-Xmin)/Xres) # creating the extent of the mesh 90 | Y = np.linspace(0,Ymax-Ymin,(Ymax-Ymin)/Yres) 91 | gridx,gridy = np.meshgrid(X,Y) # creating the mesh 92 | data = np.array(df.values) # Numpyisation of the data 93 | 94 | if(Sea_Level_rise): 95 | print(data) 96 | data = adapatSeaLevel(data, nodata) 97 | 98 | print("I have everything, I am now converting this irregular grid to a regular one %s/%s"%(Xres,Yres)) 99 | grid_z0 = griddata(data[:,0:2], data[:,2],(gridx,gridy) , method='linear') # interpolation, Linear look the more "natural" 100 | print("the minimum value is %s and the maximum is %s"%(np.nanmin(grid_z0),np.nanmax(grid_z0))) 101 | 102 | print("I am now creating and saving the raster in EPSG %s" %(EPSG)) 103 | grid_z0 = grid_z0[::-1] # inverting the array, required to make the raster 104 | array2raster(raster_output, rasterOrigin, Xres,Yres, grid_z0, nodata,EPSG) # Creating the raster 105 | print("OK, now I have to add nodata value at the hand of the hdr file because Gdal does not do it for some reason") 106 | #data ignore value = 0 107 | with open(write_Directory+hdr_name, "a") as myfile: 108 | myfile.write("data ignore value = " +str(nodata)) 109 | 110 | print("I am done. If your raster is empty (nan or -1 values) it might means that your X/Y coord./res. are not right. If the problem persists, well, try other things or ask Simon") 111 | -------------------------------------------------------------------------------- /LocationMapCartopy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Location map test script 4 | 5 | Plots a location map using the Cartopy package 6 | 7 | Install cartopy first for this to work. 8 | 9 | http://scitools.org.uk/cartopy/docs/v0.13/index.html 10 | 11 | Add annotations for locations using their lon/lats. 12 | 13 | Author: DAV 14 | 15 | """ 16 | 17 | import LSDPlottingTools.locationmap as locmap 18 | 19 | extent = [-7.5, 2, 50, 59] 20 | # Placename1 : (LATITUDE, LONGITUDE), Placename2... 21 | gazetter = { 'Boscastle' : (50.686, -4.692), 22 | 'Helmsley' : (54.246, -1.056) 23 | } 24 | 25 | locmap.location_map(extent, gazetter, offset = 0.1) -------------------------------------------------------------------------------- /MappingDriver.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Jan 27 10:17:29 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | from __future__ import print_function 9 | import sys 10 | import os 11 | import LSDPlottingTools as LSDPT 12 | 13 | 14 | 15 | 16 | #============================================================================= 17 | # This is the main function that runs the whole thing 18 | #============================================================================= 19 | def main(argv): 20 | 21 | # If there are no arguments, send to the welcome screen 22 | if not len(sys.argv) > 1: 23 | full_paramfile = print_welcome() 24 | #sys.exit() 25 | else: 26 | 27 | # Get the arguments 28 | import argparse 29 | parser = argparse.ArgumentParser() 30 | parser.add_argument("-pf", "--parameter_file",type=str, default="Params.param", 31 | help="The name, with extension and path, of your parameter file.") 32 | args = parser.parse_args() 33 | 34 | full_paramfile = args.parameter_file 35 | 36 | print("The full parameter file is: "+full_paramfile) 37 | 38 | # Now make a plotting driver object 39 | PD = LSDPT.LSDMap_PlottingDriver(full_paramfile) 40 | 41 | print(PD.FilePrefix) 42 | print(PD.FilePath) 43 | 44 | print("The plotting switches are: ") 45 | print(PD.plotting_switches) 46 | 47 | # Now make some plots!! 48 | PD.plot_data() 49 | 50 | #============================================================================= 51 | 52 | 53 | #============================================================================= 54 | # This is just a welcome screen that is displayed if no arguments are provided. 55 | #============================================================================= 56 | def print_welcome(): 57 | 58 | print("\n\n=======================================================================") 59 | print("Hello there, I am the going to help you plot LSDTopoTools data!") 60 | print("You will need to tell me where the parameter file is.") 61 | print("Use the -wd flag to define the working directory.") 62 | print("If you dont do this I will assume the data is in the same directory as this script.") 63 | print("=======================================================================\n\n ") 64 | 65 | from Tkinter import Tk 66 | from tkFileDialog import askopenfilename 67 | 68 | Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing 69 | filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file 70 | 71 | return filename 72 | 73 | 74 | 75 | #============================================================================= 76 | 77 | 78 | if __name__ == "__main__": 79 | main(sys.argv[1:]) -------------------------------------------------------------------------------- /Mapping_tools_plan.asc: -------------------------------------------------------------------------------- 1 | = Thoughts on developing the mapping tools 2 | 3 | This document is a place to put thoughts and a plan for developing the plotting tools. 4 | 5 | == Motivation 6 | 7 | [LSDTopoTools] spits out raster data and point data in the form of csv files. In the past, to look at this data we needed to use a GIS. Using GIS is a pain since: 8 | 9 | * It takes a long time to start up. 10 | * If you are running many analyses and want to just look at results it is a pain to keep loading data layers using mouse clicks. 11 | ** Whenever you load a data later you need to re-do all the styling. 12 | ** The csv import requires many, many mouse clicks. 13 | * You need to make lots of choices to generate a plot, so it is hard for two users to generate the same plot. 14 | 15 | So, we decided that using a programming language to plot the data was better since in might (in the long run) save time and in addition we could get totally reproducible plots. The added benefit would be that we could both give these script to other users and also it would help with teaching. 16 | 17 | Our mapping tools were born when SMM finally figured out how to get binary raster data in and out of python using GDAL. It probably would have taken DValts a few hours but this was a major challenge for SMM. But he got there in the end. 18 | 19 | Now we have a somewhat unwieldy plotting package that could do with some planning. Below are notes about the plan. 20 | 21 | == Basic observations 22 | 23 | * There are two time when we generally work on these scripts. We haven't really got a good balance between these things. 24 | ** When we have a paper or talk and we need a specific figure. This leads to quite specific sorts of code. 25 | ** When we need code for distribution or teaching. This leads to code that is complicated by efforts to stop it from breaking. 26 | 27 | * In making lots of plots for papers, it seems we are narrowing down to some common themes. 28 | ** There needs to be a simple way to plot multiple layers of rasters. 29 | ** There needs to be a simple way of labelling points or shapes. 30 | ** There needs to be a simple way of formatting the size of the figures (and the size of text, line weights, etc.) 31 | ** There needs to be a simple way of adding point data. 32 | ** There needs to be a simple way of having multiple plots. 33 | ** There needs to be a simple way to manage colour scales and colourbars. 34 | 35 | == Some sort of plan. 36 | 37 | * We should have basic building blocks for adding layers. Instead of many custom plots we should have one plotting function that can have up to X drapes. I have some plots with 4 raster layers (!!) but I can't see adding more than that without making it impossible to see anything. 38 | * We should also have basic building blocks for adding point data. 39 | * Labelling should be automated. 40 | 41 | Most of the above is covered in the basic observations topic. 42 | 43 | === What will these objects look like? 44 | 45 | Start writing here!! 46 | 47 | ### Drape plotter 48 | 49 | Design from the top down? How do you want the API to work? 50 | ``` 51 | # Minimal options should produce a decent looking default plot... 52 | myPlot = LSDplots.Drape(Filename, Directory, Colourmap=cmap, OtherDefaults=blah, etc ...) 53 | 54 | # oops I need to add another drape 55 | myplot.addRaster(Filename, other_options=foo) 56 | myplot.addPoints(Filename, options=etc) 57 | 58 | # But you can still tweak if you need to: 59 | # Object contains a list of Drapes/Layers that you can access: 60 | # The names are created based on the filename 61 | 62 | myPlot.Drape['water'].setCmap("rainbow") 63 | myPlot.Drape['erosion'].setCmap("jet") 64 | 65 | # Deafult sizing options 66 | myPlot.saveplot("ESurf_1col", "svg") 67 | myPlot.saveplot("Powerpoint", "png") 68 | 69 | # Tweak labels if you don't like the autogen ones 70 | myPlot.fig.setTitle("Blah") 71 | 72 | # Higher level functions for simplicity that group commonly used methods 73 | # Can be used for teaching and easy creation of commonly used plots. 74 | myChiPlot = ChiPlot(DirectoryWithAllNeededFiles), options_for_chi_defaults=defaults) 75 | myFloodPlot = FloodPlot(Directory) 76 | 77 | Etc.... 78 | -------------------------------------------------------------------------------- /Other/box_whisker.py: -------------------------------------------------------------------------------- 1 | # small tutorial to use pandas to create box and whisker plots 2 | import matplotlib 3 | matplotlib.use("Agg") 4 | 5 | from matplotlib import pyplot as plt 6 | import pandas as pd 7 | 8 | # first step: read the file you want the information 9 | ## you'll have to adapt the path of your file 10 | df = pd.read_csv("/home/s1675537/PhD/LSDTopoData/Chrystiann_Boris/movern_0.35/corsica_Mchi_Geology.csv") 11 | 12 | # your df (dataframe) now contains all the column and data of your csv file. 13 | # if you need to check the following command print the name of each columns: 14 | print(df.columns.values) 15 | 16 | # I assume you have your file with all the geology correspondances ? 17 | # you need to isolate the data bins you want 18 | # imagine I want to plot the m_chi repartition for my lithologies 5, 11 and 13/15 grouped together: I need a list of the arrays 19 | 20 | df_5 = df[df["geology"] == 5] # the logic is: df_5 is equal to the entire df WHERE the column "geology" is 5 21 | # df_5 now contains all the information of my original file, but just when the column geology was 5 22 | df_11 = df[df["geology"] == 11] # same logic 23 | 24 | df_13_15 = df[df["geology"].isin([13,15])] # the logic is slightly different when you want to check several values 25 | 26 | 27 | # I want now to gather everything in a "list of arrays" to plot: 28 | data_to_plot = [df_5["m_chi"], df_11["m_chi"], df_13_15["m_chi"]] # I only want the column m_chi 29 | # you want to name it as well, in the same order 30 | names = ["litho 5", "litho 11", "litho 13/15"] 31 | 32 | # ok now we are ready to plot: 33 | 34 | # Create a figure 35 | fig = plt.figure(1, figsize=(9, 6)) 36 | 37 | # Create an axes 38 | ax = fig.add_subplot(111) 39 | 40 | # Create the boxplot 41 | bp = ax.boxplot(data_to_plot, labels = names) 42 | 43 | # Save the figure 44 | fig.savefig('simple_boxplot.png', bbox_inches='tight') 45 | -------------------------------------------------------------------------------- /PlotDrainageCaptureMetrics.py: -------------------------------------------------------------------------------- 1 | #============================================================================= 2 | # Script to plot metrics for identifying drainage capture 3 | # 4 | # Authors: 5 | # Fiona J. Clubb 6 | #============================================================================= 7 | #============================================================================= 8 | # IMPORT MODULES 9 | #============================================================================= 10 | # set backend to run on server 11 | import matplotlib 12 | matplotlib.use('Agg') 13 | 14 | #from __future__ import print_function 15 | import sys 16 | import os 17 | from LSDPlottingTools import LSDMap_DrainageCapture as DC 18 | from LSDMapFigure import PlottingHelpers as Helper 19 | 20 | #============================================================================= 21 | # This is just a welcome screen that is displayed if no arguments are provided. 22 | #============================================================================= 23 | def print_welcome(): 24 | 25 | print("\n\n=======================================================================") 26 | print("Hello! I'm going to plot the drainage capture results for you.") 27 | print("You will need to tell me which directory to look in.") 28 | print("Use the -dir flag to define the working directory.") 29 | print("If you don't do this I will assume the data is in the same directory as this script.") 30 | print("For help type:") 31 | print(" python PlotMOverNAnalysis.py -h\n") 32 | print("=======================================================================\n\n ") 33 | 34 | #============================================================================= 35 | # This is the main function that runs the whole thing 36 | #============================================================================= 37 | def main(argv): 38 | 39 | # print("On some windows systems you need to set an environment variable GDAL_DATA") 40 | # print("If the code crashes here it means the environment variable is not set") 41 | # print("Let me check gdal enviroment for you. Currently is is:") 42 | # print(os.environ['GDAL_DATA']) 43 | #os.environ['GDAL_DATA'] = os.popen('gdal-config --datadir').read().rstrip() 44 | #print("Now I am going to get the updated version:") 45 | #print(os.environ['GDAL_DATA']) 46 | 47 | # If there are no arguments, send to the welcome screen 48 | if not len(sys.argv) > 1: 49 | full_paramfile = print_welcome() 50 | sys.exit() 51 | 52 | # Get the arguments 53 | import argparse 54 | parser = argparse.ArgumentParser() 55 | # The location of the data files 56 | parser.add_argument("-dir", "--base_directory", type=str, help="The base directory that contains your data files. If this isn't defined I'll assume it's the same as the current directory.") 57 | parser.add_argument("-fname", "--fname_prefix", type=str, help="The prefix of your DEM WITHOUT EXTENSION!!! This must be supplied or you will get an error (unless you're running the parallel plotting).") 58 | 59 | # These control the format of your figures 60 | parser.add_argument("-fmt", "--FigFormat", type=str, default='png', help="Set the figure format for the plots. Default is png") 61 | parser.add_argument("-size", "--size_format", type=str, default='ESURF', help="Set the size format for the figure. Can be 'big' (16 inches wide), 'geomorphology' (6.25 inches wide), or 'ESURF' (4.92 inches wide) (defualt esurf).") 62 | 63 | # what plots you want to make 64 | parser.add_argument("-P", "--plot_perimeter", type=bool, help="If this is true I'll make some plots of basin perimeters.") 65 | 66 | args = parser.parse_args() 67 | 68 | # get the base directory 69 | if args.base_directory: 70 | this_dir = args.base_directory 71 | # check if you remembered a / at the end of your path_name 72 | if not this_dir.endswith("/"): 73 | print("You forgot the '/' at the end of the directory, appending...") 74 | this_dir = this_dir+"/" 75 | else: 76 | this_dir = os.getcwd() 77 | 78 | # make the plots depending on your choices 79 | if args.plot_perimeter: 80 | DC.PlotBasinPerimeter(this_dir, args.fname_prefix, args.size_format, args.FigFormat) 81 | 82 | 83 | #============================================================================= 84 | if __name__ == "__main__": 85 | main(sys.argv[1:]) 86 | -------------------------------------------------------------------------------- /Rasterization.py: -------------------------------------------------------------------------------- 1 | #============================================================================= 2 | # Script to plot the litho information acquired from 3 | # 4 | # Authors: 5 | # Boris Gailleton, Simon Marius Mudd 6 | #============================================================================= 7 | #============================================================================= 8 | # IMPORT MODULES 9 | #============================================================================= 10 | # set backend to run on server 11 | import matplotlib 12 | matplotlib.use('Agg') 13 | 14 | #from __future__ import print_function 15 | import sys 16 | import os 17 | import subprocess 18 | from LSDPlottingTools import LSDMap_VectorTools as VT 19 | 20 | #============================================================================= 21 | # This is just a welcome screen that is displayed if no arguments are provided. 22 | #============================================================================= 23 | def print_welcome(): 24 | 25 | print("\n\n=======================================================================") 26 | print("Hello! I'm going to raterise a shapefile for you, the aim is to prepare it for LSDTT.") 27 | print("The LSDTopoTools MuddChi2014 repository can now ingest lithologic data from shapefiles.") 28 | print("This script creates a csv file that hold the correspondance between geologic ID and Code.") 29 | print("You will need to tell me the path and the prefix of your shapefile.") 30 | print("Use the -wd flag to define the working directory.") 31 | print("If you don't do this I will assume the data is in the same directory as this script.") 32 | print("A typical basic command would be:") 33 | print("python Rasterization.py -dir /home/PhilCollins/DataStore/GIS/US/ -fn beverly_litho -fd geology") 34 | print("A more complete one with more options:") 35 | print("python Rasterization.py -dir /home/PhilCollins/DataStore/GIS/Africa/ -fn Tanzania_litho -fd LITH -UTM 33 -SOUTH True -rn GeoRast -res 12") 36 | print("For help type:") 37 | print(" python Rasterization.py -h\n") 38 | print("=======================================================================\n\n ") 39 | 40 | #============================================================================= 41 | # This is the main function that runs the whole thing 42 | #============================================================================= 43 | def main(argv): 44 | 45 | # print("On some windows systems you need to set an environment variable GDAL_DATA") 46 | # print("If the code crashes here it means the environment variable is not set") 47 | # print("Let me check gdal enviroment for you. Currently is is:") 48 | # print(os.environ['GDAL_DATA']) 49 | #os.environ['GDAL_DATA'] = os.popen('gdal-config --datadir').read().rstrip() 50 | #print("Now I am going to get the updated version:") 51 | #print(os.environ['GDAL_DATA']) 52 | 53 | # If there are no arguments, send to the welcome screen 54 | if not len(sys.argv) > 1: 55 | full_paramfile = print_welcome() 56 | sys.exit() 57 | 58 | # Get the arguments 59 | import argparse 60 | parser = argparse.ArgumentParser() 61 | # The location of the data files 62 | parser.add_argument("-dir", "--directory", type=str, help="The base directory with the shapefile. If this isn't defined I'll assume it's the same as the current directory.") 63 | parser.add_argument("-fn", "--fname_prefix", type=str, help="The name of your shapefile without extention (no .shp at the end)") 64 | parser.add_argument("-fd", "--field_name", type=str, default = "", help="The name of the field that will give the value to the raster") 65 | parser.add_argument("-rast", "--rasterization", type = bool, default = True, help= "Rasterize your file into a tif raster and produce a lithokey csv file containing the keys for the numerisation of the data.") 66 | parser.add_argument("-rn","--rename", type=str, default = "", help = "rename your raster after rasterization, optional.") 67 | parser.add_argument("-UTM", "--UTM_CODE", type = str, default = "", help = "Give the UTM UTM_CODE of your zone to automate the conversion of the raster into an LSDTopoTools compatible raster.") 68 | parser.add_argument("-S", "--SOUTH", type = bool, default = False, help = "Turn to True if your UTM zone is in the southern hemisphere. A quick way to check that is to go on field and to observe how flow the water in a ") 69 | parser.add_argument("-res", "--resolution", type = int, default = 30, help = "Precise this argument if you want to change the raster resolution, default 30") 70 | args = parser.parse_args() 71 | #============================================================================= 72 | rast_name = "" 73 | rast_pre = "" 74 | if((not args.directory) or (not args.fname_prefix)): 75 | print("You need to feed me with a shapefile, try python Rasterization -dir /path/to/your/file/ -fn shapefile.shp") 76 | sys.exit() 77 | 78 | if(args.rasterization): 79 | if(args.field_name == ""): 80 | print("FATAL ERROR: You need to gives me the Field name you wanna rasterize. This field will give its value or a code value to the raster. The field name is in the attributary table of your shapefile.") 81 | sys.exit() 82 | #launching the rasterization 83 | # fd_name_corr = args.field_name.encode('utf-8') 84 | VT.rasterize_shapefile(args.directory + args.fname_prefix + ".shp", res = args.resolution, field = args.field_name) 85 | #getting file names and prefix 86 | rast_name = args.fname_prefix + "_new2.tif" 87 | rast_pre = args.fname_prefix + "_new2" 88 | #Renaming in case you want to 89 | if(args.rename != ""): 90 | os.rename(args.directory + rast_name,args.directory+args.rename+".tif") 91 | # updating the file name and prefix 92 | rast_name = args.rename+".tif" 93 | rast_pre = args.rename 94 | 95 | if(args.UTM_CODE != ""): 96 | #Conversion to UTM 97 | if(args.SOUTH): 98 | south_string = " +south" 99 | else: 100 | south_string = "" 101 | # preparing the gdalwarp command 102 | gdal_cmd = "gdalwarp -t_srs '+proj=utm +zone=%s%s +datum=WGS84' -of ENVI -tr %s %s %s %s" % (args.UTM_CODE,south_string,args.resolution,args.resolution,args.directory+rast_name, args.directory+rast_pre+'_rast.bil') 103 | print("You choose to convert your file, I am generating a gdalwarp command from your information hopefully you won't have errors.") 104 | print(gdal_cmd) 105 | subprocess.call(gdal_cmd, shell=True) 106 | print("Your raster is now ready to use with LSDTopotools, congrats") 107 | 108 | 109 | 110 | 111 | if __name__ == "__main__": 112 | main(sys.argv[1:]) -------------------------------------------------------------------------------- /TUTO_Mapping_Tool.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created. 4 | 5 | @author: Boris 6 | """ 7 | # WARNING, if you have $DISLPLAY$ error messages, or if the script run but does not plot anything, uncomment the following lines: 8 | # import matplotlib 9 | # matplotlib.use('Agg') 10 | from matplotlib import pyplot as plt 11 | import time as clock 12 | from matplotlib import rcParams 13 | import matplotlib.cm as cm 14 | import LSDPlottingTools as LSDP 15 | from LSDPlottingTools import colours as lsdcolours 16 | from LSDPlottingTools import init_plotting_DV 17 | from LSDMapFigure.PlottingRaster import MapFigure 18 | from LSDMapFigure.PlottingRaster import BaseRaster 19 | 20 | 21 | import pandas as bamboo_bears 22 | import sys 23 | 24 | #rcParams['font.family'] = 'sans-serif' 25 | #rcParams['font.sans-serif'] = ['Liberation Sans'] 26 | #rcParams['font.size'] = label_size 27 | #rcParams['lines.linewidth'] = 1.5 28 | 29 | ###### Parameters ###### 30 | Directory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # reading directory (if it is on windows, the path is something like C://windows/Users/blablalba/) 31 | wDirectory = "/home/s1675537/PhD/DataStoreBoris/Emma/" # writing directory (if it is on windows, the path is something like C://windows/Users/blablalba/) 32 | Base_file = "Betics_UTM30clip_PP" # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata 33 | csv_file = Directory + "new.csv" # Name of your point file, add a similar line with different name if you have more than one point file 34 | DrapeRasterName = "Betics_UTM30clip_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 35 | wname = "output" # name of your output file 36 | dpi = 300 # Quality of your output image, don't exceed 900 37 | fig_size_inches = 9 # Figure size in Inches 38 | 39 | 40 | 41 | ##### Now we can load and plot the data 42 | 43 | BackgroundRasterName = Base_file + ".bil" # Ignore this line 44 | 45 | # There are several way to load point data: Most of the time you will want to 46 | # directly load a csv_file as follow: 47 | thisPointData = LSDP.LSDMap_PointData(csv_file,data_type = 'csv', PANDEX = True) # Load the point file #1, add a similar line with different name if you have more than one point file. 48 | # But you can also load your file as a pandas dataframe, that allows you to sort your dataset first using pandas: 49 | # df = bamboo_bears.read_csv(csv_file, sep = ',') 50 | # df = df[df['elevation'] >50] # I am selecting all the points over 50 meters 51 | # thisPointData = LSDP.LSDMap_PointData(csv_file,data_type = 'pandas', PANDEX = True) # I am loading diretly a pandas dataframe rather than the csv_file 52 | 53 | 54 | ######## Now plotting the different layers ########### 55 | # Note that you can add as much rasters and points data as you want by just copying-pasting the add_drape_image and add_point_data functions 56 | # You just have to adapt the parameters and load the new data earlier in the script 57 | 58 | plt.clf() # Ignore this line, this is to make sure you're creating a brand new figure 59 | MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km", NFF_opti = True) # load the background raster 60 | 61 | MF.add_drape_image(DrapeRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one 62 | 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 63 | alpha = 0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque 64 | show_colourbar = False, # Well, this one is explicit I think 65 | colorbarlabel = "Colourbar", # Name of your Colourbar, it might bug though 66 | NFF_opti = True, 67 | colour_min_max = []) 68 | 69 | 70 | 71 | MF.add_point_data( thisPointData, # this function plot the requested point file using the lat/long column in the csv file 72 | column_for_plotting = "chi", # Column used to color the data 73 | 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 74 | colorbarlabel = "Colourbar", # Label 75 | scale_points = False, # All the point will have the same size if False 76 | column_for_scaling = "None", # If scale point True, you can scale the size of your points using one of the columns 77 | scaled_data_in_log = False, # If scale point True, you can log the scaling 78 | max_point_size = 5, # max size if scale point True again 79 | min_point_size = 0.5, # You should be able to guess that one now 80 | colour_log = False, # do you want a log scale for your colorbar ? 81 | colour_manual_scale = [], #Do you want to manually limit the scale of your colorbar? if not let is false 82 | manual_size = 0.5, # If none of above is choosen but you want to put another value than 0.5 to scale your point 83 | alpha = 1, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque 84 | minimum_log_scale_cut_off = -10) # you probably won't need this 85 | 86 | 87 | ImageName = wDirectory+str(int(clock.time()))+wname+".png" # Ignore this 88 | ax_style = "Normal" # Ignore this 89 | MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = dpi) # Save the figure 90 | -------------------------------------------------------------------------------- /TestGDALBatch.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Sep 10 09:28:53 2015 4 | 5 | @author: smudd 6 | """ 7 | 8 | #============================================================================== 9 | # These are some scripts for testing the functionality of LSDMappingTools 10 | #============================================================================== 11 | # -*- coding: utf-8 -*- 12 | """ 13 | Created on 9 July 2015 14 | 15 | @author: smudd 16 | """ 17 | 18 | import numpy as np 19 | import LSDGDALBatchProcessing as GDALbatch 20 | 21 | def TestGDALBatch(): 22 | 23 | # Set up the test folders and parameters 24 | DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/Chile_paper/SRTM_30metre/North_tiles" 25 | raster_format = "EHdr" 26 | target_format = "GTiff" 27 | merge_subfolder_name = "North_merged" 28 | merge_filename = "ChileNorthMerged" 29 | 30 | GDALbatch.GDALBatchMerge(DataDirectory,merge_subfolder_name,merge_filename,raster_format,target_format) 31 | 32 | 33 | if __name__ == "__main__": 34 | TestGDALBatch() -------------------------------------------------------------------------------- /Tests/LSDMappingTools_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a tester function for some of the mapping scripts 3 | 4 | Author: SMM 5 | 6 | Date 05/01/2018 7 | """ 8 | 9 | 10 | 11 | 12 | 13 | import sys 14 | import os 15 | 16 | 17 | 18 | def set_path(): 19 | """ 20 | This ensures that the path is included to the LSDMappingTools packages. 21 | It avoids a complicated pip installation but you need the LSDTT environment working. 22 | 23 | Author: SMM 24 | Date 08/01/2018 25 | 26 | """ 27 | # We need to import the path since we don't install mapping tools directly 28 | this_dir = os.getcwd() 29 | print("This dir is: "+this_dir) 30 | 31 | LSDMT_dir = this_dir.split(os.sep) 32 | 33 | LSDMT_dir = LSDMT_dir[:-1] 34 | LSDMT_path = (os.sep).join(LSDMT_dir) 35 | 36 | print("The path is: "+LSDMT_path) 37 | sys.path.append(LSDMT_path) 38 | 39 | 40 | def print_welcome(): 41 | """ 42 | This displays a welcome screen. 43 | 44 | Author: SMM and FJC 45 | Date: 08/01/2018 46 | """ 47 | 48 | print("\n\n=======================================================================") 49 | print("Hello! I'm going to test if your LSDTopoTools python enviroment is working.") 50 | print("You need to tell me what analysis to do:") 51 | print("1 = Basic hillshade map") 52 | print("2 = Map with some basins") 53 | print("3 = Map wit a channel network") 54 | print("Run with: python Mapping_test.py 1 ") 55 | print("The outputs can be found as files in this folder.") 56 | print("=======================================================================\n\n ") 57 | 58 | 59 | 60 | def main(argv): 61 | """ 62 | The main driving function. 63 | 64 | Author: SMM 65 | Date: 08/01/2018 66 | """ 67 | 68 | if len(argv) == 0: 69 | print_welcome() 70 | quit() 71 | else: 72 | print("Let me load the LSDMappingTools functions for you.") 73 | set_path() 74 | 75 | 76 | print("Let me check the fonts. They are:") 77 | import matplotlib.font_manager as fm 78 | flist = fm.get_fontconfig_fonts() 79 | names = [fm.FontProperties(fname=fname).get_family() for fname in flist] 80 | print(names) 81 | 82 | fm.findfont('Liberation Sans',rebuild_if_missing=True) 83 | 84 | print("The arguments are: ") 85 | print(argv) 86 | 87 | # import Maping tools 88 | import LSDMapWrappers as LSDMW 89 | DataDir = os.getcwd()+os.sep 90 | DataFname = "WA" 91 | 92 | argv[0] = int(argv[0]) 93 | 94 | if argv[0] == 1: 95 | print("Getting basic hillshade") 96 | LSDMW.SimpleHillshade(DataDir,DataFname) 97 | elif argv[0] == 2: 98 | print("Plotting some basins") 99 | LSDMW.PrintBasins(DataDir,DataFname) 100 | elif argv[0] == 3: 101 | print("Plotting the channels") 102 | LSDMW.PrintChannels(DataDir,DataFname) 103 | else: 104 | print("I didn't understand what you wanted.") 105 | print("Your choice was:" + str(argv[0])) 106 | 107 | 108 | 109 | 110 | #============================================================================= 111 | if __name__ == "__main__": 112 | main(sys.argv[1:]) -------------------------------------------------------------------------------- /Tests/WA.bil: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/Tests/WA.bil -------------------------------------------------------------------------------- /Tests/WA.hdr: -------------------------------------------------------------------------------- 1 | ENVI 2 | description = { 3 | WA2.bil} 4 | samples = 483 5 | lines = 643 6 | bands = 1 7 | header offset = 0 8 | file type = ENVI Standard 9 | data type = 4 10 | interleave = bsq 11 | byte order = 0 12 | map info = {UTM, 1, 1, 527347, 6190995, 5.00207039337474, 5.00155520995334, 30, North,WGS-84} 13 | coordinate system string = {PROJCS["WGS_1984_UTM_Zone_30N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]} 14 | band names = { 15 | Band 1} 16 | data ignore value = -9999 17 | -------------------------------------------------------------------------------- /Tests/WA_AllBasins.bil: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/Tests/WA_AllBasins.bil -------------------------------------------------------------------------------- /Tests/WA_AllBasins.hdr: -------------------------------------------------------------------------------- 1 | ENVI 2 | description = { 3 | WA_FifthExample_AllBasins.bil} 4 | samples = 483 5 | lines = 643 6 | bands = 1 7 | header offset = 0 8 | file type = ENVI Standard 9 | data type = 4 10 | interleave = bsq 11 | byte order = 0 12 | map info = {UTM, 1, 1, 527347, 6190995, 5.00207039337474, 5.00155520995334, 30, North,WGS-84} 13 | coordinate system string = {PROJCS["WGS_1984_UTM_Zone_30N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]} 14 | data ignore value = -9999 15 | -------------------------------------------------------------------------------- /Tests/WA_AllBasinsInfo.csv: -------------------------------------------------------------------------------- 1 | latitude,longitude,outlet_latitude,outlet_longitude,outlet_junction,basin_key 2 | 55.8501823,-2.55134279,55.8510715,-2.54757795,15,0 3 | 55.8507,-2.53352041,55.8505689,-2.53448033,17,1 4 | 55.8420001,-2.53769768,55.8458291,-2.54044909,20,2 5 | -------------------------------------------------------------------------------- /Tests/WA_hs.bil: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/Tests/WA_hs.bil -------------------------------------------------------------------------------- /Tests/WA_hs.hdr: -------------------------------------------------------------------------------- 1 | ENVI 2 | description = { 3 | WA_FirstExample_hs.bil} 4 | samples = 483 5 | lines = 643 6 | bands = 1 7 | header offset = 0 8 | file type = ENVI Standard 9 | data type = 4 10 | interleave = bsq 11 | byte order = 0 12 | map info = {UTM, 1, 1, 527347, 6190995, 5.00207039337474, 5.00155520995334, 30, North,WGS-84} 13 | coordinate system string = {PROJCS["WGS_1984_UTM_Zone_30N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]} 14 | data ignore value = -9999 15 | -------------------------------------------------------------------------------- /conda_environments/conda_environment_notes.asc: -------------------------------------------------------------------------------- 1 | = Using miniconda to get LSDMappingTools working on Edinburgh servers 2 | 3 | == Before you do anything 4 | 5 | Below you will be asked to edit your `.bashrc` file. 6 | Your `.bashrc` file is in your home directory. You can always get to your home directory with: 7 | 8 | [source,console] 9 | ---- 10 | $ cd ~ 11 | ---- 12 | 13 | Once you are there, make a copy of this file: 14 | 15 | [source,console] 16 | ---- 17 | $ cp .bashrc old.bashrc 18 | ---- 19 | 20 | Now you can edit the `.bashrc` file using `vim` or `emacs`. I like `vim` but you should read a tutorial before you start it because it is not intuative! 21 | To open the file with `vim` use: 22 | 23 | [source,console] 24 | ---- 25 | $ vim .bashrc 26 | ---- 27 | 28 | You can also edit this file with a text editor. It is *essential* that the file is in Unix format. See this https://kb.iu.edu/d/acux[tutorial for more information]. 29 | 30 | == If you have access to LSDTopoData 31 | 32 | .How do I get access? 33 | *************************** 34 | For various IT reasons, undergraduates and taught master's students (that is, any master's degree except master's by research) do not have access to the group datastores. I am sure there is a good IT reason why this is the case, and getting the policy changed would either be extremely time consuming or impossible. If you are in this category skip to the section about not having access. 35 | 36 | If you are a PhD student, staff or visiting researcher, then email Simon to get access. 37 | *************************** 38 | 39 | Okay, if you have access to *LSDTopoData*, do the following: 40 | 41 | 1. You need to update your path in your .bashrc file. To do that, include this line: 42 | `export PATH="/exports/csce/datastore/geos/groups/LSDTopoData/miniconda/miniconda3/bin:$PATH"` 43 | 2. Go onto one of our servers. 44 | 3. Type `source activate LSDMT3` 45 | 4. You are finished, but to use *LSDMappingTools*, you need to get them. Use git to clone the repository 46 | + 47 | [source, console] 48 | ---- 49 | $ git clone https://github.com/LSDtopotools/LSDMappingTools.git 50 | ---- 51 | + 52 | 5. To run the mapping scripts you need to go into the `LSDMappingTools` directory and run them while in the *LSDMT3* environment. 53 | 54 | === Notes for Simon 55 | 56 | These are notes for Simon that he uses to remember what he did. If you are not Simon you can ignore. 57 | 58 | 59 | . First I needed to get Miniconda in LSDTopoData: 60 | + 61 | [source,console] 62 | ---- 63 | $ cd miniconda 64 | $ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh 65 | $ sh Miniconda3-latest-Linux-x86_64.sh 66 | ---- 67 | + 68 | . In the command prompt, it asked for a location of miniconda 3. Use the location in LSDTopoData: 69 | `/exports/csce/datastore/geos/groups/LSDTopoData/miniconda/miniconda3` 70 | + 71 | . I created a new environment. 72 | + 73 | [source,console] 74 | ---- 75 | conda create -n LSDMT3 python=3.6.7 76 | ---- 77 | + 78 | . I then spent ages trying to get it to work because python GDAL is evil. 79 | . Finally, when it worked, I exported the conda environment: `conda env export > environment.yml` 80 | 81 | ==== Exporting from Docker 82 | 83 | If you have a functioning docker environment, you can export the environment with: 84 | + 85 | [source,console] 86 | ---- 87 | $ conda list --explicit > Conda_explicit_list.txt 88 | ---- 89 | + 90 | This file can be used to create an environment with: 91 | + 92 | [source,console] 93 | ---- 94 | $ conda create --name --file 95 | ---- 96 | 97 | 98 | 99 | == Getting miniconda and an environment working on a machine without access to LSDTopoData (i.e. MSc and BSc students) 100 | 101 | . Go into your directory that has the most space. Usually this is your datastore directory. 102 | + 103 | . Make a directory for miniconda, then download miniconda into it: 104 | + 105 | [source,console] 106 | ---- 107 | $ mkdir miniconda 108 | $ cd miniconda 109 | ---- 110 | + 111 | . Figure out where you are: 112 | + 113 | [source,console] 114 | ---- 115 | $ pwd 116 | ---- 117 | + 118 | . Copy the resulting path. You will use this in a second. 119 | + 120 | . Now get miniconda: 121 | + 122 | [source,console] 123 | ---- 124 | $ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh 125 | $ sh Miniconda3-latest-Linux-x86_64.sh 126 | ---- 127 | + 128 | . Now in the command prompt, it will ask for a location of miniconda 3. Use the location that `pwd` just gave you (a few steps earlier) 129 | + 130 | . You need to update your path in your .bashrc file. 131 | Include this line `export PATH="/your/path/to/miniconda/miniconda3/bin:$PATH"` 132 | + 133 | . IMPORTANT: you need to change the path so it reflects your directories!!! But you do need to include the `/bin` part of the above path. 134 | + 135 | . Then you can create the environment from an environment file. The one you want is the `conda_list_July2019.txt` in this directory. 136 | https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-from-an-environment-yml-file 137 | + 138 | . You can do this with: 139 | + 140 | [source,console] 141 | ---- 142 | $ wget https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/master/conda_environments/LSDMT_version_0.2.2.txt 143 | $ conda create --name LSDMT3 --file LSDMT_version_0.2.2.txt 144 | ---- 145 | + 146 | . This will take ages. When it is finished you can activate it with 147 | + 148 | [source,console] 149 | ---- 150 | conda activate LSDMT3 151 | ---- 152 | + 153 | . Type `source activate LSDMT3` 154 | . You are finished, but to use *LSDMappingTools*, you need to get them. Use git to clone the repository 155 | + 156 | [source, console] 157 | ---- 158 | $ git clone https://github.com/LSDtopotools/LSDMappingTools.git 159 | ---- 160 | + 161 | . To run the mapping scripts you need to go into the `LSDMappingTools` directory and run them while in the *LSDMT3* environment. 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /conda_environments/environment_linux32.yml: -------------------------------------------------------------------------------- 1 | name: LSDTT 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - affine=2.1.0=py_1 7 | - attrs=17.4.0=py_0 8 | - botocore=1.7.40=py_0 9 | - backports=1.0=py27hb64581b_1 10 | - backports.functools_lru_cache=1.4=py27h6ceb8f2_1 11 | - backports_abc=0.5=py27h9bc149d_0 12 | - boto3=1.4.7=py27h4c58894_0 13 | - bzip2=1.0.6=h1033540_2 14 | - ca-certificates=2017.08.26=h1d4fec5_0 15 | - cairo=1.14.10=h3f859d5_6 16 | - certifi=2017.11.5=py27ha9b69e6_0 17 | - click=6.7=py27h2a74859_0 18 | - click-plugins=1.0.3=py27_0 19 | - cligj=0.4.0=py27_0 20 | - curl=7.55.1=h04b7030_4 21 | - cycler=0.10.0=py27h2f912ad_0 22 | - dbus=1.10.22=ha863c99_0 23 | - docutils=0.14=py27hd690462_0 24 | - enum34=1.1.6=py27h85d59be_1 25 | - expat=2.2.5=h8d48cb0_0 26 | - fiona=1.7.10=py27h461359b_0 27 | - fontconfig=2.12.4=hcb742b8_1 28 | - freetype=2.8=hb4d7b56_1 29 | - freexl=1.0.4=h1553392_5 30 | - functools32=3.2.3.2=py27h21e16bb_1 31 | - futures=3.2.0=py27h3a05955_0 32 | - gdal=2.2.2=py27h9ee7b5a_1 33 | - geos=3.6.2=hce6ee14_2 34 | - giflib=5.1.4=hc3055b9_1 35 | - glib=2.53.6=hd466c72_1 36 | - gst-plugins-base=1.12.2=h3b3eec3_0 37 | - gstreamer=1.12.2=ha52c2f3_0 38 | - hdf4=4.2.13=h9ab743b_2 39 | - hdf5=1.10.1=h6d659dd_1 40 | - icu=58.2=he175447_1 41 | - intel-openmp=2018.0.0=h172fb5a_8 42 | - jmespath=0.9.3=py27h83a56e6_0 43 | - jpeg=9b=h29c5dd3_2 44 | - json-c=0.12.1=h93d433d_2 45 | - kealib=1.4.7=h7f80bf6_5 46 | - krb5=1.14.2=h5e1dbc0_6 47 | - libboost=1.65.1=h4826c2f_3 48 | - libdap4=3.19.0=hdc7ad4e_1 49 | - libedit=3.1=h9ac1fc1_0 50 | - libffi=3.2.1=h97ff0df_4 51 | - libgcc-ng=7.2.0=h7cc24e2_2 52 | - libgdal=2.2.2=h8061cce_1 53 | - libgfortran-ng=7.2.0=h9f7466a_2 54 | - libkml=1.3.0=h89d4305_3 55 | - libnetcdf=4.4.1.1=hf3509c5_8 56 | - libpng=1.6.32=h55ee776_4 57 | - libpq=9.6.6=hc4aea73_0 58 | - libspatialite=4.3.0a=h15e0c37_18 59 | - libssh2=1.8.0=hcf52db8_3 60 | - libstdcxx-ng=7.2.0=h7a57d05_2 61 | - libtiff=4.0.9=hb474d08_0 62 | - libxcb=1.12=h2ed087e_4 63 | - libxml2=2.9.4=h078cfa5_6 64 | - matplotlib=2.1.1=py27h0128e01_0 65 | - mkl=2018.0.1=h4fb54b9_4 66 | - munch=2.2.0=py27_0 67 | - ncurses=6.0=h8a800b7_2 68 | - numpy=1.13.3=py27h23621b1_0 69 | - openjpeg=2.2.0=hf9a27ac_2 70 | - openssl=1.0.2n=hb7f436b_0 71 | - pandas=0.22.0=py27hf484d3e_0 72 | - pcre=8.41=he509c7b_1 73 | - pip=9.0.1=py27h2c55c04_4 74 | - pixman=0.34.0=h8c3645b_3 75 | - poppler=0.60.1=h39486bb_0 76 | - poppler-data=0.4.8=hf2eda46_0 77 | - proj4=4.9.3=hf7341f3_7 78 | - pyparsing=2.2.0=py27h7e35c21_0 79 | - pyproj=1.9.5.1=py27_0 80 | - pyqt=5.6.0=py27he5ca9ac_5 81 | - python=2.7.14=h1571d57_29 82 | - python-dateutil=2.6.1=py27h143d6b4_1 83 | - pytz=2017.3=py27hca1c9f7_0 84 | - qt=5.6.2=h6a616b1_12 85 | - rasterio=0.36.0=py27h1e0aa59_1 86 | - readline=7.0=h6b4b497_4 87 | - s3transfer=0.1.11=py27hdf004a1_1 88 | - scipy=1.0.0=py27h8d5cafe_0 89 | - setuptools=36.5.0=py27hdccd021_0 90 | - shapely=1.6.2=py27h742fbfe_0 91 | - singledispatch=3.4.0.3=py27hdadf425_0 92 | - sip=4.18.1=py27ha738a01_2 93 | - six=1.11.0=py27h0b002a5_1 94 | - snuggs=1.4.1=py27h8c3aae4_0 95 | - sqlite=3.20.1=h27bc12f_2 96 | - ssl_match_hostname=3.5.0.1=py27h04b2e81_2 97 | - subprocess32=3.2.7=py27h81a5196_0 98 | - tk=8.6.7=h9a736a7_3 99 | - tornado=4.5.2=py27h35f098b_0 100 | - util-linux=2.21=0 101 | - wheel=0.30.0=py27h13c6743_1 102 | - xerces-c=3.2.0=h7bc921d_2 103 | - xz=5.2.3=ha3e1f4e_2 104 | - zlib=1.2.11=h907e355_2 105 | - pip: 106 | - backports-abc==0.5 107 | - backports.functools-lru-cache==1.4 108 | - backports.ssl-match-hostname==3.5.0.1 109 | prefix: ~/miniconda2/envs/LSDTT 110 | 111 | -------------------------------------------------------------------------------- /conda_environments/environment_linux64.yml: -------------------------------------------------------------------------------- 1 | name: LSDTT 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - affine=2.1.0=py_1 7 | - backports_abc=0.5=py27_0 8 | - basemap=1.1.0=py27_2 9 | - blas=1.1=openblas 10 | - boost=1.64.0=py27_4 11 | - boost-cpp=1.64.0=1 12 | - boto3=1.4.7=py27_0 13 | - botocore=1.5.92=py27_0 14 | - bzip2=1.0.6=1 15 | - ca-certificates=2017.7.27.1=0 16 | - cairo=1.14.6=4 17 | - certifi=2017.7.27.1=py27_0 18 | - click=6.7=py27_0 19 | - click-plugins=1.0.3=py27_0 20 | - cligj=0.4.0=py27_0 21 | - curl=7.54.1=0 22 | - cycler=0.10.0=py27_0 23 | - dbus=1.10.22=0 24 | - docutils=0.14=py27_0 25 | - enum34=1.1.6=py27_1 26 | - expat=2.1.0=3 27 | - fiona=1.7.9=py27_1 28 | - fontconfig=2.12.1=4 29 | - freetype=2.7=1 30 | - freexl=1.0.2=2 31 | - functools32=3.2.3.2=py27_1 32 | - futures=3.0.5=py27_0 33 | - gdal=2.1.3=py27_5 34 | - geos=3.5.1=1 35 | - gettext=0.19.7=1 36 | - giflib=5.1.4=0 37 | - glib=2.51.4=0 38 | - gst-plugins-base=1.8.0=0 39 | - gstreamer=1.8.0=2 40 | - hdf4=4.2.12=0 41 | - hdf5=1.8.18=0 42 | - hypothesis=3.23.0=py27_0 43 | - icu=58.1=1 44 | - jmespath=0.9.3=py27_0 45 | - jpeg=9b=1 46 | - json-c=0.12.1=0 47 | - kealib=1.4.7=2 48 | - krb5=1.14.2=0 49 | - libdap4=3.18.3=2 50 | - libffi=3.2.1=3 51 | - libgdal=2.1.4=2 52 | - libiconv=1.14=4 53 | - libkml=1.3.0=0 54 | - libnetcdf=4.4.1.1=5 55 | - libpng=1.6.28=0 56 | - libpq=9.6.3=0 57 | - libspatialite=4.3.0a=15 58 | - libssh2=1.8.0=1 59 | - libtiff=4.0.6=7 60 | - libxcb=1.12=1 61 | - libxml2=2.9.5=0 62 | - matplotlib=2.0.2=py27_2 63 | - munch=2.2.0=py27_0 64 | - ncurses=5.9=10 65 | - numpy=1.13.3=py27_blas_openblas_200 66 | - openblas=0.2.19=2 67 | - openjpeg=2.1.2=3 68 | - openssl=1.0.2l=0 69 | - pandas=0.20.3=py27_1 70 | - pcre=8.39=0 71 | - pip=9.0.1=py27_0 72 | - pixman=0.34.0=0 73 | - poppler=0.52.0=2 74 | - poppler-data=0.4.7=0 75 | - proj4=4.9.3=4 76 | - pympler=0.5=py27_0 77 | - pyparsing=2.2.0=py27_0 78 | - pyproj=1.9.5.1=py27_0 79 | - pyqt=5.6.0=py27_4 80 | - pyshp=1.2.12=py_0 81 | - python=2.7.13=1 82 | - python-dateutil=2.6.1=py27_0 83 | - pytz=2017.2=py27_0 84 | - qt=5.6.2=3 85 | - rasterio=0.36.0=py27_0 86 | - readline=6.2=0 87 | - s3transfer=0.1.11=py27_0 88 | - scipy=0.19.1=py27_blas_openblas_202 89 | - setuptools=36.3.0=py27_0 90 | - shapely=1.6.1=py27_1 91 | - singledispatch=3.4.0.3=py27_0 92 | - sip=4.18=py27_1 93 | - six=1.11.0=py27_1 94 | - snuggs=1.4.1=py27_0 95 | - sqlite=3.13.0=1 96 | - ssl_match_hostname=3.5.0.1=py27_1 97 | - subprocess32=3.2.7=py27_0 98 | - tk=8.5.19=2 99 | - tornado=4.5.2=py27_0 100 | - wheel=0.30.0=py_1 101 | - xerces-c=3.1.4=3 102 | - xorg-libxau=1.0.8=3 103 | - xorg-libxdmcp=1.1.2=3 104 | - xz=5.2.3=0 105 | - zlib=1.2.8=3 106 | - libgfortran=3.0.0=1 107 | - util-linux=2.21=0 108 | - zope=1.0=py27_0 109 | - zope.interface=4.4.2=py27_0 110 | - pip: 111 | - backports-abc==0.5 112 | - backports.ssl-match-hostname==3.5.0.1 113 | prefix: ~/miniconda2/envs/LSDTT 114 | 115 | -------------------------------------------------------------------------------- /conda_environments/python3_environment.yml: -------------------------------------------------------------------------------- 1 | name: LSDMT2 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - affine=2.2.2=py_0 6 | - asn1crypto=0.24.0=py36_1003 7 | - attrs=19.1.0=py_0 8 | - boost-cpp=1.68.0=h11c811c_1000 9 | - boto3=1.9.125=py_0 10 | - botocore=1.12.125=py_0 11 | - bzip2=1.0.6=h14c3975_1002 12 | - ca-certificates=2019.3.9=hecc5488_0 13 | - cairo=1.14.12=h8948797_3 14 | - cartopy=0.17.0=py36h0aa2c8f_1004 15 | - certifi=2019.3.9=py36_0 16 | - cffi=1.12.2=py36hf0e25f4_1 17 | - chardet=3.0.4=py36_1003 18 | - click=7.0=py_0 19 | - click-plugins=1.0.4=py_0 20 | - cligj=0.5.0=py_0 21 | - cryptography=2.5=py36hb7f436b_1 22 | - curl=7.64.0=h646f8bb_0 23 | - cycler=0.10.0=py_1 24 | - dbus=1.13.2=h714fa37_1 25 | - descartes=1.1.0=py_2 26 | - docutils=0.14=py36_1001 27 | - expat=2.2.6=he6710b0_0 28 | - fiona=1.8.6=py36hf242f0b_0 29 | - fontconfig=2.13.1=he4413a7_1000 30 | - freetype=2.10.0=he983fc9_0 31 | - freexl=1.0.5=h14c3975_1002 32 | - gdal=2.4.0=py36h1c6dbfb_1002 33 | - geos=3.7.1=hf484d3e_1000 34 | - geotiff=1.4.3=h1105359_1000 35 | - gettext=0.19.8.1=hc5be6a0_1002 36 | - giflib=5.1.7=h516909a_1 37 | - glib=2.56.2=had28632_1001 38 | - gst-plugins-base=1.14.0=hbbd80ab_1 39 | - gstreamer=1.14.0=hb453b48_1 40 | - hdf4=4.2.13=h9a582f1_1002 41 | - hdf5=1.10.4=nompi_h3c11f04_1106 42 | - icu=58.2=hf484d3e_1000 43 | - idna=2.8=py36_1000 44 | - jmespath=0.9.4=py_0 45 | - jpeg=9c=h14c3975_1001 46 | - json-c=0.13.1=h14c3975_1001 47 | - kealib=1.4.10=h1978553_1003 48 | - kiwisolver=1.0.1=py36h6bb024c_1002 49 | - krb5=1.16.3=hc83ff2d_1000 50 | - libblas=3.8.0=4_openblas 51 | - libcblas=3.8.0=4_openblas 52 | - libcurl=7.64.0=h01ee5af_0 53 | - libdap4=3.19.1=0 54 | - libedit=3.1.20170329=hf8c457e_1001 55 | - libffi=3.2.1=he1b5a44_1006 56 | - libgcc-ng=8.2.0=hdf63c60_1 57 | - libgdal=2.4.0=h982c1cc_1002 58 | - libgfortran=3.0.0=1 59 | - libgfortran-ng=7.3.0=hdf63c60_0 60 | - libiconv=1.15=h516909a_1005 61 | - libkml=1.3.0=h328b03d_1009 62 | - liblapack=3.8.0=4_openblas 63 | - libnetcdf=4.6.2=hbdf4f91_1001 64 | - libpng=1.6.36=h84994c4_1000 65 | - libpq=10.6=h13b8bad_1000 66 | - libspatialite=4.3.0a=hb5ec416_1026 67 | - libssh2=1.8.0=h1ad7b7a_1003 68 | - libstdcxx-ng=8.2.0=hdf63c60_1 69 | - libtiff=4.0.10=h648cc4a_1001 70 | - libuuid=2.32.1=h14c3975_1000 71 | - libxcb=1.13=h14c3975_1002 72 | - libxml2=2.9.8=h143f9aa_1005 73 | - libxslt=1.1.32=h4785a14_1002 74 | - lxml=4.3.3=py36h7ec2d77_0 75 | - matplotlib=3.0.3=py36_0 76 | - matplotlib-base=3.0.3=py36h167e16e_0 77 | - munch=2.3.2=py_0 78 | - ncurses=6.1=hf484d3e_1002 79 | - numpy=1.16.2=py36h8b7e671_1 80 | - olefile=0.46=py_0 81 | - openblas=0.3.5=h9ac9557_1001 82 | - openjpeg=2.3.0=hf38bd82_1003 83 | - openssl=1.0.2r=h14c3975_0 84 | - owslib=0.17.1=py_0 85 | - pandas=0.24.2=py36hf484d3e_0 86 | - pcre=8.43=he6710b0_0 87 | - pillow=5.4.1=py36h00a061d_1000 88 | - pip=19.0.3=py36_0 89 | - pixman=0.34.0=h14c3975_1003 90 | - poppler=0.67.0=h2fc8fa2_1002 91 | - poppler-data=0.4.9=1 92 | - postgresql=10.6=h66cca7a_1000 93 | - proj4=5.2.0=h14c3975_1001 94 | - pthread-stubs=0.4=h14c3975_1001 95 | - pycparser=2.19=py36_1 96 | - pyepsg=0.4.0=py_0 97 | - pykdtree=1.3.1=py36h3010b51_1002 98 | - pyopenssl=19.0.0=py36_0 99 | - pyparsing=2.3.1=py_0 100 | - pyproj=1.9.6=py36hc0953d3_1000 101 | - pyqt=5.6.0=py36h13b7fb3_1008 102 | - pyshp=2.1.0=py_0 103 | - pysocks=1.6.8=py36_1002 104 | - python=3.6.7=hd21baee_1002 105 | - python-dateutil=2.8.0=py_0 106 | - pytz=2018.9=py_0 107 | - qt=5.6.3=h8bf5577_3 108 | - rasterio=1.0.22=py36h5b3f9e8_0 109 | - readline=7.0=hf8c457e_1001 110 | - requests=2.21.0=py36_1000 111 | - s3transfer=0.2.0=py36_0 112 | - scipy=1.2.1=py36h09a28d5_1 113 | - setuptools=40.8.0=py36_0 114 | - shapely=1.6.4=py36h2afed24_1003 115 | - sip=4.18.1=py36hf484d3e_1000 116 | - six=1.12.0=py36_1000 117 | - snuggs=1.4.3=py_0 118 | - sqlite=3.26.0=h67949de_1001 119 | - tk=8.6.9=h84994c4_1001 120 | - tornado=6.0.2=py36h516909a_0 121 | - tzcode=2018g=h14c3975_1001 122 | - urllib3=1.24.1=py36_1000 123 | - util-linux=2.21=0 124 | - wheel=0.33.1=py36_0 125 | - xerces-c=3.2.2=hac72e42_1001 126 | - xorg-libxau=1.0.9=h14c3975_0 127 | - xorg-libxdmcp=1.1.3=h516909a_0 128 | - xz=5.2.4=h14c3975_1001 129 | - zlib=1.2.11=h14c3975_1004 -------------------------------------------------------------------------------- /continuous_cbar_floodmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/continuous_cbar_floodmap.png -------------------------------------------------------------------------------- /discrete_cbar_floodmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/d9137710ea18e54f3dc5b6782c5696cafdd2999f/discrete_cbar_floodmap.png -------------------------------------------------------------------------------- /docs/LSDPlottingTools.rst: -------------------------------------------------------------------------------- 1 | LSDPlottingTools package 2 | ======================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | LSDPlottingTools.LSDMap_BasicManipulation module 8 | ------------------------------------------------ 9 | 10 | .. automodule:: LSDPlottingTools.LSDMap_BasicManipulation 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | LSDPlottingTools.LSDMap_BasicPlotting module 16 | -------------------------------------------- 17 | 18 | .. automodule:: LSDPlottingTools.LSDMap_BasicPlotting 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | LSDPlottingTools.LSDMap_ChiPlotting module 24 | ------------------------------------------ 25 | 26 | .. automodule:: LSDPlottingTools.LSDMap_ChiPlotting 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | LSDPlottingTools.LSDMap_GDALIO module 32 | ------------------------------------- 33 | 34 | .. automodule:: LSDPlottingTools.LSDMap_GDALIO 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | LSDPlottingTools.LSDMap_PointTools module 40 | ---------------------------------------- 41 | 42 | .. automodule:: LSDPlottingTools.LSDMap_PointTools 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | LSDPlottingTools.LSDMap_Subplots module 48 | --------------------------------------- 49 | 50 | .. automodule:: LSDPlottingTools.LSDMap_Subplots 51 | :members: 52 | :undoc-members: 53 | :show-inheritance: 54 | 55 | LSDPlottingTools.adjust_text module 56 | ----------------------------------- 57 | 58 | .. automodule:: LSDPlottingTools.adjust_text 59 | :members: 60 | :undoc-members: 61 | :show-inheritance: 62 | 63 | LSDPlottingTools.cubehelix module 64 | --------------------------------- 65 | 66 | .. automodule:: LSDPlottingTools.cubehelix 67 | :members: 68 | :undoc-members: 69 | :show-inheritance: 70 | 71 | LSDPlottingTools.colours module 72 | --------------------------------- 73 | 74 | .. automodule:: LSDPlottingTools.colours 75 | :members: 76 | :undoc-members: 77 | :show-inheritance: 78 | 79 | LSDPlottingTools.labels module 80 | --------------------------------- 81 | 82 | .. automodule:: LSDPlottingTools.labels 83 | :members: 84 | :undoc-members: 85 | :show-inheritance: 86 | 87 | LSDPlottingTools.locationmap module 88 | --------------------------------- 89 | 90 | .. automodule:: LSDPlottingTools.locationmap 91 | :members: 92 | :undoc-members: 93 | :show-inheritance: 94 | 95 | 96 | LSDPlottingTools.scalebar module 97 | --------------------------------- 98 | 99 | .. automodule:: LSDPlottingTools.scalebar 100 | :members: 101 | :undoc-members: 102 | :show-inheritance: 103 | 104 | 105 | 106 | Module contents 107 | --------------- 108 | 109 | .. automodule:: LSDPlottingTools 110 | :members: 111 | :undoc-members: 112 | :show-inheritance: 113 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. LSDPlottingTools documentation master file, created by 2 | sphinx-quickstart on Mon Jan 23 12:45:26 2017. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to LSDPlottingTools's documentation! 7 | ============================================ 8 | 9 | This is the basic documentation that simply repeats information sored within the python files themselves. 10 | 11 | .. toctree:: 12 | :maxdepth: 4 13 | :caption: Contents: 14 | 15 | LSDPlottingTools 16 | 17 | 18 | automodule:: LSDMappingTools 19 | 20 | Indices and tables 21 | ================== 22 | 23 | * :ref:`genindex` 24 | * :ref:`modindex` 25 | * :ref:`search` 26 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | mock 3 | matplotlib 4 | scipy 5 | -------------------------------------------------------------------------------- /docs/rtfd-requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | mock 3 | matplotlib 4 | scipy 5 | -------------------------------------------------------------------------------- /plot_hillslope_traces.py: -------------------------------------------------------------------------------- 1 | #import modules 2 | from __future__ import print_function 3 | from geopandas import GeoDataFrame 4 | import pandas as pd 5 | import numpy as np 6 | from sys import platform, stdout 7 | 8 | # import plotting tools and set the back end for running on server 9 | import matplotlib 10 | matplotlib.use('Agg') 11 | 12 | from matplotlib import rcParams, ticker, gridspec, cm 13 | import matplotlib.pyplot as plt 14 | 15 | # import mapping tools 16 | import rotated_mapping_tools as rmt 17 | import LSDPlottingTools as LSDP 18 | from LSDMapFigure import PlottingHelpers as Helper 19 | from LSDMapFigure.PlottingRaster import MapFigure 20 | from LSDMapFigure.PlottingRaster import BaseRaster 21 | 22 | # set figure sizes (in inches) based on format 23 | FigSizeFormat = "EPSL" 24 | if FigSizeFormat == "geomorphology": 25 | FigWidth_Inches = 6.25 26 | elif FigSizeFormat == "big": 27 | FigWidth_Inches = 16 28 | elif FigSizeFormat == "small": 29 | FigWidth_Inches = 3.3 30 | elif FigSizeFormat == "ESURF": 31 | FigWidth_Inches = 4.92 32 | elif FigSizeFormat == "ESPL": 33 | FigWidth_Inches = 7.08 34 | elif FigSizeFormat == "EPSL": 35 | FigWidth_Inches = 7.48 36 | elif FigSizeFormat == "JGR": 37 | FigWidth_Inches = 6.6 38 | else: 39 | FigWidth_Inches = 4.92126 40 | 41 | # Set up fonts for plots 42 | rcParams['font.family'] = 'sans-serif' 43 | rcParams['font.sans-serif'] = ['Liberation Sans'] 44 | rcParams['font.size'] = 8 45 | rcParams['text.usetex'] = False 46 | 47 | # define filenames and relative workspace 48 | fname_prefix = "bolinas" 49 | HillshadeName = "bolinas_hs.bil" 50 | Directory = "/home/mhurst/bolinas_paper/" 51 | DataDirectory = Directory+"data/" 52 | ChannelDataDirectory = DataDirectory+"channel_data/" 53 | HillslopeDataDirectory = DataDirectory+"hillslope_data/" 54 | HilltopPointsData = HillslopeDataDirectory+"bolinas_HilltopData.csv" 55 | ChannelPointsDat = ChannelDataDirectory+"bolinas_MChiSegmented.csv" 56 | ChannelHeadPointsData = ChannelDataDirectory+"bolinas_CH_wiener_nodeindices_for_Arc.csv" 57 | 58 | # create the map figure 59 | MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location='None') 60 | 61 | # add hilltops 62 | HilltopPointsDF = pd.read_csv(HilltopPointsData) 63 | HilltopPoints = LSDP.LSDMap_PointData(HilltopPointsDF, data_type = "pandas", PANDEX = True) 64 | MF.add_point_data(HilltopPoints,alpha=0.5,zorder=100,unicolor="blue",manual_size=5) 65 | 66 | # add channel heads 67 | #ChannelHeadsDF = pd.read_csv(ChannelHeadPointsData) 68 | #ChannelHeadPoints = LSDP.LSDMap_PointData(ChannelHeadsDF, data_type = "pandas", PANDEX = True) 69 | #MF.add_point_data(ChannelHeadPoints,alpha=0.5,zorder=100,unicolor="blue",manual_size=5) 70 | 71 | # add channels 72 | #ChannelDF = Helper.ReadChiDataMapCSV(ChannelDataDirectory,fname_prefix) 73 | #ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type = "pandas", PANDEX = True) 74 | #MF.add_point_data(ChannelPoints,show_colourbar="False", scale_points=True, column_for_scaling='drainage_area',alpha=0.5,zorder=90) 75 | 76 | # add hillslope traces 77 | #Plot HillslopeTraces(): 78 | 79 | # Save the figure 80 | ImageName = Directory+"plots/bolinas_traces.png" 81 | MF.save_fig(fig_width_inches = FigWidth_Inches, FigFileName = ImageName, FigFormat="png", Fig_dpi = 300) 82 | -------------------------------------------------------------------------------- /plot_swath_profile.py: -------------------------------------------------------------------------------- 1 | ## plot_swath_profile.py 2 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 3 | ## Plots a simple swath profile generated by LSDTopoTools swath profiler 4 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 5 | ## DTM 16/06/2014 6 | ## Update SMM 18/06/2014 Change to handle nodata 7 | ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 8 | 9 | #import modules 10 | import numpy as np, matplotlib.pyplot as plt 11 | from matplotlib import rcParams 12 | import matplotlib.colors as colors 13 | import matplotlib.cm as cmx 14 | 15 | 16 | 17 | 18 | def plot_swath_profile(full_file_path, ax): 19 | 20 | # Set up fonts for plots 21 | rcParams['font.family'] = 'sans-serif' 22 | rcParams['font.sans-serif'] = ['Liberation Sans'] 23 | rcParams['font.size'] = 16 24 | rcParams['legend.numpoints'] = 1 25 | axis_size = 16 26 | 27 | # FileList = dir + 28 | f = open(full_file_path, 'r') 29 | lines = f.readlines() 30 | N_Segments = len(lines)-1 31 | 32 | # Initialise a bunch of vectors 33 | distance = np.zeros(N_Segments) 34 | mean = np.zeros(N_Segments) 35 | sd = np.zeros(N_Segments) 36 | minimum = np.zeros(N_Segments) 37 | LQ = np.zeros(N_Segments) 38 | median = np.zeros(N_Segments) 39 | UQ = np.zeros(N_Segments) 40 | maximum = np.zeros(N_Segments) 41 | for i in range (0, N_Segments): 42 | 43 | line = lines[i+1].strip().split(" ") 44 | distance[i] = float(line[0]) 45 | mean[i] = float(line[1]) 46 | sd[i] = float(line[2]) 47 | minimum[i] = float(line[3]) 48 | LQ[i] = float(line[4]) 49 | median[i] = float(line[5]) 50 | UQ[i] = float(line[6]) 51 | maximum[i] = float(line[7]) 52 | 53 | # if there is nodata (-9999) replace with the numpy nodata entry 54 | if (mean[i] == -9999): 55 | mean[i] = np.nan 56 | sd[i] = np.nan 57 | minimum[i] = np.nan 58 | LQ[i] = np.nan 59 | median[i] = np.nan 60 | UQ[i] = np.nan 61 | maximum[i] = np.nan 62 | 63 | f.close() 64 | 65 | ####################### 66 | # # 67 | # Plot data # 68 | # # 69 | ####################### 70 | OutputFigureFormat = 'pdf' 71 | # SET UP COLOURMAPS 72 | # PLOT 1 -> transverse profile 73 | #plt.figure(1, facecolor='White',figsize=[10,6]) 74 | 75 | #plt.plot(distance,median,'-') 76 | ax.plot(distance,LQ,'--') 77 | ax.plot(distance,UQ,'--') 78 | #plt.plot(distance,minimum,'-.',color='black') 79 | #plt.plot(distance,maximum,'-.',color='black') 80 | 81 | ax.plot(distance,mean,'-') 82 | 83 | # Configure final plot 84 | ax.spines['top'].set_linewidth(1) 85 | ax.spines['left'].set_linewidth(1) 86 | ax.spines['right'].set_linewidth(1) 87 | ax.spines['bottom'].set_linewidth(1) 88 | ax.tick_params(axis='both', width=1) 89 | plt.ylabel('Average elevation difference (m)', fontsize = axis_size) 90 | plt.xlabel('Distance along channel longitudinal profile (m)', fontsize = axis_size) 91 | plt.subplots_adjust(bottom=0.15,left=0.18) 92 | 93 | #plt.show() 94 | 95 | def multiSwathPlot(data_dir, wildcard_fname): 96 | 97 | import glob 98 | 99 | fig, ax = plt.subplots() 100 | 101 | for f in glob.glob(data_dir + wildcard_fname): 102 | print(f) 103 | full_file_path = data_dir + wildcard_fname 104 | plot_swath_profile(f, ax) 105 | 106 | fig.canvas.draw() 107 | 108 | data_dir = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/SwathProfile/Swath_secondVisit/Ryedale/" 109 | file_single = "RyedaleElevDiff_GRIDDED_TLIM_long_profile.txt" 110 | file_wildcard = "*ElevDiff_*_TLIM_long_profile.txt" 111 | 112 | #plot_swath_profile(file_single + data_dir) 113 | multiSwathPlot(data_dir, file_wildcard) 114 | 115 | -------------------------------------------------------------------------------- /readme.asc: -------------------------------------------------------------------------------- 1 | image:https://zenodo.org/badge/35153043.svg[link="https://zenodo.org/badge/latestdoi/35153043"] 2 | 3 | = Mapping tools for plotting topographic analyses using python 4 | 5 | I am very sorry to say that the documentation for these tools are minimal. We have gone through several iterations of design of these tools so there are many useless dead ends in the repository. Sorry about that. The readme below should give you some insights into where to start if you are interested in trying to use these before we actaully release them with documentation. 6 | 7 | == Authors 8 | * http://www.geos.ed.ac.uk/homes/smudd[Simon M Mudd] 9 | * https://github.com/dvalters?tab=repositories[Declan Valters] 10 | * https://fionaclubb.wordpress.com/[Fiona Clubb] 11 | * http://www.ed.ac.uk/geosciences/people/person.html?indv=5391[Boris Gailleton] 12 | * https://www.gla.ac.uk/schools/ges/staff/martinhurst/[Martin Hurst] 13 | * https://www.qmul.ac.uk/geog/staff/grieves.html[Stuart Grieve] 14 | 15 | 16 | == General information 17 | 18 | These are some plotting tools for working with geospatial data in python. The tools are mostly in the subdirectories in this repository. They are linked packages (in that each subdirectory has an `__init__` file). We have not at this stage created an installer: you simply need to clone this repository and use them from that directory. 19 | 20 | == Installation 21 | 22 | At the moment we do not have a functioning `pip` installer. So to run the tools you need to: 23 | . Clone this repository. 24 | . install all the required packages 25 | . Either add the *LSDMappingTools* directory to your [python path] or run the tools within the *LSDMappingTools* directory. 26 | 27 | === Getting the dependencies working the Docker way 28 | 29 | https://www.docker.com/[Docker] is a software package that allows you to run containers inside your computer. These containers, in the case of *LSDMappingTools*, have been carefully constructed by the *LSDTopoTools* gnomes to make sure all of the necessary packages are installed. All you need to do is download the container to start working! Easy, right? Well, Docker is a bit of a pain to install on Windows. You will need Windows 10 Enterprise for it to work. On other operating systems it is a breeze. 30 | 31 | To get it to work: 32 | 33 | . Install docker 34 | . Download the container from a terminal/powershell window: 35 | + 36 | [source,console] 37 | ---- 38 | $ docker pull lsdtopotools/lsdtt_viz_docker 39 | ---- 40 | + 41 | . Run the container 42 | + 43 | [source,console] 44 | ---- 45 | $ docker run -it -v C:\LSDTopoTools:/LSDTopoTools lsdtopotools/lsdtt_viz_docker 46 | ---- 47 | + 48 | . Run the setup script by running `sh LSDTT_start.sh`. 49 | 50 | For more details see the https://hub.docker.com/r/lsdtopotools/lsdtt_viz_docker[LSDMappingTools dockerhub page]. 51 | 52 | === Getting the dependencies the Conda way 53 | 54 | So actually our Docker container uses https://conda.io/miniconda.html[miniconda]. But all the setup is performed before the container is built so you never need to deal with it. You can set up in your own enviroment, however. The instructions are below. We do not recommend this unless there is some reason you cannot install docker. 55 | 56 | ==== Setting up python using a conda virtual environment 57 | 58 | . Download and install http://conda.pydata.org/miniconda.html[miniconda] on your host machine. 59 | . Open a command prompt (use the start menu to search for *cmd.exe*) 60 | . Get our https://raw.githubusercontent.com/LSDtopotools/LSDMappingTools/master/conda_environments/environment_docker.yml[environment file]. This is the version that work on our docker container. It is python 3 and based on a 64 bit linux system. It is the most up to date version of the python environment. 61 | . Create the environment from that file with: 62 | + 63 | [source,console] 64 | ---- 65 | > conda env create -f environment_docker.yml 66 | ---- 67 | + 68 | I'm afraid this will take a little while. Actually it will take a very long time. Sorry. 69 | . Activate the environment: 70 | + 71 | [source,console] 72 | ---- 73 | > activate LSDTT 74 | ---- 75 | 76 | NOTE: This environment does not include *spyder*, you can install it with `conda install -n LSDTT spyder` 77 | 78 | == The sub-packages are: 79 | 80 | * *LSDPlottingTools*: A collection of utilities for plotting. The main geospatial plotting routines are in *LSDMapFigure* but there are some older plotting routines, along with a lot of geospatial bells and whistles, within this packages. The other packages don't work without this. 81 | * *LSDMapArtist*: The first attempt by https://github.com/dvalters?tab=repositories[Declan Valters] to build a https://matplotlib.org/users/artists.html[artist-based] geospatial plotting platform. The _artist_ bit is an attempt to have a interface something like https://matplotlib.org/[matplotlib]. *This has been replaced by LSDMapFigure and is here for educational purposes*. 82 | * *LSDMapFigure*: This contains objects used for geospatial plotting. 83 | * *LSDChiMappingExamples*: Don't bother with this for now. It is part of some tutorials we are developing bt those aren't complete so you don't need to look in there. 84 | * *LSDMapWrappers*: These have some simple plotting functions that allow users to make maps with minimal lines of code. 85 | 86 | === Actually plotting something 87 | 88 | We have written some instructions on using the basic functionality of the mapping tools in the *LSDTopoTools* documentation. 89 | You can get started here: 90 | 91 | https://lsdtopotools.github.io/LSDTT_documentation/LSDTT_visualisation.html 92 | 93 | === Code generated documentation 94 | 95 | There is some code generated documentation. You can https://lsdmappingtools.readthedocs.io/en/latest/[find it here]. 96 | 97 | === Notes 98 | 99 | If you are developing this code, you should follow the documentation style explained on the http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html[readthedocs napolean page]. 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /test_ingest_geology.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 07 13:34:02 2017 4 | 5 | @author: smudd 6 | """ 7 | 8 | # This script modified from 9 | # http://geoinformaticstutorial.blogspot.co.uk/2012/11/convert-shapefile-to-raster-with-gdal.html 10 | 11 | # Importing needed modules 12 | import os 13 | from osgeo import ogr 14 | import LSDPlottingTools as LSDPT 15 | 16 | 17 | def Rasterize_BGS_geologic_maps(shapefile_name): 18 | 19 | # The shapefile to be rasterized: 20 | print('Rasterize ' + shapefile_name) 21 | #get path and filename seperately 22 | shapefilefilepath = LSDPT.GetPath(shapefile_name) 23 | shapefilename = LSDPT.GetFileNameNoPath(shapefile_name) 24 | shapefileshortname = LSDPT.GetFilePrefix(shapefile_name) 25 | 26 | print("Shapefile name is: "+shapefilename) 27 | 28 | # The raster file to be created and receive the rasterized shapefile 29 | outrastername = shapefileshortname + '.tif' 30 | outraster = shapefilefilepath+os.sep+ outrastername 31 | outcsv = shapefilefilepath+os.sep+shapefileshortname+'_lithokey.csv' 32 | print("Full name of out raster is: "+outraster) 33 | 34 | # Rasterize!! 35 | system_call = 'gdal_rasterize -a BGSREF -l ' + shapefileshortname +' -tr 90 -90 -a_nodata -9999 ' + shapefile_name + ' ' + outraster 36 | print("System call is: ") 37 | print(system_call) 38 | os.system(system_call) 39 | 40 | 41 | # now convert the raster to UTM, as well as delete the stupid TIF 42 | # The raster file to be created and receive the rasterized shapefile 43 | outrastername_bil = shapefileshortname + '.bil' 44 | outraster_bil = shapefilefilepath+"os.sep"+ outrastername_bil 45 | print("Full name of out raster is: "+outraster_bil) 46 | 47 | # This assumes UTM zone 30, because why would we do any work in East Anglia? 48 | system_call2 = 'gdalwarp -t_srs EPSG:32630 -of ENVI -dstnodata -9999 ' + outraster + ' ' + outraster_bil 49 | os.system(system_call2) 50 | 51 | # Now get rid of the tif 52 | system_call3 = 'rm '+ outraster 53 | os.system(system_call3) 54 | 55 | # now get the the fields from the shapefile 56 | daShapefile = shapefile_name 57 | 58 | dataSource = ogr.Open(daShapefile) 59 | daLayer = dataSource.GetLayer(0) 60 | 61 | # Make a key for the bedrock 62 | geol_dict = dict() 63 | for feature in daLayer: 64 | ID = feature.GetField("BGSREF") 65 | GEOL = feature.GetField("RCS_D") 66 | 67 | if ID not in geol_dict: 68 | print("I found a new rock type, ID: "+ str(ID)+ " and rock type: " + str(GEOL)) 69 | geol_dict[ID] = GEOL 70 | 71 | print("The rocks are: ") 72 | print(geol_dict) 73 | 74 | with open(outcsv, 'wb') as f: 75 | f.write('ID,rocktype\n') 76 | for key in geol_dict: 77 | f.write(str(key)+','+ str(geol_dict[key])+'\n') 78 | 79 | print("All done") 80 | 81 | if __name__ == "__main__": 82 | 83 | shapefile_name = '/home/smudd/SMMDataStore/analysis_for_papers/Geology_raster/bgs-50k_1726879/sc034/sc034_eyemouth_bedrock.shp' 84 | 85 | #shapefile_name = 'T:\\analysis_for_papers\\Geology_raster\\bgs-50k_1726879\\sc034\\sc034_eyemouth_bedrock.shp' 86 | 87 | Rasterize_BGS_geologic_maps(shapefile_name) --------------------------------------------------------------------------------