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,428 @@
|
|
|
1
|
+
# Specialized Topics
|
|
2
|
+
|
|
3
|
+
Advanced specialized topics: geostatistics, optimization, ethics, and best practices.
|
|
4
|
+
|
|
5
|
+
## Geostatistics
|
|
6
|
+
|
|
7
|
+
### Variogram Analysis
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.spatial.distance import pdist, squareform
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
|
|
14
|
+
def empirical_variogram(points, values, max_lag=None, n_lags=15):
|
|
15
|
+
"""
|
|
16
|
+
Calculate empirical variogram.
|
|
17
|
+
"""
|
|
18
|
+
n = len(points)
|
|
19
|
+
|
|
20
|
+
# Distance matrix
|
|
21
|
+
dist_matrix = squareform(pdist(points))
|
|
22
|
+
|
|
23
|
+
if max_lag is None:
|
|
24
|
+
max_lag = np.max(dist_matrix) / 2
|
|
25
|
+
|
|
26
|
+
# Calculate semivariance
|
|
27
|
+
semivariance = []
|
|
28
|
+
mean_distances = []
|
|
29
|
+
|
|
30
|
+
for lag in np.linspace(0, max_lag, n_lags):
|
|
31
|
+
# Pair selection
|
|
32
|
+
mask = (dist_matrix >= lag) & (dist_matrix < lag + max_lag/n_lags)
|
|
33
|
+
|
|
34
|
+
if np.sum(mask) == 0:
|
|
35
|
+
continue
|
|
36
|
+
|
|
37
|
+
# Semivariance: (1/2n) * sum(z_i - z_j)^2
|
|
38
|
+
diff_squared = (values[:, None] - values) ** 2
|
|
39
|
+
gamma = 0.5 * np.mean(diff_squared[mask])
|
|
40
|
+
|
|
41
|
+
semivariance.append(gamma)
|
|
42
|
+
mean_distances.append(lag + max_lag/(2*n_lags))
|
|
43
|
+
|
|
44
|
+
return np.array(mean_distances), np.array(semivariance)
|
|
45
|
+
|
|
46
|
+
# Fit variogram model
|
|
47
|
+
def fit_variogram_model(lags, gammas, model='spherical'):
|
|
48
|
+
"""
|
|
49
|
+
Fit theoretical variogram model.
|
|
50
|
+
"""
|
|
51
|
+
from scipy.optimize import curve_fit
|
|
52
|
+
|
|
53
|
+
def spherical(h, nugget, sill, range_):
|
|
54
|
+
"""Spherical model."""
|
|
55
|
+
h = np.asarray(h)
|
|
56
|
+
gamma = np.where(h < range_,
|
|
57
|
+
nugget + sill * (1.5 * h/range_ - 0.5 * (h/range_)**3),
|
|
58
|
+
nugget + sill)
|
|
59
|
+
return gamma
|
|
60
|
+
|
|
61
|
+
def exponential(h, nugget, sill, range_):
|
|
62
|
+
"""Exponential model."""
|
|
63
|
+
return nugget + sill * (1 - np.exp(-3 * h / range_))
|
|
64
|
+
|
|
65
|
+
def gaussian(h, nugget, sill, range_):
|
|
66
|
+
"""Gaussian model."""
|
|
67
|
+
return nugget + sill * (1 - np.exp(-3 * (h/range_)**2))
|
|
68
|
+
|
|
69
|
+
models = {
|
|
70
|
+
'spherical': spherical,
|
|
71
|
+
'exponential': exponential,
|
|
72
|
+
'gaussian': gaussian
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
# Fit model
|
|
76
|
+
popt, _ = curve_fit(models[model], lags, gammas,
|
|
77
|
+
p0=[np.min(gammas), np.max(gammas), np.max(lags)/2],
|
|
78
|
+
bounds=(0, np.inf))
|
|
79
|
+
|
|
80
|
+
return popt, models[model]
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Kriging Interpolation
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from pykrige.ok import OrdinaryKriging
|
|
87
|
+
import numpy as np
|
|
88
|
+
|
|
89
|
+
def ordinary_kriging(x, y, z, grid_resolution=100):
|
|
90
|
+
"""
|
|
91
|
+
Perform ordinary kriging interpolation.
|
|
92
|
+
"""
|
|
93
|
+
# Create grid
|
|
94
|
+
gridx = np.linspace(x.min(), x.max(), grid_resolution)
|
|
95
|
+
gridy = np.linspace(y.min(), y.max(), grid_resolution)
|
|
96
|
+
|
|
97
|
+
# Fit variogram
|
|
98
|
+
OK = OrdinaryKriging(
|
|
99
|
+
x, y, z,
|
|
100
|
+
variogram_model='spherical',
|
|
101
|
+
verbose=False,
|
|
102
|
+
enable_plotting=False,
|
|
103
|
+
coordinates_type='euclidean',
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# Interpolate
|
|
107
|
+
zinterp, sigmasq = OK.execute('grid', gridx, gridy)
|
|
108
|
+
|
|
109
|
+
return zinterp, sigmasq, gridx, gridy
|
|
110
|
+
|
|
111
|
+
# Cross-validation
|
|
112
|
+
def kriging_cross_validation(x, y, z, n_folds=5):
|
|
113
|
+
"""
|
|
114
|
+
Perform k-fold cross-validation for kriging.
|
|
115
|
+
"""
|
|
116
|
+
from sklearn.model_selection import KFold
|
|
117
|
+
|
|
118
|
+
kf = KFold(n_splits=n_folds)
|
|
119
|
+
errors = []
|
|
120
|
+
|
|
121
|
+
for train_idx, test_idx in kf.split(z):
|
|
122
|
+
# Train
|
|
123
|
+
OK = OrdinaryKriging(
|
|
124
|
+
x[train_idx], y[train_idx], z[train_idx],
|
|
125
|
+
variogram_model='spherical',
|
|
126
|
+
verbose=False
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# Predict at test locations
|
|
130
|
+
predictions, _ = OK.execute('points',
|
|
131
|
+
x[test_idx], y[test_idx])
|
|
132
|
+
|
|
133
|
+
# Calculate error
|
|
134
|
+
rmse = np.sqrt(np.mean((predictions - z[test_idx])**2))
|
|
135
|
+
errors.append(rmse)
|
|
136
|
+
|
|
137
|
+
return np.mean(errors), np.std(errors)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Spatial Optimization
|
|
141
|
+
|
|
142
|
+
### Location-Allocation Problem
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from scipy.optimize import minimize
|
|
146
|
+
import numpy as np
|
|
147
|
+
|
|
148
|
+
def facility_location(demand_points, n_facilities=5):
|
|
149
|
+
"""
|
|
150
|
+
Solve p-median facility location problem.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
n_demand = len(demand_points)
|
|
154
|
+
|
|
155
|
+
# Distance matrix
|
|
156
|
+
dist_matrix = np.zeros((n_demand, n_demand))
|
|
157
|
+
for i, p1 in enumerate(demand_points):
|
|
158
|
+
for j, p2 in enumerate(demand_points):
|
|
159
|
+
dist_matrix[i, j] = np.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
|
|
160
|
+
|
|
161
|
+
# Decision variables: which demand points get facilities
|
|
162
|
+
def objective(x):
|
|
163
|
+
"""Minimize total weighted distance."""
|
|
164
|
+
# x is binary array of facility locations
|
|
165
|
+
facility_indices = np.where(x > 0.5)[0]
|
|
166
|
+
|
|
167
|
+
# Assign each demand to nearest facility
|
|
168
|
+
total_distance = 0
|
|
169
|
+
for i in range(n_demand):
|
|
170
|
+
min_dist = np.min([dist_matrix[i, f] for f in facility_indices])
|
|
171
|
+
total_distance += min_dist
|
|
172
|
+
|
|
173
|
+
return total_distance
|
|
174
|
+
|
|
175
|
+
# Constraints: exactly n_facilities
|
|
176
|
+
constraints = {'type': 'eq', 'fun': lambda x: np.sum(x) - n_facilities}
|
|
177
|
+
|
|
178
|
+
# Bounds: binary
|
|
179
|
+
bounds = [(0, 1)] * n_demand
|
|
180
|
+
|
|
181
|
+
# Initial guess: random locations
|
|
182
|
+
x0 = np.zeros(n_demand)
|
|
183
|
+
x0[:n_facilities] = 1
|
|
184
|
+
|
|
185
|
+
# Solve
|
|
186
|
+
result = minimize(
|
|
187
|
+
objective, x0,
|
|
188
|
+
method='SLSQP',
|
|
189
|
+
bounds=bounds,
|
|
190
|
+
constraints=constraints
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
facility_indices = np.where(result.x > 0.5)[0]
|
|
194
|
+
return demand_points[facility_indices]
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Routing Optimization
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
import networkx as nx
|
|
201
|
+
|
|
202
|
+
def traveling_salesman(G, start_node):
|
|
203
|
+
"""
|
|
204
|
+
Solve TSP using heuristic.
|
|
205
|
+
"""
|
|
206
|
+
unvisited = set(G.nodes())
|
|
207
|
+
unvisited.remove(start_node)
|
|
208
|
+
|
|
209
|
+
route = [start_node]
|
|
210
|
+
current = start_node
|
|
211
|
+
|
|
212
|
+
while unvisited:
|
|
213
|
+
# Find nearest unvisited node
|
|
214
|
+
nearest = min(unvisited,
|
|
215
|
+
key=lambda n: G[current][n].get('weight', 1))
|
|
216
|
+
route.append(nearest)
|
|
217
|
+
unvisited.remove(nearest)
|
|
218
|
+
current = nearest
|
|
219
|
+
|
|
220
|
+
# Return to start
|
|
221
|
+
route.append(start_node)
|
|
222
|
+
|
|
223
|
+
return route
|
|
224
|
+
|
|
225
|
+
# Vehicle Routing Problem
|
|
226
|
+
def vehicle_routing(G, depot, customers, n_vehicles=3, capacity=100):
|
|
227
|
+
"""
|
|
228
|
+
Solve VRP using heuristic (cluster-first, route-second).
|
|
229
|
+
"""
|
|
230
|
+
from sklearn.cluster import KMeans
|
|
231
|
+
|
|
232
|
+
# 1. Cluster customers
|
|
233
|
+
coords = np.array([[G.nodes[n]['x'], G.nodes[n]['y']] for n in customers])
|
|
234
|
+
kmeans = KMeans(n_clusters=n_vehicles, random_state=42)
|
|
235
|
+
labels = kmeans.fit_predict(coords)
|
|
236
|
+
|
|
237
|
+
# 2. Route each cluster
|
|
238
|
+
routes = []
|
|
239
|
+
for i in range(n_vehicles):
|
|
240
|
+
cluster_customers = [customers[j] for j in range(len(customers)) if labels[j] == i]
|
|
241
|
+
route = traveling_salesman(G.subgraph(cluster_customers + [depot]), depot)
|
|
242
|
+
routes.append(route)
|
|
243
|
+
|
|
244
|
+
return routes
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
## Ethics and Privacy
|
|
248
|
+
|
|
249
|
+
### Privacy-Preserving Geospatial Analysis
|
|
250
|
+
|
|
251
|
+
```python
|
|
252
|
+
# Differential privacy for spatial data
|
|
253
|
+
def add_dp_noise(locations, epsilon=1.0, radius=100):
|
|
254
|
+
"""
|
|
255
|
+
Add differential privacy noise to locations.
|
|
256
|
+
"""
|
|
257
|
+
import numpy as np
|
|
258
|
+
|
|
259
|
+
noisy_locations = []
|
|
260
|
+
for lon, lat in locations:
|
|
261
|
+
# Calculate noise (Laplace mechanism)
|
|
262
|
+
sensitivity = radius
|
|
263
|
+
scale = sensitivity / epsilon
|
|
264
|
+
|
|
265
|
+
noise_lon = np.random.laplace(0, scale)
|
|
266
|
+
noise_lat = np.random.laplace(0, scale)
|
|
267
|
+
|
|
268
|
+
noisy_locations.append((lon + noise_lon, lat + noise_lat))
|
|
269
|
+
|
|
270
|
+
return noisy_locations
|
|
271
|
+
|
|
272
|
+
# K-anonymity for trajectory data
|
|
273
|
+
def k_anonymize_trajectory(trajectory, k=5):
|
|
274
|
+
"""
|
|
275
|
+
Apply k-anonymity to trajectory.
|
|
276
|
+
"""
|
|
277
|
+
# 1. Divide into segments
|
|
278
|
+
# 2. Find k-1 similar trajectories
|
|
279
|
+
# 3. Replace segment with generalization
|
|
280
|
+
|
|
281
|
+
# Simplified: spatial generalization
|
|
282
|
+
from shapely.geometry import LineString
|
|
283
|
+
|
|
284
|
+
simplified = LineString(trajectory).simplify(0.01)
|
|
285
|
+
return list(simplified.coords)
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### Data Provenance
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
# Track geospatial data lineage
|
|
292
|
+
class DataLineage:
|
|
293
|
+
def __init__(self):
|
|
294
|
+
self.history = []
|
|
295
|
+
|
|
296
|
+
def record_transformation(self, input_data, operation, output_data, params):
|
|
297
|
+
"""Record data transformation."""
|
|
298
|
+
record = {
|
|
299
|
+
'timestamp': pd.Timestamp.now(),
|
|
300
|
+
'input': input_data,
|
|
301
|
+
'operation': operation,
|
|
302
|
+
'output': output_data,
|
|
303
|
+
'parameters': params
|
|
304
|
+
}
|
|
305
|
+
self.history.append(record)
|
|
306
|
+
|
|
307
|
+
def get_lineage(self, data_id):
|
|
308
|
+
"""Get complete lineage for a dataset."""
|
|
309
|
+
lineage = []
|
|
310
|
+
for record in reversed(self.history):
|
|
311
|
+
if record['output'] == data_id:
|
|
312
|
+
lineage.append(record)
|
|
313
|
+
lineage.extend(self.get_lineage(record['input']))
|
|
314
|
+
return lineage
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
## Best Practices
|
|
318
|
+
|
|
319
|
+
### Reproducible Research
|
|
320
|
+
|
|
321
|
+
```python
|
|
322
|
+
# Use environment.yml for dependencies
|
|
323
|
+
# environment.yml:
|
|
324
|
+
"""
|
|
325
|
+
name: geomaster
|
|
326
|
+
dependencies:
|
|
327
|
+
- python=3.11
|
|
328
|
+
- geopandas
|
|
329
|
+
- rasterio
|
|
330
|
+
- scikit-learn
|
|
331
|
+
- pip
|
|
332
|
+
- pip:
|
|
333
|
+
- torchgeo
|
|
334
|
+
"""
|
|
335
|
+
|
|
336
|
+
# Capture session info
|
|
337
|
+
def capture_environment():
|
|
338
|
+
"""Capture software and data versions."""
|
|
339
|
+
import platform
|
|
340
|
+
import geopandas as gpd
|
|
341
|
+
import rasterio
|
|
342
|
+
import numpy as np
|
|
343
|
+
import pandas as pd
|
|
344
|
+
|
|
345
|
+
info = {
|
|
346
|
+
'os': platform.platform(),
|
|
347
|
+
'python': platform.python_version(),
|
|
348
|
+
'geopandas': gpd.__version__,
|
|
349
|
+
'rasterio': rasterio.__version__,
|
|
350
|
+
'numpy': np.__version__,
|
|
351
|
+
'pandas': pd.__version__,
|
|
352
|
+
'timestamp': pd.Timestamp.now()
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return info
|
|
356
|
+
|
|
357
|
+
# Save with output
|
|
358
|
+
import json
|
|
359
|
+
with open('processing_info.json', 'w') as f:
|
|
360
|
+
json.dump(capture_environment(), f, indent=2, default=str)
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Code Organization
|
|
364
|
+
|
|
365
|
+
```python
|
|
366
|
+
# Project structure
|
|
367
|
+
"""
|
|
368
|
+
project/
|
|
369
|
+
├── data/
|
|
370
|
+
│ ├── raw/
|
|
371
|
+
│ ├── processed/
|
|
372
|
+
│ └── external/
|
|
373
|
+
├── notebooks/
|
|
374
|
+
├── src/
|
|
375
|
+
│ ├── __init__.py
|
|
376
|
+
│ ├── data_loading.py
|
|
377
|
+
│ ├── preprocessing.py
|
|
378
|
+
│ ├── analysis.py
|
|
379
|
+
│ └── visualization.py
|
|
380
|
+
├── tests/
|
|
381
|
+
├── config.yaml
|
|
382
|
+
└── README.md
|
|
383
|
+
"""
|
|
384
|
+
|
|
385
|
+
# Configuration management
|
|
386
|
+
import yaml
|
|
387
|
+
|
|
388
|
+
with open('config.yaml') as f:
|
|
389
|
+
config = yaml.safe_load(f)
|
|
390
|
+
|
|
391
|
+
# Access parameters
|
|
392
|
+
crs = config['projection']['output_crs']
|
|
393
|
+
resolution = config['data']['resolution']
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
### Performance Optimization
|
|
397
|
+
|
|
398
|
+
```python
|
|
399
|
+
# Memory profiling
|
|
400
|
+
import memory_profiler
|
|
401
|
+
|
|
402
|
+
@memory_profiler.profile
|
|
403
|
+
def process_large_dataset(data_path):
|
|
404
|
+
"""Profile memory usage."""
|
|
405
|
+
data = load_data(data_path)
|
|
406
|
+
result = process(data)
|
|
407
|
+
return result
|
|
408
|
+
|
|
409
|
+
# Vectorization vs loops
|
|
410
|
+
# BAD: Iterating rows
|
|
411
|
+
for idx, row in gdf.iterrows():
|
|
412
|
+
gdf.loc[idx, 'buffer'] = row.geometry.buffer(100)
|
|
413
|
+
|
|
414
|
+
# GOOD: Vectorized
|
|
415
|
+
gdf['buffer'] = gdf.geometry.buffer(100)
|
|
416
|
+
|
|
417
|
+
# Chunked processing
|
|
418
|
+
def process_in_chunks(gdf, func, chunk_size=1000):
|
|
419
|
+
"""Process GeoDataFrame in chunks."""
|
|
420
|
+
results = []
|
|
421
|
+
for i in range(0, len(gdf), chunk_size):
|
|
422
|
+
chunk = gdf.iloc[i:i+chunk_size]
|
|
423
|
+
result = func(chunk)
|
|
424
|
+
results.append(result)
|
|
425
|
+
return pd.concat(results)
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
For more code examples, see [code-examples.md](code-examples.md).
|