Example #1
0
    def __init__(self, RasterName, Directory):

        self._RasterFileName = RasterName
        self._RasterDirectory = Directory
        self._FullPathRaster = self._RasterDirectory + self._RasterFileName

        # I think the BaseRaster should contain a numpy array of the Raster
        self._RasterArray = LSDP.ReadRasterArrayBlocks(self._FullPathRaster)

        # Get the extents as a list
        self._RasterExtents = LSDP.GetRasterExtent(self._FullPathRaster)
def findmaxval_multirasters(FileList):
    """
    Loops through a list or array of rasters (np arrays)
    and finds the maximum single value in the set of arrays.
    """
    overall_max_val = 0
    
    for i in range (len(FileList)):
        
        raster_as_array = LSDP.ReadRasterArrayBlocks(FileList[i])
        this_max_val = np.max(raster_as_array)
        
        if this_max_val > overall_max_val:
            overall_max_val = this_max_val
            print(overall_max_val)
            
    return overall_max_val
Example #3
0
    def _render_background(self, fullpath_to_raster):
        """
        Renders the background image that 
        will form the drape plot, e.g. a hillshade
        """
        if self._backgroundtype == "Hillshade":
            self.Hillshade = LSDP.Hillshade(self.fullpath_to_raster)
            self.colourmap = "gray"

        elif self._backgroundtype == "Terrain":
            self.Hillshade = LSDP.ReadRasterArrayBlocks(
                self.fullpath_to_raster)
            self.colourmap = LSDP.colours.UsefulColourmaps.niceterrain
            #self.colourmap = LSDP.colours.UsefulColourmaps.darkearth
            #self.colourmap = "terrain"
        else:
            print ("That background style is not yet supported. Currently only " \
                   " 'Hillshade' and 'Terrain' are supported.")
Example #4
0
def TestNewMappingTools2():
    DataDirectory = "T://analysis_for_papers//Manny_idaho//"
    Filename = "TestIdaho.bil"
    NewFilename = "TestIdaho_after2.bil"
    ThreshFname = "ThreshIdaho.bil"
    ConstFname = "ConstEros.bil"
    ThisFile = DataDirectory + Filename
    NewFilename = DataDirectory + NewFilename
    ThreshFname = DataDirectory + ThreshFname
    ConstFname = DataDirectory + ConstFname

    #FigFormat = 'svg'
    #FigFileN= 'Sorbas_chi.svg'
    #FigFileName= DataDirectory+FigFileN

    #Plot the basin over the elevation
    #tcmapcolorbarlabel = "Elevation (m)"
    #tcmap = 'jet'
    #tcmapcolorbarlabel='Chi'
    #clim_val = (50,300)
    #LSDP.BasicDensityPlotGridPlot(ThisFile,tcmap,tcmapcolorbarlabel,clim_val)

    #get the nodata values
    NData = LSDP.getNoDataValue(ThisFile)

    print "NoData is: " + str(NData)

    # get the data as an array
    array = LSDP.ReadRasterArrayBlocks(ThisFile)

    driver_name = "ENVI"
    LSDP.array2raster(ThisFile, NewFilename, array, driver_name, -9999)

    #get the nodata values
    NData2 = LSDP.getNoDataValue(NewFilename)

    #print "NoData 2 is: " + str(NData2)

    LSDP.SetNoDataBelowThreshold(ThisFile, ThreshFname)

    # now print the constant value file
    constant_value = 0.001
    LSDP.SetToConstantValue(ThreshFname, ConstFname, constant_value)
    def __init__(self, RasterName, Directory):

        self._RasterFileName = RasterName
        self._RasterDirectory = Directory
        self._FullPathRaster = self._RasterDirectory + self._RasterFileName

        # I think the BaseRaster should contain a numpy array of the Raster
        self._RasterArray = LSDP.ReadRasterArrayBlocks(self._FullPathRaster)

        # Get the extents as a list
        self._RasterExtents = LSDP.GetRasterExtent(self._FullPathRaster)
        self._RasterAspectRatio = (
            self._RasterExtents[1] - self._RasterExtents[0]) / (
                self._RasterExtents[3] - self._RasterExtents[2])

        # set the default colourmap
        self._colourmap = "gray"

        # get the EPSG string
        self._EPSGString = LSDP.LSDMap_IO.GetUTMEPSG(self._FullPathRaster)
def MultiDrapeMaps(DataDir, ElevationRaster, DrapeRasterWild, cmap, drape_min_threshold=None, drape_max=None):
    """
    Plots flood extents from water depth rasters
    draped over the catchment elevation raster
    in a series of subplots
    
    Takes a wildcard for the drapes
    Expexts a fixed elevation raster, but this could be
    modified in future.
    
    Thought: consider, if plotting multiple datasets, how you
    are going to deal with min a max values in the colur range.
    imshow will automatically set vmin and vmax and stretch the colour bar 
    over this - which can be visually misleading. Ideally, you
    want to have the same colour map used for *all* subplots, and 
    this is not default behaviour.
    """
    f, ax_arr = plt.subplots(2, 2, figsize=(10, 5), sharex=True, sharey=True)
    ax_arr = ax_arr.ravel()
    
    FPFiles = sorted(glob.glob(DataDirectory+DrapeRasterWild), key=str)
    n_files = len(FPFiles)
    print("Number of files = ", n_files)
    
    elev_raster_file = DataDir + ElevationRaster
    
    hillshade = LSDP.Hillshade(elev_raster_file)
    #hillshade_array = LSDP.ReadRasterArrayBlocks(elev_raster_file)
    
    # now get the extent
    extent_raster = LSDP.GetRasterExtent(elev_raster_file)
    
    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # now get the tick marks    
    n_target_tics = 5
    xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(elev_raster_file,x_max,x_min,y_max,y_min,n_target_tics)  

    print("xmax: " + str(x_max))
    print("xmin: " + str(x_min))
    print("ymax: " + str(y_max))
    print("ymin: " + str(y_min))
    
    """
    Find the maximum water depth in all rasters.
    You need this to normalize the colourscale accross
    all plots when teh imshow is done later.
    """

    try:
        print("Calculating max drape raster value by scanning rasters...")
        max_water_depth = findmaxval_multirasters(FPFiles)
        drape_max = max_water_depth
        
    except:
        print("Something went wrong trying to obtain the max value in \
                your drape raster file list.")
    finally:
        print("The drape(s) max value is set to: ", drape_max) 
    
    
    for i in range(n_files):
        
        print("The floodplain file name is: ", FPFiles[i])
        FP_raster = LSDP.ReadRasterArrayBlocks(FPFiles[i])
        #FP_raster = np.ma.masked_where(FP_raster <= 0, FP_raster)
        
        filename = os.path.basename(FPFiles[i])
        title = mplext.labels.make_line_label(filename)
        print(title)
        
        low_values_index = FP_raster < drape_min_threshold
        FP_raster[low_values_index] = np.nan
        
        im = ax_arr[i].imshow(hillshade, "gray", extent=extent_raster, interpolation="nearest")
        """
        Now we can set vmax to be the maximum water depth we calcualted earlier, making our separate
        subplots all have the same colourscale
        """
        im = ax_arr[i].imshow(FP_raster, cmap, extent=extent_raster, 
                                alpha=1.0, interpolation="none", 
                                vmin=drape_min_threshold, 
                                vmax=drape_max)
        ax_arr[i].set_title(title)
 
    f.subplots_adjust(right=0.8)
    cax = f.add_axes([0.9, 0.1, 0.03, 0.8])
    
    cbar = f.colorbar(im, cax=cax) 
    cbar.set_label("Water depth (m)")
    #cbar.set_ticks(np.linspace(0, 8, 8))
    #cbar = mplext.colours.colorbar_index(f, cax, 8, cmap, 
    #                                     drape_min_threshold, drape_max)
    cbar.set_label("Water depth (m)")
    #tick_locator = ticker.MaxNLocator(nbins=8)
    #cbar.locator = tick_locator
    #cbar.update_ticks()
    
    f.text(0.5, 0.04, 'Easting (m)', ha='center')
    f.text(0.04, 0.5, 'Northing (m)', va='center', rotation='vertical')
def coloured_chans_like_graphs(hillshade_file, tree_file):
    """
    Plots outlines of channels taken from the *.tree file over a hillshade
    giving each channel a unique colour which corresponds to the colours used
    in the Chi plotting routines in chi_visualisation.py.
    
    """
 
    label_size = 20
    #title_size = 30
    axis_size = 28

    
   
    import matplotlib.pyplot as pp
    import numpy as np
    import matplotlib.colors as colors
    import matplotlib.cm as cmx
    from matplotlib import rcParams
    import matplotlib.lines as mpllines
    
    # make sure the nodata is formatted
    LSDP.CheckNoData(hillshade_file)    
    
    #get data
    hillshade = LSDP.ReadRasterArrayBlocks(hillshade_file)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    

    # now get the extent
    extent_raster = LSDP.GetRasterExtent(hillshade_file)
    
    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['arial']
    rcParams['font.size'] = label_size  

    #get coordinates of streams from tree file   
    channel_id = []
    row = []
    col = []
        
    with open(tree_file, 'r') as f:
        lines = f.readlines()
        
    for q,line in enumerate(lines):
        if q > 0: #skip first line
            channel_id.append(int(line.split()[0]))
            row.append(float(line.split()[4]))
            col.append(float(line.split()[5]))

    #get bounding box & pad to 10% of the dimension
    x_max = max(col)
    x_min = min(col)
    y_max = max(row)
    y_min = min(row) 
    
    pad_x = (x_max - x_min) * 0.1
    pad_y = (x_max - y_min) * 0.1
    
    if (pad_y > pad_x):
        pad_x = pad_y
    else:
        pad_y = pad_x
    
    x_max += pad_x
    x_min -= pad_x
    y_max += pad_y
    y_min -= pad_y 
    
    fig = pp.figure(1, facecolor='white',figsize=(10,7.5))
    ax = fig.add_subplot(1,1,1)
    ax.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray)
    

    # now get the tick marks 
    n_target_tics = 5
    xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(hillshade_file,x_max,x_min,y_max,y_min,n_target_tics)  

    pp.xticks(xlocs, new_x_labels, rotation=60)  #[1:-1] skips ticks where we have no data
    pp.yticks(ylocs, new_y_labels) 
    


    # some formatting to make some of the ticks point outward    
    for line in ax.get_xticklines():
        line.set_marker(mpllines.TICKDOWN)
        #line.set_markeredgewidth(3)

    for line in ax.get_yticklines():
        line.set_marker(mpllines.TICKLEFT)
        #line.set_markeredgewidth(3)  
    
    pp.xlim(x_min,x_max)    
    pp.ylim(y_max,y_min)   
   
    pp.xlabel('Easting (m)',fontsize = axis_size)
    pp.ylabel('Northing (m)', fontsize = axis_size)  
                  
    # channel ID
    Channel_ID_MIN = np.min(channel_id)
    Channel_ID_MAX = np.max(channel_id)
    cNorm_channel_ID  = colors.Normalize(vmin=Channel_ID_MIN, vmax=Channel_ID_MAX)  # the max number of channel segs is the 'top' colour
    jet = pp.get_cmap('jet')
    scalarMap_channel_ID = cmx.ScalarMappable(norm=cNorm_channel_ID, cmap=jet) 
    

    #for a,i in enumerate(reversed(channel_id)):
    for a,i in enumerate(channel_id):
        if i != 0:
            # plot other stream segments
            colorVal = scalarMap_channel_ID.to_rgba(i) # this gets the distinct colour for this segment
            pp.scatter(col[a], row[a], 30,marker=".", color=colorVal,edgecolors='none') 

    for a,i in enumerate(channel_id):
        if i == 0:
            # plot trunk stream in black
            pp.scatter(col[a], row[a], 40,marker=".", color='k',edgecolors='none')
 
    ax.spines['top'].set_linewidth(2.5)
    ax.spines['left'].set_linewidth(2.5)
    ax.spines['right'].set_linewidth(2.5)
    ax.spines['bottom'].set_linewidth(2.5) 
    ax.tick_params(axis='both', width=2.5)     
 
    pp.xlim(x_min,x_max)    
    pp.ylim(y_max,y_min) 
 
    pp.title("Channels colored by channel number",fontsize=label_size)  
    pp.tight_layout()        

    
    
    pp.show()
def m_values_over_hillshade(hillshade_file, tree_file):
    """
    Plots m values of channels taken from the *.tree file over a hillshade
    
    """
 
    label_size = 20
    #title_size = 30
    axis_size = 28
   
    import matplotlib.pyplot as pp
    import numpy as np
    import matplotlib.colors as colors
    import matplotlib.cm as cmx
    from matplotlib import rcParams
    import matplotlib.lines as mpllines
    
    #get data
    hillshade = LSDP.ReadRasterArrayBlocks(hillshade_file)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    

    # now get the extent
    extent_raster = LSDP.GetRasterExtent(hillshade_file)
    
    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    
    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['arial']
    rcParams['font.size'] = label_size  

    #get coordinates of streams from tree file   
    M_chi_value = []
    channel_id = []
    row = []
    col = []
        
    with open(tree_file, 'r') as f:
        lines = f.readlines()
        
    for q,line in enumerate(lines):
        if q > 0: #skip first line
            channel_id.append(float(line.split()[0]))
            M_chi_value.append(float(line.split()[11]))
            row.append(float(line.split()[4]))
            col.append(float(line.split()[5]))

    #get bounding box & pad to 10% of the dimension
    x_max = max(col)
    x_min = min(col)
    y_max = max(row)
    y_min = min(row) 
    
    pad_x = (x_max - x_min) * 0.1
    pad_y = (x_max - y_min) * 0.1
    
    if (pad_y > pad_x):
        pad_x = pad_y
    else:
        pad_y = pad_x
    
    x_max += pad_x
    x_min -= pad_x
    y_max += pad_y
    y_min -= pad_y 
    
    fig = pp.figure(1, facecolor='white',figsize=(10,7.5))
    ax = fig.add_subplot(1,1,1)
    ax.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray)
    
    # now get the tick marks 
    n_target_tics = 5
    xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(hillshade_file,x_max,x_min,y_max,y_min,n_target_tics)  

    pp.xticks(xlocs, new_x_labels, rotation=60)  #[1:-1] skips ticks where we have no data
    pp.yticks(ylocs, new_y_labels) 
    
    for line in ax.get_xticklines():
        line.set_marker(mpllines.TICKDOWN)
        #line.set_markeredgewidth(3)

    for line in ax.get_yticklines():
        line.set_marker(mpllines.TICKLEFT)
        #line.set_markeredgewidth(3)  
 
    pp.xlim(x_min,x_max)    
    pp.ylim(y_max,y_min)  
   
    pp.xlabel('Easting (m)',fontsize = axis_size)
    pp.ylabel('Northing (m)',fontsize = axis_size)    
              
    # channel ID
    M_chi_value_MIN = np.min(M_chi_value)
    M_chi_value_MAX = np.max(M_chi_value)
    cNorm_M_chi_value  = colors.Normalize(vmin=M_chi_value_MIN, vmax=M_chi_value_MAX)  # the max number of channel segs is the 'top' colour
    hot = pp.get_cmap('RdYlBu_r')
    scalarMap_M_chi_value = cmx.ScalarMappable(norm=cNorm_M_chi_value, cmap=hot) 
    
    
    for a,i in enumerate(M_chi_value):
        #print "a: " +str(a)+" i: " +str(i)
        if channel_id[a] != 0:     
            # plot other stream segments
            colorVal = scalarMap_M_chi_value.to_rgba(i) # this gets the distinct colour for this segment
            pp.scatter(col[a], row[a], 30,marker=".", color=colorVal,edgecolors=colorVal) 

    for a,i in enumerate(M_chi_value):
        if channel_id[a] == 0:
            # plot trunk stream in black
            colorVal = scalarMap_M_chi_value.to_rgba(i)
            pp.scatter(col[a], row[a], 40,marker=".", color=colorVal,edgecolors=colorVal)

    sm = pp.cm.ScalarMappable(cmap=hot, norm=pp.normalize(vmin=min(M_chi_value), vmax=max(M_chi_value)))
    sm._A = []
    


    
    ax.spines['top'].set_linewidth(2.5)
    ax.spines['left'].set_linewidth(2.5)
    ax.spines['right'].set_linewidth(2.5)
    ax.spines['bottom'].set_linewidth(2.5) 
    ax.tick_params(axis='both', width=2.5)      
    
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(pp.gca())
    cax = divider.append_axes("right", "5%", pad="3%")
    pp.colorbar(sm, cax=cax).set_label('$M_{\chi}$',fontsize=axis_size) 
    cax.tick_params(labelsize=label_size) 
    
    #pp.xlim(x_min,x_max)    
    #pp.ylim(y_max,y_min) 

    pp.tight_layout()
        
    pp.show()
import numpy as np
import LSDPlottingTools as LSDP
import lsdmatplotlibextensions as mplext

#fit_weibull_from_file(sys.argv[1])
#TestNewMappingTools2()
#ResetErosionRaster()
#FloodThenHillshade()
#FixStupidNoData()

DataDirectory = "/run/media/dav/SHETLAND/Analyses/Ryedale_storms_simulation/Gridded/DetachLim/"
filename = DataDirectory + "Elevations0.asc"
drapename = DataDirectory + "WaterDepths2880.asc"

# Create the drape array from one of the Catchment model output rasters
drape_array = LSDP.ReadRasterArrayBlocks(drapename)
# Optional: A lot of the output rasters contain very small values for certain
# things like water depth or elevation difference, so you can mask this below:
low_values_index = drape_array < 0.005
drape_array[low_values_index] = np.nan

#cmap = plt.get_cmap("Blues")

trunc_cmap = mplext.colours.truncate_colormap("Blues", 0.4, 1.0)

LSDP.DrapedOverHillshade(filename,drape_array,clim_val=(0,400), \
                         drape_cmap=trunc_cmap, colorbarlabel='Elevation in meters',\
                         ShowColorbar=True, ShowDrapeColorbar=True,
                         drape_cbarlabel = "Water depth (m)",
                         drape_alpha=1.0)