How to use the libpysal.weights.Queen function in libpysal

To help you get started, we’ve selected a few libpysal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github martinfleis / momepy / tests / test_elements.py View on Github external
def test_Tessellation(self):
        tes = mm.Tessellation(self.df_buildings, "uID", self.limit, segment=2)
        tessellation = tes.tessellation
        assert len(tessellation) == len(self.df_tessellation)
        bands = mm.Tessellation(
            self.df_streets, "nID", mm.buffered_limit(self.df_streets, 50), segment=5
        ).tessellation
        assert len(bands) == len(self.df_streets)
        queen_corners = tes.queen_corners(2)
        w = libpysal.weights.Queen.from_dataframe(queen_corners)
        assert w.neighbors[14] == [35, 36, 13, 15, 26, 27, 28, 30, 31]
github martinfleis / momepy / tests / test_distribution.py View on Github external
def test_Alignment(self):
        self.df_buildings["orient"] = mm.Orientation(self.df_buildings).series
        sw = Queen.from_dataframe(self.df_tessellation, ids="uID")
        self.df_buildings["align_sw"] = mm.Alignment(
            self.df_buildings, sw, "uID", self.df_buildings["orient"]
        ).series
        assert self.df_buildings["align_sw"][0] == pytest.approx(18.299481296)
        sw_drop = Queen.from_dataframe(self.df_tessellation[2:], ids="uID")
        assert (
            mm.Alignment(self.df_buildings, sw_drop, "uID", self.df_buildings["orient"])
            .series.isna()
github martinfleis / momepy / tests / test_distribution.py View on Github external
def test_Neighbors(self):
        sw = Queen.from_dataframe(self.df_tessellation, ids="uID")
        sw_drop = Queen.from_dataframe(self.df_tessellation[2:], ids="uID")
        self.df_tessellation["nei_sw"] = mm.Neighbors(
            self.df_tessellation, sw, "uID"
        ).series
        self.df_tessellation["nei_wei"] = mm.Neighbors(
            self.df_tessellation, sw, "uID", weighted=True
        ).series
        check = 5.180555555555555
        check_w = 0.029066398893536072
        assert self.df_tessellation["nei_sw"].mean() == check
        assert self.df_tessellation["nei_wei"].mean() == check_w
        assert mm.Neighbors(self.df_tessellation, sw_drop, "uID").series.isna().any()
github martinfleis / momepy / momepy / dimension.py View on Github external
def __init__(self, gdf, spatial_weights=None, verbose=True):
        self.gdf = gdf

        if spatial_weights is None:

            print("Calculating spatial weights...") if verbose else None
            from libpysal.weights import Queen

            spatial_weights = Queen.from_dataframe(gdf, silence_warnings=True)
            print("Spatial weights ready...") if verbose else None
        self.sw = spatial_weights

        # dict to store walls for each uID
        walls = {}
        components = pd.Series(spatial_weights.component_labels, index=range(len(gdf)))
        geom = gdf.geometry

        for i in tqdm(range(gdf.shape[0]), total=gdf.shape[0], disable=not verbose):
            # if the id is already present in walls, continue (avoid repetition)
            if i in walls:
                continue
            else:
                comp = spatial_weights.component_labels[i]
                to_join = components[components == comp].index
                joined = geom.iloc[to_join]
github martinfleis / momepy / momepy / utils.py View on Github external
def _generate_dual(G, gdf_network, fields):
    """
    Generate dual graph
    Helper for gdf_to_nx.
    """
    G.graph["approach"] = "dual"
    sw = libpysal.weights.Queen.from_dataframe(gdf_network)
    gdf_network["mm_cent"] = gdf_network.geometry.centroid

    for i, (index, row) in enumerate(gdf_network.iterrows()):
        centroid = (row.mm_cent.x, row.mm_cent.y)
        data = [row[f] for f in fields]
        attributes = dict(zip(fields, data))
        G.add_node(centroid, **attributes)

        if sw.cardinalities[i] > 0:
            for n in sw.neighbors[i]:
                start = centroid
                end = list(gdf_network.iloc[n]["mm_cent"].coords)[0]
                p0 = row.geometry.coords[0]
                p1 = row.geometry.coords[-1]
                p2 = gdf_network.iloc[n]["geometry"].coords[0]
                p3 = gdf_network.iloc[n]["geometry"].coords[-1]
github martinfleis / momepy / benchmarks / bench_distribution.py View on Github external
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")
github martinfleis / momepy / momepy / sandbox / contiguity.py View on Github external
def Queen_higher(dataframe, k):
    first_order = libpysal.weights.Queen.from_dataframe(dataframe)
    joined = first_order
    for i in list(range(2, k + 1)):
        i_order = libpysal.weights.higher_order(first_order, k=i)
        joined = libpysal.weights.w_union(joined, i_order)
    return joined
github martinfleis / momepy / benchmarks / bench_distribution.py View on Github external
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")
github martinfleis / momepy / momepy / intensity.py View on Github external
def __init__(self, gdf, block_id=None, spatial_weights=None, verbose=True):
        if block_id is not None:
            warnings.warn(
                "block_id is deprecated and will be removed in v0.4.", FutureWarning,
            )
        self.gdf = gdf

        results_list = []
        gdf = gdf.copy()

        # if weights matrix is not passed, generate it from objects
        if spatial_weights is None:
            print("Calculating spatial weights...") if verbose else None
            from libpysal.weights import Queen

            spatial_weights = Queen.from_dataframe(gdf, silence_warnings=True)

        self.sw = spatial_weights
        # dict to store nr of courtyards for each uID
        courtyards = {}
        components = pd.Series(spatial_weights.component_labels, index=gdf.index)
        for index in tqdm(gdf.index, total=gdf.shape[0], disable=not verbose):
            # if the id is already present in courtyards, continue (avoid repetition)
            if index in courtyards:
                continue
            else:
                comp = spatial_weights.component_labels[index]
                to_join = components[components == comp].index
                joined = gdf.loc[to_join]
                dissolved = joined.geometry.buffer(
                    0.01
                ).unary_union  # buffer to avoid multipolygons where buildings touch by corners only