def PrintChiChannels(DataDirectory,
                     fname_prefix,
                     ChannelFileName,
                     add_basin_labels=True,
                     cmap="jet",
                     cbar_loc="right",
                     size_format="ESURF",
                     fig_format="png",
                     dpi=250,
                     plotting_column="source_key",
                     discrete_colours=False,
                     NColours=10,
                     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
        ChannelFileName (str): The name of the channel file (a csv) without path but with extension
        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
        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
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Returns:
        Shaded relief plot with the channels coloured by a plotting column designated by the plotting_column keyword. 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"
    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="gray",
                       alpha=0.6)
    MF.add_point_data(thisPointData,
                      column_for_plotting=plotting_column,
                      this_colourmap=cmap,
                      scale_points=True,
                      column_for_scaling="drainage_area",
                      scaled_data_in_log=True,
                      max_point_size=5,
                      min_point_size=1,
                      discrete_colours=discrete_colours,
                      NColours=NColours)

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

    MF.save_fig(fig_width_inches=fig_size_inches,
                FigFileName=ImageName,
                axis_style=ax_style,
                FigFormat=fig_format,
                Fig_dpi=dpi)
def PlotSwath(swath_csv_name, FigFileName = 'Image.png', size_format = "geomorphology", fig_format = "png", dpi = 500, aspect_ratio = 2):
    """
    This plots a swath profile
    
    Args: 
        swath_csv_name (str): the name of the csv file (with path!)
        
    Author: SMM
    
    Date 20/02/2018
    """
    
    print("STARTING swath plot.")

    # Set up fonts for plots
    label_size = 12
    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_size_inches = 6.25
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(1, facecolor='white',figsize=(16,9))
        fig_size_inches = 16
        l_pad = -50
    else:
        fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5))
        fig_size_inches = 4.92126
        l_pad = -35
    
    # Note all the below parameters are overwritten by the figure sizer routine
    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax = fig.add_subplot(gs[25:100,10:95])

    print("Getting data from the file: "+swath_csv_name)
    thisPointData = LSDMap_PD.LSDMap_PointData(swath_csv_name)
    
    distance = thisPointData.QueryData('Distance').values
    mean_val = thisPointData.QueryData('Mean').values
    min_val = thisPointData.QueryData('Min').values
    max_val = thisPointData.QueryData('Max').values
    
    # Get the minimum and maximum distances
    X_axis_min = 0
    X_axis_max = distance[-1]
    n_target_tics = 5
    xlocs,new_x_labels = LSDMap_BP.TickConverter(X_axis_min,X_axis_max,n_target_tics)
    
    ax.fill_between(distance, min_val, max_val, facecolor='orange', alpha = 0.5, interpolate=True)
    ax.plot(distance, mean_val,"b", linewidth = 1)
    ax.plot(distance, min_val,"k",distance,max_val,"k",linewidth = 1)
    
    ax.spines['top'].set_linewidth(1)
    ax.spines['left'].set_linewidth(1)
    ax.spines['right'].set_linewidth(1)
    ax.spines['bottom'].set_linewidth(1)

    ax.set_ylabel("Elevation (m)")
    ax.set_xlabel("Distance along swath (km)")
    
    ax.set_xticks(xlocs)
    ax.set_xticklabels(new_x_labels,rotation=60)

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

        
    # Lets try to size the figure
    cbar_L = "None"
    [fig_size_inches,map_axes,cbar_axes] = Helper.MapFigureSizer(fig_size_inches,aspect_ratio, cbar_loc = cbar_L, title = "None")
    
    fig.set_size_inches(fig_size_inches[0], fig_size_inches[1])
    ax.set_position(map_axes)  
    
    FigFormat = fig_format    
    print("The figure format is: " + FigFormat)
    if FigFormat == 'show':
        plt.show()
    elif FigFormat == 'return':
        return fig
    else:
        plt.savefig(FigFileName,format=FigFormat,dpi=dpi)
        fig.clf()
def BinnedRegressionDriver(DataDirectory, DEM_prefix, basin_keys=[]):
    """
    This function goes through a basin list and reports back the best fit
    m/n values for mainstem data, all data, and both of these with outliers removed

    Args:
        DataDirectory (str): the path to the directory with the csv file
        DEM_prefix (str): name of your DEM without extension
        basin_keys (list): A list of the basin keys to plot. If empty, plot all the basins.

    Author: SMM
    """
    from LSDPlottingTools import LSDMap_PointTools as PointTools

    print("These basin keys are: ")
    print(basin_keys)

    # read in binned data
    binned_csv_fname = DataDirectory + DEM_prefix + '_SAbinned.csv'
    print("I'm reading in the csv file " + binned_csv_fname)
    binnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)

    # get the basin keys and check if the basins in the basin list exist
    basin = binnedPointData.QueryData('basin_key')
    basin = [int(x) for x in basin]
    Basin = np.asarray(basin)
    these_basin_keys = np.unique(Basin)

    #print("The unique basin keys are: ")
    #print(these_basin_keys)

    final_basin_keys = []
    # A bit of logic for checking keys
    if (len(basin_keys) == 0):
        final_basin_keys = these_basin_keys
    else:
        for basin in basin_keys:
            if basin not in these_basin_keys:
                print("You were looking for basin " + str(basin) +
                      " but it isn't in the basin keys.")
            else:
                final_basin_keys.append(basin)

    #print("The final basin keys are:")
    #print(final_basin_keys)

    print("There are " + str(len(final_basin_keys)) +
          "basins that I will plot")
    mn_by_basin_dict = {}
    #basin_keys.append(0)
    # Loop through the basin keys, making a plot for each one
    for basin_key in final_basin_keys:

        (m1, m2, m3, m4) = BinnedRegression(binnedPointData, basin_key)
        this_basin_SA_mn = []
        this_basin_SA_mn.append(m1)
        this_basin_SA_mn.append(m2)
        this_basin_SA_mn.append(m3)
        this_basin_SA_mn.append(m4)

        mn_by_basin_dict[basin_key] = this_basin_SA_mn

    return mn_by_basin_dict
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 and has the option of plooting over a raster of chi values. Similar to PrintChiChannelsAndBasins but adds the map of chi coordinate underneath

    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
        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
        plot_chi_raster (bool): finds the chi raster and plots this underneath the chi points in the channels. It looks nice.
        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 = LSDV.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)
def SAPlotDriver(DataDirectory,
                 DEM_prefix,
                 FigFormat='show',
                 size_format="ESURF",
                 show_raw=True,
                 show_segments=True,
                 cmap=plt.cm.Set1,
                 n_colours=10,
                 basin_keys=[],
                 parallel=False):
    """
    This is a driver function that manages plotting of Slope-Area data

    Args:
        DataDirectory (str): the path to the directory with the csv file
        DEM_prefix (str): name of your DEM without extension
        FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command.
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).
        show_raw (bool): If true show raw data in background
        show_segments (bool): If true, show the segmented main stem,
        cmap (string or colourmap): the colourmap use to colour tributaries
        n_colours (int): The number of coulours used in plotting tributaries
        basin_keys (list): A list of the basin keys to plot. If empty, plot all the basins.
        parallel (bool): If true the data is in multiple files and must be merged

    Returns:
        Slope-area plot for each basin

    Author: SMM
    """
    from lsdviztools.lsdplottingtools import lsdmap_pointtools as PointTools

    print("These basin keys are: ")
    print(basin_keys)

    # read in binned data
    binned_csv_fname = DataDirectory + DEM_prefix + '_SAbinned.csv'
    print("I'm reading in the csv file " + binned_csv_fname)

    if not parallel:
        binnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)
    else:
        binnedPointData = Helper.AppendSABinnedCSVs(DataDirectory, DEM_prefix)
        binnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)

    # Read in the raw data
    if (show_raw):
        print("I am going to show the raw data.")
        all_csv_fname = DataDirectory + DEM_prefix + '_SAvertical.csv'
        if not parallel:
            allPointData = PointTools.LSDMap_PointData(all_csv_fname)
        else:
            allPointData = Helper.AppendSAVerticalCSVs(DataDirectory,
                                                       DEM_prefix)
            allPointData = PointTools.LSDMap_PointData(all_csv_fname)

    # Read in the segmented data
    if (show_segments):
        print("I am going to show segments on the main stem.")
        segmented_csv_fname = DataDirectory + DEM_prefix + '_SAsegmented.csv'
        if not parallel:
            segmentedPointData = PointTools.LSDMap_PointData(
                segmented_csv_fname)
        else:
            segmentedPointData = Helper.AppendSASegmentedCSVs(
                DataDirectory, DEM_prefix)
            segmentedPointData = PointTools.LSDMap_PointData(
                segmented_csv_fname)

    # get the basin keys and check if the basins in the basin list exist
    basin = binnedPointData.QueryData('basin_key')
    basin = [int(x) for x in basin]
    Basin = np.asarray(basin)
    these_basin_keys = np.unique(Basin)

    print("The unique basin keys are: ")
    print(these_basin_keys)

    final_basin_keys = []
    # A bit of logic for checking keys
    if (len(basin_keys) == 0):
        final_basin_keys = these_basin_keys
    else:
        for basin in basin_keys:
            if basin not in these_basin_keys:
                print("You were looking for basin " + str(basin) +
                      " but it isn't in the basin keys.")
            else:
                final_basin_keys.append(basin)

    print("The final basin keys are:")
    print(final_basin_keys)

    this_cmap = cmap
    print("There are " + str(len(final_basin_keys)) +
          "basins that I will plot")
    #basin_keys.append(0)
    # Loop through the basin keys, making a plot for each one
    for basin_key in final_basin_keys:
        print("I am making a plot for basin: " + str(basin_key))
        if (show_segments):
            if (show_raw):
                FileName = DEM_prefix + '_SA_plot_raw_and_segmented_basin%s.%s' % (
                    str(basin_key), FigFormat)
                SegmentedWithRawSlopeAreaPlot(segmentedPointData,
                                              allPointData,
                                              DataDirectory,
                                              FigFileName=FileName,
                                              FigFormat=FigFormat,
                                              size_format=size_format,
                                              basin_key=basin_key,
                                              cmap=this_cmap,
                                              n_colours=n_colours)
            else:
                FileName = DEM_prefix + '_SA_plot_segmented_basin%s.%s' % (
                    str(basin_key), FigFormat)
                SegmentedSlopeAreaPlot(segmentedPointData,
                                       DataDirectory,
                                       FigFileName=FileName,
                                       FigFormat=FigFormat,
                                       size_format=size_format,
                                       basin_key=basin_key)

        else:
            if (show_raw):
                FileName = DEM_prefix + '_SA_plot_raw_and_binned_basin%s.%s' % (
                    str(basin_key), FigFormat)
                BinnedWithRawSlopeAreaPlot(DataDirectory,
                                           DEM_prefix,
                                           FigFileName=FileName,
                                           FigFormat=FigFormat,
                                           size_format=size_format,
                                           basin_key=basin_key,
                                           n_colours=n_colours,
                                           cmap=this_cmap)
            else:
                print(
                    "You selected an option that doesn't produce any plots. Turn either show raw or show segments to True."
                )
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,
                        save_fig=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:
        A string with the name of the image (printed to file): 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
    """

    # 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!!"
    )

    # clear the plot
    plt.clf()

    # 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 = LSDP.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
    thing_to_return = []
    if (save_fig):
        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)

        thing_to_return = ImageName

    else:
        fig = MF.save_fig(fig_width_inches=fig_width_inches,
                          transparent=True,
                          return_fig=True)
        thing_to_return = fig

    print("I'm returning:")
    print(thing_to_return)
    return thing_to_return
def PrintChannelsAndBasins(DataDirectory,
                           fname_prefix,
                           add_basin_labels=True,
                           cmap="jet",
                           size_format="ESURF",
                           fig_format="png",
                           dpi=250,
                           out_fname_prefix="",
                           save_fig=True):
    """
    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
        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:
        A string with the name of the image (printed to file): 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 = LSDV.GetBasinOutlines(DataDirectory, BasinsName)

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

    thisPointData = LSDP.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
    thing_to_return = []
    if (save_fig):
        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,
                    FigFormat=fig_format,
                    Fig_dpi=dpi,
                    transparent=True)

        thing_to_return = ImageName

    else:
        fig = MF.save_fig(fig_width_inches=fig_size_inches,
                          transparent=True,
                          return_fig=True)
        thing_to_return = fig

    print("I'm returning:")
    print(thing_to_return)
    return thing_to_return
def PrintChannels(DataDirectory,
                  fname_prefix,
                  ChannelFileName,
                  cmap="jet",
                  size_format="ESURF",
                  fig_format="png",
                  dpi=250,
                  out_fname_prefix="",
                  plotting_column="basin_key",
                  save_fig=True):
    """
    This function prints a channel map over a hillshade. It is more flexible than PrintAllChannels since you can choose the channel csv and you can also choose the column in the csv to plot

    Args:
        DataDirectory (str): the data directory with the m/n csv files
        fname_prefix (str): The prefix for the m/n csv files
        ChannelFileName (str): The name of the channel file. Doesn't need path but needs extension
        cmap (str or colourmap): The colourmap to use for the plot
        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
        plotting_column (str): the column to plot from the csv file
        save_fig (bool): If true, saves the fig, else, returns the filename

    Returns:
        If save_fig is true, return a string with the name of the image (printed to file). If save_fig is false, returns the figure handle to the shaded relief plot with the channels.

    Returns:
        A string with the name of the image (printed to file): A string with the name of the image (printed to file): 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"
    chi_csv_fname = DataDirectory + ChannelFileName

    print("Let me get the point data")
    print("The filename is: " + chi_csv_fname)
    thisPointData = LSDP.LSDMap_PointData(chi_csv_fname)
    print("The parameter names are")
    thisPointData.GetParameterNames(True)

    # 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="gray",
                       alpha=0.6)
    MF.add_point_data(thisPointData,
                      column_for_plotting=plotting_column,
                      scale_points=True,
                      column_for_scaling="drainage_area",
                      this_colourmap=cmap,
                      scaled_data_in_log=True,
                      max_point_size=5,
                      min_point_size=1)

    # Save the image
    thing_to_return = []
    if (save_fig):
        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,
                    FigFormat=fig_format,
                    Fig_dpi=dpi,
                    transparent=True)

        thing_to_return = ImageName

    else:
        fig = MF.save_fig(fig_width_inches=fig_size_inches,
                          transparent=True,
                          return_fig=True)
        thing_to_return = fig

    print("I'm returning:")
    print(thing_to_return)
    return thing_to_return
def PrintAllChannels(DataDirectory,
                     fname_prefix,
                     add_basin_labels=True,
                     cmap="jet",
                     cbar_loc="right",
                     size_format="ESURF",
                     fig_format="png",
                     dpi=250,
                     out_fname_prefix="",
                     channel_colourmap="Blues",
                     save_fig=True):
    """
    This function prints a channel map over a hillshade. It gets ALL the channels within the DEM: it automatically selects the _CN csv file that is obtained by the print channel network tool in lsdtopotools. Channels are coloured by the stream order.

    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
        channel_colourmap (str or cmap): the colourmap of the point data
        save_fig (bool): If true, saves the fig, else, returns the filename

    Returns:
        If save_fig is true, return a string with the name of the image (printed to file). If save_fig is false, returns the figure handle to the shaded relief plot with the channels.


    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 + "_CN.csv"
    chi_csv_fname = DataDirectory + ChannelFileName

    thisPointData = LSDP.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="Stream Order",
                      this_colourmap=channel_colourmap,
                      scale_points=True,
                      column_for_scaling="Stream Order",
                      scaled_data_in_log=False,
                      max_point_size=5,
                      min_point_size=1,
                      zorder=10,
                      alpha=1)

    # Save the image
    thing_to_return = []
    if (save_fig):
        if len(out_fname_prefix) == 0:
            ImageName = DataDirectory + fname_prefix + "_channels." + fig_format
        else:
            ImageName = DataDirectory + out_fname_prefix + "_channels." + fig_format

        MF.save_fig(fig_width_inches=fig_size_inches,
                    FigFileName=ImageName,
                    FigFormat=fig_format,
                    Fig_dpi=dpi,
                    transparent=True)

        thing_to_return = ImageName

    else:
        fig = MF.save_fig(fig_width_inches=fig_size_inches,
                          transparent=True,
                          return_fig=True)
        thing_to_return = fig

    print("I'm returning:")
    print(thing_to_return)
    return thing_to_return