Beispiel #1
0
    def radial_distribution_intra_clusters(self):
        """Plots spatial distribution of rain pairs which belong to same rain cluster.
        A rain pair exists when two random points have precipitation."""
        print("\tRain pair distribution intra clusters")

        M, clustered_rain_grid = self.hoshen_kopelman()

        rain_pair_dists = []
        for key in M:
            cluster_rain_points = []
            for i in range(len(clustered_rain_grid)):
                for j in range(len(clustered_rain_grid[i])):
                    if clustered_rain_grid[i][j] == key:
                        latlon = self.index_to_coords(ij=[i,j])
                        cluster_rain_points.append(latlon)

            for latlon0 in cluster_rain_points:
                for latlon1 in cluster_rain_points:
                    if latlon0 != latlon1:
                        dist = distance.distance(latlon0, latlon1).km
                        rain_pair_dists.append(dist)

        spatial_distribution = np.histogram(rain_pair_dists, bins=20)
        # Note: We have counted every rain pair twice, so now we'll halve
        # the frequency of distances in each bin
        spatial_distribution_ = [freq/2 for freq in spatial_distribution[0]]
        bins_mean_distance = helper_functions.get_histogram_bins_centers(spatial_distribution[1])

        plt.plot(bins_mean_distance, spatial_distribution_, 'ko', markerfacecolor='grey')
        plt.ylabel('Rain pair frequency')
        plt.xlabel('Distance between pair (km)')
        plot_name = 'data_results/rain/{}/'.format(self.date) + self.file_name + '-rain-pair-distribution-intra-clusters' + '.png'
        plt.savefig(plot_name)
        plt.close()
Beispiel #2
0
    def rain_clusters_radial_distribution(self):
        """Plots radial distribution function of rain clusters."""
        print("\tRain clusters pair distribution")

        clusters = self.get_rain_clusters_coords()

        rain_clusters_pair_dists = []
        for latlon0 in clusters['Lat_Lon_CM']:
            for latlon1 in clusters['Lat_Lon_CM']:
                if latlon0 != latlon1:
                    dist = distance.distance(latlon0, latlon1).km
                    rain_clusters_pair_dists.append(dist)

        csv_name = 'data_results/rain/{}/'.format(self.date) + self.file_name + '-rain-clusters-pair-distances' + '.csv'
        with open(csv_name, 'w', newline='') as outfile:
            writer = csv.writer(outfile, delimiter=',')
            writer.writerows(map(lambda row: [row], rain_clusters_pair_dists))

        spatial_distribution = np.histogram(rain_clusters_pair_dists, bins=20)
        # Note: We have counted every cluster pair twice, so now we'll halve
        # the frequency of distances in each bin
        spatial_distribution_ = [freq/2 for freq in spatial_distribution[0]]
        bins_mean_distance = helper_functions.get_histogram_bins_centers(spatial_distribution[1])

        plt.loglog(bins_mean_distance, spatial_distribution_, 'ko', markerfacecolor='grey')
        plt.ylabel('Rain clusters pair frequency')
        plt.xlabel('Distance between pair (km)')
        plot_name = 'data_results/rain/{}/'.format(self.date) + self.file_name + '-rain-clusters-pair-distribution-loglog' + '.png'
        plt.savefig(plot_name)
        plt.close()
Beispiel #3
0
    def rain_radial_distribution(self):
        """Plots radial distribution function of rain nodes. Radial distribution
        function gives fraction of pair of nodes with precipitation over total
        pair of nodes at given distance."""
        print("\tRadial distribution function")

        print("\t\tComputing nodes coordinates and label")
        nodes = [] # array with nodes latitude and longitude coordinates
        nodes_l = [] # array with node labels: 1 if node has precipitation, 0 if not
        for i in range(len(self.rain_grid)):
            for j in range(len(self.rain_grid[i])):
                if self.rain_grid[i][j] != 0:
                    nodes_l.append(1)
                else:
                    nodes_l.append(0)
                latlon = self.index_to_coords(ij=[i,j])
                nodes.append(latlon)

        print("\t\tComputing distance between node pairs")

        rain_pair_dists = [] # distance between all pair of nodes with rain
        all_pair_dists = [] # distance between all pair of nodes
        for latlon0 in nodes:
            for latlon1 in nodes:
                if latlon0 != latlon1:
                    dist = distance.distance(latlon0, latlon1).km
                    if nodes_l[nodes.index(latlon0)] == 1 and nodes_l[nodes.index(latlon1)] == 1: # rain in both nodes
                        rain_pair_dists.append(dist)
                    all_pair_dists.append(dist)

        all_spatial_distribution = np.histogram(all_pair_dists, bins=20) # spatial distribution of all pair of nodes
        rain_spatial_distribution = np.histogram(rain_pair_dists, bins=all_spatial_distribution[1]) # spatial distribution of pair of nodes with rain
        bins_mean_distance = helper_functions.get_histogram_bins_centers(all_spatial_distribution[1])

        radial_distribution_function = []
        for i in range(len(all_spatial_distribution[0])):
            if all_spatial_distribution[0][i] != 0:
                radial_distribution_function.append(
                    rain_spatial_distribution[0][i]/all_spatial_distribution[0][i]
                    )
            else:
                radial_distribution_function.append(0)

        plt.plot(bins_mean_distance, radial_distribution_function, 'ko', markerfacecolor='grey')
        plt.ylabel('Radial Distribution Function')
        plt.xlabel('Distance (km)')
        plot_name = 'data_results/rain/{}/'.format(self.date) + self.file_name + '-radial-distribution-function' + '.png'
        plt.savefig(plot_name)
        plt.close()
Beispiel #4
0
def plot_avalanche_radial_distribution():
    """Plots avalanche radial distribution using real distance between two
    closest reaches"""
    print("Avalanche radial distribution")

    import helper_functions

    reaches = helper_functions.get_reach_coords()

    with open('data_results/avalanches/histogram/timestep-{}.csv'.format(2),
              'r') as infile:
        readlines = infile.readlines()
        avalanches = []
        for line in readlines:
            temp = line.rstrip().split(',')
            avalanches.append([int(x) for x in temp])

    distribution = []

    for avalanche1 in avalanches:
        for avalanche2 in avalanches:
            if avalanche1 != avalanche2:
                distance_between_avalanches = 10**8
                for reach1 in avalanche1:
                    for reach2 in avalanche2:
                        distance_between_avalanches = min(
                            distance_between_avalanches,
                            distance.distance(reaches.loc[reach1, 'Lat_Lon'],
                                              reaches.loc[reach2,
                                                          'Lat_Lon']).km)
                distribution.append(distance_between_avalanches)

    spatial_distribution = np.histogram(distribution, bins=20)
    # Note: We have counted every avalanche pair twice, so now we'll halve
    # the frequency of distances in each bin
    spatial_distribution_ = [freq / 2 for freq in spatial_distribution[0]]
    bins_mean_distance = helper_functions.get_histogram_bins_centers(
        spatial_distribution[1])

    plt.plot(bins_mean_distance,
             spatial_distribution_,
             'ko',
             markerfacecolor='grey')
    plt.ylabel('Avalanche radial distribution')
    plt.xlabel('Distance (km)')
    plot_name = 'data_results/avalanches/avalanche-radial-distribution-timestep-2.png'
    plt.savefig(plot_name)
    plt.close()
Beispiel #5
0
    def rain_radial_distribution_over_river_path(self):
        """Plots rain pair distribution over river path.
        Given a rain pair that belongs to the same river path, computes the
        distance between pair over path trajectory."""
        print("\tRain pair distribution over river path")

        rain_pair_dists = []
        for reach_id0 in self.rain.index:
            if self.rain.at[reach_id0, 'rain'] != 0:
                for reach_id1 in self.rain.index:
                    if ( self.rain.at[reach_id1,'rain'] != 0 ) and ( reach_id0 != reach_id1 ):
                        # go down starting at reach_id0 until finding reach_id1
                        # or reaching end of river network
                        next_down = self.rain.at[reach_id0,'Next_down']
                        path_lenght = self.rain.at[reach_id0,'Length_km']
                        while ( next_down != reach_id1 ) and ( next_down != 0 ): # next_down=0 means we reached end of river network
                            path_lenght += self.rain.at[next_down,'Length_km']
                            next_down = self.rain.at[next_down,'Next_down']

                        if next_down != reach_id1:
                            # go down starting at reach_id1 until finding reach_id0
                            # or reaching end of river network
                            next_down = self.rain.at[reach_id1,'Next_down']
                            path_lenght = self.rain.at[reach_id1,'Length_km']
                            while ( next_down != reach_id0 ) and ( next_down != 0 ):
                                path_lenght += self.rain.at[next_down,'Length_km']
                                next_down = self.rain.at[next_down,'Next_down']

                        # if reach_id0 and reach_id1 belong to same path
                        # i.e. algorithm found other reach starting from the one
                        if ( next_down == reach_id0 ) or ( next_down == reach_id1 ):
                            rain_pair_dists.append(path_lenght)

        spatial_distribution = np.histogram(rain_pair_dists, bins=20)
        # Note: We have counted every rain pair twice, so now we'll halve
        # the frequency of distances in each bin
        spatial_distribution_ = [freq/2 for freq in spatial_distribution[0]]
        bins_mean_distance = helper_functions.get_histogram_bins_centers(spatial_distribution[1])

        plt.plot(bins_mean_distance, spatial_distribution_, 'ko', markerfacecolor='grey')
        plt.ylabel('Rain pair frequency')
        plt.xlabel('Travelled Distance between pair (km)')
        plot_name = 'data_results/rain/{}/'.format(self.date) + self.file_name + '-rain-pair-over-river-path' + '.png'
        plt.savefig(plot_name)
        plt.close()
Beispiel #6
0
def plot_avalanche_under_rain_cluster_distribution():
    """For all rain clusters, computes the distance of cluster center of mass to
    last (most down) reach that is part of an avalanche that starts in a reach
    under that rain cluster. Plots histogram of this distances."""
    print("Avalanche under rain cluster distribution")

    from geopy import distance
    import rain
    import helper_functions

    with open('data_results/avalanches/histogram/timestep-{}.csv'.format(2),
              'r') as infile:
        readlines = infile.readlines()
        avalanches = []
        for line in readlines:
            temp = line.rstrip().split(',')
            avalanches.append([int(x) for x in temp])

    def get_avalanche_last_reach(avalanche_idx):
        avalanche = avalanches[avalanche_idx]
        for reachID in avalanche:
            if padma.loc[reachID, 'Next_down'] not in avalanche:
                avalanche_last_reach = reachID
                break
        return avalanche_last_reach

    rain_grid = rain.RainGrid(filename='3B-HHR.MS.MRG.3IMERG.'
                              '20130616-S010000-E012959.0060.V06B.HDF5',
                              date='2013-06-16')

    reach_coords = helper_functions.get_reach_coords()
    M, clustered_rain_grid = rain_grid.hoshen_kopelman()
    M = rain_grid.get_rain_clusters_coords()

    # distribution will store all found distances between avalanches and rain clusters
    distribution = []

    # for all rain clusters find avalanches that start under cluster
    # compute distance of cluster most precipitous point to last avalanche reach
    for cluster_key in M.index:
        # for all points in rain grid
        for i in range(len(clustered_rain_grid)):
            for j in range(len(clustered_rain_grid[i])):
                # if rain point in cluster
                if clustered_rain_grid[i][j] == cluster_key:
                    # get reaches under this rain point
                    reaches_under = reach_coords.index[
                        reach_coords['Grid_coords'] == (i, j)].tolist()

                    # find if these reaches are part of any avalanche
                    for reach_id in reaches_under:
                        for avalanche in avalanches:
                            # check which is the last reach in avalanche
                            avalanche_last_reach = get_avalanche_last_reach(
                                avalanche_idx=avalanches.index(avalanche))
                            if avalanche_last_reach == reach_id:
                                distribution.append(
                                    distance.distance(
                                        M.loc[cluster_key, 'Lat_Lon_CM'],
                                        reach_coords.loc[avalanche_last_reach,
                                                         'Lat_Lon']).km)

    # plot distribution of this distances
    spatial_distribution = np.histogram(distribution, bins=20)
    bins_mean_distance = helper_functions.get_histogram_bins_centers(
        spatial_distribution[1])

    plt.plot(bins_mean_distance,
             spatial_distribution[0],
             'ko',
             markerfacecolor='grey')
    plt.ylabel('Rain Cluster to Avalanche Distribution')
    plt.xlabel('Distance (km)')
    # plot_name = 'data_results/avalanches/2013-06-16/' + rain_grid.file_name + '-avalanche-under-rain' + '.png'
    plot_name = 'data_results/avalanches/' + rain_grid.file_name + '-avalanche-under-rain' + '.png'
    plt.savefig(plot_name)
    plt.close()