コード例 #1
0
ファイル: bench_intensity.py プロジェクト: yzuaiyou/momepy
    def setup(self):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path,
                                             layer="tessellation")
        self.df_streets["nID"] = mm.unique_id(self.df_streets)
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_tessellation["area"] = self.df_tessellation.geometry.area
        self.df_buildings["area"] = self.df_buildings.geometry.area
        self.df_buildings["fl_area"] = mm.FloorArea(self.df_buildings,
                                                    "height").series
        self.df_buildings["nID"] = mm.get_network_id(self.df_buildings,
                                                     self.df_streets, "nID")
        blocks = mm.Blocks(self.df_tessellation, self.df_streets,
                           self.df_buildings, "bID", "uID")
        self.blocks = blocks.blocks
        self.df_buildings["bID"] = blocks.buildings_id
        self.df_tessellation["bID"] = blocks.tessellation_id
        self.swb = Queen.from_dataframe(self.df_buildings)
        self.sw5 = mm.sw_high(k=5, gdf=self.df_tessellation, ids="uID")
        self.sw3 = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        self.sws = mm.sw_high(k=2, gdf=self.df_streets)
        nx = mm.gdf_to_nx(self.df_streets)
        nx = mm.node_degree(nx)
        self.nodes, self.edges, W = mm.nx_to_gdf(nx, spatial_weights=True)
        self.swn = mm.sw_high(k=3, weights=W)
コード例 #2
0
    def test_Density(self):
        sw = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        dens = mm.Density(
            self.df_tessellation,
            self.df_buildings["fl_area"],
            sw,
            "uID",
            self.df_tessellation.area,
        ).series
        dens2 = mm.Density(
            self.df_tessellation, self.df_buildings["fl_area"], sw, "uID"
        ).series
        check = 1.661587
        assert dens.mean() == approx(check)
        assert dens2.mean() == approx(check)
        sw_drop = mm.sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
        assert (
            mm.Density(
                self.df_tessellation, self.df_buildings["fl_area"], sw_drop, "uID"
            )
            .series.isna()
            .any()
        )

        # island
        sw.neighbors[1] = []
        dens3 = mm.Density(
            self.df_tessellation,
            self.df_buildings["fl_area"],
            sw,
            "uID",
            self.df_tessellation.area,
        ).series
        assert dens3.mean() == approx(1.656420)
コード例 #3
0
 def test_CoveredArea(self):
     sw = sw_high(gdf=self.df_tessellation, k=1, ids="uID")
     covered_sw = mm.CoveredArea(self.df_tessellation, sw, "uID").series
     assert covered_sw[0] == approx(24115.667, rel=1e-3)
     sw_drop = sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
     assert mm.CoveredArea(self.df_tessellation, sw_drop,
                           "uID").series.isna().any()
コード例 #4
0
ファイル: test_diversity.py プロジェクト: yzuaiyou/momepy
    def setup_method(self):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path,
                                             layer="tessellation")
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_tessellation["area"] = mm.Area(self.df_tessellation).series
        self.sw = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        self.sw.neighbors[100] = []
        self.sw_drop = sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
コード例 #5
0
ファイル: bench_diversity.py プロジェクト: yzuaiyou/momepy
    def setup(self, *args):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path, layer="tessellation")
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_tessellation["area"] = mm.Area(self.df_tessellation).series
        self.sw = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
コード例 #6
0
 def test_MeanInterbuildingDistance(self):
     sw = Queen.from_dataframe(self.df_tessellation, ids="uID")
     swh = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
     self.df_buildings["m_dist_sw"] = mm.MeanInterbuildingDistance(
         self.df_buildings, sw, "uID", swh).series
     self.df_buildings["m_dist"] = mm.MeanInterbuildingDistance(
         self.df_buildings, sw, "uID", order=3).series
     check = 29.305457092042744
     assert self.df_buildings["m_dist_sw"][0] == check
     assert self.df_buildings["m_dist"][0] == check
コード例 #7
0
ファイル: test_intensity.py プロジェクト: jessicajrc/momepy
 def test_Reached(self):
     count = mm.Reached(self.df_streets, self.df_buildings, "nID",
                        "nID").series
     area = mm.Reached(
         self.df_streets,
         self.df_buildings,
         self.df_streets.nID,
         self.df_buildings.nID,
         mode="sum",
     ).series
     mean = mm.Reached(self.df_streets,
                       self.df_buildings,
                       "nID",
                       "nID",
                       mode="mean").series
     std = mm.Reached(self.df_streets,
                      self.df_buildings,
                      "nID",
                      "nID",
                      mode="std").series
     area_v = mm.Reached(
         self.df_streets,
         self.df_buildings,
         "nID",
         "nID",
         mode="sum",
         values="fl_area",
     ).series
     mean_v = mm.Reached(
         self.df_streets,
         self.df_buildings,
         "nID",
         "nID",
         mode="mean",
         values="fl_area",
     ).series
     std_v = mm.Reached(
         self.df_streets,
         self.df_buildings,
         "nID",
         "nID",
         mode="std",
         values="fl_area",
     ).series
     sw = mm.sw_high(k=2, gdf=self.df_streets)
     count_sw = mm.Reached(self.df_streets, self.df_buildings, "nID", "nID",
                           sw).series
     assert max(count) == 18
     assert max(area) == 18085.45897711331
     assert max(count_sw) == 138
     assert max(mean) == 1808.5458977113315
     assert max(std) == 3153.7019229524785
     assert max(area_v) == 79169.31385861784
     assert max(mean_v) == 7916.931385861784
     assert max(std_v) == 8995.18003493457
コード例 #8
0
 def test_BuildingAdjacencyy(self):
     sw = Queen.from_dataframe(self.df_buildings, ids="uID")
     swh = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
     self.df_buildings["adj_sw"] = mm.BuildingAdjacency(
         self.df_buildings,
         spatial_weights=sw,
         unique_id="uID",
         spatial_weights_higher=swh,
     ).series
     self.df_buildings["adj_sw_none"] = mm.BuildingAdjacency(
         self.df_buildings, unique_id="uID",
         spatial_weights_higher=swh).series
     check = 0.2613824113909074
     assert self.df_buildings["adj_sw"].mean() == check
     assert self.df_buildings["adj_sw_none"].mean() == check
     swh_drop = mm.sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
     assert (mm.BuildingAdjacency(
         self.df_buildings,
         unique_id="uID",
         spatial_weights_higher=swh_drop).series.isna().any())
コード例 #9
0
ファイル: distribution.py プロジェクト: tristan-salles/momepy
    def __init__(
        self,
        gdf,
        spatial_weights,
        unique_id,
        spatial_weights_higher=None,
        order=3,
        verbose=True,
    ):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]

        if spatial_weights_higher is None:
            print(
                f"Generating weights matrix (Queen) of {order} topological steps..."
            ) if verbose else None
            self.order = order
            from momepy import sw_high

            # matrix to define area of analysis (more steps)
            spatial_weights_higher = sw_high(k=order, weights=spatial_weights)
        self.sw_higher = spatial_weights_higher

        data = gdf.set_index(unique_id).geometry

        # define empty list for results
        results_list = []

        # define adjacency list from lipysal
        adj_list = spatial_weights.to_adjlist()
        adj_list["distance"] = (
            data.loc[adj_list.focal]
            .reset_index()
            .distance(data.loc[adj_list.neighbor].reset_index())
        )

        print("Computing mean interbuilding distances...")
        # iterate over objects to get the final values
        for uid in tqdm(data.index, total=data.shape[0], disable=not verbose):
            # define neighbours based on weights matrix defining analysis area
            if uid in spatial_weights_higher.neighbors.keys():
                neighbours = spatial_weights_higher.neighbors[uid].copy()
                neighbours.append(uid)
                if neighbours:
                    selection = adj_list[adj_list.focal.isin(neighbours)][
                        adj_list.neighbor.isin(neighbours)
                    ]
                    results_list.append(np.nanmean(selection.distance))
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)
コード例 #10
0
    def test_WeightedCharacter(self):
        sw = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        weighted = mm.WeightedCharacter(self.df_buildings, "height", sw,
                                        "uID").series
        assert weighted[38] == approx(18.301, rel=1e-3)

        self.df_buildings["area"] = self.df_buildings.geometry.area
        sw = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        weighted = mm.WeightedCharacter(self.df_buildings, "height", sw, "uID",
                                        "area").series
        assert weighted[38] == approx(18.301, rel=1e-3)

        area = self.df_buildings.geometry.area
        sw = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        weighted = mm.WeightedCharacter(self.df_buildings,
                                        self.df_buildings.height, sw, "uID",
                                        area).series
        assert weighted[38] == approx(18.301, rel=1e-3)

        sw_drop = sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
        assert (mm.WeightedCharacter(self.df_buildings, "height", sw_drop,
                                     "uID").series.isna().any())
コード例 #11
0
 def test_NodeDensity(self):
     nx = mm.gdf_to_nx(self.df_streets)
     nx = mm.node_degree(nx)
     nodes, edges, W = mm.nx_to_gdf(nx, spatial_weights=True)
     sw = mm.sw_high(k=3, weights=W)
     density = mm.NodeDensity(nodes, edges, sw).series
     weighted = mm.NodeDensity(
         nodes, edges, sw, weighted=True, node_degree="degree"
     ).series
     array = mm.NodeDensity(nodes, edges, W).series
     assert density.mean() == 0.012690163074599968
     assert weighted.mean() == 0.023207675994368446
     assert array.mean() == 0.008554067995928158
コード例 #12
0
ファイル: test_intensity.py プロジェクト: jessicajrc/momepy
 def test_Density(self):
     sw = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
     dens = mm.Density(
         self.df_tessellation,
         self.df_buildings["fl_area"],
         sw,
         "uID",
         self.df_tessellation.area,
     ).series
     dens2 = mm.Density(self.df_tessellation, self.df_buildings["fl_area"],
                        sw, "uID").series
     check = 1.661587
     assert dens.mean() == approx(check)
     assert dens2.mean() == approx(check)
コード例 #13
0
 def test_BlocksCount(self):
     sw = mm.sw_high(k=5, gdf=self.df_tessellation, ids="uID")
     count = mm.BlocksCount(self.df_tessellation, "bID", sw, "uID").series
     count2 = mm.BlocksCount(
         self.df_tessellation, self.df_tessellation.bID, sw, "uID"
     ).series
     unweigthed = mm.BlocksCount(
         self.df_tessellation, "bID", sw, "uID", weighted=False
     ).series
     check = 3.142437439120778e-05
     check2 = 5.222222222222222
     assert count.mean() == check
     assert count2.mean() == check
     assert unweigthed.mean() == check2
     with pytest.raises(ValueError):
         count = mm.BlocksCount(
             self.df_tessellation, "bID", sw, "uID", weighted="yes"
         )
     sw_drop = mm.sw_high(k=5, gdf=self.df_tessellation[2:], ids="uID")
     assert (
         mm.BlocksCount(self.df_tessellation, "bID", sw_drop, "uID")
         .series.isna()
         .any()
     )
コード例 #14
0
    def setup(self):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path, layer="tessellation")
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_buildings["volume"] = mm.Volume(self.df_buildings, "height").series
        self.df_streets["nID"] = mm.unique_id(self.df_streets)
        self.df_buildings["nID"] = mm.get_network_id(
            self.df_buildings, self.df_streets, "nID"
        )
        self.df_buildings["orient"] = mm.Orientation(self.df_buildings).series
        self.df_tessellation["orient"] = mm.Orientation(self.df_tessellation).series
        self.sw = Queen.from_dataframe(self.df_tessellation, ids="uID")
        self.swh = mm.sw_high(k=3, gdf=self.df_tessellation, ids="uID")
        self.swb = Queen.from_dataframe(self.df_buildings, ids="uID")
コード例 #15
0
    def test_sw_high(self):
        first_order = libpysal.weights.Queen.from_dataframe(
            self.df_tessellation)
        from_sw = mm.sw_high(2, gdf=None, weights=first_order)
        from_df = mm.sw_high(2, gdf=self.df_tessellation)
        rook = mm.sw_high(2, gdf=self.df_tessellation, contiguity="rook")
        check = sorted([133, 134, 111, 112, 113, 114, 115, 121, 125])
        assert sorted(from_sw.neighbors[0]) == check
        assert sorted(from_df.neighbors[0]) == check
        assert sorted(rook.neighbors[0]) == check

        with pytest.raises(AttributeError):
            mm.sw_high(2, gdf=None, weights=None)

        with pytest.raises(ValueError):
            mm.sw_high(2, gdf=self.df_tessellation, contiguity="nonexistent")
コード例 #16
0
 def test_AverageCharacter(self):
     spatial_weights = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
     self.df_tessellation[
         "area"] = area = self.df_tessellation.geometry.area
     self.df_tessellation["mesh_ar"] = mm.AverageCharacter(
         self.df_tessellation,
         values="area",
         spatial_weights=spatial_weights,
         unique_id="uID",
         mode="mode",
     ).mode
     self.df_tessellation["mesh_array"] = mm.AverageCharacter(
         self.df_tessellation,
         values=area,
         spatial_weights=spatial_weights,
         unique_id="uID",
         mode="median",
     ).median
     self.df_tessellation["mesh_id"] = mm.AverageCharacter(
         self.df_tessellation,
         spatial_weights=spatial_weights,
         values="area",
         rng=(10, 90),
         unique_id="uID",
     ).mean
     self.df_tessellation["mesh_iq"] = mm.AverageCharacter(
         self.df_tessellation,
         spatial_weights=spatial_weights,
         values="area",
         rng=(25, 75),
         unique_id="uID",
     ).series
     all_m = mm.AverageCharacter(
         self.df_tessellation,
         spatial_weights=spatial_weights,
         values="area",
         unique_id="uID",
     )
     two = mm.AverageCharacter(
         self.df_tessellation,
         spatial_weights=spatial_weights,
         values="area",
         unique_id="uID",
         mode=["mean", "median"],
     )
     with pytest.raises(ValueError):
         self.df_tessellation["mesh_ar"] = mm.AverageCharacter(
             self.df_tessellation,
             values="area",
             spatial_weights=spatial_weights,
             unique_id="uID",
             mode="nonexistent",
         )
     with pytest.raises(ValueError):
         self.df_tessellation["mesh_ar"] = mm.AverageCharacter(
             self.df_tessellation,
             values="area",
             spatial_weights=spatial_weights,
             unique_id="uID",
             mode=["nonexistent", "mean"],
         )
     assert self.df_tessellation["mesh_ar"][0] == approx(249.503, rel=1e-3)
     assert self.df_tessellation["mesh_array"][0] == approx(2623.996,
                                                            rel=1e-3)
     assert self.df_tessellation["mesh_id"][38] == approx(2250.224,
                                                          rel=1e-3)
     assert self.df_tessellation["mesh_iq"][38] == approx(2118.609,
                                                          rel=1e-3)
     assert all_m.mean[0] == approx(2922.957, rel=1e-3)
     assert all_m.median[0] == approx(2623.996, rel=1e-3)
     assert all_m.mode[0] == approx(249.503, rel=1e-3)
     assert all_m.series[0] == approx(2922.957, rel=1e-3)
     assert two.mean[0] == approx(2922.957, rel=1e-3)
     assert two.median[0] == approx(2623.996, rel=1e-3)
     sw_drop = sw_high(k=3, gdf=self.df_tessellation[2:], ids="uID")
     assert (mm.AverageCharacter(
         self.df_tessellation,
         values="area",
         spatial_weights=sw_drop,
         unique_id="uID",
     ).series.isna().any())
コード例 #17
0
 def time_sw_high(self):
     mm.sw_high(5, gdf=None, weights=self.first_order)
コード例 #18
0
    def __init__(self,
                 gdf,
                 spatial_weights,
                 unique_id,
                 spatial_weights_higher=None,
                 order=3):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]

        if spatial_weights_higher is None:
            print(
                "Generating weights matrix (Queen) of {} topological steps...".
                format(order))
            self.order = order
            from momepy import sw_high

            # matrix to define area of analysis (more steps)
            spatial_weights_higher = sw_high(k=order, weights=spatial_weights)
        self.sw_higher = spatial_weights_higher

        data = gdf.set_index(unique_id).geometry

        # define empty list for results
        results_list = []

        print("Generating adjacency matrix based on weights matrix...")
        # define adjacency list from lipysal
        adj_list = spatial_weights.to_adjlist()
        adj_list["distance"] = -1

        print("Computing interbuilding distances...")
        # measure each interbuilding distance of neighbours and save them to adjacency list
        for row in tqdm(adj_list.itertuples(), total=adj_list.shape[0]):
            inverted = adj_list[(adj_list.focal == row.neighbor)][(
                adj_list.neighbor == row.focal)].iloc[0]["distance"]
            if inverted == -1:
                building_object = data.loc[row.focal]

                building_neighbour = data.loc[row.neighbor]
                adj_list.loc[row.Index,
                             "distance"] = building_neighbour.distance(
                                 building_object)
            else:
                adj_list.at[row.Index, "distance"] = inverted

        print("Computing mean interbuilding distances...")
        # iterate over objects to get the final values
        for uid in tqdm(data.index, total=data.shape[0]):
            # define neighbours based on weights matrix defining analysis area
            if uid in spatial_weights_higher.neighbors.keys():
                neighbours = spatial_weights_higher.neighbors[uid].copy()
                neighbours.append(uid)
                if neighbours:
                    selection = adj_list[adj_list.focal.isin(neighbours)][
                        adj_list.neighbor.isin(neighbours)]
                    results_list.append(np.nanmean(selection.distance))
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)
コード例 #19
0
ファイル: test_dimension.py プロジェクト: AtelierLibre/momepy
 def test_PerimeterWall(self):
     sw = sw_high(gdf=self.df_buildings, k=1)
     wall = mm.PerimeterWall(self.df_buildings).series
     wall_sw = mm.PerimeterWall(self.df_buildings, sw).series
     assert wall[0] == wall_sw[0]
     assert wall[0] == approx(137.210, rel=1e-3)
コード例 #20
0
#
# nodes, edges, sw = mm.nx_to_gdf(graph, spatial_weights=True)
#
# fo = libpysal.io.open("/Users/martin/Dropbox/Academia/Data/Geo/Prague/Redo/nodes.gal", "w")
# fo.write(sw)
# fo.close()
#
# nodes.to_file("/Users/martin/Dropbox/Academia/Data/Geo/Prague/Redo/elements.gpkg", layer="nodes", driver="GPKG")
# edges.to_file("/Users/martin/Dropbox/Academia/Data/Geo/Prague/Redo/elements.gpkg", layer="edges", driver="GPKG")
nodes = gpd.read_file(
    "/Users/martin/Dropbox/Academia/Data/Geo/Prague/Redo/elements.gpkg", layer="nodes"
)
edges = gpd.read_file(
    "/Users/martin/Dropbox/Academia/Data/Geo/Prague/Redo/elements.gpkg", layer="edges"
)
edges_w3 = mm.sw_high(k=3, gdf=edges)
edges["ldsMSL"] = mm.segments_length(edges, spatial_weights=edges_w3, mean=True)

edges["ldsRea"] = mm.reached(edges, tess, "nID", "nID", spatial_weights=edges_w3)
edges["ldsRea"] = mm.reached(
    edges, tess, "nID", "nID", spatial_weights=edges_w3, mode="sum", values="sdcAre"
)
# error below
# Traceback (most recent call last):
#   File "03_fix_streets.py", line 99, in <module>
#     nodes_w5 = mm.sw_high(k=5, weights=sw)
#   File "/home/ubuntu/momepy/utils.py", line 94, in sw_high
#     first_order, k=i, silence_warnings=silent
#   File "/home/ubuntu/miniconda3/envs/mmp/lib/python3.7/site-packages/libpysal/weights/util.py", line 427, in higher_order
#     return higher_order_sp(w, k, **kwargs)
#   File "/home/ubuntu/miniconda3/envs/mmp/lib/python3.7/site-packages/libpysal/weights/util.py", line 486, in higher_order_sp
コード例 #21
0
 def test_PerimeterWall(self):
     sw = sw_high(gdf=self.df_buildings, k=1)
     wall = mm.PerimeterWall(self.df_buildings).series
     wall_sw = mm.PerimeterWall(self.df_buildings, sw).series
     assert wall[0] == wall_sw[0]
     assert wall[0] == 137.2106961418436
コード例 #22
0
import momepy as mm
import geopandas as gpd
import libpysal

tess = gpd.read_file('files/elements.gpkg', layer='tessellation')
blg = gpd.read_file('files/elements.gpkg', layer='buildings')
blocks = gpd.read_file('files/elements.gpkg', layer='blocks')
streets = gpd.read_file('files/elements.gpkg', layer='streets')

queen1 = mm.sw_high(k=1, gdf=tess, ids='uID')
queen3 = mm.sw_high(k=3, weights=queen1)
blg_queen = mm.sw_high(k=1, gdf=blg, ids='uID')

blg['ltbIBD'] = mm.MeanInterbuildingDistance(blg, queen1, 'uID', queen3).series
blg['ltcBuA'] = mm.BuildingAdjacency(blg, queen3, 'uID', blg_queen).series

# blg['temp_fa'] = mm.floor_area(blg, 'sdbHei', 'sdbAre')
# tess = tess.merge(blg[['temp_fa', 'uID']], on='uID', how='left')
# tess['licGDe'] = mm.density(tess, 'temp_fa', queen3, 'uID', 'sdcAre')
tess['ltcWRB'] = mm.BlocksCount(tess, 'bID', queen3, 'uID').series

tess.to_file('files/elements.gpkg', layer='tessellation', driver='GPKG')
blg.to_file('files/elements.gpkg', layer='buildings', driver='GPKG')

fo = libpysal.io.open('files/GRqueen1.gal', 'w')
fo.write(queen1)
fo.close()

fo = libpysal.io.open('files/GRqueen3.gal', 'w')
fo.write(queen3)
fo.close()