示例#1
0
def simulation_inundation_timeseries(glob_wildcard,
                                     floodplain_mask,
                                     stream_mask,
                                     threshold=0,
                                     savefilename="inundation_metrics.txt"):
    """Creates a timeseries of a given inundation metric. 
    
    Options should be:
        Inundation Area (Entire catchment)
        Mean Water Depth (Entire catchment)
        Mean Water Depth (Floodplain only)
        Mean Water Depth (Channel)
    """
    # Create an empty array with the correct number of columns
    data_array = _np.empty((0, 5), dtype=_np.float32)
    print("Data array shape: ", data_array.shape)

    for water_raster_file in sorted(glob.glob(glob_wildcard), key=natural_key):
        print(water_raster_file)
        water_raster = lsdgdal.ReadRasterArrayBlocks(water_raster_file)

        timestep_row = []  # Empty list to store elements of the row
        cur_timestep = timestep_string_from_filename(
            water_raster_file
        )  # get the current timestep by parsing the filename

        # Inundation area
        this_inundation_area = calculate_waterinundation_area(
            water_raster, DX, 0.02)
        this_mean_catchment_waterdepth = calculate_mean_waterdepth(
            water_raster)
        this_mean_floodplain_waterdepth = floodplain_mean_depth(
            water_raster, floodplain_mask)
        this_mean_mainchannel_waterdepth = main_channel_mean_depth(
            water_raster, floodplain_mask, stream_mask)

        # Append each value to the current row list object
        timestep_row.append([
            cur_timestep, this_inundation_area, this_mean_catchment_waterdepth,
            this_mean_floodplain_waterdepth, this_mean_mainchannel_waterdepth
        ])
        # Convert the list into a numpy array
        timestep_row = _np.asarray(timestep_row, dtype=_np.float32)

        # Now append (stack) that row onto the bottom of the array (axis=0)
        data_array = _np.append(data_array, timestep_row, axis=0)

    print(data_array)
    print(data_array.shape)

    with open(savefilename, 'wb') as f:
        _np.savetxt(f, data_array, fmt='%i %f %f %f %f')
def BasicMassBalance(path, file1, file2):

    # make sure names are in correct format
    NewPath = LSDOst.AppendSepToDirectoryPath(path)

    raster_file1 = NewPath + file1
    raster_file2 = NewPath + file2

    PixelArea = LSDMap_IO.GetPixelArea(raster_file1)
    print "PixelArea is: " + str(PixelArea)

    print "The formatted path is: " + NewPath
    Raster1 = LSDMap_IO.ReadRasterArrayBlocks(raster_file1, raster_band=1)
    Raster2 = LSDMap_IO.ReadRasterArrayBlocks(raster_file2, raster_band=1)

    NewRaster = np.subtract(Raster2, Raster1)

    mass_balance = np.sum(NewRaster) * PixelArea

    print "linear dif " + str(np.sum(NewRaster))

    return mass_balance
def RasterMeanValue(path, file1):

    # make sure names are in correct format
    NewPath = LSDOst.AppendSepToDirectoryPath(path)

    raster_file1 = NewPath + file1

    NPixels = LSDMap_IO.GetNPixelsInRaster(raster_file1)

    Raster1 = LSDMap_IO.ReadRasterArrayBlocks(raster_file1, raster_band=1)

    mean_value = np.sum(Raster1) / float(NPixels)

    return mean_value
示例#4
0
def Hillshade(raster_file, azimuth=315, angle_altitude=45):

    array = LSDMap_IO.ReadRasterArrayBlocks(raster_file, raster_band=1)

    x, y = np.gradient(array)
    slope = np.pi / 2. - np.arctan(np.sqrt(x * x + y * y))
    aspect = np.arctan2(-x, y)
    azimuthrad = azimuth * np.pi / 180.
    altituderad = angle_altitude * np.pi / 180.


    shaded = np.sin(altituderad) * np.sin(slope)\
     + np.cos(altituderad) * np.cos(slope)\
     * np.cos(azimuthrad - aspect)

    #this_array = 255*(shaded + 1)/2
    return 255 * (shaded + 1) / 2
def SimpleSwath(path, file1, axis):

    # make sure names are in correct format
    NewPath = LSDOst.AppendSepToDirectoryPath(path)

    raster_file1 = NewPath + file1

    # get some information about the raster
    NDV, xsize, ysize, GeoT, Projection, DataType = LSDMap_IO.GetGeoInfo(
        raster_file1)

    print "NDV is: "
    print NDV

    if NDV == None:
        NDV = -9999
        print "No NDV defined"

    Raster1 = LSDMap_IO.ReadRasterArrayBlocks(raster_file1, raster_band=1)

    #nan_raster = Raster1[Raster1==NDV]=np.nan
    #print nan_raster

    #now mask the nodata
    masked_Raster1 = np.ma.masked_values(Raster1, NDV)

    means = np.mean(masked_Raster1, axis)
    medians = np.median(masked_Raster1, axis)
    std_deviations = np.std(masked_Raster1, axis)
    twentyfifth_percentile = np.percentile(masked_Raster1, 25, axis)
    seventyfifth_percentile = np.percentile(masked_Raster1, 75, axis)

    # This stuff only works with numpy 1.8 or later, wich we don't have
    #means = np.nanmean(nan_raster, axis)
    #medians = np.nanmedian(nan_raster, axis)
    #std_deviations = np.nanstd(nan_raster, axis)
    #twentyfifth_percentile = np.nanpercentile(nan_raster, 25, axis)
    #seventyfifth_percentile = np.nanpercentile(nan_raster, 75, axis)

    #print means
    #print medians
    #print std_deviations
    #print twentyfifth_percentile
    #print seventyfifth_percentile

    return means, medians, std_deviations, twentyfifth_percentile, seventyfifth_percentile
def SetNoDataBelowThreshold(raster_filename,
                            new_raster_filename,
                            threshold=0,
                            driver_name="ENVI",
                            NoDataValue=-9999):

    # read the data
    rasterArray = LSDMap_IO.ReadRasterArrayBlocks(raster_filename)
    print "Read the data"

    # set any point on the raster below the threshold as nodata
    rasterArray[rasterArray <= threshold] = NoDataValue
    print "Reset raster values"

    # write the data to a new file
    LSDMap_IO.array2raster(raster_filename, new_raster_filename, rasterArray,
                           driver_name, NoDataValue)
    print "Wrote raster"
def SetToConstantValue(raster_filename,
                       new_raster_filename,
                       constant_value,
                       driver_name="ENVI"):

    # get the nodata value
    NoDataValue = LSDMap_IO.getNoDataValue(raster_filename)

    # read the data
    rasterArray = LSDMap_IO.ReadRasterArrayBlocks(raster_filename)
    print "Read the data"

    # set any nodata to a constant value
    rasterArray[rasterArray != NoDataValue] = constant_value
    print "Changed to a constant value"

    # write the data to a new file
    LSDMap_IO.array2raster(raster_filename, new_raster_filename, rasterArray,
                           driver_name, NoDataValue)
    print "Wrote raster"
示例#8
0
def Hillshade(raster_file, azimuth=315, angle_altitude=45, NoDataVal=-9999.0):

    array = LSDMap_IO.ReadRasterArrayBlocks(raster_file, raster_band=1)

    # Addition DAV to cope with rasters that are not rectangles (e.g. clipped basins)
    nodata = NoDataVal
    array[array == nodata] = np.nan  #Set nodatas to NaN

    x, y = np.gradient(array)
    slope = np.pi / 2. - np.arctan(np.sqrt(x * x + y * y))
    aspect = np.arctan2(-x, y)
    azimuthrad = azimuth * np.pi / 180.
    altituderad = angle_altitude * np.pi / 180.


    shaded = np.sin(altituderad) * np.sin(slope)\
     + np.cos(altituderad) * np.cos(slope)\
     * np.cos(azimuthrad - aspect)

    #this_array = 255*(shaded + 1)/2
    return 255 * (shaded + 1) / 2
示例#9
0
    print(data_array)
    print(data_array.shape)

    with open(savefilename, 'wb') as f:
        _np.savetxt(f, data_array, fmt='%i %f %f %f %f')


"""Get your rasters into arrays"""
water_raster_wildcard = "/run/media/dav/SHETLAND/ModelRuns/Ryedale_storms/Gridded/Hydro/WaterDepths*.asc"
water_raster_file = "/mnt/SCRATCH/Analyses/HydrogeomorphPaper/peak_flood_maps/ryedale/WaterDepths2880_GRID_TLIM.asc"
#raster_file = "/run/media/dav/SHETLAND/Analyses/HydrogeomorphPaper/peak_flood_maps/boscastle/peak_flood/WaterDepths2400_GRID_HYDRO.asc"
floodplain_file = "/mnt/SCRATCH/Analyses/ChannelMaskAnalysis/floodplain_ryedale/RyedaleElevations_FP.bil"
stream_raster_file = "/mnt/SCRATCH/Analyses/ChannelMaskAnalysis/floodplain_ryedale/RyedaleElevations_SO.bil"

water_raster = lsdgdal.ReadRasterArrayBlocks(water_raster_file)

floodplain_mask = lsdgdal.ReadRasterArrayBlocks(floodplain_file)
stream_mask = lsdgdal.ReadRasterArrayBlocks(stream_raster_file)
#print(stream_mask)

DX = lsdgdal.GetUTMMaxMin(water_raster_file)[
    0]  # I never realised you could do this!
print(DX)
"""Calculate the depths and areas"""
#calculate_mean_waterdepth(water_raster)
#calcualte_max_waterdepth(water_raster)
#calculate_waterinundation_area(water_raster, DX, 0.02)
#floodplain_mean_depth(water_raster, floodplain_mask)
#main_channel_mean_depth(water_raster, floodplain_mask, stream_mask)
"""Make the timeseries file"""
示例#10
0
def DrapedOverHillshade(FileName,
                        DrapeName,
                        thiscmap='gray',
                        drape_cmap='gray',
                        colorbarlabel='Elevation in meters',
                        clim_val=(0, 0),
                        drape_alpha=0.6,
                        ShowColorbar=False):

    import matplotlib.pyplot as plt
    import matplotlib.lines as mpllines
    from mpl_toolkits.axes_grid1 import AxesGrid

    label_size = 20
    #title_size = 30
    axis_size = 28

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

    hillshade = Hillshade(FileName)
    #hillshade = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)
    raster_drape = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)

    # now get the extent
    extent_raster = LSDMap_IO.GetRasterExtent(FileName)

    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # make a figure, sized for a ppt slide
    fig = plt.figure(1, facecolor='white', figsize=(10, 7.5))

    if ShowColorbar:
        grid = AxesGrid(
            fig,
            111,
            nrows_ncols=(1, 1),
            axes_pad=(0.45, 0.15),
            label_mode="1",
            share_all=True,
            cbar_location="right",
            cbar_mode="each",
            cbar_size="7%",
            cbar_pad="2%",
        )
    else:
        grid = AxesGrid(
            fig,
            111,
            nrows_ncols=(1, 1),
            axes_pad=(0.45, 0.15),
            label_mode="1",
            share_all=True,
        )

    # now get the tick marks
    n_target_tics = 5
    xlocs, ylocs, new_x_labels, new_y_labels = GetTicksForUTM(
        FileName, 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)

    im = grid[0].imshow(hillshade[::-1],
                        thiscmap,
                        extent=extent_raster,
                        interpolation="nearest")
    #im = grid[0].imshow(raster, thiscmap, interpolation="nearest")
    if ShowColorbar:
        cbar = grid.cbar_axes[0].colorbar(im)
        cbar.set_label_text(colorbarlabel)

    # set the colour limits
    print "Setting colour limits to " + str(clim_val[0]) + " and " + str(
        clim_val[1])
    if (clim_val == (0, 0)):
        print "I don't think I should be here"
        im.set_clim(0, np.max(hillshade))
    else:
        print "Now setting colour limits to " + str(
            clim_val[0]) + " and " + str(clim_val[1])
        im.set_clim(clim_val[0], clim_val[1])

    # Now for the drape: it is in grayscape
    im = grid[0].imshow(raster_drape[::-1],
                        drape_cmap,
                        extent=extent_raster,
                        alpha=drape_alpha,
                        interpolation="nearest")

    # This affects all axes because we set share_all = True.
    grid.axes_llc.set_xlim(x_min, x_max)
    grid.axes_llc.set_ylim(y_max, y_min)

    grid.axes_llc.set_xticks(xlocs)
    grid.axes_llc.set_yticks(ylocs)

    grid.axes_llc.set_xticklabels(new_x_labels, rotation=60)
    grid.axes_llc.set_yticklabels(new_y_labels)

    grid.axes_llc.set_xlabel("Easting (m)")
    grid.axes_llc.set_ylabel("Northing (m)")

    plt.show()
示例#11
0
def BasicDrapedPlotGridPlot(FileName,
                            DrapeName,
                            thiscmap='gray',
                            drape_cmap='gray',
                            colorbarlabel='Elevation in meters',
                            clim_val=(0, 0),
                            drape_alpha=0.6,
                            FigFileName='Image.pdf',
                            FigFormat='show'):

    print "======================================"
    print "Yo, I'm doing a draped plot"
    print FigFileName
    print FigFormat
    print "======================================"

    import matplotlib.pyplot as plt
    import matplotlib.lines as mpllines
    from mpl_toolkits.axes_grid1 import AxesGrid

    label_size = 20
    #title_size = 30
    axis_size = 28

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

    # get the data
    raster = LSDMap_IO.ReadRasterArrayBlocks(FileName)
    raster_drape = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)

    # now get the extent
    extent_raster = LSDMap_IO.GetRasterExtent(FileName)

    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # make a figure, sized for a ppt slide
    fig = plt.figure(1, facecolor='white', figsize=(10, 7.5))

    gs = plt.GridSpec(100, 75, bottom=0.1, left=0.1, right=0.9, top=1.0)
    ax = fig.add_subplot(gs[10:100, 10:75])

    #grid = AxesGrid(fig, 111,
    #                nrows_ncols=(1, 1),
    #                axes_pad=(0.45, 0.15),
    #                label_mode="1",
    #                share_all=True,
    #                cbar_location="right",
    #                cbar_mode="each",
    #                cbar_size="7%",
    #                cbar_pad="2%",
    #                )

    # now get the tick marks
    n_target_tics = 5
    xlocs, ylocs, new_x_labels, new_y_labels = GetTicksForUTM(
        FileName, 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)

    im = ax.imshow(raster[::-1],
                   thiscmap,
                   extent=extent_raster,
                   interpolation="nearest")
    #im = grid[0].imshow(raster, thiscmap, interpolation="nearest")

    cbar = plt.colorbar(im)
    cbar.set_label(colorbarlabel)
    #cbar.set_height(1)

    #cbar = fig.cbar_axes[0].colorbar(im)
    #cbar.set_label_text(colorbarlabel)

    # set the colour limits
    print "Setting colour limits to " + str(clim_val[0]) + " and " + str(
        clim_val[1])
    if (clim_val == (0, 0)):
        print "I don't think I should be here"
        im.set_clim(0, np.max(raster))
    else:
        print "Now setting colour limits to " + str(
            clim_val[0]) + " and " + str(clim_val[1])
        im.set_clim(clim_val[0], clim_val[1])

    # Now for the drape: it is in grayscape
    im = ax.imshow(raster_drape[::-1],
                   drape_cmap,
                   extent=extent_raster,
                   alpha=drape_alpha,
                   interpolation="nearest")

    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)

    # This affects all axes because we set share_all = True.
    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_max, y_min)

    ax.set_xticks(xlocs)
    ax.set_yticks(ylocs)

    ax.set_xticklabels(new_x_labels, rotation=60)
    ax.set_yticklabels(new_y_labels)

    ax.set_xlabel("Easting (m)")
    ax.set_ylabel("Northing (m)")

    # This gets all the ticks, and pads them away from the axis so that the corners don't overlap
    ax.tick_params(axis='both', width=2.5, pad=10)
    for tick in ax.xaxis.get_major_ticks():
        tick.set_pad(10)

    print "The figure format is: " + FigFormat
    if FigFormat == 'show':
        plt.show()
    else:
        plt.savefig(FigFileName, format=FigFormat)
        fig.clf()
示例#12
0
def BasicDensityPlot(FileName,
                     thiscmap='gray',
                     colorbarlabel='Elevation in meters',
                     clim_val=(0, 0)):

    import matplotlib.pyplot as plt
    import matplotlib.lines as mpllines

    label_size = 20
    #title_size = 30
    axis_size = 28

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

    # get the data
    raster = LSDMap_IO.ReadRasterArrayBlocks(FileName)

    # now get the extent
    extent_raster = LSDMap_IO.GetRasterExtent(FileName)

    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # make a figure, sized for a ppt slide
    fig = plt.figure(1, facecolor='white', figsize=(10, 7.5))

    # make room for the colorbar
    #fig.subplots_adjust(bottom=0.1)
    #fig.subplots_adjust(top=0.9)
    #fig.subplots_adjust(left=0.2)
    #fig.subplots_adjust(right=0.8)

    ax1 = fig.add_subplot(1, 1, 1)
    im = ax1.imshow(raster[::-1], thiscmap, extent=extent_raster)

    print "The is the extent raster data element"
    print extent_raster

    print "now I am in the mapping routine"
    print "x_min: " + str(x_min)
    print "x_max: " + str(x_max)
    print "y_min: " + str(y_min)
    print "y_max: " + str(y_max)

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

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

    print "The x locs are: "
    print xlocs

    print "The x labels are: "
    print new_x_labels

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

    for line in ax1.get_yticklines():
        line.set_marker(mpllines.TICKLEFT)
        #line.set_markeredgewidth(3)

    plt.xlim(x_min, x_max)
    plt.ylim(y_max, y_min)

    plt.xlabel('Easting (m)', fontsize=axis_size)
    plt.ylabel('Northing (m)', fontsize=axis_size)

    ax1.set_xlabel("Easting (m)")
    ax1.set_ylabel("Northing (m)")

    # set the colour limits
    print "Setting colour limits to " + str(clim_val[0]) + " and " + str(
        clim_val[1])
    if (clim_val == (0, 0)):
        print "I don't think I should be here"
        im.set_clim(0, np.max(raster))
    else:
        print "Now setting colour limits to " + str(
            clim_val[0]) + " and " + str(clim_val[1])
        im.set_clim(clim_val[0], clim_val[1])

    cbar = fig.colorbar(im, orientation='vertical')
    cbar.set_label(colorbarlabel)

    #plt.tight_layout()

    plt.show()
示例#13
0
def BasicChiPlotGridPlot(FileName,
                         DrapeName,
                         chi_csv_fname,
                         thiscmap='gray',
                         drape_cmap='gray',
                         colorbarlabel='Elevation in meters',
                         clim_val=(0, 0),
                         drape_alpha=0.6,
                         FigFileName='Image.pdf',
                         FigFormat='show',
                         elevation_threshold=0):

    import matplotlib.pyplot as plt
    import matplotlib.lines as mpllines
    from mpl_toolkits.axes_grid1 import AxesGrid
    from matplotlib import colors

    label_size = 10
    #title_size = 30
    axis_size = 12

    # Set up fonts for plots
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['arial']
    rcParams['font.size'] = label_size
    #plt.rc('text', usetex=True)

    # get the data
    raster = LSDMap_IO.ReadRasterArrayBlocks(FileName)
    raster_drape = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)

    # now get the extent
    extent_raster = LSDMap_IO.GetRasterExtent(FileName)

    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # make a figure, sized for a ppt slide
    fig = plt.figure(1, facecolor='white', figsize=(4.92126, 3.5))

    gs = plt.GridSpec(100, 100, bottom=0.25, left=0.1, right=1.0, top=1.0)
    ax = fig.add_subplot(gs[25:100, 10:95])

    # This is the axis for the colorbar
    ax2 = fig.add_subplot(gs[10:15, 15:70])

    #grid = AxesGrid(fig, 111,
    #                nrows_ncols=(1, 1),
    #                axes_pad=(0.45, 0.15),
    #                label_mode="1",
    #                share_all=True,
    #                cbar_location="right",
    #                cbar_mode="each",
    #                cbar_size="7%",
    #                cbar_pad="2%",
    #                )

    # now get the tick marks
    n_target_tics = 5
    xlocs, ylocs, new_x_labels, new_y_labels = LSDMap_BP.GetTicksForUTM(
        FileName, 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)

    #Z1 = np.array(([0, 1]*4 + [1, 0]*4)*4)
    #Z1.shape = (8, 8)  # chessboard
    #im2 = ax.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest',
    #             extent=extent_raster)

    #plt.hold(True)

    im1 = ax.imshow(raster[::-1],
                    thiscmap,
                    extent=extent_raster,
                    interpolation="nearest")

    # set the colour limits
    print "Setting colour limits to " + str(clim_val[0]) + " and " + str(
        clim_val[1])
    if (clim_val == (0, 0)):
        print "Im setting colour limits based on minimum and maximum values"
        im1.set_clim(0, np.max(raster))
    else:
        print "Now setting colour limits to " + str(
            clim_val[0]) + " and " + str(clim_val[1])
        im1.set_clim(clim_val[0], clim_val[1])

    plt.hold(True)

    # Now for the drape: it is in grayscale
    #print "drape_cmap is: "+drape_cmap
    im3 = ax.imshow(raster_drape[::-1],
                    drape_cmap,
                    extent=extent_raster,
                    alpha=drape_alpha,
                    interpolation="nearest")

    # Set the colour limits of the drape
    im3.set_clim(0, np.max(raster_drape))

    ax.spines['top'].set_linewidth(1)
    ax.spines['left'].set_linewidth(1)
    ax.spines['right'].set_linewidth(1)
    ax.spines['bottom'].set_linewidth(1)

    #ax.spines['bottom'].set_capstyle('projecting')

    #for spine in ax.spines.values():
    #    spine.set_capstyle('projecting')

    ax.set_xticklabels(new_x_labels, rotation=60)
    ax.set_yticklabels(new_y_labels)

    ax.set_xlabel("Easting (m)")
    ax.set_ylabel("Northing (m)")

    # This gets all the ticks, and pads them away from the axis so that the corners don't overlap
    ax.tick_params(axis='both', width=1, pad=2)
    for tick in ax.xaxis.get_major_ticks():
        tick.set_pad(2)

    # Now we get the chi points
    EPSG_string = LSDMap_IO.GetUTMEPSG(FileName)
    print "EPSG string is: " + EPSG_string

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)
    thisPointData.ThinData('elevation', elevation_threshold)

    # convert to easting and northing
    [easting, northing] = thisPointData.GetUTMEastingNorthing(EPSG_string)

    # The image is inverted so we have to invert the northing coordinate
    Ncoord = np.asarray(northing)
    Ncoord = np.subtract(extent_raster[3], Ncoord)
    Ncoord = np.add(Ncoord, extent_raster[2])

    M_chi = thisPointData.QueryData('m_chi')
    #print M_chi
    M_chi = [float(x) for x in M_chi]

    # make a color map of fixed colors
    this_cmap = colors.ListedColormap(
        ['#2c7bb6', '#abd9e9', '#ffffbf', '#fdae61', '#d7191c'])
    bounds = [0, 50, 100, 175, 250, 1205]
    norm = colors.BoundaryNorm(bounds, this_cmap.N)

    sc = ax.scatter(easting,
                    Ncoord,
                    s=0.5,
                    c=M_chi,
                    cmap=this_cmap,
                    norm=norm,
                    edgecolors='none')

    # This affects all axes because we set share_all = True.
    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_max, y_min)

    ax.set_xticks(xlocs)
    ax.set_yticks(ylocs)

    cbar = plt.colorbar(sc,
                        cmap=this_cmap,
                        norm=norm,
                        spacing='uniform',
                        ticks=bounds,
                        boundaries=bounds,
                        orientation='horizontal',
                        cax=ax2)
    cbar.set_label(colorbarlabel, fontsize=10)
    ax2.set_xlabel(colorbarlabel, fontname='Arial', labelpad=-35)

    print "The figure format is: " + FigFormat
    if FigFormat == 'show':
        plt.show()
    elif FigFormat == 'return':
        return fig
    else:
        plt.savefig(FigFileName, format=FigFormat, dpi=500)
        fig.clf()
示例#14
0
def DrapedOverHillshade(FileName,
                        DrapeName,
                        thiscmap='gray',
                        drape_cmap='gray',
                        colorbarlabel='Elevation in meters',
                        clim_val=(0, 0),
                        drape_alpha=0.6,
                        ShowColorbar=False,
                        ShowDrapeColorbar=False,
                        drape_cbarlabel=None):

    import matplotlib.pyplot as plt
    import matplotlib.lines as mpllines
    from mpl_toolkits.axes_grid1 import AxesGrid, make_axes_locatable

    label_size = 20
    #title_size = 30
    axis_size = 28

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

    hillshade = Hillshade(FileName)
    #hillshade = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)

    # DAV - option to supply array directly (after masking for example, rather
    # than reading directly from a file. Should not break anyone's code)
    # (You can't overload functions in Python...)
    if isinstance(DrapeName, str):
        raster_drape = LSDMap_IO.ReadRasterArrayBlocks(DrapeName)
    elif isinstance(DrapeName, np.ndarray):
        raster_drape = DrapeName
    else:
        print "DrapeName supplied is of type: ", type(DrapeName)
        raise ValueError('DrapeName must either be a string to a filename, \
      or a numpy ndarray type. Please try again.')

    # now get the extent
    extent_raster = LSDMap_IO.GetRasterExtent(FileName)

    x_min = extent_raster[0]
    x_max = extent_raster[1]
    y_min = extent_raster[2]
    y_max = extent_raster[3]

    # make a figure, sized for a ppt slide
    fig = plt.figure(1, facecolor='white', figsize=(10, 7.5))

    if ShowColorbar:
        grid = AxesGrid(
            fig,
            111,
            nrows_ncols=(1, 1),
            axes_pad=(0.45, 0.15),
            label_mode="1",
            share_all=True,
            cbar_location="right",
            cbar_mode="each",
            cbar_size="7%",
            cbar_pad="2%",
        )

    #ShowDrapeColorbar = True
    #if ShowDrapeColorbar and ShowColorbar:
    #divider = make_axes_locatable(fig)
    #cax = divider.append_axes("right", size = "5%", pad=0.05)

    else:
        grid = AxesGrid(
            fig,
            111,
            nrows_ncols=(1, 1),
            axes_pad=(0.45, 0.15),
            label_mode="1",
            share_all=True,
        )

    # now get the tick marks
    n_target_tics = 5
    xlocs, ylocs, new_x_labels, new_y_labels = GetTicksForUTM(
        FileName, 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)

    im = grid[0].imshow(hillshade[::-1],
                        thiscmap,
                        extent=extent_raster,
                        interpolation="nearest")
    #im = grid[0].imshow(raster, thiscmap, interpolation="nearest")
    if ShowColorbar:
        cbar = grid.cbar_axes[0].colorbar(im)
        cbar.set_label_text(colorbarlabel)

    # set the colour limits
    print "Setting colour limits to " + str(clim_val[0]) + " and " + str(
        clim_val[1])
    if (clim_val == (0, 0)):
        print "I don't think I should be here"
        im.set_clim(0, np.max(hillshade))
    else:
        print "Now setting colour limits to " + str(
            clim_val[0]) + " and " + str(clim_val[1])
        im.set_clim(clim_val[0], clim_val[1])

    # Now for the drape: it is in grayscape
    im2 = grid[0].imshow(raster_drape[::-1],
                         drape_cmap,
                         extent=extent_raster,
                         alpha=drape_alpha,
                         interpolation="nearest")

    if ShowDrapeColorbar:
        cbar2 = grid.cbar_axes[0].colorbar(im2)
        cbar2.set_label_text(drape_cbarlabel)

        #plt.colorbar(im)

    # This affects all axes because we set share_all = True.
    grid.axes_llc.set_xlim(x_min, x_max)
    grid.axes_llc.set_ylim(y_max, y_min)

    grid.axes_llc.set_xticks(xlocs)
    grid.axes_llc.set_yticks(ylocs)

    grid.axes_llc.set_xticklabels(new_x_labels, rotation=60)
    grid.axes_llc.set_yticklabels(new_y_labels)

    grid.axes_llc.set_xlabel("Easting (m)")
    grid.axes_llc.set_ylabel("Northing (m)")

    plt.show()