Skip to content

Commit

Permalink
extract geoagents as geodataframe
Browse files Browse the repository at this point in the history
  • Loading branch information
wang-boyu committed Aug 13, 2022
1 parent baa1094 commit c72e679
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions mesa_geo/geospace.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,9 @@ def get_neighbors(self, agent):
"""Get (touching) neighbors of an agent."""
return self._agent_layer.get_neighbors(agent)

def get_agents_as_GeoDataFrame(self, agent_cls=GeoAgent) -> gpd.GeoDataFrame:
return self._agent_layer.get_agents_as_GeoDataFrame(agent_cls)


class _AgentLayer:
"""Layer that contains the GeoAgents. Mainly for internal usage within `GeoSpace`.
Expand Down Expand Up @@ -368,3 +371,19 @@ def get_neighbors(self, agent):
neighbors_idx = self._neighborhood.neighbors[idx]
neighbors = [self.agents[i] for i in neighbors_idx]
return neighbors

def get_agents_as_GeoDataFrame(self, agent_cls=GeoAgent) -> gpd.GeoDataFrame:
agents_list = []
crs = None
for agent in self.agents:
if isinstance(agent, agent_cls):
crs = agent.crs
agent_dict = {
attr: value
for attr, value in vars(agent).items()
if attr not in {"model", "pos", "_crs"}
}
agents_list.append(agent_dict)
agents_gdf = gpd.GeoDataFrame.from_records(agents_list, index="unique_id")
agents_gdf.crs = crs
return agents_gdf
18 changes: 18 additions & 0 deletions tests/test_GeoSpace.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import warnings

import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point

Expand Down Expand Up @@ -116,3 +117,20 @@ def test_get_neighbors_within_distance(self):
self.geo_space.get_neighbors_within_distance(agent_to_check, distance=1.0)
)
self.assertEqual(len(neighbors), 7)

def test_get_agents_as_GeoDataFrame(self):
self.geo_space.add_agents(self.agents)

agents_list = [
{"geometry": agent.geometry, "unique_id": agent.unique_id}
for agent in self.agents
]
agents_gdf = gpd.GeoDataFrame.from_records(agents_list, index="unique_id")
agents_gdf.crs = self.geo_space.crs

pd.testing.assert_frame_equal(
self.geo_space.get_agents_as_GeoDataFrame(), agents_gdf
)
self.assertEqual(
self.geo_space.get_agents_as_GeoDataFrame().crs, agents_gdf.crs
)

0 comments on commit c72e679

Please sign in to comment.