diff --git a/gis/geo_schelling/model.py b/gis/geo_schelling/model.py index 7436af92..613a7e59 100644 --- a/gis/geo_schelling/model.py +++ b/gis/geo_schelling/model.py @@ -1,12 +1,29 @@ import random from pathlib import Path +import geopandas as gpd +import libpysal import mesa import mesa_geo as mg script_directory = Path(__file__).resolve().parent +def get_largest_connected_components(gdf): + """Get the largest connected component of a GeoDataFrame.""" + # create spatial weights matrix + W = libpysal.weights.Queen.from_dataframe( + gdf, use_index=True, silence_warnings=True + ) + # get component labels + gdf["component"] = W.component_labels + # get the largest component + largest_component = gdf["component"].value_counts().idxmax() + # subset the GeoDataFrame + gdf = gdf[gdf["component"] == largest_component] + return gdf + + class SchellingAgent(mg.GeoAgent): """Schelling segregation agent.""" @@ -71,7 +88,9 @@ def __init__(self, density=0.6, minority_pc=0.2, export_data=False): # Set up the grid with patches for every NUTS region ac = mg.AgentCreator(SchellingAgent, model=self) data_path = script_directory / "data/nuts_rg_60M_2013_lvl_2.geojson" - agents = ac.from_file(filename=data_path) + agents_gdf = gpd.read_file(data_path) + agents_gdf = get_largest_connected_components(agents_gdf) + agents = ac.from_GeoDataFrame(agents_gdf, unique_id="index") self.space.add_agents(agents) # Set up agents diff --git a/gis/geo_schelling/server.py b/gis/geo_schelling/server.py index 0871e219..c8e85d09 100644 --- a/gis/geo_schelling/server.py +++ b/gis/geo_schelling/server.py @@ -38,9 +38,7 @@ def schelling_draw(agent): happy_element = HappyElement() -map_element = mg.visualization.MapModule( - schelling_draw, [52, 12], 4, tiles=xyz.CartoDB.Positron -) +map_element = mg.visualization.MapModule(schelling_draw, tiles=xyz.CartoDB.Positron) happy_chart = mesa.visualization.ChartModule([{"Label": "happy", "Color": "Black"}]) server = mesa.visualization.ModularServer( GeoSchelling, [map_element, happy_element, happy_chart], "Schelling", model_params