terraproof 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +356 -2
- package/bin/terraproof.js +4 -0
- package/dist/router/apply.js +147 -0
- package/dist/router/classify.js +111 -0
- package/dist/router/explain.js +9 -0
- package/dist/router/index.js +272 -0
- package/dist/router/resolve.js +239 -0
- package/dist/router/score.js +60 -0
- package/dist/router/types.js +1 -0
- package/dist/router/validate.js +81 -0
- package/instructions/engineering.md +14 -0
- package/instructions/security.md +14 -0
- package/instructions/simplicity.md +13 -0
- package/package.json +65 -4
- package/routing/DOMAIN_ROUTING.md +161 -0
- package/routing/ROUTER_DESIGN.md +173 -0
- package/routing/SKILL_MANIFEST.md +86 -0
- package/routing/checks.json +121 -0
- package/routing/collections.json +47 -0
- package/routing/registry.json +2211 -0
- package/routing/rules.json +64 -0
- package/skills/accuracy-assessment/SKILL.md +213 -0
- package/skills/accuracy-assessment/UPSTREAM.md +7 -0
- package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
- package/skills/accuracy-assessment/skill.json +103 -0
- package/skills/brainstorming/SKILL.md +250 -0
- package/skills/brainstorming/UPSTREAM.md +29 -0
- package/skills/brainstorming/scripts/frame-template.html +213 -0
- package/skills/brainstorming/scripts/helper.js +167 -0
- package/skills/brainstorming/scripts/server.cjs +723 -0
- package/skills/brainstorming/scripts/start-server.sh +209 -0
- package/skills/brainstorming/scripts/stop-server.sh +120 -0
- package/skills/brainstorming/skill.json +73 -0
- package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
- package/skills/brainstorming/visual-companion.md +299 -0
- package/skills/crs-and-units/SKILL.md +200 -0
- package/skills/crs-and-units/UPSTREAM.md +7 -0
- package/skills/crs-and-units/skill.json +74 -0
- package/skills/design-postgis-tables/SKILL.md +494 -0
- package/skills/design-postgis-tables/UPSTREAM.md +21 -0
- package/skills/design-postgis-tables/skill.json +90 -0
- package/skills/gdal/SKILL.md +125 -0
- package/skills/gdal/UPSTREAM.md +22 -0
- package/skills/gdal/references/gdal-recipes.md +103 -0
- package/skills/gdal/skill.json +66 -0
- package/skills/geomaster/README.md +105 -0
- package/skills/geomaster/SKILL.md +366 -0
- package/skills/geomaster/UPSTREAM.md +21 -0
- package/skills/geomaster/references/advanced-gis.md +376 -0
- package/skills/geomaster/references/big-data.md +363 -0
- package/skills/geomaster/references/code-examples.md +531 -0
- package/skills/geomaster/references/coordinate-systems.md +364 -0
- package/skills/geomaster/references/core-libraries.md +273 -0
- package/skills/geomaster/references/data-sources.md +330 -0
- package/skills/geomaster/references/gis-software.md +369 -0
- package/skills/geomaster/references/industry-applications.md +420 -0
- package/skills/geomaster/references/machine-learning.md +462 -0
- package/skills/geomaster/references/programming-languages.md +456 -0
- package/skills/geomaster/references/remote-sensing.md +370 -0
- package/skills/geomaster/references/scientific-domains.md +416 -0
- package/skills/geomaster/references/specialized-topics.md +428 -0
- package/skills/geomaster/references/troubleshooting.md +439 -0
- package/skills/geomaster/skill.json +157 -0
- package/skills/geopandas/SKILL.md +250 -0
- package/skills/geopandas/UPSTREAM.md +22 -0
- package/skills/geopandas/references/crs-management.md +231 -0
- package/skills/geopandas/references/data-io.md +323 -0
- package/skills/geopandas/references/data-structures.md +207 -0
- package/skills/geopandas/references/geometric-operations.md +262 -0
- package/skills/geopandas/references/spatial-analysis.md +294 -0
- package/skills/geopandas/references/visualization.md +230 -0
- package/skills/geopandas/scripts/_common.py +605 -0
- package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
- package/skills/geopandas/scripts/export_plan.py +305 -0
- package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
- package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
- package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
- package/skills/geopandas/scripts/vector_inventory.py +140 -0
- package/skills/geopandas/skill.json +116 -0
- package/skills/geoparquet-validation/SKILL.md +125 -0
- package/skills/geoparquet-validation/UPSTREAM.md +24 -0
- package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
- package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
- package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
- package/skills/geoparquet-validation/skill.json +71 -0
- package/skills/geospatial-data-discovery/SKILL.md +49 -0
- package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
- package/skills/geospatial-data-discovery/skill.json +51 -0
- package/skills/geospatial-frontend/SKILL.md +86 -0
- package/skills/geospatial-frontend/UPSTREAM.md +23 -0
- package/skills/geospatial-frontend/references/design-system.md +283 -0
- package/skills/geospatial-frontend/references/user-preferences.md +96 -0
- package/skills/geospatial-frontend/skill.json +87 -0
- package/skills/geozarr/SKILL.md +244 -0
- package/skills/geozarr/UPSTREAM.md +21 -0
- package/skills/geozarr/skill.json +97 -0
- package/skills/networkx/SKILL.md +440 -0
- package/skills/networkx/UPSTREAM.md +22 -0
- package/skills/networkx/references/algorithms.md +384 -0
- package/skills/networkx/references/generators.md +385 -0
- package/skills/networkx/references/graph-basics.md +284 -0
- package/skills/networkx/references/io.md +457 -0
- package/skills/networkx/references/visualization.md +531 -0
- package/skills/networkx/skill.json +93 -0
- package/skills/raster-processing/SKILL.md +222 -0
- package/skills/raster-processing/UPSTREAM.md +7 -0
- package/skills/raster-processing/skill.json +81 -0
- package/skills/sar-basics/SKILL.md +202 -0
- package/skills/sar-basics/UPSTREAM.md +7 -0
- package/skills/sar-basics/references/calibration-lut.md +98 -0
- package/skills/sar-basics/skill.json +97 -0
- package/skills/satellite-preprocessing/SKILL.md +241 -0
- package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
- package/skills/satellite-preprocessing/skill.json +84 -0
- package/skills/scientific-visualization/SKILL.md +285 -0
- package/skills/scientific-visualization/UPSTREAM.md +25 -0
- package/skills/scientific-visualization/assets/color_palettes.py +263 -0
- package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
- package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
- package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
- package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
- package/skills/scientific-visualization/references/color_palettes.md +227 -0
- package/skills/scientific-visualization/references/journal_requirements.md +169 -0
- package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
- package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
- package/skills/scientific-visualization/references/sources.md +76 -0
- package/skills/scientific-visualization/scripts/_common.py +136 -0
- package/skills/scientific-visualization/scripts/export_plan.py +493 -0
- package/skills/scientific-visualization/scripts/figure_export.py +642 -0
- package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
- package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
- package/skills/scientific-visualization/scripts/style_presets.py +501 -0
- package/skills/scientific-visualization/scripts/style_preview.py +232 -0
- package/skills/scientific-visualization/skill.json +95 -0
- package/skills/spectral-indices/SKILL.md +235 -0
- package/skills/spectral-indices/UPSTREAM.md +7 -0
- package/skills/spectral-indices/skill.json +88 -0
- package/skills/stac-and-cloud-access/SKILL.md +209 -0
- package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
- package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
- package/skills/stac-and-cloud-access/skill.json +98 -0
- package/skills/statistical-analysis/SKILL.md +446 -0
- package/skills/statistical-analysis/UPSTREAM.md +24 -0
- package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
- package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
- package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
- package/skills/statistical-analysis/references/reporting_standards.md +482 -0
- package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
- package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
- package/skills/statistical-analysis/skill.json +127 -0
- package/skills/systematic-debugging/SKILL.md +283 -0
- package/skills/systematic-debugging/UPSTREAM.md +28 -0
- package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
- package/skills/systematic-debugging/condition-based-waiting.md +115 -0
- package/skills/systematic-debugging/defense-in-depth.md +122 -0
- package/skills/systematic-debugging/find-polluter.sh +72 -0
- package/skills/systematic-debugging/root-cause-tracing.md +169 -0
- package/skills/systematic-debugging/skill.json +88 -0
- package/skills/time-series-and-change/SKILL.md +217 -0
- package/skills/time-series-and-change/UPSTREAM.md +7 -0
- package/skills/time-series-and-change/references/change-methods.md +42 -0
- package/skills/time-series-and-change/skill.json +116 -0
- package/skills/vector-quality/SKILL.md +204 -0
- package/skills/vector-quality/UPSTREAM.md +7 -0
- package/skills/vector-quality/skill.json +82 -0
- package/skills/verification/SKILL.md +120 -0
- package/skills/verification/UPSTREAM.md +31 -0
- package/skills/verification/skill.json +67 -0
- package/skills/writing-plans/SKILL.md +171 -0
- package/skills/writing-plans/UPSTREAM.md +23 -0
- package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
- package/skills/writing-plans/skill.json +80 -0
- package/sources/SOURCES.md +374 -0
- package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
- package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
- package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
- package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
- package/third_party/superpowers/LICENSE +21 -0
- package/third_party/superpowers/NOTICE.md +17 -0
- package/third_party/timescale-pg-aiguide/LICENSE +176 -0
- package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
# Advanced GIS Topics
|
|
2
|
+
|
|
3
|
+
Advanced spatial analysis techniques: 3D GIS, spatiotemporal analysis, topology, and network analysis.
|
|
4
|
+
|
|
5
|
+
## 3D GIS
|
|
6
|
+
|
|
7
|
+
### 3D Vector Operations
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import geopandas as gpd
|
|
11
|
+
from shapely.geometry import Point, LineString, Polygon
|
|
12
|
+
import pyproj
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
# Create 3D geometries (with Z coordinate)
|
|
16
|
+
point_3d = Point(0, 0, 100) # x, y, elevation
|
|
17
|
+
line_3d = LineString([(0, 0, 0), (100, 100, 50)])
|
|
18
|
+
|
|
19
|
+
# Load 3D data
|
|
20
|
+
gdf_3d = gpd.read_file('buildings_3d.geojson')
|
|
21
|
+
|
|
22
|
+
# Access Z coordinates
|
|
23
|
+
gdf_3d['height'] = gdf_3d.geometry.apply(lambda g: g.coords[0][2] if g.has_z else None)
|
|
24
|
+
|
|
25
|
+
# 3D buffer (cylinder)
|
|
26
|
+
def buffer_3d(point, radius, height):
|
|
27
|
+
"""Create a 3D cylindrical buffer."""
|
|
28
|
+
base = Point(point.x, point.y).buffer(radius)
|
|
29
|
+
# Extrude to 3D (conceptual)
|
|
30
|
+
return base, point.z, point.z + height
|
|
31
|
+
|
|
32
|
+
# 3D distance (Euclidean in 3D space)
|
|
33
|
+
def distance_3d(point1, point2):
|
|
34
|
+
"""Calculate 3D Euclidean distance."""
|
|
35
|
+
dx = point2.x - point1.x
|
|
36
|
+
dy = point2.y - point1.y
|
|
37
|
+
dz = point2.z - point1.z
|
|
38
|
+
return np.sqrt(dx**2 + dy**2 + dz**2)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### 3D Raster Analysis
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import rasterio
|
|
45
|
+
import numpy as np
|
|
46
|
+
|
|
47
|
+
# Voxel-based analysis
|
|
48
|
+
def voxel_analysis(dem_path, dsm_path):
|
|
49
|
+
"""Analyze volume between DEM and DSM."""
|
|
50
|
+
with rasterio.open(dem_path) as src_dem:
|
|
51
|
+
dem = src_dem.read(1)
|
|
52
|
+
transform = src_dem.transform
|
|
53
|
+
|
|
54
|
+
with rasterio.open(dsm_path) as src_dsm:
|
|
55
|
+
dsm = src_dsm.read(1)
|
|
56
|
+
|
|
57
|
+
# Height difference
|
|
58
|
+
height = dsm - dem
|
|
59
|
+
|
|
60
|
+
# Volume calculation
|
|
61
|
+
pixel_area = transform[0] * transform[4] # Usually negative
|
|
62
|
+
volume = np.sum(height[height > 0]) * abs(pixel_area)
|
|
63
|
+
|
|
64
|
+
# Volume per height class
|
|
65
|
+
height_bins = [0, 5, 10, 20, 50, 100]
|
|
66
|
+
volume_by_class = {}
|
|
67
|
+
|
|
68
|
+
for i in range(len(height_bins) - 1):
|
|
69
|
+
mask = (height >= height_bins[i]) & (height < height_bins[i + 1])
|
|
70
|
+
volume_by_class[f'{height_bins[i]}-{height_bins[i+1]}m'] = \
|
|
71
|
+
np.sum(height[mask]) * abs(pixel_area)
|
|
72
|
+
|
|
73
|
+
return volume, volume_by_class
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Viewshed Analysis
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
def viewshed(dem, observer_x, observer_y, observer_height=1.7, max_distance=5000):
|
|
80
|
+
"""
|
|
81
|
+
Calculate viewshed using line-of-sight algorithm.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
# Convert observer to raster coordinates
|
|
85
|
+
observer_row = int((observer_y - dem_origin_y) / cell_size)
|
|
86
|
+
observer_col = int((observer_x - dem_origin_x) / cell_size)
|
|
87
|
+
|
|
88
|
+
rows, cols = dem.shape
|
|
89
|
+
viewshed = np.zeros_like(dem, dtype=bool)
|
|
90
|
+
|
|
91
|
+
observer_z = dem[observer_row, observer_col] + observer_height
|
|
92
|
+
|
|
93
|
+
# For each direction
|
|
94
|
+
for angle in np.linspace(0, 2*np.pi, 360):
|
|
95
|
+
# Cast ray
|
|
96
|
+
for r in range(1, int(max_distance / cell_size)):
|
|
97
|
+
row = observer_row + int(r * np.sin(angle))
|
|
98
|
+
col = observer_col + int(r * np.cos(angle))
|
|
99
|
+
|
|
100
|
+
if row < 0 or row >= rows or col < 0 or col >= cols:
|
|
101
|
+
break
|
|
102
|
+
|
|
103
|
+
target_z = dem[row, col]
|
|
104
|
+
|
|
105
|
+
# Line-of-sight calculation
|
|
106
|
+
dist = r * cell_size
|
|
107
|
+
line_height = observer_z + (target_z - observer_z) * (dist / max_distance)
|
|
108
|
+
|
|
109
|
+
if target_z > line_height:
|
|
110
|
+
viewshed[row, col] = False
|
|
111
|
+
else:
|
|
112
|
+
viewshed[row, col] = True
|
|
113
|
+
|
|
114
|
+
return viewshed
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Spatiotemporal Analysis
|
|
118
|
+
|
|
119
|
+
### Trajectory Analysis
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
import movingpandas as mpd
|
|
123
|
+
import geopandas as gpd
|
|
124
|
+
import pandas as pd
|
|
125
|
+
|
|
126
|
+
# Create trajectory from point data
|
|
127
|
+
gdf = gpd.read_file('gps_points.gpkg')
|
|
128
|
+
|
|
129
|
+
# Convert to trajectory
|
|
130
|
+
traj_collection = mpd.TrajectoryCollection(gdf, 'track_id', t='timestamp')
|
|
131
|
+
|
|
132
|
+
# Split trajectories (e.g., by time gap)
|
|
133
|
+
traj_collection = mpd.SplitByObservationGap(traj_collection, gap=pd.Timedelta('1 hour'))
|
|
134
|
+
|
|
135
|
+
# Trajectory statistics
|
|
136
|
+
for traj in traj_collection:
|
|
137
|
+
print(f"Trajectory {traj.id}:")
|
|
138
|
+
print(f" Length: {traj.get_length() / 1000:.2f} km")
|
|
139
|
+
print(f" Duration: {traj.get_duration()}")
|
|
140
|
+
print(f" Speed: {traj.get_speed() * 3.6:.2f} km/h")
|
|
141
|
+
|
|
142
|
+
# Stop detection
|
|
143
|
+
stops = mpd.stop_detection(
|
|
144
|
+
traj_collection,
|
|
145
|
+
max_diameter=100, # meters
|
|
146
|
+
min_duration=pd.Timedelta('5 minutes')
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Generalization (simplify trajectories)
|
|
150
|
+
traj_generalized = mpd.DouglasPeuckerGeneralizer(traj_collection, tolerance=10).generalize()
|
|
151
|
+
|
|
152
|
+
# Split by stop
|
|
153
|
+
traj_moving, stops = mpd.StopSplitter(traj_collection).split()
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Space-Time Cube
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
def create_space_time_cube(gdf, time_column='timestamp', grid_size=100, time_step='1H'):
|
|
160
|
+
"""
|
|
161
|
+
Create a 3D space-time cube for hotspot analysis.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
# 1. Spatial binning
|
|
165
|
+
gdf['x_bin'] = (gdf.geometry.x // grid_size).astype(int)
|
|
166
|
+
gdf['y_bin'] = (gdf.geometry.y // grid_size).astype(int)
|
|
167
|
+
|
|
168
|
+
# 2. Temporal binning
|
|
169
|
+
gdf['t_bin'] = gdf[time_column].dt.floor(time_step)
|
|
170
|
+
|
|
171
|
+
# 3. Create cube (x, y, time)
|
|
172
|
+
cube = gdf.groupby(['x_bin', 'y_bin', 't_bin']).size().unstack(fill_value=0)
|
|
173
|
+
|
|
174
|
+
return cube
|
|
175
|
+
|
|
176
|
+
def emerging_hot_spot_analysis(cube, k=8):
|
|
177
|
+
"""
|
|
178
|
+
Emerging Hot Spot Analysis (as implemented in ArcGIS).
|
|
179
|
+
Simplified version using Getis-Ord Gi* statistic.
|
|
180
|
+
"""
|
|
181
|
+
from esda.getisord import G_Local
|
|
182
|
+
|
|
183
|
+
# Calculate Gi* statistic for each time step
|
|
184
|
+
hotspots = {}
|
|
185
|
+
for timestep in cube.columns:
|
|
186
|
+
data = cube[timestep].values.reshape(-1, 1)
|
|
187
|
+
g_local = G_Local(data, k=k)
|
|
188
|
+
hotspots[timestep] = g_local.p_sim < 0.05 # Significant hotspots
|
|
189
|
+
|
|
190
|
+
return hotspots
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Topology
|
|
194
|
+
|
|
195
|
+
### Topological Relationships
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
from shapely.geometry import Point, LineString, Polygon
|
|
199
|
+
from shapely.ops import unary_union
|
|
200
|
+
|
|
201
|
+
# Planar graph
|
|
202
|
+
def build_planar_graph(lines_gdf):
|
|
203
|
+
"""Build a planar graph from line features."""
|
|
204
|
+
import networkx as nx
|
|
205
|
+
|
|
206
|
+
G = nx.Graph()
|
|
207
|
+
|
|
208
|
+
# Add nodes at intersections
|
|
209
|
+
for i, line1 in lines_gdf.iterrows():
|
|
210
|
+
for j, line2 in lines_gdf.iterrows():
|
|
211
|
+
if i < j:
|
|
212
|
+
if line1.geometry.intersects(line2.geometry):
|
|
213
|
+
intersection = line1.geometry.intersection(line2.geometry)
|
|
214
|
+
G.add_node((intersection.x, intersection.y))
|
|
215
|
+
|
|
216
|
+
# Add edges
|
|
217
|
+
for _, line in lines_gdf.iterrows():
|
|
218
|
+
coords = list(line.geometry.coords)
|
|
219
|
+
G.add_edge(coords[0], coords[-1],
|
|
220
|
+
weight=line.geometry.length,
|
|
221
|
+
geometry=line.geometry)
|
|
222
|
+
|
|
223
|
+
return G
|
|
224
|
+
|
|
225
|
+
# Topology validation
|
|
226
|
+
def validate_topology(gdf):
|
|
227
|
+
"""Check for topological errors."""
|
|
228
|
+
|
|
229
|
+
errors = []
|
|
230
|
+
|
|
231
|
+
# 1. Check for gaps
|
|
232
|
+
if gdf.geom_type.iloc[0] == 'Polygon':
|
|
233
|
+
dissolved = unary_union(gdf.geometry)
|
|
234
|
+
for i, geom in enumerate(gdf.geometry):
|
|
235
|
+
if not geom.touches(dissolved - geom):
|
|
236
|
+
errors.append(f"Gap detected at feature {i}")
|
|
237
|
+
|
|
238
|
+
# 2. Check for overlaps
|
|
239
|
+
for i, geom1 in enumerate(gdf.geometry):
|
|
240
|
+
for j, geom2 in enumerate(gdf.geometry):
|
|
241
|
+
if i < j and geom1.overlaps(geom2):
|
|
242
|
+
errors.append(f"Overlap between features {i} and {j}")
|
|
243
|
+
|
|
244
|
+
# 3. Check for self-intersections
|
|
245
|
+
for i, geom in enumerate(gdf.geometry):
|
|
246
|
+
if not geom.is_valid:
|
|
247
|
+
errors.append(f"Self-intersection at feature {i}: {geom.is_valid}")
|
|
248
|
+
|
|
249
|
+
return errors
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Network Analysis
|
|
253
|
+
|
|
254
|
+
### Advanced Routing
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
import osmnx as ox
|
|
258
|
+
import networkx as nx
|
|
259
|
+
|
|
260
|
+
# Download and prepare network
|
|
261
|
+
G = ox.graph_from_place('Portland, Maine, USA', network_type='drive')
|
|
262
|
+
G = ox.add_edge_speeds(G)
|
|
263
|
+
G = ox.add_edge_travel_times(G)
|
|
264
|
+
|
|
265
|
+
# Multi-criteria routing
|
|
266
|
+
def multi_criteria_routing(G, orig, dest, weights=['length', 'travel_time']):
|
|
267
|
+
"""
|
|
268
|
+
Find routes optimizing for multiple criteria.
|
|
269
|
+
"""
|
|
270
|
+
# Normalize weights
|
|
271
|
+
for w in weights:
|
|
272
|
+
values = [G.edges[e][w] for e in G.edges]
|
|
273
|
+
min_val, max_val = min(values), max(values)
|
|
274
|
+
for e in G.edges:
|
|
275
|
+
G.edges[e][f'{w}_norm'] = (G.edges[e][w] - min_val) / (max_val - min_val)
|
|
276
|
+
|
|
277
|
+
# Combined weight
|
|
278
|
+
for e in G.edges:
|
|
279
|
+
G.edges[e]['combined'] = sum(G.edges[e][f'{w}_norm'] for w in weights) / len(weights)
|
|
280
|
+
|
|
281
|
+
# Find path
|
|
282
|
+
route = nx.shortest_path(G, orig, dest, weight='combined')
|
|
283
|
+
return route
|
|
284
|
+
|
|
285
|
+
# Isochrone (accessibility area)
|
|
286
|
+
def isochrone(G, center_node, time_limit=600):
|
|
287
|
+
"""
|
|
288
|
+
Calculate accessible area within time limit.
|
|
289
|
+
"""
|
|
290
|
+
# Get subgraph of reachable nodes
|
|
291
|
+
subgraph = nx.ego_graph(G, center_node,
|
|
292
|
+
radius=time_limit,
|
|
293
|
+
distance='travel_time')
|
|
294
|
+
|
|
295
|
+
# Get node geometries
|
|
296
|
+
nodes = ox.graph_to_gdfs(subgraph, edges=False)
|
|
297
|
+
|
|
298
|
+
# Create polygon of accessible area
|
|
299
|
+
from shapely.geometry import MultiPoint
|
|
300
|
+
points = MultiPoint(nodes.geometry.tolist())
|
|
301
|
+
isochrone_polygon = points.convex_hull
|
|
302
|
+
|
|
303
|
+
return isochrone_polygon, subgraph
|
|
304
|
+
|
|
305
|
+
# Betweenness centrality (importance of nodes)
|
|
306
|
+
def calculate_centrality(G):
|
|
307
|
+
"""
|
|
308
|
+
Calculate betweenness centrality for network analysis.
|
|
309
|
+
"""
|
|
310
|
+
centrality = nx.betweenness_centrality(G, weight='length')
|
|
311
|
+
|
|
312
|
+
# Add to nodes
|
|
313
|
+
for node, value in centrality.items():
|
|
314
|
+
G.nodes[node]['betweenness'] = value
|
|
315
|
+
|
|
316
|
+
return centrality
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Service Area Analysis
|
|
320
|
+
|
|
321
|
+
```python
|
|
322
|
+
def service_area(G, facilities, max_distance=1000):
|
|
323
|
+
"""
|
|
324
|
+
Calculate service areas for facilities.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
service_areas = []
|
|
328
|
+
|
|
329
|
+
for facility in facilities:
|
|
330
|
+
# Find nearest node
|
|
331
|
+
node = ox.distance.nearest_nodes(G, facility.x, facility.y)
|
|
332
|
+
|
|
333
|
+
# Get nodes within distance
|
|
334
|
+
subgraph = nx.ego_graph(G, node, radius=max_distance, distance='length')
|
|
335
|
+
|
|
336
|
+
# Create convex hull
|
|
337
|
+
nodes = ox.graph_to_gdfs(subgraph, edges=False)
|
|
338
|
+
service_area = nodes.geometry.unary_union.convex_hull
|
|
339
|
+
|
|
340
|
+
service_areas.append({
|
|
341
|
+
'facility': facility,
|
|
342
|
+
'area': service_area,
|
|
343
|
+
'nodes_served': len(subgraph.nodes())
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
return service_areas
|
|
347
|
+
|
|
348
|
+
# Location-allocation (facility location)
|
|
349
|
+
def location_allocation(demand_points, candidate_sites, n_facilities=5):
|
|
350
|
+
"""
|
|
351
|
+
Solve facility location problem (p-median).
|
|
352
|
+
"""
|
|
353
|
+
from scipy.spatial.distance import cdist
|
|
354
|
+
|
|
355
|
+
# Distance matrix
|
|
356
|
+
coords_demand = [[p.x, p.y] for p in demand_points]
|
|
357
|
+
coords_sites = [[s.x, s.y] for s in candidate_sites]
|
|
358
|
+
distances = cdist(coords_demand, coords_sites)
|
|
359
|
+
|
|
360
|
+
# Simple heuristic: K-means clustering
|
|
361
|
+
from sklearn.cluster import KMeans
|
|
362
|
+
|
|
363
|
+
kmeans = KMeans(n_clusters=n_facilities, random_state=42)
|
|
364
|
+
labels = kmeans.fit_predict(coords_demand)
|
|
365
|
+
|
|
366
|
+
# Find nearest candidate site to each cluster center
|
|
367
|
+
facilities = []
|
|
368
|
+
for i in range(n_facilities):
|
|
369
|
+
cluster_center = kmeans.cluster_centers_[i]
|
|
370
|
+
nearest_site_idx = np.argmin(cdist([cluster_center], coords_sites))
|
|
371
|
+
facilities.append(candidate_sites[nearest_site_idx])
|
|
372
|
+
|
|
373
|
+
return facilities
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
For more advanced examples, see [code-examples.md](code-examples.md).
|