0
# AI and Machine Learning
1
2
AI-powered features including the Genie assistant widget, machine learning utilities for Earth Engine classifiers, and advanced data analysis capabilities with precomputed embeddings and semantic search.
3
4
## Capabilities
5
6
### Genie AI Assistant
7
8
Interactive AI assistant widget for Earth Engine code generation and geospatial analysis guidance.
9
10
```python { .api }
11
class Genie:
12
"""AI assistant widget for Earth Engine and geospatial analysis."""
13
14
def __init__(
15
self,
16
project: Optional[str] = None,
17
google_api_key: Optional[str] = None,
18
gemini_model: str = "gemini-1.5-flash",
19
target_score: float = 0.8,
20
widget_height: str = "600px",
21
initialize_ee: bool = True,
22
**kwargs
23
) -> None:
24
"""
25
Initialize Genie AI assistant.
26
27
Args:
28
project: Google Cloud project ID
29
google_api_key: Google API key for authentication
30
gemini_model: Gemini model to use for AI assistance
31
target_score: Target confidence score for responses
32
widget_height: Height of the widget UI
33
initialize_ee: Whether to initialize Earth Engine
34
**kwargs: Additional configuration parameters
35
"""
36
```
37
38
### Earth Engine Classifier Utilities
39
40
Tools for creating, training, and deploying machine learning classifiers using Earth Engine.
41
42
```python { .api }
43
def fc_to_classifier(
44
features: ee.FeatureCollection,
45
classifier: str = "RandomForest",
46
mode: str = "classification",
47
**kwargs
48
) -> ee.Classifier:
49
"""
50
Convert feature collection to Earth Engine classifier.
51
52
Args:
53
features: Training feature collection
54
classifier: Classifier type ('RandomForest', 'SVM', 'NaiveBayes', 'DecisionTree')
55
mode: Classification mode ('classification' or 'regression')
56
**kwargs: Additional classifier parameters
57
58
Returns:
59
Trained Earth Engine classifier
60
"""
61
62
def strings_to_classifier(
63
strings: List[str],
64
classifier_type: str = "RandomForest",
65
**kwargs
66
) -> ee.Classifier:
67
"""
68
Convert decision tree strings to Earth Engine classifier.
69
70
Args:
71
strings: List of decision tree string representations
72
classifier_type: Type of classifier to create
73
**kwargs: Additional parameters
74
75
Returns:
76
Earth Engine classifier object
77
"""
78
79
def export_trees_to_fc(
80
classifier: ee.Classifier,
81
features: ee.FeatureCollection,
82
**kwargs
83
) -> ee.FeatureCollection:
84
"""
85
Export decision trees to feature collection.
86
87
Args:
88
classifier: Trained classifier
89
features: Feature collection to export trees for
90
**kwargs: Additional export parameters
91
92
Returns:
93
Feature collection containing tree representations
94
"""
95
```
96
97
### Decision Tree Processing
98
99
Utilities for processing and converting decision tree models between different formats.
100
101
```python { .api }
102
def tree_to_string(tree, **kwargs) -> str:
103
"""
104
Convert decision tree to string representation.
105
106
Args:
107
tree: Decision tree object
108
**kwargs: Conversion parameters
109
110
Returns:
111
String representation of decision tree
112
"""
113
114
def rf_to_strings(
115
random_forest,
116
**kwargs
117
) -> List[str]:
118
"""
119
Convert random forest to list of tree strings.
120
121
Args:
122
random_forest: Random forest model
123
**kwargs: Conversion parameters
124
125
Returns:
126
List of decision tree strings
127
"""
128
129
def trees_to_csv(
130
trees: List[str],
131
output_path: str,
132
**kwargs
133
) -> None:
134
"""
135
Export decision trees to CSV file.
136
137
Args:
138
trees: List of tree string representations
139
output_path: Output CSV file path
140
**kwargs: Export parameters
141
"""
142
143
def csv_to_classifier(
144
csv_path: str,
145
classifier_type: str = "RandomForest",
146
**kwargs
147
) -> ee.Classifier:
148
"""
149
Import classifier from CSV file.
150
151
Args:
152
csv_path: Path to CSV file containing tree data
153
classifier_type: Type of classifier to create
154
**kwargs: Additional parameters
155
156
Returns:
157
Earth Engine classifier
158
"""
159
```
160
161
### Earth Engine Data Catalog Integration
162
163
AI-powered tools for searching and discovering Earth Engine datasets with semantic capabilities.
164
165
```python { .api }
166
class Catalog:
167
"""Earth Engine data catalog with AI-powered search."""
168
169
def __init__(self, **kwargs) -> None:
170
"""Initialize catalog interface."""
171
172
def search(
173
self,
174
keywords: str = None,
175
spatial_filter: ee.Geometry = None,
176
temporal_filter: List[str] = None,
177
**kwargs
178
) -> List[Dict]:
179
"""
180
Search Earth Engine catalog with AI assistance.
181
182
Args:
183
keywords: Search keywords or natural language query
184
spatial_filter: Geographic area of interest
185
temporal_filter: Date range [start_date, end_date]
186
**kwargs: Additional search parameters
187
188
Returns:
189
List of matching dataset information
190
"""
191
192
class Collection:
193
"""Earth Engine collection wrapper with AI capabilities."""
194
195
def __init__(self, collection_id: str, **kwargs) -> None:
196
"""
197
Initialize collection wrapper.
198
199
Args:
200
collection_id: Earth Engine collection ID
201
**kwargs: Additional parameters
202
"""
203
204
class CollectionList:
205
"""List of Earth Engine collections with search capabilities."""
206
207
def __init__(self, collections: List[Collection] = None, **kwargs) -> None:
208
"""
209
Initialize collection list.
210
211
Args:
212
collections: List of collection objects
213
**kwargs: Additional parameters
214
"""
215
```
216
217
### Precomputed Embeddings
218
219
Manage and utilize precomputed embeddings for semantic search and analysis.
220
221
```python { .api }
222
class PrecomputedEmbeddings:
223
"""Precomputed embeddings for semantic search."""
224
225
def __init__(
226
self,
227
embeddings_path: str = None,
228
**kwargs
229
) -> None:
230
"""
231
Initialize precomputed embeddings.
232
233
Args:
234
embeddings_path: Path to embeddings file
235
**kwargs: Additional parameters
236
"""
237
238
def search(
239
self,
240
query: str,
241
top_k: int = 10,
242
**kwargs
243
) -> List[Dict]:
244
"""
245
Search using semantic embeddings.
246
247
Args:
248
query: Search query text
249
top_k: Number of top results to return
250
**kwargs: Additional search parameters
251
252
Returns:
253
List of semantically similar results
254
"""
255
```
256
257
### Bounding Box and Geometry
258
259
AI-enhanced geometry processing and bounding box operations.
260
261
```python { .api }
262
class BBox:
263
"""Bounding box representation with AI utilities."""
264
265
def __init__(
266
self,
267
bounds: List[float] = None,
268
crs: str = "EPSG:4326",
269
**kwargs
270
) -> None:
271
"""
272
Initialize bounding box.
273
274
Args:
275
bounds: Bounding box coordinates [minx, miny, maxx, maxy]
276
crs: Coordinate reference system
277
**kwargs: Additional parameters
278
"""
279
280
def to_ee_geometry(self) -> ee.Geometry:
281
"""
282
Convert bounding box to Earth Engine geometry.
283
284
Returns:
285
Earth Engine geometry object
286
"""
287
```
288
289
### Code Execution and Analysis
290
291
Execute and analyze Earth Engine code with AI assistance.
292
293
```python { .api }
294
def run_ee_code(
295
code: str,
296
show_map: bool = True,
297
**kwargs
298
) -> Any:
299
"""
300
Execute Earth Engine code with AI assistance.
301
302
Args:
303
code: Earth Engine Python code to execute
304
show_map: Whether to display map if created
305
**kwargs: Additional execution parameters
306
307
Returns:
308
Execution result
309
"""
310
311
def make_langchain_index(
312
docs: List[str],
313
index_name: str = "geemap_index",
314
**kwargs
315
) -> Any:
316
"""
317
Create LangChain index for document search.
318
319
Args:
320
docs: List of documents to index
321
index_name: Name for the index
322
**kwargs: Index configuration parameters
323
324
Returns:
325
LangChain index object
326
"""
327
```
328
329
### Utility Functions
330
331
Helper functions for AI and machine learning workflows.
332
333
```python { .api }
334
def matches_interval(
335
value: float,
336
interval: List[float],
337
**kwargs
338
) -> bool:
339
"""
340
Check if value matches specified interval.
341
342
Args:
343
value: Value to check
344
interval: Interval bounds [min, max]
345
**kwargs: Additional parameters
346
347
Returns:
348
True if value is within interval
349
"""
350
351
def matches_datetime(
352
date_str: str,
353
pattern: str,
354
**kwargs
355
) -> bool:
356
"""
357
Check if datetime string matches pattern.
358
359
Args:
360
date_str: Date string to check
361
pattern: Date pattern to match
362
**kwargs: Additional parameters
363
364
Returns:
365
True if date matches pattern
366
"""
367
```
368
369
## Usage Examples
370
371
### Genie AI Assistant
372
373
```python
374
import geemap
375
376
# Create Genie AI assistant
377
genie = geemap.Genie()
378
379
# Display the assistant widget
380
genie
381
382
# The Genie widget provides:
383
# - Natural language to Earth Engine code conversion
384
# - Interactive guidance for geospatial analysis
385
# - Code suggestions and optimization
386
# - Help with Earth Engine API usage
387
```
388
389
### Machine Learning Classification
390
391
```python
392
import ee
393
394
# Initialize Earth Engine
395
ee.Initialize()
396
397
# Prepare training data
398
training_points = ee.FeatureCollection('projects/google/ml_training_data')
399
400
# Create and train classifier
401
classifier = geemap.fc_to_classifier(
402
training_points,
403
classifier='RandomForest',
404
mode='classification'
405
)
406
407
# Apply classifier to image
408
image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318')
409
classified = image.classify(classifier)
410
411
# Display results
412
m = geemap.Map()
413
m.addLayer(classified, {'min': 0, 'max': 3, 'palette': ['red', 'green', 'blue', 'yellow']}, 'Classified')
414
m
415
```
416
417
### Decision Tree Export and Import
418
419
```python
420
# Export trained classifier trees
421
trees_fc = geemap.export_trees_to_fc(classifier, training_points)
422
423
# Convert trees to strings
424
tree_strings = geemap.rf_to_strings(classifier)
425
426
# Export to CSV
427
geemap.trees_to_csv(tree_strings, 'classifier_trees.csv')
428
429
# Import classifier from CSV
430
imported_classifier = geemap.csv_to_classifier('classifier_trees.csv')
431
```
432
433
### AI-Powered Dataset Search
434
435
```python
436
# Create catalog interface
437
catalog = geemap.Catalog()
438
439
# Search with natural language
440
results = catalog.search(
441
keywords="high resolution satellite imagery of forests",
442
spatial_filter=ee.Geometry.Rectangle([-120, 35, -115, 40]),
443
temporal_filter=['2020-01-01', '2020-12-31']
444
)
445
446
# Display results
447
for result in results[:5]:
448
print(f"Dataset: {result['title']}")
449
print(f"Description: {result['description']}")
450
print(f"ID: {result['id']}")
451
print("---")
452
```
453
454
### Semantic Search with Embeddings
455
456
```python
457
# Initialize precomputed embeddings
458
embeddings = geemap.PrecomputedEmbeddings('path/to/embeddings.pkl')
459
460
# Perform semantic search
461
results = embeddings.search(
462
query="forest loss detection using machine learning",
463
top_k=5
464
)
465
466
# Process results
467
for result in results:
468
print(f"Similarity: {result['score']:.3f}")
469
print(f"Content: {result['text']}")
470
print("---")
471
```
472
473
### Code Execution with AI
474
475
```python
476
# Execute Earth Engine code with assistance
477
ee_code = """
478
var image = ee.Image('MODIS/006/MOD13A2/2020_01_01');
479
var ndvi = image.select('NDVI');
480
Map.addLayer(ndvi, {min: 0, max: 9000, palette: ['red', 'yellow', 'green']}, 'NDVI');
481
"""
482
483
result = geemap.run_ee_code(ee_code, show_map=True)
484
```
485
486
### LangChain Integration
487
488
```python
489
# Create document index for search
490
documents = [
491
"Earth Engine provides access to satellite imagery",
492
"MODIS data is useful for vegetation monitoring",
493
"Landsat offers medium resolution multispectral data"
494
]
495
496
index = geemap.make_langchain_index(
497
documents,
498
index_name="earth_engine_docs"
499
)
500
501
# Use index for question answering
502
# (Additional LangChain code would go here)
503
```
504
505
### Bounding Box Operations
506
507
```python
508
# Create bounding box
509
bbox = geemap.BBox(bounds=[-122, 37, -121, 38])
510
511
# Convert to Earth Engine geometry
512
ee_geom = bbox.to_ee_geometry()
513
514
# Use in Earth Engine operations
515
image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318')
516
clipped = image.clip(ee_geom)
517
```
518
519
## Types
520
521
```python { .api }
522
# Classifier types
523
ClassifierType = Literal["RandomForest", "SVM", "NaiveBayes", "DecisionTree"]
524
525
# Classification mode
526
ClassificationMode = Literal["classification", "regression"]
527
528
# Search results
529
SearchResult = Dict[str, Union[str, float, List]]
530
531
# Embedding vector
532
Embedding = List[float]
533
534
# Date interval
535
DateInterval = List[str] # [start_date, end_date]
536
537
# Bounding box coordinates
538
BoundsCoords = List[float] # [minx, miny, maxx, maxy]
539
540
# Tree representation
541
TreeString = str
542
543
# AI query response
544
AIResponse = Dict[str, Any]
545
```