ipygee 0.1.0__py3-none-any.whl

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.
ipygee/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """A set of tools for working with Google Earth Engine Python API in Jupyter notebooks."""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "Rodrigo Principe"
5
+ __email__ = "fitoprincipe82@gmail.com"
ipygee/map.py ADDED
@@ -0,0 +1,484 @@
1
+ """Display an interactive Map for Google Earth Engine using ipyleaflet."""
2
+
3
+ import re
4
+ from collections import OrderedDict
5
+ from copy import copy
6
+
7
+ import ee
8
+ import ipyleaflet
9
+ from IPython.display import Javascript, display
10
+ from ipywidgets import Layout
11
+ from traitlets import Dict, Int, observe
12
+
13
+ from .maptools import getBounds, getImageTile, getZoom, inverseCoordinates
14
+
15
+ ZOOM_SCALES = {
16
+ 0: 156543,
17
+ 1: 78271,
18
+ 2: 39135,
19
+ 3: 19567,
20
+ 4: 9783,
21
+ 5: 4891,
22
+ 6: 2445,
23
+ 7: 1222,
24
+ 8: 611,
25
+ 9: 305,
26
+ 10: 152,
27
+ 11: 76,
28
+ 12: 38,
29
+ 13: 19,
30
+ 14: 9,
31
+ 15: 5,
32
+ 16: 2,
33
+ 17: 1,
34
+ 18: 0.5,
35
+ 19: 0.3,
36
+ 20: 0.15,
37
+ 21: 0.07,
38
+ 22: 0.03,
39
+ }
40
+
41
+
42
+ class _LayersControlWithDelay(ipyleaflet.LayersControl):
43
+ """LayersControl extension exposing Leaflet's collapseDelay option."""
44
+
45
+ collapseDelay = Int(0).tag(sync=True, o=True)
46
+
47
+
48
+ class Map(ipyleaflet.Map):
49
+ """Interactive Map for Google Earth Engine using ipyleaflet."""
50
+
51
+ EELayers = Dict(default_value=OrderedDict())
52
+
53
+ def __init__(
54
+ self,
55
+ center: list | tuple = (0, 0),
56
+ zoom: int = 2,
57
+ scroll_wheel_zoom: bool = True,
58
+ max_zoom: int = 22,
59
+ width: str | None = None,
60
+ height: str | None = None,
61
+ ):
62
+ """Initialize the interactive map."""
63
+ # Change defaults
64
+ super(Map, self).__init__(
65
+ center=center, zoom=zoom, scroll_wheel_zoom=scroll_wheel_zoom, max_zoom=max_zoom
66
+ )
67
+ self.is_shown = False
68
+
69
+ # Width and Height
70
+ self.width = width
71
+ self.height = height
72
+ self.setDimensions(self.width, self.height)
73
+
74
+ # create EELayers
75
+ self.EELayers = OrderedDict()
76
+
77
+ def _add_EELayer(self, name: str, data: dict):
78
+ """Add a pair of name, data to EELayers.
79
+
80
+ Data must be:
81
+
82
+ - type: str
83
+ - object: ee object
84
+ - visParams: dict
85
+ - layer: ipyleaflet layer
86
+ """
87
+ copyEELayers = copy(self.EELayers)
88
+ copyEELayers[name] = data
89
+ self.EELayers = copyEELayers
90
+
91
+ def _remove_EELayer(self, name: str):
92
+ """Remove layer from EELayers."""
93
+ copyEELayers = copy(self.EELayers)
94
+ if name in copyEELayers:
95
+ copyEELayers.pop(name)
96
+ self.EELayers = copyEELayers
97
+
98
+ def addBasemap(self, name: str, url: str, **kwargs):
99
+ """Add a basemap with the given URL.
100
+
101
+ Args:
102
+ name (str): The name of the basemap.
103
+ url (str): The URL template for the basemap tiles.
104
+ **kwargs: Additional keyword arguments to pass to the TileLayer.
105
+ """
106
+ layer = ipyleaflet.TileLayer(url=url, name=name, base=True, **kwargs)
107
+ self.add_layer(layer)
108
+
109
+ def setDimensions(
110
+ self,
111
+ width: int | float | str | None = None,
112
+ height: int | float | str | None = None,
113
+ ):
114
+ """Set the dimensions for the map.
115
+
116
+ Args:
117
+ width (int | None): The width of the map. Can be an integer (pixels) or a string with units.
118
+ height (int | None): The height of the map. Can be an integer (pixels) or a string with units.
119
+ """
120
+
121
+ def check(value: int | float | str | None, t: str) -> str | None:
122
+ if value is None:
123
+ return value
124
+ if isinstance(value, (int, float)):
125
+ return "{}px".format(value)
126
+ elif isinstance(value, (str,)):
127
+ search = re.search(r"(\d+)", value)
128
+ if search is None:
129
+ return None
130
+ intvalue = search.group(1)
131
+ units = value.split(intvalue)[1]
132
+ if units == "%":
133
+ if t == "width":
134
+ return "{}%".format(intvalue)
135
+ else:
136
+ return None
137
+ else:
138
+ return "{}px".format(intvalue)
139
+ else:
140
+ msg = "parameter {} of setDimensions must be int or str"
141
+ raise ValueError(msg.format(t))
142
+
143
+ self.layout = Layout(width=check(width, "width"), height=check(height, "height"))
144
+
145
+ def moveLayer(self, layer_name: str, position: int):
146
+ """Move one step up a layer.
147
+
148
+ Args:
149
+ layer_name (str): The name of the layer to move.
150
+ position (int): The new position index for the layer.
151
+ """
152
+ names = list(self.EELayers.keys())
153
+ values = list(self.EELayers.values())
154
+
155
+ if position < 0 or position >= len(names):
156
+ return
157
+
158
+ if layer_name in names: # if layer exists
159
+ # index and value of layer to move_layer
160
+ actual_index = names.index(layer_name)
161
+ iname_before = names[position]
162
+ ival_before = values[position]
163
+ # Change order
164
+ # set layer and value in the new index
165
+ names[position] = layer_name
166
+ values[position] = values[actual_index]
167
+ # set replaced layer and its value in the index of moving layer
168
+ names[actual_index] = iname_before
169
+ values[actual_index] = ival_before
170
+ newlayers = OrderedDict(zip(names, values))
171
+ self.EELayers = newlayers
172
+
173
+ @observe("EELayers")
174
+ def _ob_EELayers(self, change: dict):
175
+ new = change["new"]
176
+ proxy_layers = [
177
+ layer for layer in getattr(self, "layers", ()) if getattr(layer, "base", False)
178
+ ]
179
+
180
+ for val in new.values():
181
+ layer = val["layer"]
182
+ proxy_layers.append(layer)
183
+
184
+ self.layers = tuple(proxy_layers)
185
+
186
+ @property
187
+ def addedImages(self):
188
+ """Return a list of added image layers."""
189
+ return [self.EELayers[key] for key, val in self.EELayers.items() if val["type"] == "Image"]
190
+
191
+ @property
192
+ def addedGeometries(self):
193
+ """Return a list of added geometry layers."""
194
+ return [
195
+ self.EELayers[key] for key, val in self.EELayers.items() if val["type"] == "Geometry"
196
+ ]
197
+
198
+ def show(
199
+ self,
200
+ layers_control: bool = True,
201
+ fullscreen: bool = True,
202
+ layers_collapse_delay_ms: int | None = None,
203
+ ):
204
+ """Show the Map on the Notebook.
205
+
206
+ Args:
207
+ layers_control (bool): Whether to show the layer control.
208
+ fullscreen (bool): Whether to show the fullscreen control.
209
+ layers_collapse_delay_ms (int | None): Delay before collapsing the layers control when collapsed=True.
210
+ """
211
+ delay_ms = max(0, int(layers_collapse_delay_ms or 0))
212
+ if not self.is_shown:
213
+ if layers_control:
214
+ if delay_ms > 0:
215
+ lc = _LayersControlWithDelay(collapsed=True, collapseDelay=delay_ms)
216
+ else:
217
+ lc = ipyleaflet.LayersControl(collapsed=True)
218
+ self.add_control(lc)
219
+ if fullscreen:
220
+ # Control
221
+ full_control = ipyleaflet.FullScreenControl()
222
+ self.add_control(full_control)
223
+
224
+ self.is_shown = True
225
+ # Start with crosshair cursor
226
+ self.default_style = {"cursor": "crosshair"}
227
+ display(self)
228
+ if delay_ms > 0:
229
+ self._apply_layers_delay_fallback(delay_ms)
230
+
231
+ def _apply_layers_delay_fallback(self, delay_ms: int) -> None:
232
+ """Fallback for frontends where Leaflet does not support collapseDelay."""
233
+ script = (
234
+ """
235
+ (function(delayMs) {
236
+ if (window.L && window.L.Control && window.L.Control.Layers) {
237
+ var options = window.L.Control.Layers.prototype.options || {};
238
+ if (Object.prototype.hasOwnProperty.call(options, "collapseDelay")) {
239
+ return;
240
+ }
241
+ }
242
+
243
+ var patch = function(controlEl) {
244
+ if (!controlEl || controlEl.__ipygeeDelayPatched) {
245
+ return;
246
+ }
247
+ controlEl.__ipygeeDelayPatched = true;
248
+ var timeoutId = null;
249
+
250
+ controlEl.addEventListener("mouseenter", function() {
251
+ if (timeoutId) {
252
+ clearTimeout(timeoutId);
253
+ timeoutId = null;
254
+ }
255
+ controlEl.classList.add("leaflet-control-layers-expanded");
256
+ }, true);
257
+
258
+ controlEl.addEventListener("mouseleave", function(event) {
259
+ event.stopImmediatePropagation();
260
+ if (timeoutId) {
261
+ clearTimeout(timeoutId);
262
+ }
263
+ timeoutId = window.setTimeout(function() {
264
+ controlEl.classList.remove("leaflet-control-layers-expanded");
265
+ }, delayMs);
266
+ }, true);
267
+ };
268
+
269
+ var controls = document.querySelectorAll(".leaflet-control-layers");
270
+ controls.forEach(patch);
271
+
272
+ var observer = new MutationObserver(function() {
273
+ document.querySelectorAll(".leaflet-control-layers").forEach(patch);
274
+ });
275
+ observer.observe(document.body, { childList: true, subtree: true });
276
+ window.setTimeout(function() {
277
+ observer.disconnect();
278
+ }, 5000);
279
+ })(%d);
280
+ """
281
+ % delay_ms
282
+ )
283
+ display(Javascript(script))
284
+
285
+ def addImage(
286
+ self,
287
+ image: ee.Image,
288
+ visParams: dict | None = None,
289
+ name: str | None = None,
290
+ show: bool = True,
291
+ opacity: float | None = None,
292
+ replace: bool = True,
293
+ ) -> dict:
294
+ """Add an ee.Image to the Map.
295
+
296
+ Args:
297
+ image (ee.Image): Image to add to Map.
298
+ visParams (dict, optional): Visualization parameters. Can have the
299
+ following arguments: bands, min, max.
300
+ name (str, optional): Name for the layer.
301
+ show (bool, optional): Whether to show the layer immediately.
302
+ opacity (float, optional): Opacity of the layer.
303
+ replace (bool, optional): Whether to replace the layer if it already exists.
304
+
305
+ Returns:
306
+ dict: A dictionary containing information about the added layer, including its type, object, visualization parameters, and the ipyleaflet layer object.
307
+ """
308
+ # Check if layer exists
309
+ if name is not None and name in self.EELayers.keys():
310
+ if not replace:
311
+ existing = self.getLayer(name)
312
+ if existing is None:
313
+ raise KeyError(name)
314
+ return existing
315
+ else:
316
+ # Remove Layer
317
+ self.removeLayer(name)
318
+
319
+ # Get URL, attribution & vis params
320
+ params = getImageTile(image, visParams or {}, show, opacity)
321
+
322
+ layer = ipyleaflet.TileLayer(
323
+ url=params["url"], attribution=params["attribution"], name=name
324
+ )
325
+
326
+ EELayer = {
327
+ "type": "Image",
328
+ "object": image,
329
+ "visParams": params["visParams"],
330
+ "layer": layer,
331
+ }
332
+ return EELayer
333
+
334
+ def addLayer(
335
+ self,
336
+ eeObject,
337
+ visParams: dict | None = None,
338
+ name: str | None = None,
339
+ show: bool = True,
340
+ opacity: float | None = None,
341
+ replace=True,
342
+ ):
343
+ """Adds a given EE object to the map as a layer.
344
+
345
+ :param eeObject: Earth Engine object to add to map
346
+ :type eeObject: ee.Image || ee.Geometry || ee.Feature
347
+ :param replace: if True, if there is a layer with the same name, this
348
+ replace that layer.
349
+ :type replace: bool
350
+
351
+ For ee.Image and ee.ImageCollection see `addImage`
352
+ for ee.Geometry and ee.Feature see `addGeometry`
353
+ """
354
+ if name in self.EELayers.keys():
355
+ return None
356
+
357
+ visParams = visParams if visParams else {}
358
+
359
+ # CASE: ee.Image
360
+ if isinstance(eeObject, ee.Image):
361
+ image_name = name if name else "Image {}".format(self.addedImages)
362
+ EELayer = self.addImage(
363
+ eeObject,
364
+ visParams=visParams,
365
+ name=image_name,
366
+ show=show,
367
+ opacity=opacity,
368
+ replace=replace,
369
+ )
370
+
371
+ self._add_EELayer(image_name, EELayer)
372
+
373
+ def removeLayer(self, name: str) -> None:
374
+ """Remove a layer by its name."""
375
+ if name in self.EELayers.keys():
376
+ self._remove_EELayer(name)
377
+ else:
378
+ print("Layer {} is not present in the map".format(name))
379
+ return None
380
+
381
+ # GETTERS
382
+ def getLayer(self, name: str) -> dict | None:
383
+ """Get a layer by its name.
384
+
385
+ Args:
386
+ name (str): the name of the layer to retrieve
387
+ Returns:
388
+ dict: The complete EELayer which is a dict containing the type, object, visParams, and layer.
389
+ """
390
+ if name in self.EELayers:
391
+ layer = self.EELayers[name]
392
+ return layer
393
+ else:
394
+ print("Layer {} is not present in the map".format(name))
395
+ return None
396
+
397
+ def getObject(
398
+ self, name: str
399
+ ) -> ee.Image | ee.Geometry | ee.Feature | ee.FeatureCollection | None:
400
+ """Get the EE Object from a layer's name.
401
+
402
+ Args:
403
+ name (str): the name of the layer to retrieve the EE Object from
404
+
405
+ Returns:
406
+ ee.Image | ee.Geometry | ee.Feature | ee.FeatureCollection | None: The EE Object associated with the layer, or None if the layer is not found.
407
+ """
408
+ layer = self.getLayer(name)
409
+ if layer:
410
+ obj = layer["object"]
411
+ return obj
412
+ return None
413
+
414
+ def getVisParams(self, name: str) -> dict | None:
415
+ """Get the Visualization Parameters from a layer's name.
416
+
417
+ Args:
418
+ name (str): the name of the layer to retrieve the visualization parameters from
419
+
420
+ Returns:
421
+ dict | None: The visualization parameters associated with the layer, or None if the layer is not found.
422
+ """
423
+ layer = self.getLayer(name)
424
+ if layer:
425
+ vis = layer["visParams"]
426
+ return vis
427
+ return None
428
+
429
+ def getLayerURL(self, name: str) -> str | None:
430
+ """Get the layer URL by name.
431
+
432
+ Args:
433
+ name (str): the name of the layer to retrieve the URL from
434
+
435
+ Returns:
436
+ str: The URL of the layer.
437
+ """
438
+ layer = self.getLayer(name)
439
+ if layer:
440
+ tile = layer["layer"]
441
+ return tile.url
442
+ return None
443
+
444
+ def getCenter(self) -> ee.Geometry:
445
+ """Returns the coordinates at the center of the map."""
446
+ center = self.center
447
+ coords = inverseCoordinates(center)
448
+ return ee.Geometry.Point(coords)
449
+
450
+ def getBounds(self, asGeoJSON: bool = True) -> ee.Geometry | list:
451
+ """Returns the bounds of the current map view, as a list in the format [west, south, east, north] in degrees.
452
+
453
+ Args:
454
+ asGeoJSON (Boolean, optional): If true, returns map bounds as GeoJSON.
455
+
456
+ Returns:
457
+ GeoJSONGeometry|List<Number>|String: The bounds of the map, either as a GeoJSON geometry or a list of coordinates.
458
+ """
459
+ bounds = inverseCoordinates(self.bounds)
460
+ if asGeoJSON:
461
+ return ee.Geometry.Rectangle(bounds)
462
+ else:
463
+ return bounds
464
+
465
+ def centerObject(self, eeObject, zoom: int | None = None):
466
+ """Center an eeObject.
467
+
468
+ Args:
469
+ eeObject: The Earth Engine object to center on the map.
470
+ zoom (int | None, optional): The zoom level to set. If None, the zoom will be estimated to fit the bounds.
471
+ """
472
+ bounds = getBounds(eeObject)
473
+ if bounds:
474
+ try:
475
+ inverse = inverseCoordinates(bounds)
476
+ centroid = ee.Geometry.Polygon(inverse).centroid().getInfo()["coordinates"]
477
+ except ee.EEException:
478
+ centroid = [0, 0]
479
+
480
+ self.center = inverseCoordinates(centroid)
481
+ if zoom:
482
+ self.zoom = zoom
483
+ else:
484
+ self.zoom = getZoom(bounds)
ipygee/maptools.py ADDED
@@ -0,0 +1,358 @@
1
+ """Map tools for ipygee, including functions to get image tiles from Earth Engine."""
2
+
3
+ import math
4
+ from typing import Any
5
+
6
+ import ee
7
+
8
+
9
+ def visparamsStrToList(params: str) -> list:
10
+ """Transform a string formatted as needed by ee.data.getMapId to a list.
11
+
12
+ Args:
13
+ params (str): String formatted as needed by ee.data.getMapId.
14
+
15
+ Returns:
16
+ list: List of individual parameters.
17
+ """
18
+ proxy_bands = []
19
+ bands = params.split(",")
20
+ for band in bands:
21
+ proxy_bands.append(band.strip())
22
+ return proxy_bands
23
+
24
+
25
+ def visparamsListToStr(params: list) -> str:
26
+ """Transform a list to a string formatted as needed by ee.data.getMapId.
27
+
28
+ Args:
29
+ params (list): List of parameters to convert.
30
+
31
+ Returns:
32
+ str: String formatted as needed by ee.data.getMapId.
33
+
34
+ :param params: params to convert
35
+ :type params: list
36
+ :return: a string formatted as needed by ee.data.getMapId
37
+ :rtype: str
38
+ """
39
+ n = len(params)
40
+ if n == 1:
41
+ newbands = "{}".format(params[0])
42
+ elif n == 3:
43
+ newbands = "{},{},{}".format(params[0], params[1], params[2])
44
+ else:
45
+ newbands = "{}".format(params[0])
46
+ return newbands
47
+
48
+
49
+ def getImageTile(
50
+ image: ee.Image,
51
+ visParams: dict,
52
+ show: bool = True,
53
+ opacity: float | None = None,
54
+ overlay: bool = True,
55
+ ) -> dict:
56
+ """Get an image tile from Earth Engine with the specified visualization parameters.
57
+
58
+ Args:
59
+ image (ee.Image): The Earth Engine image.
60
+ visParams (dict): Visualization parameters.
61
+ show (bool, optional): Whether to show the image. Defaults to True.
62
+ opacity (float | None, optional): Opacity of the image. Defaults to None.
63
+ overlay (bool, optional): Whether to overlay the image. Defaults to True.
64
+
65
+ Returns:
66
+ dict: Dictionary containing the tile URL, attribution, overlay status, show status, opacity, and visualization parameters.
67
+ """
68
+ proxy: dict[str, Any] = {}
69
+ params: dict[str, Any] = visParams if visParams else {}
70
+
71
+ # BANDS #############
72
+ def default_bands(image: ee.Image) -> list[str]:
73
+ bandnames: list[str] = image.bandNames().getInfo()
74
+ if len(bandnames) < 3:
75
+ bands = [bandnames[0]]
76
+ else:
77
+ bands = [bandnames[0], bandnames[1], bandnames[2]]
78
+ return bands
79
+
80
+ raw_bands: Any = params.get("bands", default_bands(image))
81
+ bands: str | list[str]
82
+ if isinstance(raw_bands, (str, list)):
83
+ bands = raw_bands
84
+ else:
85
+ bands = default_bands(image)
86
+
87
+ # if the passed bands is a string formatted like required by GEE, get the
88
+ # list out of it
89
+ bands_list: list[str]
90
+ if isinstance(bands, str):
91
+ bands_list = visparamsStrToList(bands)
92
+ else:
93
+ bands_list = bands
94
+ bands_str = visparamsListToStr(bands_list)
95
+
96
+ # Set proxy parameters
97
+ proxy["bands"] = bands_str
98
+
99
+ # MIN #################
100
+ themin: str = params.get("min", "0")
101
+
102
+ # if the passed min is a list, convert to the format required by GEE
103
+ if isinstance(themin, list):
104
+ themin = visparamsListToStr(themin)
105
+
106
+ proxy["min"] = themin
107
+
108
+ # MAX #################
109
+ def default_max(image, bands):
110
+ proxy_maxs = []
111
+ maxs = {
112
+ "float": 1,
113
+ "double": 1,
114
+ "int8": ((2**8) - 1) / 2,
115
+ "uint8": (2**8) - 1,
116
+ "int16": ((2**16) - 1) / 2,
117
+ "uint16": (2**16) - 1,
118
+ "int32": ((2**32) - 1) / 2,
119
+ "uint32": (2**32) - 1,
120
+ "int64": ((2**64) - 1) / 2,
121
+ }
122
+ for band in bands:
123
+ ty = image.select([band]).getInfo()["bands"][0]["data_type"]
124
+ try:
125
+ themax = maxs[ty]
126
+ except KeyError:
127
+ themax = 1
128
+ proxy_maxs.append(themax)
129
+ return proxy_maxs
130
+
131
+ themax: str = params.get("max", default_max(image, bands_list))
132
+
133
+ # if the passed max is a list or the max is computed by the default function
134
+ # convert to the format required by GEE
135
+ if isinstance(themax, list):
136
+ themax = visparamsListToStr(themax)
137
+
138
+ proxy["max"] = themax
139
+
140
+ # PALETTE ################
141
+ if "palette" in params:
142
+ if len(bands_list) == 1:
143
+ raw_palette: Any = params.get("palette")
144
+ palette: list[str] | None
145
+ if isinstance(raw_palette, str):
146
+ palette = visparamsStrToList(raw_palette)
147
+ elif isinstance(raw_palette, list):
148
+ palette = raw_palette
149
+ else:
150
+ palette = None
151
+ if palette is not None:
152
+ toformat = "{}," * len(palette)
153
+ proxy["palette"] = toformat[:-1].format(*palette)
154
+ else:
155
+ print("Can't use palette parameter with more than one band")
156
+
157
+ # Get the MapID and Token after applying parameters
158
+ image_info = image.getMapId(proxy)
159
+ fetcher = image_info["tile_fetcher"]
160
+ tiles = fetcher.url_format
161
+ attribution = (
162
+ 'Map Data &copy; <a href="https://earthengine.google.com/">Google Earth Engine</a> '
163
+ )
164
+ overlay = overlay
165
+
166
+ return {
167
+ "url": tiles,
168
+ "attribution": attribution,
169
+ "overlay": overlay,
170
+ "show": show,
171
+ "opacity": opacity,
172
+ "visParams": proxy,
173
+ }
174
+
175
+
176
+ def unpack(iterable):
177
+ """Helper function to unpack an iterable."""
178
+ unpacked = []
179
+ for tt in iterable:
180
+ for t in tt:
181
+ unpacked.append(t)
182
+ return unpacked
183
+
184
+
185
+ def getRegion(eeobject, bounds: bool = False, error: int = 1) -> list:
186
+ """Gets the region of a given geometry to use in exporting tasks. The argument can be a Geometry, Feature or Image.
187
+
188
+ Args:
189
+ eeobject: The Earth Engine object (Geometry, Feature, Image, FeatureCollection, or ImageCollection) to get the region of.
190
+ bounds: Boolean indicating whether to get the bounding region. Defaults to False.
191
+ error: Error parameter for ee.Element.geometry. Defaults to 1.
192
+
193
+ Returns:
194
+ The region coordinates ready to use in a client-side EE function.
195
+ """
196
+
197
+ def dispatch(geometry):
198
+ info = geometry.getInfo()
199
+ geomtype = info["type"]
200
+ if geomtype == "GeometryCollection":
201
+ geometries = info["geometries"]
202
+ region = []
203
+ for geom in geometries:
204
+ this_type = geom["type"]
205
+ if this_type in ["Polygon", "Rectangle"]:
206
+ region.append(geom["coordinates"][0])
207
+ elif this_type in ["MultiPolygon"]:
208
+ geometries2 = geom["coordinates"]
209
+ region.append(unpack(geometries2))
210
+
211
+ elif geomtype == "MultiPolygon":
212
+ subregion = info["coordinates"]
213
+ region = unpack(subregion)
214
+ else:
215
+ region = info["coordinates"]
216
+
217
+ return region
218
+
219
+ # Geometry
220
+ if isinstance(eeobject, ee.Geometry):
221
+ geometry = eeobject.bounds() if bounds else eeobject
222
+ region = dispatch(geometry)
223
+ # Feature and Image
224
+ elif isinstance(eeobject, (ee.Feature, ee.Image)):
225
+ geometry = eeobject.geometry(error).bounds() if bounds else eeobject.geometry(error)
226
+ region = dispatch(geometry)
227
+ # FeatureCollection and ImageCollection
228
+ elif isinstance(eeobject, (ee.FeatureCollection, ee.ImageCollection)):
229
+ if bounds:
230
+ geometry = eeobject.geometry(error).bounds()
231
+ else:
232
+ geometry = eeobject.geometry(error).dissolve()
233
+ region = dispatch(geometry)
234
+ # List
235
+ elif isinstance(eeobject, list):
236
+ condition = all([isinstance(item, list) for item in eeobject])
237
+ if condition:
238
+ region = eeobject
239
+ else:
240
+ region = eeobject
241
+
242
+ return region
243
+
244
+
245
+ def isPoint(item: list | tuple) -> bool:
246
+ """Determine if the given list has the structure of a point. This is: it is a list or tuple with two int or float items."""
247
+ if isinstance(item, list) or isinstance(item, tuple):
248
+ if len(item) == 2:
249
+ lon = item[0]
250
+ if isinstance(lon, int) or isinstance(lon, float):
251
+ return True
252
+ else:
253
+ return False
254
+ else:
255
+ return False
256
+ else:
257
+ return False
258
+
259
+
260
+ def inverseCoordinates(
261
+ coords: list[Any] | tuple[Any, ...],
262
+ ) -> list[Any] | tuple[Any, ...]:
263
+ """Inverse a set of coordinates (any nesting depth).
264
+
265
+ Args:
266
+ coords (list[Any] | tuple[Any, ...]): A nested list or tuple of coordinates.
267
+
268
+ Returns:
269
+ list[Any] | tuple[Any, ...]: The coordinates with latitude and longitude inverted.
270
+ """
271
+ newlist = []
272
+ if isPoint(coords):
273
+ return [coords[1], coords[0]]
274
+ elif not isinstance(coords, list) and not isinstance(coords, tuple):
275
+ raise ValueError("coordinates to inverse must be minimum a point")
276
+ for it in coords:
277
+ p = isPoint(it)
278
+ if not p and (isinstance(it, list) or isinstance(it, tuple)):
279
+ newlist.append(inverseCoordinates(it))
280
+ else:
281
+ newp = [it[1], it[0]]
282
+ newlist.append(newp)
283
+ return newlist
284
+
285
+
286
+ def getBounds(eeObject):
287
+ """Get the bounds of an Earth Engine object or a list of coordinates.
288
+
289
+ Args:
290
+ eeObject: The Earth Engine object or list of coordinates to get the bounds for.
291
+
292
+ Returns:
293
+ list: The bounds of the object in the format [[south, west], [north, east]] or None if unbounded.
294
+ """
295
+ if isinstance(eeObject, list):
296
+ bounds = eeObject
297
+ else:
298
+ # Make a buffer if object is a Point
299
+ if isinstance(eeObject, ee.Geometry):
300
+ t = eeObject.type().getInfo()
301
+ if t == "Point":
302
+ eeObject = eeObject.buffer(1000)
303
+
304
+ bounds = getRegion(eeObject, True)
305
+
306
+ # Catch unbounded images
307
+ unbounded = [[[-180.0, -90.0], [180.0, -90.0], [180.0, 90.0], [-180.0, 90.0], [-180.0, -90.0]]]
308
+
309
+ if bounds == unbounded:
310
+ print("can't center object because it is unbounded")
311
+ return None
312
+
313
+ bounds = inverseCoordinates(bounds)
314
+ return bounds
315
+
316
+
317
+ def getZoom(bounds: list) -> int:
318
+ """Estimate the zoom level to fit the given bounds.
319
+
320
+ https://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom-level-for-a-given-bounds
321
+
322
+ Args:
323
+ bounds (list): List of coordinates in the format [[south, west], [north, east]]
324
+
325
+ Returns:
326
+ int: Zoom level
327
+ """
328
+ bounds = bounds[0]
329
+ sw = bounds[0]
330
+ ne = bounds[2]
331
+
332
+ sw_lon = sw[1]
333
+ sw_lat = sw[0]
334
+ ne_lon = ne[1]
335
+ ne_lat = ne[0]
336
+
337
+ WORLD_DIM = {"height": 256, "width": 256}
338
+ ZOOM_MAX = 21
339
+
340
+ def latRad(lat):
341
+ sin = math.sin(lat * math.pi / 180)
342
+ radX2 = math.log((1 + sin) / (1 - sin)) / 2
343
+ return max(min(radX2, math.pi), -math.pi) / 2
344
+
345
+ def zoom(mapPx, worldPx, fraction):
346
+ return math.floor(math.log(mapPx / worldPx / fraction) / math.log(2))
347
+
348
+ latFraction = float(latRad(ne_lat) - latRad(sw_lat)) / math.pi
349
+
350
+ lngDiff = ne_lon - sw_lon
351
+
352
+ lngFraction = (lngDiff + 360) if (lngDiff < 0) else lngDiff
353
+ lngFraction = lngFraction / 360
354
+
355
+ latZoom = zoom(400, WORLD_DIM["height"], latFraction)
356
+ lngZoom = zoom(970, WORLD_DIM["width"], lngFraction)
357
+
358
+ return int(min(latZoom, lngZoom, ZOOM_MAX))
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: ipygee
3
+ Version: 0.1.0
4
+ Summary: A set of tools for working with Google Earth Engine python API in jupyter notebooks
5
+ Project-URL: Homepage, https://github.com/fitoprincipe/ipygee
6
+ Author-email: Rodrigo Principe <fitoprincipe82@gmail.com>
7
+ License: MIT
8
+ License-File: AUTHORS.rst
9
+ License-File: LICENSE
10
+ Keywords: Python,skeleton
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: deprecated>=1.2.14
18
+ Requires-Dist: earthengine-api
19
+ Requires-Dist: geetools
20
+ Requires-Dist: ipyleaflet
21
+ Requires-Dist: ipywidgets
22
+ Provides-Extra: dev
23
+ Requires-Dist: ipykernel; extra == 'dev'
24
+ Provides-Extra: doc
25
+ Requires-Dist: pydata-sphinx-theme; extra == 'doc'
26
+ Requires-Dist: sphinx-autoapi; extra == 'doc'
27
+ Requires-Dist: sphinx-copybutton; extra == 'doc'
28
+ Requires-Dist: sphinx-design; extra == 'doc'
29
+ Requires-Dist: sphinx>=6.2.1; extra == 'doc'
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest; extra == 'test'
32
+ Requires-Dist: pytest-cov; extra == 'test'
33
+ Requires-Dist: pytest-deadfixtures; extra == 'test'
34
+ Description-Content-Type: text/x-rst
35
+
36
+
37
+ ipygee
38
+ ======
39
+
40
+ .. |license| image:: https://img.shields.io/badge/License-MIT-yellow.svg?logo=opensourceinitiative&logoColor=white
41
+ :target: LICENSE
42
+ :alt: License: MIT
43
+
44
+ .. |commit| image:: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg?logo=git&logoColor=white
45
+ :target: https://conventionalcommits.org
46
+ :alt: conventional commit
47
+
48
+ .. |ruff| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
49
+ :target: https://github.com/astral-sh/ruff
50
+ :alt: ruff badge
51
+
52
+ .. |prettier| image:: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?logo=prettier&logoColor=white
53
+ :target: https://github.com/prettier/prettier
54
+ :alt: prettier badge
55
+
56
+ .. |pre-commmit| image:: https://img.shields.io/badge/pre--commit-active-yellow?logo=pre-commit&logoColor=white
57
+ :target: https://pre-commit.com/
58
+ :alt: pre-commit
59
+
60
+ .. |pypi| image:: https://img.shields.io/pypi/v/ipygee?color=blue&logo=pypi&logoColor=white
61
+ :target: https://pypi.org/project/ipygee/
62
+ :alt: PyPI version
63
+
64
+ .. |build| image:: https://img.shields.io/github/actions/workflow/status/fitoprincipe/ipygee/unit.yaml?logo=github&logoColor=white
65
+ :target: https://github.com/fitoprincipe/ipygee/actions/workflows/unit.yaml
66
+ :alt: build
67
+
68
+ .. |coverage| image:: https://img.shields.io/codecov/c/github/fitoprincipe/ipygee?logo=codecov&logoColor=white
69
+ :target: https://codecov.io/gh/fitoprincipe/ipygee
70
+ :alt: Test Coverage
71
+
72
+ .. |docs| image:: https://img.shields.io/readthedocs/ipygee?logo=readthedocs&logoColor=white
73
+ :target: https://ipygee.readthedocs.io/en/latest/
74
+ :alt: Documentation Status
75
+
76
+ |license| |commit| |ruff| |prettier| |pre-commmit| |pypi| |build| |coverage| |docs|
77
+
78
+ Overview
79
+ --------
80
+
81
+ A set of tools for working with Google Earth Engine python API in jupyter notebooks
82
+
83
+ Credits
84
+ -------
85
+
86
+ This package was created with `Copier <https://copier.readthedocs.io/en/latest/>`__ and the `@12rambau/pypackage <https://github.com/12rambau/pypackage>`__ 0.1.18 project template.
@@ -0,0 +1,8 @@
1
+ ipygee/__init__.py,sha256=4NaSn1Kh0a2hfYO1fTyb8eqwtJll7o2Jndhog4jTBu8,185
2
+ ipygee/map.py,sha256=U1des9Q9lGnY4ueevrp3xjmlyGPrr3KgdI8FbotjcVc,16155
3
+ ipygee/maptools.py,sha256=k1c1J8Jln0KaBTY2NCTBL9nxm-YuyOWzB4J2JUG-1BA,11234
4
+ ipygee-0.1.0.dist-info/METADATA,sha256=WBR9DrPXp_-zeuNtNeyqC8Xgl4218TjNjmBSqAH4D7Y,3331
5
+ ipygee-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ ipygee-0.1.0.dist-info/licenses/AUTHORS.rst,sha256=pSrXGEDXw_HosfGgmpcGh4Q6NC5qb0MSE4rxn43ZtxY,741
7
+ ipygee-0.1.0.dist-info/licenses/LICENSE,sha256=bOnNLi8V8ZOJsR9XcfsBEBCSXB2t-ZFF57fvZUnVsKY,1073
8
+ ipygee-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/docs/en/emoji-key>`_):
2
+
3
+ .. raw:: html
4
+
5
+ <table class="table table-bordered">
6
+ <tr>
7
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
8
+ <td align="center">
9
+ <a href="#">
10
+ <img src="https://github.com/fitoprincipe.png" width="70px;" alt="fitoprincipe"/><br />
11
+ <sub><b>Rodrigo Principe</b></sub>
12
+ </a>
13
+ <a href="#code" title="Code">💻</a>
14
+ </td>
15
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
16
+ </tr>
17
+ </table>
18
+
19
+ This project follows the `all-contributors <https://allcontributors.org>`_ specification.
20
+
21
+ Contributions of any kind are welcome!
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rodrigo Principe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.