Access S2S API

Access S2S API#

This notebook walks through an example of sending an API call directly

from typing import Dict

import folium as flm  # Comment out if you have not installed, or run pip install folium matplotlib mapclassify
import geopandas as gpd
import numpy as np
import pandas as pd
import requests
from geojson_pydantic import Feature, Polygon
from lonboard import Map, ScatterplotLayer
from shapely import from_geojson
BASE_URL = "https://space2stats.ds.io"
FIELDS_ENDPOINT = f"{BASE_URL}/fields"
SUMMARY_ENDPOINT = f"{BASE_URL}/summary"
response = requests.get(FIELDS_ENDPOINT)
if response.status_code != 200:
    raise Exception(f"Failed to get fields: {response.text}")

available_fields = response.json()
print("Available Fields:", available_fields)
Available Fields: ['pop_flood_pct', 'ogc_fid', 'sum_pop_f_0_2020', 'sum_pop_f_10_2020', 'sum_pop_f_15_2020', 'sum_pop_f_1_2020', 'sum_pop_f_20_2020', 'sum_pop_f_25_2020', 'sum_pop_f_30_2020', 'sum_pop_f_35_2020', 'sum_pop_f_40_2020', 'sum_pop_f_45_2020', 'sum_pop_f_50_2020', 'sum_pop_f_55_2020', 'sum_pop_f_5_2020', 'sum_pop_f_60_2020', 'sum_pop_f_65_2020', 'sum_pop_f_70_2020', 'sum_pop_f_75_2020', 'sum_pop_f_80_2020', 'sum_pop_m_0_2020', 'sum_pop_m_10_2020', 'sum_pop_m_15_2020', 'sum_pop_m_1_2020', 'sum_pop_m_20_2020', 'sum_pop_m_25_2020', 'sum_pop_m_30_2020', 'sum_pop_m_35_2020', 'sum_pop_m_40_2020', 'sum_pop_m_45_2020', 'sum_pop_m_50_2020', 'sum_pop_m_55_2020', 'sum_pop_m_5_2020', 'sum_pop_m_60_2020', 'sum_pop_m_65_2020', 'sum_pop_m_70_2020', 'sum_pop_m_75_2020', 'sum_pop_m_80_2020', 'sum_pop_m_2020', 'sum_pop_f_2020', 'sum_pop_2020', 'pop', 'pop_flood']
AOIModel = Feature[Polygon, Dict]

# ~burundi
minx, miny, maxx, maxy = 29.038924, -4.468958, 30.850461, -2.310523

aoi = {
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [minx, maxy],
                [minx, miny],
                [maxx, miny],
                [maxx, maxy],
                [minx, maxy],
            ]
        ],
    },
    "properties": {"name": "Updated AOI"},
}


feat = AOIModel(**aoi)
# Define the Request Payload
request_payload = {
    "aoi": aoi,
    "spatial_join_method": "touches",
    "fields": ["sum_pop_2020"],
    "geometry": "polygon",
}

# Get Summary Data
response = requests.post(SUMMARY_ENDPOINT, json=request_payload)
if response.status_code != 200:
    raise Exception(f"Failed to get summary: {response.text}")

summary_data = response.json()
df = pd.DataFrame(summary_data)
df["geometry"] = df["geometry"].apply(lambda geom: from_geojson(geom))
gdf = gpd.GeoDataFrame(df, geometry="geometry", crs="EPSG:4326")
gdf.head()
hex_id geometry sum_pop_2020
0 866ad8087ffffff POLYGON ((30.10399 -2.3257, 30.11745 -2.29278,... 25345.874701
1 866ad808fffffff POLYGON ((30.16219 -2.34876, 30.17563 -2.31584... 11870.360712
2 866ad8097ffffff POLYGON ((30.05471 -2.36355, 30.06817 -2.33062... 19034.332476
3 866ad809fffffff POLYGON ((30.11291 -2.38662, 30.12636 -2.35369... 14700.551092
4 866ad80c7ffffff POLYGON ((30.26964 -2.33398, 30.28307 -2.30106... 12067.935215
m = gdf.explore(
    column="sum_pop_2020",
    tooltip="sum_pop_2020",
    cmap="YlGnBu",
    legend=True,
    scheme="naturalbreaks",
    legend_kwds=dict(colorbar=True, caption="Population", interval=False),
    style_kwds=dict(weight=0, fillOpacity=0.8),
    name="Population by Hexagon",
)
flm.LayerControl("topright", collapsed=False).add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
gdf.loc[:, "geometry"] = gdf.geometry.representative_point()
# Define custom breaks and corresponding RGBA colors
breaks = [
    gdf["sum_pop_2020"].min(),
    1,
    1000,
    10000,
    50000,
    100000,
    200000,
    gdf["sum_pop_2020"].max(),
]
colors = np.array(
    [
        [211, 211, 211, 255],  # Light gray for 0
        [255, 255, 0, 255],  # Yellow for 1-1000
        [255, 165, 0, 255],  # Orange for 1000-10000
        [255, 0, 0, 255],  # Red for 10000-50000
        [128, 0, 128, 255],  # Purple for 50000-100000
        [0, 0, 255, 255],  # Blue for 100000-200000
        [0, 0, 139, 255],  # Dark blue for 200000+
    ]
)

# Function to assign colors based on custom bins


def assign_color(value, breaks, colors):
    for i in range(len(breaks) - 1):
        if breaks[i] <= value < breaks[i + 1]:
            return colors[i]
    return colors[-1]  # In case value exceeds all breaks


# Map sum_pop_2020 values to colors using the custom function
gdf["color"] = gdf["sum_pop_2020"].apply(lambda x: assign_color(x, breaks, colors))
colors = np.uint8(gdf["color"].tolist())

# Create the scatterplot layer with the assigned colors
layer = ScatterplotLayer.from_geopandas(gdf, get_radius=2000, get_fill_color=colors)

m = Map(layer)
m