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 GetHillshade(raster_filename,
                 new_raster_filename,
                 azimuth=315,
                 angle_altitude=45,
                 driver_name="ENVI",
                 NoDataValue=-9999):

    # get the hillshade
    hillshade_raster = LSDMBP.Hillshade(raster_filename, azimuth,
                                        angle_altitude)

    # write to file
    LSDMap_IO.array2raster(raster_filename, new_raster_filename,
                           hillshade_raster, driver_name, NoDataValue)
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
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"
Пример #5
0
def SwathPlot(path, filename, axis):

    # get the path to the raster file
    NewPath = LSDOst.AppendSepToDirectoryPath(path)
    FileName = NewPath + filename

    # get the data vectors
    means, medians, std_deviations, twentyfifth_percentile, seventyfifth_percentile = LSDMap_BM.SimpleSwath(
        path, filename, axis)

    print "Means shape is: "
    print means.shape

    x_vec, y_vec = LSDMap_IO.GetLocationVectors(FileName)

    print "X shape is: "
    print x_vec.shape

    print "Y shape is: "
    print y_vec.shape

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

    label_size = 20
    #title_size = 30
    axis_size = 28

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

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

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

    if axis == 0:
        dir_vec = x_vec
    else:
        dir_vec = y_vec

    min_sd = np.subtract(means, std_deviations)
    plus_sd = np.add(means, std_deviations)

    ax.plot(dir_vec, means, linewidth=2, color="red")
    #ax.fill_between(dir_vec, twentyfifth_percentile, seventyfifth_percentile, facecolor='green', alpha = 0.7, interpolate=True)
    ax.fill_between(dir_vec,
                    min_sd,
                    plus_sd,
                    facecolor='blue',
                    alpha=0.5,
                    interpolate=True)

    ax.set_xlim(dir_vec[0], dir_vec[-1])

    plt.show()
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"
Пример #9
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
Пример #11
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
Пример #12
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
Пример #13
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"""
Пример #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):

    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()
Пример #15
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()
Пример #16
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()
Пример #17
0
def GetTicksForUTM(FileName, x_max, x_min, y_max, y_min, n_target_tics):

    CellSize, XMin, XMax, YMin, YMax = LSDMap_IO.GetUTMMaxMin(FileName)
    NDV, xsize, ysize, GeoT, Projection, DataType = LSDMap_IO.GetGeoInfo(
        FileName)

    xmax_UTM = XMax
    xmin_UTM = XMin

    ymax_UTM = YMax
    ymin_UTM = YMin

    #print "now UTM, xmax: " +str(xmax_UTM)+" x_min: " +str(xmin_UTM)+" y_maxb: " +str(ymax_UTM)+" y_minb: " +str(ymin_UTM)

    dy_fig = ymax_UTM - ymin_UTM
    dx_fig = xmax_UTM - xmin_UTM

    dx_spacing = dx_fig / n_target_tics
    dy_spacing = dy_fig / n_target_tics

    if (dx_spacing > dy_spacing):
        dy_spacing = dx_spacing

    str_dy = str(dy_spacing)
    str_dy = str_dy.split('.')[0]
    n_digits = str_dy.__len__()
    nd = int(n_digits)

    first_digit = float(str_dy[0])

    #print "str_dy: " +str_dy+ " n_digits: " +str(nd)+" first_digit: " + str(first_digit)

    dy_spacing_rounded = first_digit * pow(10, (nd - 1))
    #print "n_digits: "+str(n_digits)+" dy_spacing: " +str(dy_spacing) + " and rounded: "+str(dy_spacing_rounded)

    str_xmin = str(xmin_UTM)
    str_ymin = str(ymin_UTM)
    #print "before split str_xmin: "+ str_xmin + " str ymin: " + str_ymin
    str_xmin = str_xmin.split('.')[0]
    str_ymin = str_ymin.split('.')[0]
    #print "after split str_xmin: "+ str_xmin + " str ymin: " + str_ymin
    xmin_UTM = float(str_xmin)
    ymin_UTM = float(str_ymin)
    #print "UTM: "+ str(xmin_UTM) + " str ymin: " + str(ymin_UTM)

    n_digx = str_xmin.__len__()
    n_digy = str_ymin.__len__()

    #print "n_dig_x: " + str(n_digx)+ " nd: " + str(nd)

    if (n_digx - nd + 1) >= 1:
        front_x = str_xmin[:(n_digx - nd + 1)]
    else:
        front_x = str_xmin

    if (n_digy - nd + 1) >= 1:
        front_y = str_ymin[:(n_digy - nd + 1)]
    else:
        front_y = str_ymin

    #print "xmin: " + str_xmin + " ymin: " + str_ymin + " n_digx: " + str(n_digx)+ " n_digy: " + str(n_digy)
    #print "frontx: " +front_x+" and fronty: "+ front_y

    round_xmin = float(front_x) * pow(10, nd - 1)
    round_ymin = float(front_y) * pow(10, nd - 1)

    #print "x_min: " +str(xmin_UTM)+ " round xmin: " +str(round_xmin)+ " y_min: " +str(ymin_UTM)+" round y_min: " + str(round_ymin)

    # now we need to figure out where the xllocs and ylocs are
    xUTMlocs = np.zeros(2 * n_target_tics)
    yUTMlocs = np.zeros(2 * n_target_tics)
    xlocs = np.zeros(2 * n_target_tics)
    ylocs = np.zeros(2 * n_target_tics)

    new_x_labels = []
    new_y_labels = []

    round_ymax = round_ymin + dy_spacing_rounded * (2 * n_target_tics - 1)
    #print "n_target_tics: " + str(n_target_tics) + " round_ymax: " +str(round_ymax)

    for i in range(0, 2 * n_target_tics):
        xUTMlocs[i] = round_xmin + (i) * dy_spacing_rounded
        yUTMlocs[i] = round_ymin + (i) * dy_spacing_rounded

        #xlocs[i] = (xUTMlocs[i]-XMin)
        xlocs[i] = xUTMlocs[i]

        # need to account for the rows starting at the upper boundary
        ylocs[i] = round_ymax - (yUTMlocs[i] - round_ymin)

        #print "i: " + str(i) +" yUTM: " + str(yUTMlocs[i])+ " rounded, reversed: " +str( ylocs[i])

        new_x_labels.append(str(xUTMlocs[i]).split(".")[0])
        new_y_labels.append(str(yUTMlocs[i]).split(".")[0])

    #print xUTMlocs
    #print xlocs
    #print yUTMlocs
    #print ylocs
    #print new_x_labels
    #print new_y_labels

    new_xlocs = []
    new_xUTMlocs = []
    x_labels = []

    # Now loop through these to get rid of those not in range
    for index, xloc in enumerate(xlocs):
        #print xloc
        if (xloc < XMax and xloc > XMin):
            new_xlocs.append(xloc)
            new_xUTMlocs.append(xUTMlocs[index])
            x_labels.append(new_x_labels[index])

    new_ylocs = []
    new_yUTMlocs = []
    y_labels = []

    # Now loop through these to get rid of those not in range
    for index, yloc in enumerate(ylocs):
        #print yloc
        if (yloc < YMax and yloc > YMin):
            new_ylocs.append(yloc)
            new_yUTMlocs.append(yUTMlocs[index])
            y_labels.append(new_y_labels[index])

    #print "======================================="
    #print "I am getting the tick marks now"
    #print "X extent: " + str(XMin)+ " " +str(XMax)
    #print "Y extent: " + str(YMin)+ " " +str(YMax)
    #print "x ticks: "
    #print new_xlocs
    #print "y ticks: "
    #print new_ylocs

    #return xlocs,ylocs,new_x_labels,new_y_labels
    return new_xlocs, new_ylocs, x_labels, y_labels
Пример #18
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()
Пример #19
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()