def ExampleOne_PartOne_SimpleHillshade(DataDirectory,Base_file):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        Base_file (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: FJC
    """
    # specify the figure size and format
    fig_size_inches = 12
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    DrapeRasterName = Base_file+".bil"

    # clear the plot
    plt.clf()

    # this is where we want the colourbar
    cbar_loc = "right"

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = "jet", alpha = 0.6, colorbarlabel = "Elevation (m)")

    # Save the image
    ImageName = DataDirectory+"Xian_example1_hillshade.png"
    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250)
def PrintChannels(DataDirectory,fname_prefix, add_basin_labels = True, cmap = "jet", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function prints a channel map over a hillshade.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = fname_prefix+"_hs.bil"
    DrapeRasterName = fname_prefix+".bil"
    ChannelFileName = fname_prefix+"_chi_data_map.csv"
    chi_csv_fname = DataDirectory+ChannelFileName

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)


    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = "None")
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = cmap, alpha = 0.6)
    MF.add_point_data(thisPointData,column_for_plotting = "basin_key",
                       scale_points = True,column_for_scaling = "drainage_area",
                       scaled_data_in_log = True,
                       max_point_size = 5, min_point_size = 1)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_channels_coloured_by_basin."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_channels_coloured_by_basin."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
def SimpleHillshade(DataDirectory,Base_file, cmap = "jet", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function makes a shaded relief plot of the DEM.

    Args:
        DataDirectory (str): the data directory with the rasters
        Base_file (str): The prefix for the rasters
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix

    Returns:
        Shaded relief plot. The elevation is also included in the plot.

    Author: FJC, SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    DrapeRasterName = Base_file+".bil"

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = cmap, alpha = 0.6, colorbarlabel = "Elevation (m)")

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+Base_file+"_hillshade."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_hillshade."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
def map_custom():
    """
    Testing function to plot custom maps before creating real function for mapping routines

    Args:
        Yes.
    returns:
        No.
    Author:
        BG
    """
    ###### Parameters ######
    Directory = "/home/s1675537/PhD/DataStoreBoris/GIS/Data/Carpathian/knickpoint/" # reading directory
    wDirectory = Directory # writing directory
    Base_file = "Buzau" # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata
    csv_file = Directory + "test_sign_m_chi.csv" # Name of your point file, add a similar line with different name if you have more than one point file
    DrapeRasterName = "Buzau_hs.bil" # if you want to drap a raster on your background one. Just add a similar line in case you want another raster to drap and so on
    wname = "sign_test" # name of your output file
    dpi = 500 # Quality of your output image, don't exceed 900
    fig_size_inches = 7 # Figure size in Inches

    ##### Now we can load and plot the data

    BackgroundRasterName = Base_file + ".bil" # Ignore this line
    thisPointData = LSDP.LSDMap_PointData(csv_file, PANDEX = True) # Load the point file #1, add a similar line with different name if you have more than one point file.

    plt.clf() # Ignore this line

    MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km") # load the background raster

    MF.add_drape_image(DrapeRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one
                        colourmap = "gray", # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                        alpha=0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                        show_colourbar = False, # Well, this one is explicit I think
                        colorbarlabel = "Colourbar") # Name of your Colourbar, it might bug though



    MF.add_point_data( thisPointData, # this function plot the requested point file using the lat/long column in the csv file
                       column_for_plotting = "m_chi_sign",  # Column used to color the data
                       this_colourmap = "cubehelix", # Colormap used, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                       colorbarlabel = "Colourbar", # Label
                       scale_points = False, # All the point will have the same size if False
                       column_for_scaling = "None", # If scale point True, you can scale the size of your points using one of the columns
                       scaled_data_in_log = False, # If scale point True, you can log the scaling
                       max_point_size = 5, # max size if scale point True again
                       min_point_size = 0.5, # You should be able to guess that one now
                       coulor_log = False, # do you want a log scale for your colorbar ?
                       coulor_manual_scale = [], #Do you want to manually limit the scale of your colorbar? if not let is false
                       manual_size = 0.5, # If none of above is choosen but you want to put another value than 0.5 to scale your point
                       alpha = 1, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                       minimum_log_scale_cut_off = -10) # you probably won't need this

    ImageName = wDirectory+str(int(clock.time()))+wname+".png" # Ignore this
    ax_style = "Normal" # Ignore this
    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = dpi) # Save the figure
def PrintChannels(DataDirectory,fname_prefix, add_basin_labels = True, cmap = "jet", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function prints a channel map over a hillshade.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = fname_prefix+"_hs.bil"
    DrapeRasterName = fname_prefix+".bil"
    ChannelFileName = fname_prefix+"_chi_data_map.csv"
    chi_csv_fname = DataDirectory+ChannelFileName

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)


    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = "None")
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = cmap, alpha = 0.6)
    MF.add_point_data(thisPointData,column_for_plotting = "basin_key",
                       scale_points = True,column_for_scaling = "drainage_area",
                       scaled_data_in_log = True,
                       max_point_size = 5, min_point_size = 1)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_channels_coloured_by_basin."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_channels_coloured_by_basin."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
def SimpleDrape(DataDirectory,Base_file, Drape_prefix, cmap = "jet", cbar_loc = "right", cbar_label = "drape colourbar", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = "", coord_type = "UTM_km", use_scalebar = False, drape_cnorm = "none", colour_min_max = []):
    """
    This function makes a simple drape plot. You can choose the colourbar in this one. Similar to the PlotHillshade routine but a bit more flexible.

    Args:
        DataDirectory (str): the data directory with the rasters
        Base_file (str): The prefix for the rasters
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
        coord_type (str): this can be in UTM_km or UTM_m
        use_scalebar (bool): If true inserts a scalebar in the image
        drape_cnorm (str): Sets the normalisation of the colourbar. 
        colour_min_max (float list): Sets the minimum and maximum values of the colourbar

    Returns:
        Shaded relief plot. The elevation is also included in the plot.

    Author: FJC, SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    ElevationName = Base_file+".bil"
    DrapeName = Drape_prefix+".bil"

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type=coord_type,colourbar_location = cbar_loc)
    #MF.add_drape_image(ElevationName,DataDirectory,colourmap = "gray", alpha = 0.6, colorbarlabel = None)
    MF.add_drape_image(DrapeName,DataDirectory,colourmap = cmap, alpha = 0.6, colorbarlabel = cbar_label, norm = drape_cnorm, colour_min_max = colour_min_max)
    
    if(use_scalebar):
        print("Let me add a scalebar")
        MF.add_scalebar()

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+Base_file+"_drape."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_drape."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
示例#7
0
def ExampleOne_PartOne_SimpleHillshade(DataDirectory,Base_file):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        Base_file (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: FJC
    """
    # specify the figure size and format
    fig_size_inches = 12
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    DrapeRasterName = Base_file+".bil"

    # clear the plot
    plt.clf()

    # this is where we want the colourbar
    cbar_loc = "right"

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = "jet", alpha = 0.6, colorbarlabel = "Elevation (m)")

    # Save the image
    ImageName = DataDirectory+"Xian_example1_hillshade.png"
    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250)
def SimpleHillshadeForAnimation(DataDirectory,Base_file, cmap = "jet", cbar_loc = "right",
                                size_format = "ESURF", fig_format = "png",
                                dpi = 250, imgnumber = 0, full_basefile = [],
                                custom_cbar_min_max = [], out_fname_prefix = ""):
    """
    This function make a hillshade image that is optimised for creating
    an animation. Used with the MuddPILE model

    Args:
        DataDirectory (str): the data directory with the data files
        Base_file (str): The prefix for the data files
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        imgnumber (int): the number of the image. Usually frames from model runs have integer numbers after them
        full_basefile (str): The root name of the figures you want. If empty, it uses the data_directory+base_file
        custom_min_max (list of int/float): if it contains two elements, recast the raster to [min,max] values for display.
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix

    Returns:
        Shaded relief plot. The elevation is also included in the plot.

    Author: FJC, SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    DrapeRasterName = Base_file+".bil"

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = cmap, alpha = 0.6, colorbarlabel = "Elevation (m)",colour_min_max = custom_cbar_min_max)

    # Save the image
    if(full_basefile == []):
        if len(out_fname_prefix) == 0:
            ImageName = DataDirectory+Base_file+"_img"+"%004d" % (imgnumber)+"."+fig_format
        else:
            ImageName = DataDirectory+out_fname_prefix+"_img"+"%004d" % (imgnumber)+"."+fig_format
    else:
        ImageName = full_basefile+"_img"+"%004d" % (imgnumber)+"."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi, adjust_cbar_characters=False,
                 fixed_cbar_characters=4)
def SimpleDrape(DataDirectory,Base_file, Drape_prefix, cmap = "jet", cbar_loc = "right", cbar_label = "drape colourbar", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function makes a simple drape plot. You can choose the colourbar in this one. Similar to the PlotHillshade routine but a bit more flexible.

    Args:
        DataDirectory (str): the data directory with the rasters
        Base_file (str): The prefix for the rasters
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix

    Returns:
        Shaded relief plot. The elevation is also included in the plot.

    Author: FJC, SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    ElevationName = Base_file+".bil"
    DrapeName = Drape_prefix+".bil"

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
    #MF.add_drape_image(ElevationName,DataDirectory,colourmap = "gray", alpha = 0.6, colorbarlabel = None)
    MF.add_drape_image(DrapeName,DataDirectory,colourmap = cmap, alpha = 0.6, colorbarlabel = cbar_label)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+Base_file+"_drape."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_drape."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
示例#10
0
def PlotRasterLithology(DataDirectory, fname_prefix, geol_raster='geol'):
    """
        Make a hillshade and rasterise a geology shapefile and drape on the top.
        Uses the LSDPlottingTools libraries. https://github.com/LSDtopotools/LSDMappingTools

        Args:
            stream_order: the stream order of the profiles that you are analysing
            shapefile_name: name of the lithology shapefile
            geol_field: the field of the shapefile that has the lithology information

        Author: FJC
        """
    import LSDPlottingTools as LSDP
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    fig_width_inches = 8

    # some raster names
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HSName = fname_prefix + '_hs' + raster_ext

    if not os.path.isfile(DataDirectory + HSName):
        # make a hillshade
        BM.GetHillshade(DataDirectory + BackgroundRasterName,
                        DataDirectory + HSName)

    # create the map figure
    MF = MapFigure(HSName, DataDirectory, coord_type="UTM")

    #geology
    LithName = geol_raster
    print("The geology raster is" + LithName)
    MF.add_drape_image(LithName,
                       DataDirectory,
                       colourmap=plt.cm.jet,
                       alpha=0.5,
                       show_colourbar=False,
                       discrete_cmap=True,
                       cbar_type=int,
                       mask_value=0)

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=DataDirectory + fname_prefix + '_lith.png',
                FigFormat='png',
                Fig_dpi=300,
                fixed_cbar_characters=6,
                adjust_cbar_characters=False,
                transparent=True)  # Save the figure
def PrintChannelsAndBasins(DataDirectory,
                           fname_prefix,
                           add_basin_labels=True,
                           cmap="jet",
                           cbar_loc="right",
                           size_format="ESURF",
                           fig_format="png",
                           dpi=250,
                           out_fname_prefix=""):
    """
    This function prints a channel map over a hillshade.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print('Basin keys are: ')
    print(basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print(
        "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!"
    )

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix + '_hs' + raster_ext
    BasinsName = fname_prefix + '_AllBasins' + raster_ext
    print(BasinsName)
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)

    ChannelFileName = fname_prefix + "_chi_data_map.csv"
    chi_csv_fname = DataDirectory + ChannelFileName

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)

    # clear the plot
    plt.clf()

    # set up the base image and the map
    print("I am showing the basins without text labels.")
    MF = MapFigure(HillshadeName,
                   DataDirectory,
                   coord_type="UTM_km",
                   colourbar_location="None")
    MF.plot_polygon_outlines(Basins, linewidth=0.8)
    MF.add_drape_image(BasinsName,
                       DataDirectory,
                       colourmap=cmap,
                       alpha=0.1,
                       discrete_cmap=False,
                       n_colours=len(basin_keys),
                       show_colourbar=False,
                       modify_raster_values=True,
                       old_values=basin_junctions,
                       new_values=basin_keys,
                       cbar_type=int)

    MF.add_point_data(thisPointData,
                      column_for_plotting="basin_key",
                      scale_points=True,
                      column_for_scaling="drainage_area",
                      this_colourmap=cmap,
                      scaled_data_in_log=True,
                      max_point_size=3,
                      min_point_size=1)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory + fname_prefix + "_channels_with_basins." + fig_format
    else:
        ImageName = DataDirectory + out_fname_prefix + "_channels_with_basins." + fig_format

    MF.save_fig(fig_width_inches=fig_size_inches,
                FigFileName=ImageName,
                axis_style=ax_style,
                FigFormat=fig_format,
                Fig_dpi=dpi)
def PrintBasins_Complex(DataDirectory,
                        fname_prefix,
                        use_keys_not_junctions=True,
                        show_colourbar=False,
                        Remove_Basins=[],
                        Rename_Basins={},
                        Value_dict={},
                        cmap="jet",
                        colorbarlabel="colourbar",
                        size_format="ESURF",
                        fig_format="png",
                        dpi=250,
                        out_fname_prefix="",
                        include_channels=False,
                        label_basins=True):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        use_keys_not_junctions (bool): If true use basin keys to locate basins, otherwise use junction indices
        show_colourbar (bool): if true show the colourbar
        Remove_Basins (list): A lists containing either key or junction indices of basins you want to remove from plotting
        Rename_Basins (dict): A dict where the key is either basin key or junction index, and the value is a new name for the basin denoted by the key
        Value_dict (dict): A dict where the key is either basin key or junction index, and the value is a value of the basin that is used to colour the basins
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
        include_channels (bool): If true, adds a channel plot. It uses the chi_data_maps file
        label_basins (bool): If true, the basins get labels

    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin. This allows more complex plotting with renamed and excluded basins.

    Author: FJC, SMM
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print('Basin keys are: ')
    print(basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print(
        "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!"
    )

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix + '_hs' + raster_ext
    BasinsName = fname_prefix + '_AllBasins' + raster_ext

    # This initiates the figure
    MF = MapFigure(HillshadeName,
                   DataDirectory,
                   coord_type="UTM_km",
                   colourbar_location="None")

    # This adds the basins
    MF.add_basin_plot(BasinsName,
                      fname_prefix,
                      DataDirectory,
                      mask_list=Remove_Basins,
                      rename_dict=Rename_Basins,
                      value_dict=Value_dict,
                      use_keys_not_junctions=use_keys_not_junctions,
                      show_colourbar=show_colourbar,
                      discrete_cmap=True,
                      n_colours=15,
                      colorbarlabel=colorbarlabel,
                      colourmap=cmap,
                      adjust_text=False,
                      label_basins=label_basins)

    # See if you need the channels
    if include_channels:
        print("I am going to add some channels for you")
        ChannelFileName = fname_prefix + "_chi_data_map.csv"
        chi_csv_fname = DataDirectory + ChannelFileName

        thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)

        MF.add_point_data(thisPointData,
                          column_for_plotting="basin_key",
                          scale_points=True,
                          column_for_scaling="drainage_area",
                          this_colourmap="Blues_r",
                          scaled_data_in_log=True,
                          max_point_size=3,
                          min_point_size=1,
                          discrete_colours=True,
                          NColours=1,
                          zorder=5)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory + fname_prefix + "_selected_basins." + fig_format
    else:
        ImageName = DataDirectory + out_fname_prefix + "_selected_basins." + fig_format

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=ImageName,
                FigFormat=fig_format,
                Fig_dpi=dpi,
                transparent=True)  # Save the figure
def PlotTopoRaster(DataDirectory,
                   fname_prefix,
                   size_format='ESURF',
                   FigFormat='png',
                   colors="terrain"):
    """
    Creates a basic Terrain topographic raster. Needs the Hillshade 

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).
        FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command.

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: BG, FJC
    """
    # check if a directory exists for the chi plots. If not then make it.
    raster_directory = DataDirectory + 'raster_plots/'
    if not os.path.isdir(raster_directory):
        os.makedirs(raster_directory)

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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make a cabic topographic plot")

    # get the rasters
    raster_ext = '.bil'
    ## Just checking if you have a PP version of it
    if os.path.isfile(DataDirectory + fname_prefix + "_PP.bil"):
        BackgroundRasterName = fname_prefix + "_PP" + raster_ext
    else:
        BackgroundRasterName = fname_prefix + raster_ext

    HillshadeName = fname_prefix + '_hs' + raster_ext

    # create the map figure
    MF = MapFigure(BackgroundRasterName,
                   DataDirectory,
                   coord_type="UTM_km",
                   colourbar_location='None')

    # Drape the hillshade and add the color
    ## Frist plot the terrain toporaster
    MF.add_drape_image(
        BackgroundRasterName,
        DataDirectory,  # Calling the function will add a drapped raster on the top of the background on
        colourmap=
        colors,  # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
        alpha=
        1,  # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
        show_colourbar=True,  # Well, this one is explicit I think
        colorbarlabel="None",
        NFF_opti=True)
    ## Drape the Hillshade raster
    MF.add_drape_image(
        HillshadeName,
        DataDirectory,  # Calling the function will add a drapped raster on the top of the background on
        colourmap=
        "gray",  # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
        alpha=
        0.4,  # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
        show_colourbar=True,  # Well, this one is explicit I think
        colorbarlabel="None",
        NFF_opti=True)

    # Save the figure
    ImageName = raster_directory + fname_prefix + '_Topo.' + FigFormat
    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=ImageName,
                FigFormat=FigFormat,
                Fig_dpi=300)
    '#C8C864', '#9D78C1', '#6E9C6E', '#AF5A5A', '#A6835F', '#A7DBA7',
    '#AF5A5A', '#F3C79B', '#AF5A5A', '#6E899B', '#B1DEDE'
]
CustomColorCombMap = matplotlib.colors.ListedColormap(CustomColorComb)

#%%======================CONVERT_CSV_FILE_TO_SHAPEFILES=====================%%#
thisPointData = LSDP.LSDMap_PointData(csv_file, PANDEX=True)

#%%============================LOAD_AND_PLOT_DATA===========================%%#

plt.clf()

MF = MapFigure(BaseRasterName=BaseRasterName,
               Directory=Import_Directory,
               coord_type="UTM",
               colourbar_location="None",
               basemap_colourmap="gray",
               plot_title='None',
               NFF_opti=False,
               alpha=1)  # load and display the background hillslope raster

MF.add_basin_plot(RasterName=RasterNameCatch,
                  BasinInfoPrefix=BasinInfoPrefix,
                  Directory=Import_Directory,
                  colourmap="gray",
                  alpha=1,
                  show_colourbar="False",
                  colorbarlabel="Colourbar",
                  discrete_cmap=False,
                  n_colours=10,
                  cbar_type=float,
                  use_keys_not_junctions=True,
#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#label_size = 100
#rcParams['font.family'] = 'sans-serif'
#rcParams['font.sans-serif'] = ['arial']
#rcParams['font.size'] = label_size
#rcParams['lines.linewidth']  = 1.5

plt.clf()
MF = MapFigure(DrapeRasterName, Directory,coord_type="UTM_km",colourbar_location='None')
# add the basins drape
cmap = cm.Set1
MF.add_drape_image(BasinsName, Directory, colourmap = cmap, alpha = 0.5, colorbarlabel='Basin ID', show_colourbar = False)
# add the basin outlines
Basins = LSDMap_VT.GetBasinOutlines(Directory, BasinsName)
MF.plot_polygon_outlines(Basins, linewidth=0.8)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True)
#MF.show_plot()
MF.save_fig(fig_width_inches = 12, FigFileName=Directory+Base_file+'.png', FigFormat='png', Fig_dpi=300, transparent=True)

# Customise the DrapePlot
#dp.make_drape_colourbar(cbar_label=colourbar_label)
#dp.set_fig_axis_labels()

#dp.show_plot()
#label_size = 100
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['arial']
#rcParams['font.size'] = label_size
#rcParams['lines.linewidth']  = 1.5   


DataDirectory = "/home/smudd/SMMDataStore/analysis_for_papers/movern_testing/"
Base_file = "Irian_Jaya_PP"

#Directory = "/home/s1563094/Datastore/DATA/UK/LiDAR_DTM_1m/HIN/"
#Base_file = "HIN_"

#BackgroundRasterName = Base_file+".bil"
BackgroundRasterName = Base_file+".bil"
DrapeRasterName = Base_file+"_hs.bil"
BasinRasterName = Base_file+"_AllBasins.bil"
DischargeRasterName= Base_file+"_Q.bil"



plt.clf() 
cbar_loc = "right"
MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
#MF.add_drape_image(BackgroundRasterName,DataDirectory,alpha = 1)
MF.add_drape_image(DischargeRasterName,DataDirectory,colourmap = "cubehelix", alpha = 0.6)
ImageName = DataDirectory+"TestNewArtist.png" 
fig_size_inches = 12
ax_style = "Normal"
MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250)
def ExampleOne_PartFour_MaskBasins(DataDirectory, fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID. It shows how to mask certain basins.
    Search the function for "Basins_to_mask".

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: SMM
    """
    import numpy as np
    Basins_to_mask = [0,4,6]

    FigFormat = "png"
    size_format = "geomorphology"

    #import modules
    # from LSDMapFigure.PlottingRaster import MapFigure
    # from LSDMapFigure.PlottingRaster import BaseRaster
    # import LSDPlottingTools.LSDMap_VectorTools as LSDMap_VT
    # import LSDPlottingTools.LSDMap_PointTools as LSDMap_PT

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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126



    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]
    
    
    # get the junctions to mask
    key_to_index_dict = dict(zip(basin_keys,basin_junctions))
    junctions_to_mask = []
    for basin in Basins_to_mask:
        junctions_to_mask.append( key_to_index_dict[basin])
    print("The junctions to mask are")
    print(junctions_to_mask)

    print ('Basin keys are: ')
    print basin_keys
    
    print("Let me mask those for you")
    new_keys = []
    for key in basin_keys:
        if key in Basins_to_mask:
            new_keys.append(np.nan)
        else:
            new_keys.append(key)
    print("The new keys are: ")
    print(new_keys)
    basin_keys = new_keys

    # get a discrete colormap
    cmap = plt.cm.jet

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    # We set colourbar location to none since we are labelling the figures
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='none')

    # add the basins drape
    MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)

    # add the basin outlines
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    
    # get rid of the basins that are being masked
    for junction in junctions_to_mask:
        del Basins[junction]
        
        
        
    
    # note that at this stage the Basins are keyed with the junction index
    MF.plot_polygon_outlines(Basins, linewidth=0.8)

    # add the basin labelling
    label_dict = dict(zip(basin_junctions,basin_keys))
    # this dict has the basin junction as the key and the basin_key as the value
    

    Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName)
    
    # get rid of points as well
    for junction in junctions_to_mask:
        del Points[junction]
        del label_dict[junction]
    
    MF.add_text_annotation_from_shapely_points(Points, text_colour='k', label_dict=label_dict)

    # Save the figure
    ImageName = DataDirectory+fname_prefix+'_labelled_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250)
def SimpleHillshadeForAnimation(DataDirectory,Base_file, cmap = "jet", cbar_loc = "right",
                                size_format = "ESURF", fig_format = "png",
                                dpi = 250, imgnumber = 0, full_basefile = [],
                                custom_cbar_min_max = [], out_fname_prefix = "", coord_type="UTM_km", hide_ticklabels=False):
    """
    This function make a hillshade image that is optimised for creating
    an animation. Used with the MuddPILE model

    Args:
        DataDirectory (str): the data directory with the data files
        Base_file (str): The prefix for the data files
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        imgnumber (int): the number of the image. Usually frames from model runs have integer numbers after them
        full_basefile (str): The root name of the figures you want. If empty, it uses the data_directory+base_file
        custom_min_max (list of int/float): if it contains two elements, recast the raster to [min,max] values for display.
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
        coord_type (str): either UTM or UTM_km
        hide_ticklabels (bool): if true, hide the tick labels from the plot

    Returns:
        Shaded relief plot. The elevation is also included in the plot.

    Author: FJC, SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # Get the filenames you want
    BackgroundRasterName = Base_file+"_hs.bil"
    DrapeRasterName = Base_file+".bil"

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type=coord_type,colourbar_location = cbar_loc)
    MF.add_drape_image(DrapeRasterName,DataDirectory,colourmap = cmap, alpha = 0.6, colorbarlabel = "Elevation (m)",colour_min_max = custom_cbar_min_max)

    # Save the image
    if(full_basefile == []):
        if len(out_fname_prefix) == 0:
            ImageName = DataDirectory+Base_file+"_img"+"%004d" % (imgnumber)+"."+fig_format
        else:
            ImageName = DataDirectory+out_fname_prefix+"_img"+"%004d" % (imgnumber)+"."+fig_format
    else:
        ImageName = full_basefile+"_img"+"%004d" % (imgnumber)+"."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi, adjust_cbar_characters=False,
                 fixed_cbar_characters=4, hide_ticklabels=hide_ticklabels)
示例#19
0
Base_file = "area"

BackgroundRasterName = Base_file + ".bil"
DrapeRasterName = Base_file + "_hs.bil"
ChiRasterName = Base_file + "_curvature.bil"

#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

plt.clf()
MF = MapFigure(BackgroundRasterName, Directory, coord_type="UTM_km")
MF.add_drape_image(DrapeRasterName, Directory, alpha=0.4)
MF.add_drape_image(ChiRasterName,
                   Directory,
                   colourmap="cubehelix",
                   alpha=0.4,
                   show_colourbar=True)
#MF.show_plot()
ImageName = Directory + "boris.png"
fig_size_inches = 6
ax_style = "Madhouse"
MF.save_fig(fig_width_inches=fig_size_inches,
            FigFileName=ImageName,
            axis_style=ax_style)

# Customise the DrapePlot
示例#20
0
RasterName_Seg = 'Extract_Basin_Segre_AllBasins.bil'
BasinInfoPrefix_Sal = 'Extract_Basin_Salat2'
RasterName_Sal = 'Extract_Basin_Salat2_AllBasins.bil'
BasinInfoPrefix_Sai = 'Extract_Basin_Saison'
RasterName_Sai = 'Extract_Basin_Saison_AllBasins.bil'

csv_file1 = Import_Directory + 'AHe_Data_used.csv'
csv_file2 = Import_Directory + 'AHe_Data_not_used.csv'

#%%============================LOAD_AND_PLOT_DATA===========================%%#
plt.clf()
MF = MapFigure(BaseRasterName=BaseRasterName,
               Directory=Import_Directory,
               coord_type="UTM",
               colourbar_location="None",
               basemap_colourmap="gray",
               plot_title='None',
               NFF_opti=False,
               alpha=1,
               zorder=1)

MF.add_drape_image(RasterName=HSRaster,
                   Directory=Import_Directory,
                   colourmap="gray",
                   alpha=0.25,
                   colorbarlabel="Colourbar",
                   discrete_cmap=False,
                   n_colours=10,
                   norm="None",
                   colour_min_max=[],
                   modify_raster_values=False,
示例#21
0
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#label_size = 100
#rcParams['font.family'] = 'sans-serif'
#rcParams['font.sans-serif'] = ['arial']
#rcParams['font.size'] = label_size
#rcParams['lines.linewidth']  = 1.5

plt.clf()
MF = MapFigure(DrapeRasterName,
               Directory,
               coord_type="UTM_km",
               colourbar_location='None')
# add the basins drape
cmap = cm.Set1
MF.add_drape_image(BasinsName,
                   Directory,
                   colourmap=cmap,
                   alpha=0.5,
                   colorbarlabel='Basin ID',
                   show_colourbar=False)
# add the basin outlines
Basins = LSDMap_VT.GetBasinOutlines(Directory, BasinsName)
MF.plot_polygon_outlines(Basins, linewidth=0.8)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True)
#MF.show_plot()
MF.save_fig(fig_width_inches=12,
rcParams['text.usetex'] = False

# define filenames and relative workspace
fname_prefix = "bolinas"
HillshadeName = "bolinas_hs.bil"
Directory = "/home/mhurst/bolinas_paper/"
DataDirectory = Directory + "data/"
ChannelDataDirectory = DataDirectory + "channel_data/"
HillslopeDataDirectory = DataDirectory + "hillslope_data/"
HilltopPointsData = HillslopeDataDirectory + "bolinas_HilltopData.csv"
ChannelPointsDat = ChannelDataDirectory + "bolinas_MChiSegmented.csv"
ChannelHeadPointsData = ChannelDataDirectory + "bolinas_CH_wiener_nodeindices_for_Arc.csv"

# create the map figure
MF = MapFigure(HillshadeName,
               DataDirectory,
               coord_type="UTM_km",
               colourbar_location='None')

# add hilltops
HilltopPointsDF = pd.read_csv(HilltopPointsData)
HilltopPoints = LSDP.LSDMap_PointData(HilltopPointsDF,
                                      data_type="pandas",
                                      PANDEX=True)
MF.add_point_data(HilltopPoints,
                  alpha=0.5,
                  zorder=100,
                  unicolor="blue",
                  manual_size=5)

# add channel heads
#ChannelHeadsDF = pd.read_csv(ChannelHeadPointsData)
示例#23
0
liste = ["autumn"]

for i in range(len(liste)) :
    
    color = random.choice(liste)
    

##### Now we can load and plot the data

    BackgroundRasterName = Base_file + ".bil" # Ignore this line
    
    thisPointData = LSDP.LSDMap_PointData(df, data_type = "pandas", PANDEX = True) # Load the point file #1, add a similar line with different name if you have more than one point file.
    
    plt.clf() # Ignore this line
    
    MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km", NFF_opti = True, colourbar_location = 'bottom') # load the background raster
    
    MF.add_drape_image(BackgroundRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one
                    colourmap = "gray", # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                    alpha = 0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                    show_colourbar = False, # Well, this one is explicit I think
                    colorbarlabel = "Colourbar", # Name of your Colourbar, it might bug though
                    NFF_opti = True)
                    
    MF.add_drape_image(DrapeRasterName,Directory, # Calling the function will add a drapped raster on the top of the background one
                    colourmap = "gray", # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                    alpha = 0.5, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                    show_colourbar = False, # Well, this one is explicit I think
                    colorbarlabel = "Colourbar", # Name of your Colourbar, it might bug though
                    NFF_opti = True)
                                                
#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#PD_file = Base_file+"_chi_coord_basins.csv"
PD_file = Base_file + "_MChiSegmented.csv"
PointData = LSDMap_PointTools.LSDMap_PointData(Directory + PD_file)

plt.clf()
cbar_loc = "Bottom"
MF = MapFigure(BackgroundRasterName,
               Directory,
               coord_type="UTM_km",
               colourbar_location=cbar_loc)
MF.add_drape_image(DrapeRasterName, Directory, alpha=0.4)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4)
MF.add_point_data(PointData,
                  column_for_plotting="source_key",
                  colorbarlabel="I am point data",
                  scale_points=True,
                  column_for_scaling="drainage area",
                  scaled_data_in_log=False)
#MF.show_plot()
ImageName = Directory + "TestNewArtist.png"
fig_size_inches = 6
ax_style = "Normal"
MF.save_fig(fig_width_inches=fig_size_inches,
            FigFileName=ImageName,
def ExampleOne_PartFive_MaskBasinsMF(DataDirectory, fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: SMM
    """

    FigFormat = "png"
    size_format = "geomorphology"


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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    # We set colourbar location to none since we are labelling the figures
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='bottom',basemap_colourmap = "gray")

    # add the basins drape
    #MF.add_drape_image(HillshadeName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = False)
    Remove_Basins = [4,8]
    Rename_Basins = { 12: 'chumbox', 14: 'zeppo'}
    Value_dict= { 1: 0.2, 2:0.3, 3:0.4, 5:0.9,6:0.7, 7:0.3, 9:0.5, 10:0.5}
    MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, mask_list = Remove_Basins, 
                      rename_dict = Rename_Basins, value_dict = Value_dict,
                      use_keys_not_junctions = True, show_colourbar = True, 
                      discrete_cmap=True, n_colours=8, colorbarlabel = "$m/n$",
                      colourmap = plt.cm.jet, adjust_text = False)
    
    # Save the figure
    ImageName = DataDirectory+fname_prefix+'_test_Coloured_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250)
示例#26
0
def MakeRasterPlotTerraceDips(DataDirectory,fname_prefix,min_size=5000,FigFormat='png',size_format='ESURF'):
    """
    This function makes a raster plot of terrace locations with arrows showing the terrace
    dip and dip directions.
    Dip and dip direction are calculated by fitting a plane to each terrace using least-squares
    regression.

    Args:
        DataDirectory (str): the data directory
        fname_prefix (str): the name of the DEM without extension.
        min_size (int): minimum number of pixels for a terrace, smaller ones will be removed
        FigFormat (str): the figure format, default='png'
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).

    Returns:
        plot of terrace locations and dip/dip directions

    Author: FJC

    """
    from LSDMapFigure.PlottingRaster import BaseRaster
    from LSDMapFigure.PlottingRaster import MapFigure

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

    # make a figure
    if size_format == "geomorphology":
        #fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
        fig_width_inches=6.25
        #l_pad = -40
    elif size_format == "big":
        #fig = plt.figure(1, facecolor='white',figsize=(16,9))
        fig_width_inches=16
        #l_pad = -50
    else:
        fig_width_inches = 4.92126
        #fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2))
        #l_pad = -35

    # going to make the terrace plots - need to have bil extensions.
    print("I'm going to make a raster plot of terrace elevations. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    TerraceElevName = fname_prefix+'_terrace_relief_final'+raster_ext

    # get the terrace csv
    terraces = H.read_terrace_csv(DataDirectory,fname_prefix)
    filter_terraces(terraces)

    # get the terrace IDs
    terraceIDs = terraces.TerraceID.unique()
    n_colours=len(terraceIDs)

    # get the terrace dip and dip dirs
    terrace_dips = get_terrace_dip_and_dipdir(terraces)

    # create the map figure
    MF = MapFigure(HillshadeName, DataDirectory, coord_type='UTM_km', colourbar_location='right')
    # add the terrace drape
    terrace_cmap = plt.cm.Reds
    #terrace_cmap = colours.cmap_discretize(n_colours,terrace_cmap)
    MF.add_drape_image(TerraceElevName, DataDirectory, colourmap = terrace_cmap, colorbarlabel="Elevation above channel (m)", alpha=0.8)

    # add arrows oriented in the direction of dip. We might want to colour these by the dip angle?
    # MF.add_arrows_from_points(terrace_dips,azimuth_header='dip_azimuth', arrow_length=100)
    MF.add_strike_and_dip_symbols(terrace_dips,symbol_length=100,linewidth=0.5)


    ImageName = DataDirectory+fname_prefix+'_terrace_dips_raster_plot.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 300) # Save the figure
def MakeRasterLithoBasinMap(DataDirectory, fname_prefix, lname_prefix, lithodict, size_format='ESURF', FigFormat='png', basins = True, m_chi = False, mancol = [], log_scale_river = False, minmax_m_chi = []):
	"""
	This function makes a shaded relief plot of the DEM with lithologic map on the top and basin outline

	Args:
	DataDirectory (str): the data directory with the m/n csv files
	fname_prefix (str): The prefix for the m/n csv files
	size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).
	FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command.
	Basins (bool): Do you want the basin on top
	minmax_m_chi (list): define a minimum/maximum for plotting m_chi on the top of litho (at the moment this plot is generated from knickpoint dataset)

	Returns:
	Shaded relief plot with the basins coloured by basin ID

	Author: BG, FJC
	"""
		# check if a directory exists for the chi plots. If not then make it.
	raster_directory = DataDirectory+'raster_plots/'
	if not os.path.isdir(raster_directory):
		os.makedirs(raster_directory)

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

	# set figure sizes based on format
	if size_format == "geomorphology":
		fig_width_inches = 6.25
	elif size_format == "big":
		fig_width_inches = 16
	else:
		fig_width_inches = 4.92126

	raster_ext = '.bil'

	# get the basin IDs to make a discrete colourmap for each ID
	if(basins):
		BasinInfoDF = Helper.ReadBasinInfoCSV(DataDirectory, fname_prefix)

		basin_keys = list(BasinInfoDF['basin_key'])
		basin_keys = [int(x) for x in basin_keys]

		basin_junctions = list(BasinInfoDF['outlet_junction'])
		basin_junctions = [float(x) for x in basin_junctions]

		print ('Basin keys are: ')
		print (basin_keys)
		BasinsName = fname_prefix+'_AllBasins.bil'



	# going to make the basin plots - need to have bil extensions.
	print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

	# get the rasters
	raster_ext = '.bil'
	BackgroundRasterName = fname_prefix+raster_ext
	HillshadeName = fname_prefix+'_hs'+raster_ext

	LithoMap = lname_prefix+raster_ext

	# create the map figure
	MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='None')
	MF.add_drape_image(HillshadeName,DataDirectory,NFF_opti = True, custom_min_max = [90,240], alpha = 1)
	# add the geology drape
	# MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory,
	#				  use_keys_not_junctions = True, show_colourbar = True,
	#				  discrete_cmap=True, n_colours=len(basin_keys), colorbarlabel = "Basin ID",
	#				  colourmap = cmap, adjust_text = False)
	# getting the right color now

	color_map_litho  = getLithoColorMap(fname_prefix, DataDirectory)
	df_litho_size = pd.read_csv(DataDirectory+fname_prefix+"_lithokey.csv")

	MF.add_drape_image(LithoMap,DataDirectory,colourmap = color_map_litho,
						alpha=0.6,
						show_colourbar = False,
						colorbarlabel = "Colourbar", discrete_cmap=False,
						norm = "None",
						colour_min_max = [0,df_litho_size["rocktype"].max()-1],
						modify_raster_values=False,
						old_values=[], new_values=[], cbar_type=int,
						NFF_opti = True, custom_min_max = [])

	if(basins):
	# add the basin outlines

		Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
		MF.plot_polygon_outlines(Basins, linewidth=0.8)

		# knickpoints!
		if(m_chi):
			ChannelDF = pd.read_csv(DataDirectory+fname_prefix+"_ksnkp_mchi.csv")
			ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type = "pandas", PANDEX = True)
			MF.add_point_data(ChannelPoints,column_for_plotting = 'm_chi',show_colourbar = True, scale_points=True, column_for_scaling='drainage_area',alpha=0.5,zorder=100,this_colourmap = "RdBu_r" ,colour_manual_scale = mancol, scaled_data_in_log = log_scale_river,max_point_size = minmax_m_chi[1], min_point_size = minmax_m_chi[0])
		else:
		# add the channel network
			ChannelDF = Helper.ReadChiDataMapCSV(DataDirectory,fname_prefix)
			ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type = "pandas", PANDEX = True)
			MF.add_point_data(ChannelPoints,show_colourbar="False", scale_points=True, column_for_scaling='drainage_area',alpha=0.5,zorder=100)

	if(basins):
		# add the basin labelling
		label_dict = dict(zip(basin_junctions,basin_keys))
		Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName)
		MF.add_text_annotation_from_shapely_points(Points, text_colour='k', label_dict=label_dict,zorder=200)

	if(basins):
		# Save the figure
		ImageName = raster_directory+fname_prefix+'_basin_keys_litho.'+FigFormat
	else:
		ImageName = raster_directory+fname_prefix+'_litho.'+FigFormat

	MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 500)
def PrintChannelsAndBasins(DataDirectory,fname_prefix, add_basin_labels = True, cmap = "jet", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function prints a channel map over a hillshade.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print ('Basin keys are: ')
    print (basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)


    ChannelFileName = fname_prefix+"_chi_data_map.csv"
    chi_csv_fname = DataDirectory+ChannelFileName

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)


    # clear the plot
    plt.clf()

    # set up the base image and the map
    print("I am showing the basins without text labels.")
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location="None")
    MF.plot_polygon_outlines(Basins, linewidth=0.8)
    MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.1, discrete_cmap=False, n_colours=len(basin_keys), show_colourbar = False, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)

    MF.add_point_data(thisPointData,column_for_plotting = "basin_key",
                       scale_points = True,column_for_scaling = "drainage_area",
                       this_colourmap = cmap, scaled_data_in_log = True,
                       max_point_size = 3, min_point_size = 1)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_channels_with_basins."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_channels_with_basins."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)
def ExampleOne_PartTwo_PrintBasins(DataDirectory,fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: FJC
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]


    print ('Basin keys are: ')
    print basin_keys

    # get a discrete colormap
    cmap = plt.cm.jet

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='bottom')
    # add the basins drape
    MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)
    # add the basin outlines
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    MF.plot_polygon_outlines(Basins, linewidth=0.8)

    FigFormat = "png"
    ImageName = DataDirectory+fname_prefix+'_coloured_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250) # Save the figure
示例#30
0
def ExampleOne_PartFive_MaskBasinsMF(DataDirectory, fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: SMM
    """

    FigFormat = "png"
    size_format = "geomorphology"


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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    # We set colourbar location to none since we are labelling the figures
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='bottom',basemap_colourmap = "gray")

    # add the basins drape
    #MF.add_drape_image(HillshadeName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = False)
    Remove_Basins = [4,8]
    Rename_Basins = { 12: 'chumbox', 14: 'zeppo'}
    Value_dict= { 1: 0.2, 2:0.3, 3:0.4, 5:0.9,6:0.7, 7:0.3, 9:0.5, 10:0.5}
    MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, mask_list = Remove_Basins, 
                      rename_dict = Rename_Basins, value_dict = Value_dict,
                      use_keys_not_junctions = True, show_colourbar = True, 
                      discrete_cmap=True, n_colours=8, colorbarlabel = "$m/n$",
                      colourmap = plt.cm.jet, adjust_text = False)
    
    # Save the figure
    ImageName = DataDirectory+fname_prefix+'_test_Coloured_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250)
CustomColorMap = matplotlib.colors.ListedColormap(CustomColor)

CustomColorComb=['#C8C864','#9D78C1','#6E9C6E','#AF5A5A','#A6835F','#A7DBA7','#AF5A5A','#F3C79B','#AF5A5A','#6E899B','#B1DEDE']
CustomColorCombMap = matplotlib.colors.ListedColormap(CustomColorComb)

#%%======================CONVERT_CSV_FILE_TO_SHAPEFILES=====================%%#
thisPointData=LSDP.LSDMap_PointData(csv_file, PANDEX=True)

#%%============================LOAD_AND_PLOT_DATA===========================%%#

plt.clf() 

MF = MapFigure(BaseRasterName=BaseRasterName,
               Directory=Import_Directory,
               coord_type="UTM",
               colourbar_location="Top",
               basemap_colourmap="gray",
               plot_title='None',
               NFF_opti=False,alpha=1) # load and display the background hillslope raster

MF.add_drape_image(RasterName=RasterName,
                   Directory=Import_Directory,
                   colourmap=CustomColorCombMap,
                   alpha=0.6,
                   show_colourbar=True,
                   colorbarlabel='Lithology',
                   modify_raster_values=False,
                   NFF_opti=False)               
               
MF.add_basin_plot(RasterName=RasterNameCatch,BasinInfoPrefix=BasinInfoPrefix,Directory=Import_Directory,
                 colourmap = "gray",alpha=1,
示例#32
0
def ExampleOne_PartTwo_PrintBasins(DataDirectory,fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: FJC
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # Set up fonts for plots
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size
    size_format  = "geomorphology"

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]


    print ('Basin keys are: ')
    print basin_keys

    # get a discrete colormap
    cmap = plt.cm.jet

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='bottom')
    # add the basins drape
    MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)
    # add the basin outlines
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    MF.plot_polygon_outlines(Basins, linewidth=0.8)

    FigFormat = "png"
    ImageName = DataDirectory+fname_prefix+'_coloured_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250) # Save the figure
示例#33
0
def PlotHillshadewithClusters(DataDirectory,
                              OutDirectory,
                              fname_prefix,
                              stream_order=1):
    """
        Make a hillshade of the raster with the channels coloured by the cluster
        value. Uses the LSDPlottingTools libraries. https://github.com/LSDtopotools/LSDMappingTools

        Args:
            stream_order: the stream order of the profiles that you are analysing

        Author: FJC
        """
    import LSDPlottingTools as LSDP
    from LSDMapFigure.PlottingRaster import MapFigure

    print(
        "I'm plotting a shaded relief map with the channels coloured by cluster"
    )

    df = pd.read_csv(DataDirectory + fname_prefix + '_all_tribs.csv')
    cluster_df = pd.read_csv(
        OutDirectory + fname_prefix +
        '_profiles_clustered_SO{}.csv'.format(stream_order))

    # set figure sizes based on format
    fig_width_inches = 8

    # some raster names
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HSName = fname_prefix + '_hs' + raster_ext

    if not os.path.isfile(DataDirectory + HSName):
        # make a hillshade
        BM.GetHillshade(DataDirectory + BackgroundRasterName,
                        DataDirectory + HSName)

    # create the map figure
    MF = MapFigure(HSName, DataDirectory, coord_type="UTM")

    clusters = cluster_df.cluster_id.unique()
    for cl in clusters:
        # plot the whole channel network in black
        ChannelPoints = LSDP.LSDMap_PointData(df,
                                              data_type="pandas",
                                              PANDEX=True)
        MF.add_point_data(ChannelPoints,
                          show_colourbar="False",
                          unicolor='0.9',
                          manual_size=2,
                          zorder=1,
                          alpha=0.5)
        # plot the clustered profiles in the correct colour
        this_df = cluster_df[cluster_df.cluster_id == cl]
        this_colour = str(this_df.colour.unique()[0])
        ClusteredPoints = LSDP.LSDMap_PointData(this_df,
                                                data_type="pandas",
                                                PANDEX=True)
        MF.add_point_data(ClusteredPoints,
                          show_colourbar="False",
                          zorder=100,
                          unicolor=this_colour,
                          manual_size=3)

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=OutDirectory + fname_prefix +
                '_hs_clusters_SO{}.png'.format(stream_order),
                FigFormat='png',
                Fig_dpi=300,
                fixed_cbar_characters=6,
                adjust_cbar_characters=False,
                transparent=True)  # Save the figure
示例#34
0
#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#PD_file = Base_file+"_chi_coord_basins.csv"
#PointData = LSDMap_PointTools.LSDMap_PointData(Directory+PD_file)

plt.clf()
cbar_loc = "bottom"
MF = MapFigure(BackgroundRasterName,
               DataDirectory,
               coord_type="UTM_km",
               colourbar_location=cbar_loc)
#MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4)
#MF.add_point_data(PointData)
#MF.show_plot()
ImageName = DataDirectory + "TestNewArtist.png"
fig_size_inches = 12
ax_style = "Normal"
MF.save_fig(fig_width_inches=fig_size_inches,
            FigFileName=ImageName,
            axis_style=ax_style,
            Fig_dpi=250)

# Customise the DrapePlot
#dp.make_drape_colourbar(cbar_label=colourbar_label)
示例#35
0
def PlotRasterLithologyWithClusters(DataDirectory,
                                    OutDirectory,
                                    fname_prefix,
                                    stream_order=1,
                                    geol_raster='geol'):
    """
        Make a hillshade of the raster with the channels coloured by the cluster
        value. Rasterise a geology shapefile and drape on the top.
        Uses the LSDPlottingTools libraries. https://github.com/LSDtopotools/LSDMappingTools

        Args:
            stream_order: the stream order of the profiles that you are analysing
            shapefile_name: name of the lithology shapefile
            geol_field: the field of the shapefile that has the lithology information

        Author: FJC
        """
    import LSDPlottingTools as LSDP
    from LSDMapFigure.PlottingRaster import MapFigure

    df = pd.read_csv(DataDirectory + fname_prefix + '_all_tribs.csv')
    cluster_df = pd.read_csv(
        OutDirectory + fname_prefix +
        '_profiles_clustered_SO{}.csv'.format(stream_order))

    # set figure sizes based on format
    fig_width_inches = 8

    # some raster names
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HSName = fname_prefix + '_hs' + raster_ext

    if not os.path.isfile(DataDirectory + HSName):
        # make a hillshade
        BM.GetHillshade(DataDirectory + BackgroundRasterName,
                        DataDirectory + HSName)

    # create the map figure
    MF = MapFigure(HSName, DataDirectory, coord_type="UTM")

    #geology
    LithName = geol_raster
    print("The geology raster is" + LithName)
    MF.add_drape_image(LithName,
                       DataDirectory,
                       colourmap=plt.cm.jet,
                       alpha=0.5,
                       show_colourbar=False,
                       discrete_cmap=True,
                       cbar_type=int,
                       mask_value=0)

    clusters = cluster_df.cluster_id.unique()
    for cl in clusters:
        # plot the whole channel network in black
        ChannelPoints = LSDP.LSDMap_PointData(df,
                                              data_type="pandas",
                                              PANDEX=True)
        MF.add_point_data(ChannelPoints,
                          show_colourbar="False",
                          unicolor='white',
                          manual_size=1.5,
                          zorder=2,
                          alpha=0.5)
        # plot the clustered profiles in the correct colour
        this_df = cluster_df[cluster_df.cluster_id == cl]
        this_colour = str(this_df.colour.unique()[0])
        ClusteredPoints = LSDP.LSDMap_PointData(this_df,
                                                data_type="pandas",
                                                PANDEX=True)
        MF.add_point_data(ClusteredPoints,
                          show_colourbar="False",
                          zorder=100,
                          unicolor=this_colour,
                          manual_size=2.5)

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=OutDirectory + fname_prefix +
                '_lith_clusters_SO{}.png'.format(stream_order),
                FigFormat='png',
                Fig_dpi=300,
                fixed_cbar_characters=6,
                adjust_cbar_characters=False,
                transparent=True)  # Save the figure
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
wname = "output"  # name of your output file
dpi = 900  # Quality of your output image, don't exceed 900
fig_size_inches = 24  # Figure size in Inches

##### Now we can load and plot the data

BackgroundRasterName = Base_file + ".bil"  # Ignore this line
thisPointData = LSDP.LSDMap_PointData(
    csv_file, PANDEX=True
)  # Load the point file #1, add a similar line with different name if you have more than one point file.

plt.clf()  # Ignore this line

MF = MapFigure(BackgroundRasterName,
               Directory,
               coord_type="UTM_km",
               NFF_opti=True)  # load the background raster

MF.add_drape_image(
    DrapeRasterName,
    Directory,  # Calling the function will add a drapped raster on the top of the background one
    colourmap=
    "gray",  # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
    alpha=
    0.5,  # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
    show_colourbar=False,  # Well, this one is explicit I think
    colorbarlabel="Colourbar",  # Name of your Colourbar, it might bug though
    NFF_opti=True)

MF.add_point_data(
    thisPointData,  # this function plot the requested point file using the lat/long column in the csv file
def PrintBasins(DataDirectory,fname_prefix, add_basin_labels = True, cmap = "jet", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = ""):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    IMPORTANT: To get this to run you need to set the flags in chi mapping tool to:
    write_hillshade: true
    print_basin_raster: true
    print_chi_data_maps: true

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: FJC, SMM
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print ('Basin keys are: ')
    print (basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)

    # If wanted, add the labels
    if add_basin_labels:
        print("I am going to add basin labels, there will be no colourbar.")
        MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location="None")
        MF.plot_polygon_outlines(Basins, linewidth=0.8)
        MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = False, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)

        # This is used to label the basins
        label_dict = dict(zip(basin_junctions,basin_keys))
        # this dict has the basin junction as the key and the basin_key as the value

        Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName)
        MF.add_text_annotation_from_shapely_points(Points, text_colour='k', label_dict=label_dict)
    else:
        print("I am showing the basins without text labels.")
        MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location=cbar_loc)
        MF.plot_polygon_outlines(Basins, linewidth=0.8)
        MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_basins."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_basins."+fig_format

    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=fig_format, Fig_dpi = dpi) # Save the figure
def PrintBasins(DataDirectory,
                fname_prefix,
                add_basin_labels=True,
                cmap="jet",
                cbar_loc="right",
                size_format="ESURF",
                fig_format="png",
                dpi=250,
                out_fname_prefix=""):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    IMPORTANT: To get this to run you need to set the flags in chi mapping tool to:
    write_hillshade: true
    print_basin_raster: true
    print_chi_data_maps: true

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_lox (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin

    Author: FJC, SMM
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print('Basin keys are: ')
    print(basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print(
        "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!"
    )

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix + '_hs' + raster_ext
    BasinsName = fname_prefix + '_AllBasins' + raster_ext
    print(BasinsName)
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)

    # If wanted, add the labels
    if add_basin_labels:
        print("I am going to add basin labels, there will be no colourbar.")
        MF = MapFigure(HillshadeName,
                       DataDirectory,
                       coord_type="UTM_km",
                       colourbar_location="None")
        MF.plot_polygon_outlines(Basins, linewidth=0.8)
        MF.add_drape_image(BasinsName,
                           DataDirectory,
                           colourmap=cmap,
                           alpha=0.8,
                           colorbarlabel='Basin ID',
                           discrete_cmap=True,
                           n_colours=len(basin_keys),
                           show_colourbar=False,
                           modify_raster_values=True,
                           old_values=basin_junctions,
                           new_values=basin_keys,
                           cbar_type=int)

        # This is used to label the basins
        label_dict = dict(zip(basin_junctions, basin_keys))
        # this dict has the basin junction as the key and the basin_key as the value

        Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName)
        MF.add_text_annotation_from_shapely_points(Points,
                                                   text_colour='k',
                                                   label_dict=label_dict)
    else:
        print("I am showing the basins without text labels.")
        MF = MapFigure(HillshadeName,
                       DataDirectory,
                       coord_type="UTM_km",
                       colourbar_location=cbar_loc)
        MF.plot_polygon_outlines(Basins, linewidth=0.8)
        MF.add_drape_image(BasinsName,
                           DataDirectory,
                           colourmap=cmap,
                           alpha=0.8,
                           colorbarlabel='Basin ID',
                           discrete_cmap=True,
                           n_colours=len(basin_keys),
                           show_colourbar=True,
                           modify_raster_values=True,
                           old_values=basin_junctions,
                           new_values=basin_keys,
                           cbar_type=int)

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory + fname_prefix + "_basins." + fig_format
    else:
        ImageName = DataDirectory + out_fname_prefix + "_basins." + fig_format

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=ImageName,
                FigFormat=fig_format,
                Fig_dpi=dpi)  # Save the figure

#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#PD_file = Base_file+"_chi_coord_basins.csv"  
#PointData = LSDMap_PointTools.LSDMap_PointData(Directory+PD_file)

plt.clf() 
cbar_loc = "bottom"
MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km",colourbar_location = cbar_loc)
#MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4)
#MF.add_point_data(PointData)
#MF.show_plot()
ImageName = DataDirectory+"TestNewArtist.png" 
fig_size_inches = 12
ax_style = "Normal"
MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250)



# Customise the DrapePlot
#dp.make_drape_colourbar(cbar_label=colourbar_label)
#dp.set_fig_axis_labels()
def main(argv):

    # If there are no arguments, send to the welcome screen
    if not len(sys.argv) > 1:
        full_paramfile = print_welcome()
        sys.exit()

    # Get the arguments
    import argparse
    parser = argparse.ArgumentParser()

    # The location of the data files
    parser.add_argument(
        "-dir",
        "--base_directory",
        type=str,
        help="The base directory. If not defined, current directory.")
    parser.add_argument("-fname",
                        "--fname_prefix",
                        type=str,
                        help="The prefix of your DEM WITHOUT EXTENSION!")
    parser.add_argument(
        "-fmt",
        "--FigFormat",
        type=str,
        default='png',
        help="Set the figure format for the plots. Default is png")
    args = parser.parse_args()

    # get the base directory
    if args.base_directory:
        DataDirectory = args.base_directory
        # check if you remembered a / at the end of your path_name
        if not DataDirectory.endswith("/"):
            print(
                "You forgot the '/' at the end of the directory, appending...")
            DataDirectory = this_dir + "/"
    else:
        this_dir = os.getcwd()

    if not args.fname_prefix:
        print(
            "WARNING! You haven't supplied your DEM name. Please specify this with the flag '-fname'"
        )
        sys.exit()
    else:
        fname_prefix = args.fname_prefix

    # set to not parallel
    parallel = False
    faults = True
    FigFormat = args.FigFormat

    # check if a directory exists for the chi plots. If not then make it.
    raster_directory = DataDirectory + 'raster_plots/'
    if not os.path.isdir(raster_directory):
        os.makedirs(raster_directory)

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

    # set figure sizes based on format
    size_format = ""
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = Helper.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [int(x) for x in basin_junctions]

    # get a discrete colormap
    cmap = plt.cm.viridis

    # going to make the basin plots - need to have bil extensions.
    print(
        "I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!"
    )

    # get the rasters
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HillshadeName = fname_prefix + '_hs' + raster_ext
    BasinsName = fname_prefix + '_AllBasins' + raster_ext

    # create the map figure
    MF = MapFigure(HillshadeName,
                   DataDirectory,
                   coord_type="UTM_km",
                   colourbar_location='none')

    # add the basins drape
    BasinsDict = dict(zip(basin_keys, basin_keys))
    #    MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, label_basins=False,
    #                      use_keys_not_junctions = True, show_colourbar = False,
    #                      value_dict = BasinsDict, discrete_cmap=True, n_colours=len(basin_keys),
    #                      colorbarlabel = "Basin ID", cbar_type=int, tickspacefactor=2,
    #                      colourmap = cmap, edgecolour='none', adjust_text = True, parallel=parallel)

    # add the channel network
    if not parallel:
        ChannelDF = Helper.ReadChiDataMapCSV(DataDirectory, fname_prefix)
    else:
        ChannelDF = Helper.AppendChiDataMapCSVs(DataDirectory)

    # remove chi no data values
    ChannelDF = ChannelDF[ChannelDF.chi != -9999]

    ChannelPoints = LSDP.LSDMap_PointData(ChannelDF,
                                          data_type="pandas",
                                          PANDEX=True)

    # add chi map
    MF.add_point_data(ChannelPoints,
                      column_for_plotting="chi",
                      column_for_scaling="chi",
                      colorbarlabel="$\chi$ (m)",
                      show_colourbar=True,
                      this_colourmap=cmap,
                      colourbar_location="top")

    # add the faults
    if faults:
        LineFileName = DataDirectory + fname_prefix + "_faults.shp"
        MF.add_line_data(LineFileName,
                         linestyle="-",
                         linewidth=1.5,
                         zorder=99,
                         legend=True,
                         label="Fault Segments")

    # add the basin outlines ### need to parallelise
    if not parallel:
        Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    else:
        Basins = LSDP.GetMultipleBasinOutlines(DataDirectory)

    # Find the relay basins and plot separately
    RelayBasinIDs = [1248, 4788, 4995, 5185, 6187, 6758, 6805]
    RelayBasins = {
        key: value
        for key, value in Basins.items() if key in RelayBasinIDs
    }

    # Plot all basins
    MF.plot_polygon_outlines(Basins,
                             colour='k',
                             linewidth=0.5,
                             alpha=1,
                             legend=True,
                             label="Catchments")
    MF.plot_polygon_outlines(RelayBasins,
                             colour='r',
                             linewidth=0.5,
                             alpha=1,
                             legend=True,
                             label="Relay Catchments")

    # Add the legend
    MF.add_legend()

    # Save the figure
    ImageName = raster_directory + fname_prefix + '_chi_map.' + FigFormat
    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=ImageName,
                FigFormat=FigFormat,
                Fig_dpi=300)
rcParams['font.size'] = 8
rcParams['text.usetex'] = False
   
# define filenames and relative workspace
fname_prefix = "bolinas"
HillshadeName = "bolinas_hs.bil"
Directory = "/home/mhurst/bolinas_paper/"
DataDirectory = Directory+"data/"
ChannelDataDirectory = DataDirectory+"channel_data/"
HillslopeDataDirectory = DataDirectory+"hillslope_data/"
HilltopPointsData = HillslopeDataDirectory+"bolinas_HilltopData.csv"
ChannelPointsDat = ChannelDataDirectory+"bolinas_MChiSegmented.csv"
ChannelHeadPointsData = ChannelDataDirectory+"bolinas_CH_wiener_nodeindices_for_Arc.csv"

# create the map figure
MF = MapFigure(HillshadeName, DataDirectory, coord_type="UTM_km", colourbar_location='None')

# add hilltops
HilltopPointsDF = pd.read_csv(HilltopPointsData)
HilltopPoints = LSDP.LSDMap_PointData(HilltopPointsDF, data_type = "pandas", PANDEX = True)
MF.add_point_data(HilltopPoints,alpha=0.5,zorder=100,unicolor="blue",manual_size=5)

# add channel heads
#ChannelHeadsDF = pd.read_csv(ChannelHeadPointsData)
#ChannelHeadPoints = LSDP.LSDMap_PointData(ChannelHeadsDF, data_type = "pandas", PANDEX = True)
#MF.add_point_data(ChannelHeadPoints,alpha=0.5,zorder=100,unicolor="blue",manual_size=5)

# add channels
#ChannelDF = Helper.ReadChiDataMapCSV(ChannelDataDirectory,fname_prefix)
#ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type = "pandas", PANDEX = True)
#MF.add_point_data(ChannelPoints,show_colourbar="False", scale_points=True, column_for_scaling='drainage_area',alpha=0.5,zorder=90)
def main(argv):

    # If there are no arguments, send to the welcome screen
    if not len(sys.argv) > 1:
        full_paramfile = print_welcome()
        sys.exit()

    # Get the arguments
    import argparse
    parser = argparse.ArgumentParser()
    
    # The location of the data files
    parser.add_argument("-dir", "--base_directory", type=str, help="The base directory. If not defined, current directory.")
    parser.add_argument("-fname", "--fname_prefix", type=str, help="The prefix of your DEM WITHOUT EXTENSION!")
    parser.add_argument("-fmt", "--FigFormat", type=str, default='png', help="Set the figure format for the plots. Default is png")
    args = parser.parse_args()
    
    # get the base directory
    if args.base_directory:
        DataDirectory = args.base_directory
        # check if you remembered a / at the end of your path_name
        if not DataDirectory.endswith("/"):
            print("You forgot the '/' at the end of the directory, appending...")
            DataDirectory = this_dir+"/"
    else:
        this_dir = os.getcwd()
    
    if not args.fname_prefix:
        print("WARNING! You haven't supplied your DEM name. Please specify this with the flag '-fname'")
        sys.exit()
    else:
        fname_prefix = args.fname_prefix
        
    # set to not parallel
    parallel = False
    faults = True
    FigFormat = args.FigFormat
   
    # check if a directory exists for the chi plots. If not then make it.
    raster_directory = DataDirectory+'raster_plots/'
    if not os.path.isdir(raster_directory):
        os.makedirs(raster_directory)

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

    # set figure sizes based on format
    size_format = ""
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = Helper.ReadBasinInfoCSV(DataDirectory, fname_prefix)
    
    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [int(x) for x in basin_junctions]

    # get a discrete colormap
    cmap = plt.cm.viridis

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext

    # create the map figure
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='none')

    # add the basins drape
    BasinsDict = dict(zip(basin_keys,basin_keys))
#    MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, label_basins=False,
#                      use_keys_not_junctions = True, show_colourbar = False, 
#                      value_dict = BasinsDict, discrete_cmap=True, n_colours=len(basin_keys),
#                      colorbarlabel = "Basin ID", cbar_type=int, tickspacefactor=2,
#                      colourmap = cmap, edgecolour='none', adjust_text = True, parallel=parallel)

    # add the channel network
    if not parallel:
        ChannelDF = Helper.ReadChiDataMapCSV(DataDirectory,fname_prefix)
    else:
        ChannelDF = Helper.AppendChiDataMapCSVs(DataDirectory)
    
    # remove chi no data values
    ChannelDF = ChannelDF[ChannelDF.chi != -9999]
    
    ChannelPoints = LSDP.LSDMap_PointData(ChannelDF, data_type = "pandas", PANDEX = True)
    
	# add chi map
    MF.add_point_data(ChannelPoints, column_for_plotting = "chi", column_for_scaling = "chi", colorbarlabel = "$\chi$ (m)", show_colourbar=True, this_colourmap = cmap, colourbar_location="top")
	
    # add the faults
    if faults:
        LineFileName = DataDirectory + fname_prefix + "_faults.shp"
        MF.add_line_data(LineFileName, linestyle="-", linewidth=1.5, zorder=99, legend=True, label="Fault Segments")
        
    # add the basin outlines ### need to parallelise
    if not parallel:
      Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    else:
      Basins = LSDP.GetMultipleBasinOutlines(DataDirectory)
    
    # Find the relay basins and plot separately
    RelayBasinIDs = [1248, 4788, 4995, 5185, 6187, 6758, 6805]
    RelayBasins = {key:value for key, value in Basins.items() if key in RelayBasinIDs}

    # Plot all basins
    MF.plot_polygon_outlines(Basins, colour='k', linewidth=0.5, alpha = 1, legend=True, label="Catchments")
    MF.plot_polygon_outlines(RelayBasins, colour='r', linewidth=0.5, alpha = 1,legend=True, label="Relay Catchments")

    # Add the legend
    MF.add_legend()
    
    # Save the figure
    ImageName = raster_directory+fname_prefix+'_chi_map.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 300)
def PrintCategorised(DataDirectory,
                     fname_prefix,
                     Drape_prefix,
                     show_colourbar=False,
                     cmap="jet",
                     cbar_loc="right",
                     cbar_label="drape colourbar",
                     size_format="ESURF",
                     fig_format="png",
                     dpi=250,
                     out_fname_prefix=""):
    """
    This function makes a shaded relief plot of the DEM a drape plot that has categorised colours.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        Drape_prefix (str): The prefix of the drape name
        show_colourbar (bool): if true show the colourbar
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        cbar_label (str): The text on the colourbar label
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix

    Returns:
        Shaded relief plot with categorised data.

    Author: SMM
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # going to make the basin plots - need to have bil extensions.
    print(
        "I'm going to make a plot of categorised data. Your topographic data must be in ENVI bil format or I'll break!!"
    )

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    BackgroundRasterName = fname_prefix + '_hs' + raster_ext
    CatName = Drape_prefix + raster_ext

    # clear the plot
    plt.clf()

    # set up the base image and the map
    MF = MapFigure(BackgroundRasterName,
                   DataDirectory,
                   coord_type="UTM_km",
                   colourbar_location=cbar_loc)
    #MF.add_drape_image(ElevationName,DataDirectory,colourmap = "gray", alpha = 0.6, colorbarlabel = None)
    MF.add_categorised_drape_image(CatName,
                                   DataDirectory,
                                   colourmap=cmap,
                                   alpha=0.7,
                                   colorbarlabel=cbar_label,
                                   norm="none")

    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory + fname_prefix + "_categorised." + fig_format
    else:
        ImageName = DataDirectory + out_fname_prefix + "_categorised." + fig_format

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=ImageName,
                FigFormat=fig_format,
                Fig_dpi=dpi,
                transparent=True)  # Save the figure
示例#44
0
def MakeRasterPlotTerraceElev(DataDirectory,fname_prefix, FigFormat='png', size_format='ESURF'):
    """
    This function makes a hillshade of the DEM with the terraces
    plotted onto it coloured by their elevation

    Args:
        DataDirectory (str): the data directory
        fname_prefix (str): the name of the DEM without extension.
        FigFormat (str): the figure format, default='png'
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).

    Returns:
        Raster plot of terrace IDs

    Author: FJC

    """
    from LSDMapFigure.PlottingRaster import BaseRaster
    from LSDMapFigure.PlottingRaster import MapFigure

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

    # make a figure
    if size_format == "geomorphology":
        #fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
        fig_width_inches=6.25
        #l_pad = -40
    elif size_format == "big":
        #fig = plt.figure(1, facecolor='white',figsize=(16,9))
        fig_width_inches=16
        #l_pad = -50
    else:
        fig_width_inches = 4.92126
        #fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2))
        #l_pad = -35

    # going to make the terrace plots - need to have bil extensions.
    print("I'm going to make a raster plot of terrace elevations. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    TerraceElevName = fname_prefix+'_terrace_relief_final'+raster_ext

    # get the terrace csv
    terraces = H.read_terrace_csv(DataDirectory,fname_prefix)
    terraceIDs = sorted(list(set(list(terraces.TerraceID))))
    xTerraces = []
    zTerraces = []
    yTerraces = []
    newIDs = []

    # loop through the terrace IDs and get the x, y, and z values
    for terraceID in terraceIDs:
        _terrace_subset = (terraces.TerraceID.values == terraceID)
        _x = terraces['DistAlongBaseline'].values[_terrace_subset]
        _y = terraces['DistToBaseline'].values[_terrace_subset]
        _z = terraces['Elevation'].values[_terrace_subset]
        _x_unique = sorted(list(set(list(_x))))
        _z_unique = []
        # Filter
        if len(_x) > 50 and len(_x_unique) > 1 and len(_x_unique) < 1000:
            #print np.max(np.diff(_x_unique))
            #if len(_x_unique) > 10 and len(_x_unique) < 1000 \
            #and :
            for _x_unique_i in _x_unique:
                #_y_unique_i = np.min(np.array(_y)[_x == _x_unique_i])
                #_z_unique.append(np.min(_z[_y == _y_unique_i]))
                _z_unique.append(np.min(_z[_x == _x_unique_i]))
            if np.mean(np.diff(_z_unique)/np.diff(_x_unique)) < 10:
                xTerraces.append(_x_unique)
                zTerraces.append(_z_unique)
                newIDs.append(terraceID)

    n_colours=len(newIDs)

    # create the map figure
    MF = MapFigure(HillshadeName, DataDirectory, coord_type='UTM_km', colourbar_location='right')
    # add the terrace drape
    terrace_cmap = plt.cm.Reds
    #terrace_cmap = colours.cmap_discretize(n_colours,terrace_cmap)
    MF.add_drape_image(TerraceElevName, DataDirectory, colourmap = terrace_cmap, colorbarlabel="Elevation above channel (m)", alpha=0.8)

    ImageName = DataDirectory+fname_prefix+'_terrace_elev_raster_plot.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 300) # Save the figure
#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()
thisPointData = LSDP.LSDMap_PointData(csv_file)
river_network = LSDP.LSDMap_PointData("/home/s1675537/PhD/DataStoreBoris/Emma/rv.csv")

#names = ['cubehelix','CMRmap','RdBu']
#names = ['spring_r', 'autumn_r','YlOrRd','YlOrRd_r']
names = ['autumn_r']
for nami in names:
    plt.clf()
    MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km", alpha = 1)
    MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.5)
    #MF.add_drape_image(BlackRaster, BlackRasterD, alpha = alpha_black)
    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)
    MF.add_point_data( thisPointData,column_for_plotting = "elevation",
                       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 )


    #MF.add_drape_image(CurveRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True, colorbarlabel= "Colourbar")
    #MF.show_plot()
    ImageName = wDirectory+str(int(clock.time()))+nami+".png"
    fig_size_inches = 12
    ax_style = "Normal"
    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 500)

DrapeRasterName = Base_file+"_hs.bil"
ChiRasterName = Base_file+"_curvature.bil"

#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()




plt.clf()
MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km")
MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4)
MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True)
#MF.show_plot()
ImageName = Directory+"boris.png"
fig_size_inches = 6
ax_style = "Madhouse"
MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style)



# Customise the DrapePlot
#dp.make_drape_colourbar(cbar_label=colourbar_label)
#dp.set_fig_axis_labels()

#dp.show_plot()
示例#47
0
def ExampleOne_PartFour_MaskBasins(DataDirectory, fname_prefix):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID. It shows how to mask certain basins.
    Search the function for "Basins_to_mask".

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: SMM
    """
    import numpy as np
    Basins_to_mask = [0,4,6]

    FigFormat = "png"
    size_format = "geomorphology"

    #import modules
    # from LSDMapFigure.PlottingRaster import MapFigure
    # from LSDMapFigure.PlottingRaster import BaseRaster
    # import LSDPlottingTools.LSDMap_VectorTools as LSDMap_VT
    # import LSDPlottingTools.LSDMap_PointTools as LSDMap_PT

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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126



    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]
    
    
    # get the junctions to mask
    key_to_index_dict = dict(zip(basin_keys,basin_junctions))
    junctions_to_mask = []
    for basin in Basins_to_mask:
        junctions_to_mask.append( key_to_index_dict[basin])
    print("The junctions to mask are")
    print(junctions_to_mask)

    print ('Basin keys are: ')
    print basin_keys
    
    print("Let me mask those for you")
    new_keys = []
    for key in basin_keys:
        if key in Basins_to_mask:
            new_keys.append(np.nan)
        else:
            new_keys.append(key)
    print("The new keys are: ")
    print(new_keys)
    basin_keys = new_keys

    # get a discrete colormap
    cmap = plt.cm.jet

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    print (BasinsName)

    # create the map figure
    # We set colourbar location to none since we are labelling the figures
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location='none')

    # add the basins drape
    MF.add_drape_image(BasinsName, DataDirectory, colourmap = cmap, alpha = 0.8, colorbarlabel='Basin ID', discrete_cmap=True, n_colours=len(basin_keys), show_colourbar = True, modify_raster_values=True, old_values=basin_junctions, new_values=basin_keys, cbar_type = int)

    # add the basin outlines
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)
    
    # get rid of the basins that are being masked
    for junction in junctions_to_mask:
        del Basins[junction]
        
        
        
    
    # note that at this stage the Basins are keyed with the junction index
    MF.plot_polygon_outlines(Basins, linewidth=0.8)

    # add the basin labelling
    label_dict = dict(zip(basin_junctions,basin_keys))
    # this dict has the basin junction as the key and the basin_key as the value
    

    Points = LSDP.GetPointWithinBasins(DataDirectory, BasinsName)
    
    # get rid of points as well
    for junction in junctions_to_mask:
        del Points[junction]
        del label_dict[junction]
    
    MF.add_text_annotation_from_shapely_points(Points, text_colour='k', label_dict=label_dict)

    # Save the figure
    ImageName = DataDirectory+fname_prefix+'_labelled_basins.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 250)
示例#48
0
def PlotElevationWithClusters(DataDirectory,
                              OutDirectory,
                              fname_prefix,
                              stream_order=1,
                              cbar_loc='right',
                              custom_cbar_min_max=[]):
    """
    Make a plot of the raster with the channels coloured by the cluster
    value. Uses the LSDPlottingTools libraries. https://github.com/LSDtopotools/LSDMappingTools

    Args:
        stream_order: the stream order of the profiles that you are analysing
        cbar_loc: location of the colourbar, can be right, top, bottom, left, or none.
        custom_cbar_min_max: list of [min, max] to recast the raster to for display.

    Author: FJC
    """
    print("I'm plotting the elevation with channels coloured by cluster")
    df = pd.read_csv(DataDirectory + fname_prefix + '_all_tribs.csv')
    cluster_df = pd.read_csv(
        OutDirectory + fname_prefix +
        '_profiles_clustered_SO{}.csv'.format(stream_order))

    # set figure sizes based on format
    fig_width_inches = 4.92126

    # some raster names
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HSName = fname_prefix + '_hs' + raster_ext

    if not os.path.isfile(DataDirectory + HSName):
        # make a hillshade
        BM.GetHillshade(DataDirectory + BackgroundRasterName,
                        DataDirectory + HSName)

    MF = MapFigure(HSName,
                   DataDirectory,
                   coord_type="UTM",
                   colourbar_location=cbar_loc)
    MF.add_drape_image(BackgroundRasterName,
                       DataDirectory,
                       colourmap='gray',
                       alpha=0.5,
                       colorbarlabel="Elevation (m)",
                       colour_min_max=custom_cbar_min_max)

    # # create the map figure
    # MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM",colour_min_max = custom_cbar_min_max)

    clusters = cluster_df.cluster_id.unique()
    for cl in clusters:
        # plot the whole channel network in black
        ChannelPoints = LSDP.LSDMap_PointData(df,
                                              data_type="pandas",
                                              PANDEX=True)
        MF.add_point_data(ChannelPoints,
                          show_colourbar="False",
                          unicolor='w',
                          manual_size=1,
                          zorder=2,
                          alpha=1)
        # plot the clustered profiles in the correct colour
        this_df = cluster_df[cluster_df.cluster_id == cl]
        this_colour = str(this_df.colour.unique()[0])
        ClusteredPoints = LSDP.LSDMap_PointData(this_df,
                                                data_type="pandas",
                                                PANDEX=True)
        MF.add_point_data(ClusteredPoints,
                          show_colourbar="False",
                          zorder=100,
                          unicolor=this_colour,
                          manual_size=2)

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=OutDirectory + fname_prefix +
                '_elev_clusters_SO{}.png'.format(stream_order),
                FigFormat='png',
                Fig_dpi=300,
                fixed_cbar_characters=6,
                adjust_cbar_characters=False,
                axis_style='Thin',
                transparent=True)  # Save the figure
#BR = BaseRaster(BackgroundRasterName, Directory)
#BR.set_raster_type("Terrain")
#print(BR._colourmap)
#BR.show_raster()

#BR.set_colourmap("RdYlGn")
#BR.show_raster()

#PD_file = Base_file+"_chi_coord_basins.csv"  
PD_file = Base_file+"_MChiSegmented.csv"
PointData = LSDMap_PointTools.LSDMap_PointData(Directory+PD_file)

plt.clf() 
cbar_loc = "Bottom"
MF = MapFigure(BackgroundRasterName, Directory,coord_type="UTM_km",colourbar_location = cbar_loc)
MF.add_drape_image(DrapeRasterName,Directory,alpha = 0.4)
#MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4)
MF.add_point_data(PointData,column_for_plotting = "source_key",colorbarlabel = "I am point data",
                  scale_points = True,column_for_scaling = "drainage area",
                       scaled_data_in_log = False)
#MF.show_plot()
ImageName = Directory+"TestNewArtist.png" 
fig_size_inches = 6
ax_style = "Normal"
MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, Fig_dpi = 250)



# Customise the DrapePlot
#dp.make_drape_colourbar(cbar_label=colourbar_label)
def PrintBasins_Complex(DataDirectory,fname_prefix,
                   use_keys_not_junctions = True, show_colourbar = False,
                   Remove_Basins = [], Rename_Basins = {}, Value_dict= {},
                   cmap = "jet", colorbarlabel = "colourbar", size_format = "ESURF",
                   fig_format = "png", dpi = 250, out_fname_prefix = "", include_channels = False, label_basins = True):
    """
    This function makes a shaded relief plot of the DEM with the basins coloured
    by the basin ID.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        use_keys_not_junctions (bool): If true use basin keys to locate basins, otherwise use junction indices
        show_colourbar (bool): if true show the colourbar
        Remove_Basins (list): A lists containing either key or junction indices of basins you want to remove from plotting
        Rename_Basins (dict): A dict where the key is either basin key or junction index, and the value is a new name for the basin denoted by the key
        Value_dict (dict): A dict where the key is either basin key or junction index, and the value is a value of the basin that is used to colour the basins
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
        include_channels (bool): If true, adds a channel plot. It uses the chi_data_maps file
        label_basins (bool): If true, the basins get labels

    Returns:
        Shaded relief plot with the basins coloured by basin ID. Uses a colourbar to show each basin. This allows more complex plotting with renamed and excluded basins.

    Author: FJC, SMM
    """
    #import modules
    from LSDMapFigure.PlottingRaster import MapFigure

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print ('Basin keys are: ')
    print (basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext

    # This initiates the figure
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location="None")

    # This adds the basins
    MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, mask_list = Remove_Basins,
                      rename_dict = Rename_Basins, value_dict = Value_dict,
                      use_keys_not_junctions = use_keys_not_junctions, show_colourbar = show_colourbar,
                      discrete_cmap=True, n_colours=15, colorbarlabel = colorbarlabel,
                      colourmap = cmap, adjust_text = False, label_basins = label_basins)

    # See if you need the channels
    if include_channels:
        print("I am going to add some channels for you")
        ChannelFileName = fname_prefix+"_chi_data_map.csv"
        chi_csv_fname = DataDirectory+ChannelFileName

        thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)

        MF.add_point_data(thisPointData,column_for_plotting = "basin_key",
                       scale_points = True,column_for_scaling = "drainage_area",
                       this_colourmap = "Blues_r", scaled_data_in_log = True,
                       max_point_size = 3, min_point_size = 1, discrete_colours = True, NColours = 1, zorder = 5)


    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_selected_basins."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_selected_basins."+fig_format

    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=fig_format, Fig_dpi = dpi, transparent=True) # Save the figure
示例#51
0
def PlotKsnFromSlopeArea(DataDirectory,
                         fname_prefix,
                         theta=0.45,
                         cbar_loc='right',
                         custom_cbar_min_max=[]):
    """
    Make a plot of the slope area data with a fixed concavity
    """
    import numpy as np

    print("Calculating ksn...")
    # read the csv and get some info
    df = pd.read_csv(DataDirectory + fname_prefix + "_slopes.csv")

    # now force a fit of ks based on this concavity
    area = df['drainage_area'].values
    slope = df['slope'].values

    ksn = slope / (area**(-theta))
    df['ksn'] = ksn
    print(np.max(ksn), np.min(ksn))
    print(ksn)

    df.to_csv(DataDirectory + fname_prefix + '_ksn.csv', index=False)

    # set figure sizes based on format
    fig_width_inches = 6

    # some raster names
    raster_ext = '.bil'
    BackgroundRasterName = fname_prefix + raster_ext
    HSName = fname_prefix + '_hs' + raster_ext

    if not os.path.isfile(DataDirectory + HSName):
        # make a hillshade
        BM.GetHillshade(DataDirectory + BackgroundRasterName,
                        DataDirectory + HSName)

    # create the map figure
    MF = MapFigure(HSName,
                   DataDirectory,
                   coord_type="UTM",
                   cbar_loc='right',
                   font_size=16)
    #MF.add_drape_image(BackgroundRasterName,DataDirectory,colourmap = 'gray', alpha=0.5)

    # add the ksn data
    ChannelPoints = LSDP.LSDMap_PointData(df, data_type="pandas", PANDEX=True)
    MF.add_point_data(ChannelPoints,
                      this_colourmap='viridis',
                      column_for_plotting='ksn',
                      colour_log=True,
                      zorder=100,
                      show_colourbar=True,
                      colourbar_location='bottom',
                      font_size=24,
                      colorbarlabel="log$_{10}(k_{sn})",
                      manual_size=1.5,
                      colour_manual_scale=[0, 1.8])
    #plt.show()

    MF.save_fig(fig_width_inches=fig_width_inches,
                FigFileName=DataDirectory + fname_prefix + '_ksn.png',
                FigFormat='png',
                Fig_dpi=300,
                fixed_cbar_characters=6,
                adjust_cbar_characters=False,
                axis_style='Thin',
                transparent=True)  # Save the figure
    plt.clf()
def PlotTopoRaster(DataDirectory, fname_prefix, size_format='ESURF', FigFormat='png', colors = "terrain"):
    """
    Creates a basic Terrain topographic raster. Needs the Hillshade 

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).
        FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command.

    Returns:
        Shaded relief plot with the basins coloured by basin ID

    Author: BG, FJC
    """
    # check if a directory exists for the chi plots. If not then make it.
    raster_directory = DataDirectory+'raster_plots/'
    if not os.path.isdir(raster_directory):
        os.makedirs(raster_directory)

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

    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_width_inches = 6.25
    elif size_format == "big":
        fig_width_inches = 16
    else:
        fig_width_inches = 4.92126

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make a cabic topographic plot")

    # get the rasters
    raster_ext = '.bil'
    ## Just checking if you have a PP version of it
    if os.path.isfile(DataDirectory + fname_prefix +"_PP.bil"):
        BackgroundRasterName = fname_prefix+"_PP"+raster_ext
    else:
        BackgroundRasterName = fname_prefix+raster_ext

    HillshadeName = fname_prefix+'_hs'+raster_ext
    

    # create the map figure
    MF = MapFigure(BackgroundRasterName, DataDirectory,coord_type="UTM_km", colourbar_location='None')

    # Drape the hillshade and add the color
    ## Frist plot the terrain toporaster 
    MF.add_drape_image(BackgroundRasterName,DataDirectory, # Calling the function will add a drapped raster on the top of the background on
                        colourmap = colors, # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                        alpha=1, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                        show_colourbar = True, # Well, this one is explicit I think
                        colorbarlabel = "None",
                        NFF_opti = True) 
    ## Drape the Hillshade raster
    MF.add_drape_image(HillshadeName,DataDirectory, # Calling the function will add a drapped raster on the top of the background on
                        colourmap = "gray", # colormap used for this raster, see http://matplotlib.org/users/colormaps.html for examples, put _r at the end of a colormap to get the reversed version
                        alpha=0.4, # transparency of this specific layer, 0 for fully transparent (why not) and 1 for fully opaque
                        show_colourbar = True, # Well, this one is explicit I think
                        colorbarlabel = "None",
                        NFF_opti = True) 

    # Save the figure
    ImageName = raster_directory+fname_prefix+'_Topo.'+FigFormat
    MF.save_fig(fig_width_inches = fig_width_inches, FigFileName = ImageName, FigFormat=FigFormat, Fig_dpi = 300)
def PrintChiCoordChannelsAndBasins(DataDirectory,fname_prefix, ChannelFileName, add_basin_labels = True, cmap = "cubehelix", cbar_loc = "right", size_format = "ESURF", fig_format = "png", dpi = 250,plotting_column = "source_key",discrete_colours = False, NColours = 10, colour_log = True, colorbarlabel = "Colourbar", Basin_remove_list = [], Basin_rename_dict = {} , value_dict = {}, plot_chi_raster = False, out_fname_prefix = "", show_basins = True, min_channel_point_size = 0.5, max_channel_point_size = 2):
    """
    This function prints a channel map over a hillshade.

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        add_basin_labels (bool): If true, label the basins with text. Otherwise use a colourbar.
        cmap (str or colourmap): The colourmap to use for the plot
        cbar_loc (str): where you want the colourbar. Options are none, left, right, top and botton. The colourbar will be of the elevation.
                        If you want only a hillshade set to none and the cmap to "gray"
        size_format (str): Either geomorphology or big. Anything else gets you a 4.9 inch wide figure (standard ESURF size)
        fig_format (str): An image format. png, pdf, eps, svg all valid
        dpi (int): The dots per inch of the figure
        plotting_column (str): the name of the column to plot
        discrete_colours (bool): if true use a discrete colourmap
        NColours (int): the number of colours to cycle through when making the colourmap
        colour_log (bool): If true the colours are in log scale
        Basin_remove_list (list): A lists containing either key or junction indices of basins you want to remove from plotting
        Basin_rename_dict (dict): A dict where the key is either basin key or junction index, and the value is a new name for the basin denoted by the key
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
        show_basins (bool): If true, plot the basins
        min_channel_point_size (float): The minimum size of a channel point in points
        max_channel_point_size (float): The maximum size of a channel point in points

    Returns:
        Shaded relief plot with the basins coloured by basin ID. Includes channels. These can be plotted by various metrics denoted but the plotting_column parameter.

    Author: SMM
    """
    # specify the figure size and format
    # set figure sizes based on format
    if size_format == "geomorphology":
        fig_size_inches = 6.25
    elif size_format == "big":
        fig_size_inches = 16
    else:
        fig_size_inches = 4.92126
    ax_style = "Normal"

    # get the basin IDs to make a discrete colourmap for each ID
    BasinInfoDF = PlotHelp.ReadBasinInfoCSV(DataDirectory, fname_prefix)

    basin_keys = list(BasinInfoDF['basin_key'])
    basin_keys = [int(x) for x in basin_keys]

    basin_junctions = list(BasinInfoDF['outlet_junction'])
    basin_junctions = [float(x) for x in basin_junctions]

    print ('Basin keys are: ')
    print (basin_keys)

    # going to make the basin plots - need to have bil extensions.
    print("I'm going to make the basin plots. Your topographic data must be in ENVI bil format or I'll break!!")

    # get the rasters
    raster_ext = '.bil'
    #BackgroundRasterName = fname_prefix+raster_ext
    HillshadeName = fname_prefix+'_hs'+raster_ext
    BasinsName = fname_prefix+'_AllBasins'+raster_ext
    ChiCoordName = fname_prefix+'_Maskedchi'+raster_ext
    print (BasinsName)
    Basins = LSDP.GetBasinOutlines(DataDirectory, BasinsName)

    chi_csv_fname = DataDirectory+ChannelFileName
    chi_csv_fname = DataDirectory+ChannelFileName

    thisPointData = LSDMap_PD.LSDMap_PointData(chi_csv_fname)
    
    # Remove data that has nodata values
    thisPointData.selectValue(plotting_column,value = -9999, operator = "!=")

    thisPointData.selectValue("basin_key",value = Basin_remove_list, operator = "!=")
    #print("The new point data is:")
    #print(thisPointData.GetLongitude())


    # clear the plot
    plt.clf()

    # set up the base image and the map
    print("I am showing the basins without text labels.")
    MF = MapFigure(HillshadeName, DataDirectory,coord_type="UTM_km", colourbar_location="None")

    # This adds the basins


    if plot_chi_raster:
        if show_basins:
            MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, mask_list = Basin_remove_list, rename_dict = Basin_rename_dict, value_dict = value_dict, label_basins = add_basin_labels, show_colourbar = False, colourmap = "gray", alpha = 1, outlines_only = True)

        MF.add_drape_image(ChiCoordName,DataDirectory,colourmap = "cubehelix",alpha=0.6,zorder = 0.5)

        MF.add_point_data(thisPointData,column_for_plotting = plotting_column,scale_points = True,column_for_scaling = "drainage_area", show_colourbar = True, colourbar_location = cbar_loc,colorbarlabel = colorbarlabel, this_colourmap = cmap,scaled_data_in_log = True,max_point_size = max_channel_point_size, min_point_size = min_channel_point_size,zorder=0.4, colour_log = colour_log, discrete_colours = discrete_colours, NColours = NColours)
    else:
        if show_basins:
            MF.add_basin_plot(BasinsName,fname_prefix,DataDirectory, mask_list = Basin_remove_list, rename_dict = Basin_rename_dict, value_dict = value_dict, label_basins = add_basin_labels, show_colourbar = False, colourmap = "gray", alpha = 0.7, outlines_only = False)

        MF.add_point_data(thisPointData,column_for_plotting = plotting_column,scale_points = True,column_for_scaling = "drainage_area", show_colourbar = True, colourbar_location = cbar_loc,colorbarlabel = colorbarlabel, this_colourmap = cmap,scaled_data_in_log = True,max_point_size = 2, min_point_size = 0.5,zorder=10, colour_log = colour_log, discrete_colours = discrete_colours, NColours = NColours)





    # Save the image
    if len(out_fname_prefix) == 0:
        ImageName = DataDirectory+fname_prefix+"_chicoord_and_basins."+fig_format
    else:
        ImageName = DataDirectory+out_fname_prefix+"_chicoord_and_basins."+fig_format

    MF.save_fig(fig_width_inches = fig_size_inches, FigFileName = ImageName, axis_style = ax_style, FigFormat=fig_format, Fig_dpi = dpi)