How to use libpysal - 10 common examples

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_intensity.py View on Github external
def test_Courtyards(self):
        courtyards = mm.Courtyards(self.df_buildings, "bID").series
        sw = Queen.from_dataframe(self.df_buildings)
        courtyards_wm = mm.Courtyards(
            self.df_buildings, self.df_buildings.bID, sw
        ).series
        check = 0.6805555555555556
        assert courtyards.mean() == check
        assert courtyards_wm.mean() == check
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 / tests / test_weights.py View on Github external
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 = [133, 134, 111, 112, 113, 114, 115, 121, 125]
        assert from_sw.neighbors[0] == check
        assert from_df.neighbors[0] == check
        assert 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")
github martinfleis / momepy / tests / test_weights.py View on Github external
def test_DistanceBand(self):
        lp = libpysal.weights.DistanceBand.from_dataframe(self.df_buildings, 100)
        lp_ids = libpysal.weights.DistanceBand.from_dataframe(
            self.df_buildings, 100, ids="uID"
        )
        db = mm.DistanceBand(self.df_buildings, 100)
        db_ids = mm.DistanceBand(self.df_buildings, 100, ids="uID")

        for k in range(len(self.df_buildings)):
            assert k in db.neighbors.keys()
            assert sorted(lp.neighbors[k]) == sorted(db.neighbors[k])
        for k in self.df_buildings.uID:
            assert k in db_ids.neighbors.keys()
            assert sorted(lp_ids.neighbors[k]) == sorted(db_ids.neighbors[k])

        db_cent_false = mm.DistanceBand(self.df_buildings, 100, centroid=False)
        assert sorted(db_cent_false.neighbors[0]) == sorted(
            [125, 133, 114, 134, 113, 121]
github martinfleis / momepy / tests / test_weights.py View on Github external
def test_DistanceBand(self):
        lp = libpysal.weights.DistanceBand.from_dataframe(self.df_buildings, 100)
        lp_ids = libpysal.weights.DistanceBand.from_dataframe(
            self.df_buildings, 100, ids="uID"
        )
        db = mm.DistanceBand(self.df_buildings, 100)
        db_ids = mm.DistanceBand(self.df_buildings, 100, ids="uID")

        for k in range(len(self.df_buildings)):
            assert k in db.neighbors.keys()
            assert sorted(lp.neighbors[k]) == sorted(db.neighbors[k])
        for k in self.df_buildings.uID:
            assert k in db_ids.neighbors.keys()
            assert sorted(lp_ids.neighbors[k]) == sorted(db_ids.neighbors[k])

        db_cent_false = mm.DistanceBand(self.df_buildings, 100, centroid=False)
        assert sorted(db_cent_false.neighbors[0]) == sorted(
            [125, 133, 114, 134, 113, 121]
        )
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 / dimension.py View on Github external
def __init__(self, gdf, spatial_weights=None, mean=False, 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

        lenghts = gdf.geometry.length

        sums = []
        means = []
        for index in tqdm(gdf.index, total=gdf.shape[0], disable=not verbose):
            neighbours = spatial_weights.neighbors[index].copy()
            if neighbours:
                neighbours.append(index)
            else:
                neighbours = [index]

            dims = lenghts.iloc[neighbours]
            if mean:
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]