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.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
@@ -0,0 +1,462 @@
1
+ # Machine Learning for Geospatial Data
2
+
3
+ Guide to ML and deep learning applications for remote sensing and spatial analysis.
4
+
5
+ ## Traditional Machine Learning
6
+
7
+ ### Random Forest for Land Cover
8
+
9
+ ```python
10
+ from sklearn.ensemble import RandomForestClassifier
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.metrics import classification_report, confusion_matrix
13
+ import rasterio
14
+ from rasterio.features import rasterize
15
+ import geopandas as gpd
16
+ import numpy as np
17
+
18
+ def train_random_forest_classifier(raster_path, training_gdf):
19
+ """Train Random Forest for image classification."""
20
+
21
+ # Load imagery
22
+ with rasterio.open(raster_path) as src:
23
+ image = src.read()
24
+ profile = src.profile
25
+ transform = src.transform
26
+
27
+ # Extract training data
28
+ X, y = [], []
29
+
30
+ for _, row in training_gdf.iterrows():
31
+ mask = rasterize(
32
+ [(row.geometry, 1)],
33
+ out_shape=(profile['height'], profile['width']),
34
+ transform=transform,
35
+ fill=0,
36
+ dtype=np.uint8
37
+ )
38
+ pixels = image[:, mask > 0].T
39
+ X.extend(pixels)
40
+ y.extend([row['class_id']] * len(pixels))
41
+
42
+ X = np.array(X)
43
+ y = np.array(y)
44
+
45
+ # Split data
46
+ X_train, X_val, y_train, y_val = train_test_split(
47
+ X, y, test_size=0.2, random_state=42, stratify=y
48
+ )
49
+
50
+ # Train model
51
+ rf = RandomForestClassifier(
52
+ n_estimators=100,
53
+ max_depth=20,
54
+ min_samples_split=10,
55
+ min_samples_leaf=4,
56
+ class_weight='balanced',
57
+ n_jobs=-1,
58
+ random_state=42
59
+ )
60
+ rf.fit(X_train, y_train)
61
+
62
+ # Validate
63
+ y_pred = rf.predict(X_val)
64
+ print("Classification Report:")
65
+ print(classification_report(y_val, y_pred))
66
+
67
+ # Feature importance
68
+ feature_names = [f'Band_{i}' for i in range(X.shape[1])]
69
+ importances = pd.DataFrame({
70
+ 'feature': feature_names,
71
+ 'importance': rf.feature_importances_
72
+ }).sort_values('importance', ascending=False)
73
+
74
+ print("\nFeature Importance:")
75
+ print(importances)
76
+
77
+ return rf
78
+
79
+ # Classify full image
80
+ def classify_image(model, image_path, output_path):
81
+ with rasterio.open(image_path) as src:
82
+ image = src.read()
83
+ profile = src.profile
84
+
85
+ image_reshaped = image.reshape(image.shape[0], -1).T
86
+ prediction = model.predict(image_reshaped)
87
+ prediction = prediction.reshape(image.shape[1], image.shape[2])
88
+
89
+ profile.update(dtype=rasterio.uint8, count=1)
90
+ with rasterio.open(output_path, 'w', **profile) as dst:
91
+ dst.write(prediction.astype(rasterio.uint8), 1)
92
+ ```
93
+
94
+ ### Support Vector Machine
95
+
96
+ ```python
97
+ from sklearn.svm import SVC
98
+ from sklearn.preprocessing import StandardScaler
99
+
100
+ def svm_classifier(X_train, y_train):
101
+ """SVM classifier for remote sensing."""
102
+
103
+ # Scale features
104
+ scaler = StandardScaler()
105
+ X_train_scaled = scaler.fit_transform(X_train)
106
+
107
+ # Train SVM
108
+ svm = SVC(
109
+ kernel='rbf',
110
+ C=100,
111
+ gamma='scale',
112
+ class_weight='balanced',
113
+ probability=True
114
+ )
115
+ svm.fit(X_train_scaled, y_train)
116
+
117
+ return svm, scaler
118
+
119
+ # Multi-class classification
120
+ def multiclass_svm(X_train, y_train):
121
+ from sklearn.multiclass import OneVsRestClassifier
122
+
123
+ scaler = StandardScaler()
124
+ X_train_scaled = scaler.fit_transform(X_train)
125
+
126
+ svm_ovr = OneVsRestClassifier(
127
+ SVC(kernel='rbf', C=10, probability=True),
128
+ n_jobs=-1
129
+ )
130
+ svm_ovr.fit(X_train_scaled, y_train)
131
+
132
+ return svm_ovr, scaler
133
+ ```
134
+
135
+ ## Deep Learning
136
+
137
+ ### CNN with TorchGeo
138
+
139
+ ```python
140
+ import torch
141
+ import torch.nn as nn
142
+ import torchgeo.datasets as datasets
143
+ import torchgeo.models as models
144
+ from torch.utils.data import DataLoader
145
+
146
+ # Define CNN
147
+ class LandCoverCNN(nn.Module):
148
+ def __init__(self, in_channels=12, num_classes=10):
149
+ super().__init__()
150
+ self.encoder = nn.Sequential(
151
+ nn.Conv2d(in_channels, 64, 3, padding=1),
152
+ nn.BatchNorm2d(64),
153
+ nn.ReLU(),
154
+ nn.MaxPool2d(2),
155
+
156
+ nn.Conv2d(64, 128, 3, padding=1),
157
+ nn.BatchNorm2d(128),
158
+ nn.ReLU(),
159
+ nn.MaxPool2d(2),
160
+
161
+ nn.Conv2d(128, 256, 3, padding=1),
162
+ nn.BatchNorm2d(256),
163
+ nn.ReLU(),
164
+ nn.MaxPool2d(2),
165
+ )
166
+
167
+ self.decoder = nn.Sequential(
168
+ nn.ConvTranspose2d(256, 128, 2, stride=2),
169
+ nn.BatchNorm2d(128),
170
+ nn.ReLU(),
171
+
172
+ nn.ConvTranspose2d(128, 64, 2, stride=2),
173
+ nn.BatchNorm2d(64),
174
+ nn.ReLU(),
175
+
176
+ nn.ConvTranspose2d(64, num_classes, 2, stride=2),
177
+ )
178
+
179
+ def forward(self, x):
180
+ x = self.encoder(x)
181
+ x = self.decoder(x)
182
+ return x
183
+
184
+ # Training
185
+ def train_model(train_loader, val_loader, num_epochs=50):
186
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
187
+ model = LandCoverCNN().to(device)
188
+
189
+ criterion = nn.CrossEntropyLoss()
190
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
191
+
192
+ for epoch in range(num_epochs):
193
+ model.train()
194
+ train_loss = 0
195
+
196
+ for images, labels in train_loader:
197
+ images, labels = images.to(device), labels.to(device)
198
+
199
+ optimizer.zero_grad()
200
+ outputs = model(images)
201
+ loss = criterion(outputs, labels)
202
+ loss.backward()
203
+ optimizer.step()
204
+
205
+ train_loss += loss.item()
206
+
207
+ # Validation
208
+ model.eval()
209
+ val_loss = 0
210
+ with torch.no_grad():
211
+ for images, labels in val_loader:
212
+ images, labels = images.to(device), labels.to(device)
213
+ outputs = model(images)
214
+ loss = criterion(outputs, labels)
215
+ val_loss += loss.item()
216
+
217
+ print(f'Epoch {epoch+1}/{num_epochs}, Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')
218
+
219
+ return model
220
+ ```
221
+
222
+ ### U-Net for Semantic Segmentation
223
+
224
+ ```python
225
+ class UNet(nn.Module):
226
+ def __init__(self, in_channels=4, num_classes=5):
227
+ super().__init__()
228
+
229
+ # Encoder
230
+ self.enc1 = self.conv_block(in_channels, 64)
231
+ self.enc2 = self.conv_block(64, 128)
232
+ self.enc3 = self.conv_block(128, 256)
233
+ self.enc4 = self.conv_block(256, 512)
234
+
235
+ # Bottleneck
236
+ self.bottleneck = self.conv_block(512, 1024)
237
+
238
+ # Decoder
239
+ self.up1 = nn.ConvTranspose2d(1024, 512, 2, stride=2)
240
+ self.dec1 = self.conv_block(1024, 512)
241
+
242
+ self.up2 = nn.ConvTranspose2d(512, 256, 2, stride=2)
243
+ self.dec2 = self.conv_block(512, 256)
244
+
245
+ self.up3 = nn.ConvTranspose2d(256, 128, 2, stride=2)
246
+ self.dec3 = self.conv_block(256, 128)
247
+
248
+ self.up4 = nn.ConvTranspose2d(128, 64, 2, stride=2)
249
+ self.dec4 = self.conv_block(128, 64)
250
+
251
+ # Final layer
252
+ self.final = nn.Conv2d(64, num_classes, 1)
253
+
254
+ def conv_block(self, in_ch, out_ch):
255
+ return nn.Sequential(
256
+ nn.Conv2d(in_ch, out_ch, 3, padding=1),
257
+ nn.BatchNorm2d(out_ch),
258
+ nn.ReLU(inplace=True),
259
+ nn.Conv2d(out_ch, out_ch, 3, padding=1),
260
+ nn.BatchNorm2d(out_ch),
261
+ nn.ReLU(inplace=True)
262
+ )
263
+
264
+ def forward(self, x):
265
+ # Encoder
266
+ e1 = self.enc1(x)
267
+ e2 = self.enc2(F.max_pool2d(e1, 2))
268
+ e3 = self.enc3(F.max_pool2d(e2, 2))
269
+ e4 = self.enc4(F.max_pool2d(e3, 2))
270
+
271
+ # Bottleneck
272
+ b = self.bottleneck(F.max_pool2d(e4, 2))
273
+
274
+ # Decoder with skip connections
275
+ d1 = self.dec1(torch.cat([self.up1(b), e4], dim=1))
276
+ d2 = self.dec2(torch.cat([self.up2(d1), e3], dim=1))
277
+ d3 = self.dec3(torch.cat([self.up3(d2), e2], dim=1))
278
+ d4 = self.dec4(torch.cat([self.up4(d3), e1], dim=1))
279
+
280
+ return self.final(d4)
281
+ ```
282
+
283
+ ### Change Detection with Siamese Network
284
+
285
+ ```python
286
+ class SiameseNetwork(nn.Module):
287
+ """Siamese network for change detection."""
288
+
289
+ def __init__(self):
290
+ super().__init__()
291
+ self.feature_extractor = nn.Sequential(
292
+ nn.Conv2d(3, 32, 3, padding=1),
293
+ nn.BatchNorm2d(32),
294
+ nn.ReLU(),
295
+ nn.MaxPool2d(2),
296
+
297
+ nn.Conv2d(32, 64, 3, padding=1),
298
+ nn.BatchNorm2d(64),
299
+ nn.ReLU(),
300
+ nn.MaxPool2d(2),
301
+
302
+ nn.Conv2d(64, 128, 3, padding=1),
303
+ nn.BatchNorm2d(128),
304
+ nn.ReLU(),
305
+ )
306
+
307
+ self.classifier = nn.Sequential(
308
+ nn.Conv2d(256, 128, 3, padding=1),
309
+ nn.ReLU(),
310
+ nn.Conv2d(128, 64, 3, padding=1),
311
+ nn.ReLU(),
312
+ nn.Conv2d(64, 2, 1), # Binary: change / no change
313
+ )
314
+
315
+ def forward(self, x1, x2):
316
+ f1 = self.feature_extractor(x1)
317
+ f2 = self.feature_extractor(x2)
318
+
319
+ # Concatenate features
320
+ diff = torch.abs(f1 - f2)
321
+ combined = torch.cat([f1, f2, diff], dim=1)
322
+
323
+ return self.classifier(combined)
324
+ ```
325
+
326
+ ## Graph Neural Networks
327
+
328
+ ### PyTorch Geometric for Spatial Data
329
+
330
+ ```python
331
+ import torch
332
+ from torch_geometric.data import Data
333
+ from torch_geometric.nn import GCNConv
334
+
335
+ # Create spatial graph
336
+ def create_spatial_graph(points_gdf, k_neighbors=5):
337
+ """Create graph from point data using k-NN."""
338
+
339
+ from sklearn.neighbors import NearestNeighbors
340
+
341
+ coords = np.array([[p.x, p.y] for p in points_gdf.geometry])
342
+
343
+ # Find k-nearest neighbors
344
+ nbrs = NearestNeighbors(n_neighbors=k_neighbors).fit(coords)
345
+ distances, indices = nbrs.kneighbors(coords)
346
+
347
+ # Create edge index
348
+ edge_index = []
349
+ for i, neighbors in enumerate(indices):
350
+ for j in neighbors:
351
+ edge_index.append([i, j])
352
+
353
+ edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous()
354
+
355
+ # Node features
356
+ features = points_gdf.drop('geometry', axis=1).values
357
+ x = torch.tensor(features, dtype=torch.float)
358
+
359
+ return Data(x=x, edge_index=edge_index)
360
+
361
+ # GCN for spatial prediction
362
+ class SpatialGCN(torch.nn.Module):
363
+ def __init__(self, num_features, hidden_channels=64):
364
+ super().__init__()
365
+ self.conv1 = GCNConv(num_features, hidden_channels)
366
+ self.conv2 = GCNConv(hidden_channels, hidden_channels)
367
+ self.conv3 = GCNConv(hidden_channels, 1)
368
+
369
+ def forward(self, data):
370
+ x, edge_index = data.x, data.edge_index
371
+ x = self.conv1(x, edge_index).relu()
372
+ x = F.dropout(x, p=0.5, training=self.training)
373
+ x = self.conv2(x, edge_index).relu()
374
+ x = self.conv3(x, edge_index)
375
+ return x
376
+ ```
377
+
378
+ ## Explainable AI (XAI) for Geospatial
379
+
380
+ ### SHAP for Model Interpretation
381
+
382
+ ```python
383
+ import shap
384
+ import numpy as np
385
+
386
+ def explain_model(model, X, feature_names):
387
+ """Explain model predictions using SHAP."""
388
+
389
+ # Create explainer
390
+ explainer = shap.Explainer(model, X)
391
+
392
+ # Calculate SHAP values
393
+ shap_values = explainer(X)
394
+
395
+ # Summary plot
396
+ shap.summary_plot(shap_values, X, feature_names=feature_names)
397
+
398
+ # Dependence plot for important features
399
+ for i in range(X.shape[1]):
400
+ shap.dependence_plot(i, shap_values, X, feature_names=feature_names)
401
+
402
+ return shap_values
403
+
404
+ # Spatial SHAP (accounting for spatial autocorrelation)
405
+ def spatial_shap(model, X, coordinates):
406
+ """Spatial explanation considering neighborhood effects."""
407
+
408
+ # Compute SHAP values
409
+ explainer = shap.Explainer(model, X)
410
+ shap_values = explainer(X)
411
+
412
+ # Spatial aggregation
413
+ shap_spatial = {}
414
+ for i, coord in enumerate(coordinates):
415
+ # Find neighbors
416
+ neighbors = find_neighbors(coord, coordinates, radius=1000)
417
+
418
+ # Aggregate SHAP values for neighborhood
419
+ neighbor_shap = shap_values.values[neighbors]
420
+ shap_spatial[i] = np.mean(neighbor_shap, axis=0)
421
+
422
+ return shap_spatial
423
+ ```
424
+
425
+ ### Attention Maps for CNNs
426
+
427
+ ```python
428
+ import cv2
429
+ import torch
430
+ import torch.nn.functional as F
431
+
432
+ def generate_attention_map(model, image_tensor, target_layer):
433
+ """Generate attention map using Grad-CAM."""
434
+
435
+ # Forward pass
436
+ model.eval()
437
+ output = model(image_tensor)
438
+
439
+ # Backward pass
440
+ model.zero_grad()
441
+ output[0, torch.argmax(output)].backward()
442
+
443
+ # Get gradients
444
+ gradients = model.get_gradient(target_layer)
445
+
446
+ # Global average pooling
447
+ weights = torch.mean(gradients, axis=(2, 3), keepdim=True)
448
+
449
+ # Weighted combination of activation maps
450
+ activations = model.get_activation(target_layer)
451
+ attention = torch.sum(weights * activations, axis=1, keepdim=True)
452
+
453
+ # ReLU and normalize
454
+ attention = F.relu(attention)
455
+ attention = F.interpolate(attention, size=image_tensor.shape[2:],
456
+ mode='bilinear', align_corners=False)
457
+ attention = (attention - attention.min()) / (attention.max() - attention.min())
458
+
459
+ return attention.squeeze().cpu().numpy()
460
+ ```
461
+
462
+ For more ML examples, see [code-examples.md](code-examples.md).