Projected boundary distance

From XuShuwenn/RedAct · View interactive version

Projected boundary distance is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Compute distances from point events to the nearest relevant boundary within a parent polygon using GeoPandas projections, then select the extremal case (e.g., farthest).

How to use this skill

Skill file

Projected Boundary Distance Analysis

A reusable workflow to:

This pattern applies to plates and plate boundaries, administrative regions and borders, protected areas and perimeters, and similar tasks.

When to Use

Activate this skill when you need to:

Core Workflow

1) Inspect and Load Data

2) Identify the Target Polygon

3) Filter Points by Containment

4) Build the Relevant Boundary Geometry

5) Choose a Projection and Compute Distances

6) Select the Extremal Point and Prepare Output

Reference Implementation (concise pattern)

from shapely.ops import unary_union as ops_unary_union

def union_geoms(gdf):
    # Try GeoSeries.union_all (newer) then .unary_union, else shapely.ops
    gs = gdf.geometry
    if hasattr(gs, "union_all"):
        return gs.union_all()
    if hasattr(gs, "unary_union"):
        return gs.unary_union
    return ops_unary_union(gs)
import geopandas as gpd
from shapely.geometry import Point
from datetime import datetime, timezone

# 1) Load
points = gpd.read_file(points_path)            # EPSG:4326 expected
polys  = gpd.read_file(polygons_path)          # EPSG:4326 expected
bounds = gpd.read_file(boundaries_path)        # EPSG:4326 expected

# 2) Target polygon selection (prefer code, fallback to name contains)
poly_sel = polys[polys[target_code_col] == target_code]
if len(poly_sel) == 0 and target_name_col and target_name_value:
    poly_sel = polys[polys[target_name_col].str.contains(target_name_value, case=False, na=False)]
poly_geom = union_geoms(poly_sel)

# 3) Filter points inside polygon
points = points.set_crs("EPSG:4326", allow_override=True)
inside = points[points.within(poly_geom)].copy()
if inside.empty:
    # Optional repair
    try:
        inside = points[points.within(poly_geom.buffer(0))].copy()
    except Exception:
        pass

# 4) Relevant boundaries
rel_bounds = bounds[(bounds[bound_col_a] == target_code) | (bounds[bound_col_b] == target_code)]
bound_union = union_geoms(rel_bounds)

# 5) Project and measure
METRIC_CRS = "EPSG:4087"
inside_proj = inside.to_crs(METRIC_CRS)
bounds_proj = gpd.GeoSeries([bound_union], crs="EPSG:4326").to_crs(METRIC_CRS).iloc[0]
inside_proj["distance_m"] = inside_proj.geometry.distance(bounds_proj)
inside_proj["distance_km"] = inside_proj["distance_m"] / 1000.0

# 6) Select extremal
choice = inside_proj.loc[inside_proj["distance_km"].idxmax()]
# Normalize time if milliseconds since epoch
if isinstance(choice.get("time"), (int, float)):
    iso_time = datetime.fromtimestamp(choice["time"] / 1000.0, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
else:
    iso_time = str(choice.get("time"))

result = {
    "id": choice.get("id"),
    "place": choice.get("place"),
    "time": iso_time,
    "magnitude": float(choice.get("mag", choice.get("magnitude", 0)) or 0),
    "latitude": float(choice.geometry.y),
    "longitude": float(choice.geometry.x),
    "distance_km": round(float(choice["distance_km"]), 2)
}
from shapely.ops import unary_union

def aeqd_distance_km(pt_wgs84, lines_gdf_wgs84):
    lat = pt_wgs84.y
    lon = pt_wgs84.x
    aeqd = f"+proj=aeqd +lat_0={lat} +lon_0={lon} +datum=WGS84 +units=m +no_defs"
    pt_proj = gpd.GeoSeries([pt_wgs84], crs="EPSG:4326").to_crs(aeqd).iloc[0]
    lines_proj = lines_gdf_wgs84.to_crs(aeqd)
    line_union = union_geoms(lines_proj)
    return pt_proj.distance(line_union) / 1000.0

Use AEQD for higher precision at the cost of computation time.

Verification

Perform these checks before finalizing:

Common Pitfalls and How to Avoid Them

Success Criteria

Optional Script Usage

This skill ships with a small helper module for robust geometry unions, projection, distance computation, and time normalization. See scripts/geo_helpers.py for details.

Example usage snippet:

from scripts.geo_helpers import union_geoms_safe, to_metric, ms_to_iso8601

# After loading and filtering to inside points and relevant boundaries:
inside_proj = to_metric(inside, "EPSG:4087")
bounds_union = union_geoms_safe(rel_bounds)
bounds_proj = to_metric(gpd.GeoDataFrame(geometry=[bounds_union], crs="EPSG:4326"), "EPSG:4087").geometry.iloc[0]
inside_proj["distance_km"] = inside_proj.geometry.distance(bounds_proj) / 1000.0
chosen = inside_proj.loc[inside_proj["distance_km"].idxmax()]
iso = ms_to_iso8601(chosen.get("time"))
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.