def load_Point_Tool(thing):
    """
    Returns a PointTools object from a csv_file or a pandas dataframe (automatically detects the type)

    Author:
        PointTools object
    """

    if(isinstance(thing, pandas.DataFrame)):
        PointData = PointTools.LSDMap_PointData(thing,data_type ="pandas", PANDEX = True)
    else:
        if(isinstance(thing, str)):
            if(thing[-3:] == "csv"):
                tdf = read_MChi_file(thing)
                PointData = PointTools.LSDMap_PointData(tdf,data_type ="pandas", PANDEX = True)
            else:
                if(isinstance(thing, dict)):
                    print("WARNING, I am concatenating your dictionnary of dataframe")
                    thing = pandas.concat(thing)
                    PointData = PointTools.LSDMap_PointData(thing,data_type ="pandas", PANDEX = True)
                else:
                    print("Hum, your file does not exists or your pandas is not a pandas (then what is it???), anyway I am aborting")
                    quit()

    return PointData
def MakeChannelsMap(DataDirectory,
                    DEM_prefix,
                    FigFormat='show',
                    size_format='ESURF'):
    """
    Function to make a raster map with the channels
    colour-coded by source node. The colours should match up between the slope-area plot and the map.

    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).

    Returns:
        Figure with map and slope-area plot for each basin

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

    # read in the raw csv file
    raw_csv_fname = DataDirectory + DEM_prefix + '_SAvertical.csv'
    print("I'm reading in the csv file " + raw_csv_fname)

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

    # get the point data objects
    RawPointData = PointTools.LSDMap_PointData(raw_csv_fname)
    BinnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)

    # get the basin keys
    basin = BinnedPointData.QueryData('basin_key')
    basin = [int(x) for x in basin]
    Basin = np.asarray(basin)
    basin_keys = np.unique(Basin)
    print('There are %s basins') % (len(basin_keys))

    # loop through each basin and make the figure
    for basin_key in basin_keys:
        # set up the figure
        FileName = DEM_prefix + '_raster_SA_basin%s.%s' % (str(basin_key),
                                                           FigFormat)

        # get the channels map
        raster_fname = DataDirectory + DEM_prefix + ".bil"
        hs_fname = DataDirectory + DEM_prefix + "_hs.bil"
        LSDP.LSDMap_ChiPlotting.BasicChannelPlotByBasin(
            raster_fname,
            hs_fname,
            raw_csv_fname,
            size_format=size_format,
            basin_key=basin,
            FigFileName=DataDirectory + FileName,
            FigFormat=FigFormat)
Пример #3
0
def knickpoint_plotter(DataDirectory = "none", DEM_prefix ="none" , kp_type = "diff", FigFormat='pdf', processed = False, pd_name = "none"):
    """
    Function to test LSDMap_KnickpointPlotting

    Args:
        DataDirectory (str): the data directory of the chi csv file
        DEM_prefix (str): DEM name without extension
        kp_type (string): select the type of knickpoint data you want (diff vs ratio).
        processed (bool): Switch on to directly give a pandas dataframe to plots
        pd_name (string or pandas dataframe): Name of this theoretical pandas dataframe

    Returns:
        Plot of knickpoint (diff or ratio) for each basin

    Author: FJC
    """
    from LSDPlottingTools import LSDMap_PointTools as PointTools
    from LSDPlottingTools import LSDMap_KnickpointPlotting as KP

    # read in the raw csv file
    if(processed):
        if(DEM_prefix !="none" and DataDirectory != "none"):
            print("I will directly load your pandas dataframe, or at least try")
            kp_csv_fname = read_MChi_file(DataDirectory,DEM_prefix+'_KsnKn.csv')
            # get the point data objects
            PointData = PointTools.LSDMap_PointData(kp_csv_fname,data_type ="pandas", PANDEX = True)
        else:
            if(isinstance(pd_name, pandas.DataFrame)):
                PointData = PointTools.LSDMap_PointData(pd_name,data_type ="pandas", PANDEX = True)
    else:
        kp_csv_fname = DataDirectory+DEM_prefix+'_KsnKn.csv'
        print("I'm reading in the csv file "+kp_csv_fname)

        # get the point data objects
        PointData = PointTools.LSDMap_PointData(+kp_csv_fname, data_type ="csv", PANDEX = True)

    # get the basin keys
    basin = PointData.QueryData('basin_key')
    basin = [int(x) for x in basin]
    Basin = np.asarray(basin)
    basin_keys = np.unique(Basin)
    print('There are %s basins') %(len(basin_keys))

    # loop through each basin and make the figure
    for basin_key in basin_keys:
        FileName = DEM_prefix+"_KP_elevations_%s.%s" %(str(basin_key),FigFormat)
        KP.plot_knickpoint_elevations(PointData, DataDirectory, DEM_prefix, basin_key, kp_type, FileName, FigFormat)
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)
Пример #5
0
def MakeSegmentedSlopeAreaPlot(DataDirectory,
                               DEM_prefix,
                               FigFormat='show',
                               size_format='ESURF',
                               x_param='midpoints',
                               y_param='mean'):
    """
    This function makes a slope-area plot based on the raw data, using the
    channel file generated from the chi mapping tool (ends in the extension
    "_SAsegmented.csv".)  It has a separate plot for each basin and colour codes
    the points by source node so different tributaries can be identified.

    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).
        x_param (str): Key for which parameter to plot on the x axis, either 'midpoints' for the midpoints of the area data (default), or 'mean' for the mean of the area data.
        y_param (str): Key for which parameter to plot on the y axis, either 'mean' for the mean of the slope data (default), or 'median', for the median of the slope data.

    Returns:
        Slope-area plot for each basin

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

    # read in the csv file
    chi_csv_fname = DataDirectory + DEM_prefix + '_SAsegmented.csv'
    print("I'm reading in the csv file " + chi_csv_fname)

    # get the point data object
    thisPointData = PointTools.LSDMap_PointData(chi_csv_fname)

    # get the basin keys
    basin = thisPointData.QueryData('basin_key')
    basin = [int(x) for x in basin]
    Basin = np.asarray(basin)
    basin_keys = np.unique(Basin)
    print('There are %s basins') % (len(basin_keys))

    #basin_keys = []
    #basin_keys.append(0)
    FigFormat = "png"
    for basin_key in basin_keys:
        FileName = DEM_prefix + '_SA_plot_segmented_basin%s.%s' % (
            str(basin_key), FigFormat)
        LSDP.LSDMap_ChiPlotting.SegmentedSlopeAreaPlot(thisPointData,
                                                       DataDirectory,
                                                       FigFileName=FileName,
                                                       FigFormat=FigFormat,
                                                       size_format=size_format,
                                                       basin_key=basin_key)
def BinnedRegressionDriver(DataDirectory, DEM_prefix, basin_keys=[]):
    """
    This function analyses slope-area data based on the binned data, using the
    channel file generated from the chi mapping tool (ends in the extension
    "_SAbinned.csv".)  It has a separate plot for each basin and colour codes
    the points by source node so different tributaries can be identified.

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

    Returns:
        Slope-area plot for each basin

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

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

    # get the point data object
    binnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)

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

    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)

    # Loop through the basin keys, making a plot for each one
    for basin_key in final_basin_keys:
        LSDP.LSDMap_SAPlotting.BinnedRegression(binnedPointData,
                                                basin_key=basin_key)
Пример #7
0
def BoxPlotByCluster(DataDirectory, OutDirectory, fname_prefix,  raster_name, stream_order=1):
    """
    Make a boxplot of the results of the clustering compared to the raster specified
    by raster_name
    """
    #df = pd.read_csv(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order))

    # read in the raster
    raster_ext = '.bil'
    this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name)
    EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name)
    NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name)
    CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name)

    pts = PT.LSDMap_PointData(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order),data_type ='csv')
    easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string)
    cluster_id = pts.QueryData('cluster_id', PANDEX=True)
    clusters = list(set(cluster_id))

    # dict for the data
    data = {k: [] for k in clusters}
    for x, (i, j) in enumerate(zip(northing, easting)):
    # convert to rows and cols
        X_coordinate_shifted_origin = j - XMin;
        Y_coordinate_shifted_origin = i - YMin;

        col_point = int(X_coordinate_shifted_origin/CellSize);
        row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize));
        # check for data at this cell
        this_value = this_raster[row_point][col_point]
        if not np.isnan(this_value):
            if this_value < 10:
                # get the cluster id
                data[cluster_id[x]].append(this_value)

    print(data)

    # now make a boxplot
    labels, these_data = [*zip(*data.items())]  # 'transpose' items to parallel key, value lists

    plt.boxplot(these_data)
    plt.xticks(range(1, len(labels) + 1), labels)
    plt.show()
Пример #8
0
def GetLithologyPercentages(DataDirectory, OutDirectory, fname_prefix, raster_name, stream_order=1):
    """
    Get the percentage of the nodes in each cluster that drain each lithology
    """
    from collections import Counter
    # read in the raster
    raster_ext = '.bil'
    this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name)
    EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name)
    NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name)
    CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name)

    pts = PT.LSDMap_PointData(OutDirectory+fname_prefix+'_profiles_clustered_SO{}.csv'.format(stream_order),data_type ='csv')
    easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string)
    cluster_id = pts.QueryData('cluster_id', PANDEX=True)
    clusters = list(set(cluster_id))

    # dict for the data
    data = {k: [] for k in clusters}
    for x, (i, j) in enumerate(zip(northing, easting)):
    # convert to rows and cols
        X_coordinate_shifted_origin = j - XMin;
        Y_coordinate_shifted_origin = i - YMin;

        col_point = int(X_coordinate_shifted_origin/CellSize);
        row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize));
        # check for data at this cell
        this_value = this_raster[row_point][col_point]
        if not np.isnan(this_value):
            data[cluster_id[x]].append(this_value)

    # you have the values. now what percentage are each?
    for key, liths in data.items():
        c = Counter(liths)
        n_ndv = c[0.0]
        print(c)
        [print(x,": ",vals/len(liths) * 100) for x, vals in c.items()]
Пример #9
0
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 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 MakeBinnedWithRawSlopeAreaPlot(DataDirectory,
                                   DEM_prefix,
                                   FigFormat='show',
                                   size_format='ESURF',
                                   basin_keys=[]):
    """
    This function makes a slope-area plot based on the raw data, using the
    channel file generated from the chi mapping tool (ends in the extension
    "_SAvertical.csv".)  It has a separate plot for each basin and colour codes
    the points by source node so different tributaries can be identified.

    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).
        basin_key (list): A list of the basin keys to plot. If empty, plot all the basins.

    Returns:
        Slope-area plot for each basin

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

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

    # get the point data object
    binnedPointData = PointTools.LSDMap_PointData(binned_csv_fname)
    allPointData = PointTools.LSDMap_PointData(all_csv_fname)

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

    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)

    this_cmap = plt.cm.Set1
    print('There are %s basins') % (len(basin_keys))
    #basin_keys.append(0)
    # Loop through the basin keys, making a plot for each one
    for basin_key in final_basin_keys:
        FileName = DEM_prefix + '_SA_plot_raw_and_binned_basin%s.%s' % (
            str(basin_key), FigFormat)
        LSDP.LSDMap_SAPlotting.BinnedWithRawSlopeAreaPlot(
            binnedPointData,
            allPointData,
            DataDirectory,
            FigFileName=FileName,
            FigFormat=FigFormat,
            size_format=size_format,
            basin_key=basin_key,
            n_colours=10,
            cmap=this_cmap)
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 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)
Пример #13
0
def MakeBoxPlotsKsnLithology(DataDirectory, fname_prefix, raster_name, theta=0.45, label_list=[]):
    """
    Make boxplots of ksn compared to lithology raster. Lithology should have integer
    values for the different rock types (rock type with 0 is excluded). Pass in list of
    labels for the different units, which must be the same length as the number of lithology codes.
    If none is passed then just use the integer values for labelling.
    """
    from scipy import stats

    # read in the raster
    raster_ext = '.bil'
    this_raster = IO.ReadRasterArrayBlocks(DataDirectory+raster_name)
    #EPSG_string = IO.GetUTMEPSG(DataDirectory+raster_name)
    EPSG_string='epsg:32611'
    print(EPSG_string)
    NDV, xsize, ysize, GeoT, Projection, DataType = IO.GetGeoInfo(DataDirectory+raster_name)
    CellSize,XMin,XMax,YMin,YMax = IO.GetUTMMaxMin(DataDirectory+raster_name)

    pts = PT.LSDMap_PointData(DataDirectory+fname_prefix+'_ksn.csv',data_type ='csv')
    print(pts)
    easting, northing = pts.GetUTMEastingNorthing(EPSG_string=EPSG_string)
    ksn = pts.QueryData('ksn', PANDEX=True)
    #print(ksn)

    # get the unique values in the raster
    raster_values = np.unique(this_raster)
    raster_values = raster_values[1:]


    # dict for the data
    data = {k: [] for k in raster_values}

    for x, (i, j) in enumerate(zip(northing, easting)):
    # convert to rows and cols
        X_coordinate_shifted_origin = j - XMin;
        Y_coordinate_shifted_origin = i - YMin;

        col_point = int(X_coordinate_shifted_origin/CellSize);
        row_point = (ysize - 1) - int(round(Y_coordinate_shifted_origin/CellSize));
        # check for data at this cell
        this_raster_value = this_raster[row_point][col_point]
        if not np.isnan(this_raster_value) and this_raster_value != 0:
            data[this_raster_value].append(ksn[x])

    # set up a figure
    fig,ax = plt.subplots(nrows=1,ncols=1, figsize=(5,5), sharex=True, sharey=True)

    labels, dict = [*zip(*data.items())]  # 'transpose' items to parallel key, value lists
    print(label_list)
    if label_list:
        labels = label_list
    print(labels)
    box = plt.boxplot(dict, patch_artist=True)
    plt.xticks(range(1, len(labels) + 1), labels)
    plt.ylabel('$k_{sn}$', fontsize=14)

    # get the medians for plotting as an upper label
    medians = []
    print("========SOME KSN STATISTICS=========")
    for key, value in data.items():
        print("Key {}, median ksn = {}".format(key, np.median(value)))
        medians.append(np.median(value))
        print("Key {}, IQR = {}".format(key, stats.iqr(value)))
    print("========================================")
    pos = np.arange(len(labels)) + 1
    upperLabels = [str(np.round(s, 2)) for s in medians]

    # change the colours for each lithology
    colors=['#60609fff', '#fdbb7fff', '#935353ff', '#f07b72ff']
    for patch, color in zip(box['boxes'], colors):
        patch.set_facecolor(color)
        patch.set_alpha(0.9)
        patch.set_edgecolor('k')
    for cap in box['caps']:
        cap.set(color='k')
    for wh in box['whiskers']:
        wh.set(color='k')
    for med in box['medians']:
        med.set(color='k')
    for flier, color in zip(box['fliers'], colors):
        flier.set_markeredgecolor(color)
        flier.set_markerfacecolor(color)
        flier.set_markersize(2)

    # for tick, label in zip(range(len(labels)), ax.get_xticklabels()):
    #     k = tick % 2
    #     ax.text(pos[tick], top - (top*0.05), upperLabels[tick],
    #              horizontalalignment='center', color=colors[k])

    ax.grid(color='0.8', linestyle='--', which='major', zorder=1)
    plt.title('Boxplots of $k_{sn}$ by lithology', fontsize=14)
    plt.savefig(DataDirectory+fname_prefix+'_boxplot_lith_ksn.png', dpi=300, transparent=True)
    plt.clf()



    # Do some stats, yo
    # KS test to see if we can distinguish the distributions at a confidence level of p = 0.05
    # https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html
    # relief
    keys = list(data.keys())
    values = list(data.values())
    k=0
    for i in range(len(keys)-1):
        for j in range(i+1, len(keys)):
            print("KS test between {} and {}".format(keys[i], keys[j]))
            d, p = stats.ks_2samp(values[i], values[j])
            print(d, p)
            k += 1
Пример #14
0
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'] = ['arial']
    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 plot_outliers_x_vs_diff_ratio(PointData, DataDirectory,x_col = "elevation", saveName = "Outliers", save_fmt = ".png", size_format = "ESURF", log_data = False, ylim_ratio = [], ylim_diff = []):
    """
    Basic plot to have a general view of the knickpoints: flow distance against ratio and diff colored by elevation

    Args:
        PointData: A PointData object
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    # Merging the dictionnary
    if(isinstance(PointData, dict)):
        print("Your data is a dictionnary of dataframes, let me create a PointTool object that contains all of these.")
        PointData = pd.concat(PointData)
        PointData = LSDMap_PD.LSDMap_PointData(PointData,data_type ="pandas", PANDEX = True)


    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['arial']
    rcParams['font.size'] = label_size

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

    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax1 = fig.add_subplot(gs[5:45,10:95])
    ax2 = fig.add_subplot(gs[55:100,10:95])


    diff = PointData.QueryData("diff")
    ratio = PointData.QueryData("ratio")
    Z = PointData.QueryData(x_col)
    PointData.selectValue('diff_outlier',value = True, operator = "==")
    PointData.selectValue('ratio_outlier',value = True, operator = "==")

    diffout = PointData.QueryData("diff")
    ratioout = PointData.QueryData("ratio")
    Z_out = PointData.QueryData(x_col)
    if(log_data):
        print("I am logging the data")

        diff = np.log10(diff)
        ratio = np.log10(ratio)
        if(isinstance(diffout, list) == False):
            diffout = [diffout]
            ratioout = [ ratioout]

        for i in range(len(diffout)):

            diffout[i]= np.log10(diffout[i])

            ratioout[i]= np.log10(ratioout[i])

    sign = PointData.QueryData("sign")

    ax1.scatter(Z,ratio, s=1.5, lw = 0, c = "gray")
    ax1.scatter(Z_out,ratioout, s=1.5, lw = 0, c = sign)
    ax1.set_ylabel("Ratio")
    ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0)
    ax1.spines['bottom'].set_visible(False)
    ax2.scatter(Z,diff,s=1.5, lw = 0, c = "gray")
    ax2.scatter(Z_out,diffout,s=1.5, lw = 0, c = sign)
    ax2.set_ylabel("Diff")
    ax2.set_xlabel(x_col)
    if(ylim_diff != []):
        ax2.set_ylim(ylim_diff[0],ylim_diff[1])
    if ylim_ratio != []:
        ax.set_ylim(ylim_ratio[0],ylim_ratio[1])

    #ax2.tick_params(axis = 'x', labelsize = 6)
    #ax1.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"])

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
def plot_outliers_vs_others(PointData, DataDirectory, saveName = "Basic_diff_ratio", save_fmt = ".png", size_format = "ESURF", log_data = False):
    """
    Basic plot to have a general view of the knickpoints: diff against ratio colored by elevation

    Args:
        PointData: A PointData object or a dictionnary of dataframe containing outliers and none outliers
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    # Merging the dictionnary
    if(isinstance(PointData, dict)):
        print("Your data is a dictionnary of dataframes, let me create a PointTool object that contains all of these.")
        PointData = pd.concat(PointData)
        PointData = LSDMap_PD.LSDMap_PointData(PointData,data_type ="pandas", PANDEX = True)


    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['arial']
    rcParams['font.size'] = label_size

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

    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])


    diff = PointData.QueryData("diff")
    ratio = PointData.QueryData("ratio")

    PointData.selectValue('diff_outlier',value = True, operator = "==")
    PointData.selectValue('ratio_outlier',value = True, operator = "==")

    diffout = PointData.QueryData("diff")
    ratioout = PointData.QueryData("ratio")
    elevation = PointData.QueryData("elevation")
    if(log_data):
        print("I am logging the data")

        diff = np.log10(diff)
        ratio = np.log10(ratio)
        if(isinstance(diffout, list) == False):
            diffout = [diffout]
            ratioout = [ ratioout]

        for i in range(len(diffout)):

            diffout[i]= np.log10(diffout[i])

            ratioout[i]= np.log10(ratioout[i])
    print("Now plotting the outliers vs the non-outliers")
    ax.scatter(diff,ratio, s=0.5, lw = 0, c = 'gray')
    ax.scatter(diffout,ratioout, s = 0.5,c = elevation,lw = 0)
    ax.set_xlabel("Diff")
    ax.set_ylabel("Ratio")

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
    print("Your figure is " +DataDirectory+saveName+save_fmt)
def map_knickpoint_sign(PointData, DataDirectory, Raster_base_name, HS_name = "none",Time_in_name = False, river_network = "none", saveName = "none", size = 2, outliers = 'none'):
    """
    Will create a map of the knickpoint simply colored by sign.

    Args:
        PointData (PointTools object)
        DataDirectory (str): directory where the data will be saved and loaded.
        Raster_base_name (str): Base name of your files without the .bil
        HS_name (str): name of your Hillshade file, by default baseName + _hs.bil like LSDTT create it
        Time_in_name (bool): Option to add timing info in the nae of the figure. Can be useful if you test loads of parameters and you want to be sure that your files names are different (but awful).
    returns:
        No, but creates a map named map_knickpoint_sign.png
    Author:
        BG
    """
    ###### Parameters ######
    if(isinstance(PointData, dict)):
        print("Your data is a dictionnary of dataframes, let me create a PointTool object that contains all of these.")
        PointData = pd.concat(PointData)
        PointData = LSDMap_PD.LSDMap_PointData(PointData,data_type ="pandas", PANDEX = False)
    if(outliers != 'none' ):
        PointData.selectValue(outliers, operator = "==", value = True)
        print PointData

    Directory = DataDirectory # reading directory
    wDirectory = Directory # writing directory
    Base_file = Raster_base_name # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata
    if(saveName == "none"):
        wname = "map_knickpoint_sign" # name of your output file
    else:
        wname = saveName
    dpi = 500 # Quality of your output image, don't exceed 900
    fig_size_inches = 7 # Figure size in Inches
    if(HS_name == "none"):
        HS_name = Raster_base_name+("_hs.bil")
    DrapeRasterName = HS_name # 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

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

    BackgroundRasterName = Base_file + ".bil" # Ignore this line
    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)


    if(isinstance(river_network,LSDP.LSDMap_PointData)):
        MF.add_point_data( river_network, # this function plot the requested point file using the lat/long column in the csv file
                           column_for_plotting = "none",  # 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

    MF.add_point_data( PointData, # this function plot the requested point file using the lat/long column in the csv file
                       column_for_plotting = "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 = size, # 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
                      )
    if(Time_in_name):
        ImageName = wDirectory+str(int(clock.time()))+wname+".png" # Ignore this
    else:
        ImageName = wDirectory+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
Пример #18
0
    def plot_data(self):
        """This is the bit that actually plots the data.
        
        """
        import LSDPlottingTools.LSDMap_PointTools as LSDMap_PD

        if self.plotting_switches["BasicDensityPlot"]:

            # Check to see if there is a filename. If not set a default file name
            if self.plotting_parameters["FigFileName"] == "None":
                self.plotting_parameters[
                    "FigFileName"] = self.FilePath + os.sep + self.FilePrefix + "BDP." + self.plotting_parameters[
                        "FigFormat"]

            print("Hey there partner, I am making a grid plot.")
            LSDMap_BP.BasicDensityPlot(self.base_faster_fname,
                                       self.plotting_parameters["base_cmap"],
                                       self.plotting_parameters["cbar_label"],
                                       self.plotting_parameters["clim_val"],
                                       self.plotting_parameters["FigFileName"],
                                       self.plotting_parameters["FigFormat"],
                                       self.plotting_parameters["size_format"],
                                       self.plotting_parameters["is_log"])

        if self.plotting_switches["BasicDrapedPlotGridPlot"]:
            # Check to see if there is a filename. If not set a default file name
            if self.plotting_parameters["FigFileName"] == "None":
                self.plotting_parameters[
                    "FigFileName"] = self.FilePath + os.sep + self.FilePrefix + "BDPDPG." + self.plotting_parameters[
                        "FigFormat"]

            LSDMap_BP.BasicDrapedPlotGridPlot(
                self.base_faster_fname, self.plotting_parameters["DrapeName"],
                self.plotting_parameters["base_cmap"],
                self.plotting_parameters["drape_cmap"],
                self.plotting_parameters["cbar_label"],
                self.plotting_parameters["clim_val"],
                self.plotting_parameters["drape_alpha"],
                self.plotting_parameters["FigFileName"],
                self.plotting_parameters["FigFormat"])

        if self.plotting_switches["BasinsOverFancyHillshade"]:
            # Check to see if there is a filename. If not set a default file name
            if self.plotting_parameters["FigFileName"] == "None":
                self.plotting_parameters[
                    "FigFileName"] = self.FilePath + os.sep + self.FilePrefix + "Basins." + self.plotting_parameters[
                        "FigFormat"]

            print("Type of base raster is: " +
                  str(type(self.base_faster_fname)))
            print("The chan net csv is: " +
                  str(self.plotting_parameters["chan_net_csv"]))
            print("The drape cmap is: " +
                  self.plotting_parameters["drape_cmap"])

            thisPointData = LSDMap_PD.LSDMap_PointData(self.basin_csv_fname)

            if self.plotting_parameters["chan_net_csv"] == "None":
                chanPointData = "None"
            else:
                chanPointData = LSDMap_PD.LSDMap_PointData(
                    self.plotting_parameters["chan_net_csv"])

            LSDMap_BP.BasinsOverFancyHillshade(
                self.base_faster_fname, self.hs_fname, self.basin_fname,
                self.basin_csv_fname, thisPointData,
                self.plotting_parameters["base_cmap"],
                self.plotting_parameters["drape_cmap"],
                self.plotting_parameters["clim_val"],
                self.plotting_parameters["drape_alpha"],
                self.plotting_parameters["FigFileName"],
                self.plotting_parameters["FigFormat"],
                self.plotting_parameters["elevation_threshold"],
                self.plotting_parameters["grouped_basin_list"],
                self.plotting_parameters["basin_rename_list"],
                self.plotting_parameters["spread"], chanPointData,
                self.plotting_parameters["label_sources"],
                self.plotting_parameters["source_chi_threshold"],
                self.plotting_parameters["size_format"])

        if self.plotting_switches["BasicChiCoordinatePlot"]:
            print("I am plotting a basic chi plot!")

            # Check to see if there is a filename. If not set a default file name
            if self.plotting_parameters["FigFileName"] == "None":
                self.plotting_parameters[
                    "FigFileName"] = self.FilePath + os.sep + self.FilePrefix + "Chi." + self.plotting_parameters[
                        "FigFormat"]

            thisBasinData = LSDMap_PD.LSDMap_PointData(self.basin_csv_fname)
            chi_drape_cname = 'CMRmap_r'
            #chi_drape_cname = 'brg_r'
            cbar_lablel = "$\chi$ (m)"

            LSDMap_CP.BasicChiCoordinatePlot(
                self.hs_fname, self.chi_raster_fname, self.basic_chi_csv_fname,
                self.plotting_parameters["base_cmap"], chi_drape_cname,
                cbar_lablel, self.plotting_parameters["clim_val"],
                self.plotting_parameters["basin_order_list"], thisBasinData,
                self.basin_fname, self.plotting_parameters["drape_alpha"],
                self.plotting_parameters["FigFileName"],
                self.plotting_parameters["FigFormat"],
                self.plotting_parameters["size_format"])

        if self.plotting_switches["ChiProfiles"]:
            print("I am plotting a basic chi profile plot!")

            # Check to see if there is a filename. If not set a default file name
            if self.plotting_parameters["FigFileName"] == "None":
                self.plotting_parameters[
                    "FigFileName"] = self.FilePath + os.sep + self.FilePrefix + "ChiProfile." + self.plotting_parameters[
                        "FigFormat"]

            thisBasinData = LSDMap_PD.LSDMap_PointData(self.basin_csv_fname)
            chi_drape_cname = 'CMRmap_r'
            #chi_drape_cname = 'brg_r'
            cbar_lablel = "$\chi$ (m)"

            print("The csv filename is: " + self.chi_csv_fname)

            LSDMap_CP.ChiProfiles(
                self.chi_csv_fname, self.plotting_parameters["FigFileName"],
                self.plotting_parameters["FigFormat"],
                self.plotting_parameters["basin_order_list"],
                self.plotting_parameters["basin_rename_list"],
                self.plotting_parameters["label_sources"],
                self.plotting_parameters["elevation_threshold"],
                self.plotting_parameters["source_thinning_threshold"],
                self.plotting_parameters["plot_M_chi"],
                self.plotting_parameters["plot_segments"],
                self.plotting_parameters["size_format"])
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)

    #thisPointData.ThinDataSelection("basin_key",[10])

    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)
BackgroundRasterName = Base_file + ".bil"
DrapeRasterName = Base_file + "_hs.bil"
ChiRasterName = Base_file + "_chi_coord.bil"

#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)
Пример #21
0
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