geeltermap 0.1.0__py3-none-any.whl → 0.1.8__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.
@@ -0,0 +1,231 @@
1
+ """Tile layers that show EE objects."""
2
+
3
+ # *******************************************************************************#
4
+ # This module contains core features features of the geemap package. #
5
+ # The Earth Engine team and the geemap community will maintain the core features.#
6
+ # *******************************************************************************#
7
+
8
+ import box
9
+ import ee
10
+ import folium
11
+ import ipyleaflet
12
+ from functools import lru_cache
13
+
14
+ from . import common
15
+
16
+
17
+ def _get_tile_url_format(ee_object, vis_params):
18
+ image = _ee_object_to_image(ee_object, vis_params)
19
+ map_id_dict = ee.Image(image).getMapId(vis_params)
20
+ return map_id_dict["tile_fetcher"].url_format
21
+
22
+
23
+ def _validate_vis_params(vis_params):
24
+ if vis_params is None:
25
+ return {}
26
+
27
+ if not isinstance(vis_params, dict):
28
+ raise TypeError("vis_params must be a dictionary")
29
+
30
+ valid_dict = vis_params.copy()
31
+
32
+ if "palette" in valid_dict:
33
+ valid_dict["palette"] = _validate_palette(valid_dict["palette"])
34
+
35
+ return valid_dict
36
+
37
+
38
+ def _ee_object_to_image(ee_object, vis_params):
39
+ if isinstance(ee_object, (ee.Geometry, ee.Feature, ee.FeatureCollection)):
40
+ features = ee.FeatureCollection(ee_object)
41
+ color = vis_params.get("color", "000000")
42
+ image_outline = features.style(
43
+ **{
44
+ "color": color,
45
+ "fillColor": "00000000",
46
+ "width": vis_params.get("width", 2),
47
+ }
48
+ )
49
+ return (
50
+ features.style(**{"fillColor": color})
51
+ .updateMask(ee.Image.constant(0.5))
52
+ .blend(image_outline)
53
+ )
54
+ elif isinstance(ee_object, ee.Image):
55
+ return ee_object
56
+ elif isinstance(ee_object, ee.ImageCollection):
57
+ return ee_object.mosaic()
58
+ raise AttributeError(
59
+ f"\n\nCannot add an object of type {ee_object.__class__.__name__} to the map."
60
+ )
61
+
62
+
63
+ def _validate_palette(palette):
64
+ if isinstance(palette, tuple):
65
+ palette = list(palette)
66
+ if isinstance(palette, box.Box):
67
+ if "default" not in palette:
68
+ raise ValueError("The provided palette Box object is invalid.")
69
+ return list(palette["default"])
70
+ if isinstance(palette, str):
71
+ return common.check_cmap(palette)
72
+ if isinstance(palette, list):
73
+ return palette
74
+ raise ValueError("The palette must be a list of colors, a string, or a Box object.")
75
+
76
+
77
+ class EEFoliumTileLayer(folium.raster_layers.TileLayer):
78
+ """A Folium raster TileLayer that shows an EE object."""
79
+
80
+ def __init__(
81
+ self,
82
+ ee_object,
83
+ vis_params=None,
84
+ name="Layer untitled",
85
+ shown=True,
86
+ opacity=1.0,
87
+ **kwargs,
88
+ ):
89
+ """Initialize the folium tile layer.
90
+
91
+ Args:
92
+ ee_object (Collection|Feature|Image|MapId): The object to add to the map.
93
+ vis_params (dict, optional): The visualization parameters. Defaults to None.
94
+ name (str, optional): The name of the layer. Defaults to 'Layer untitled'.
95
+ shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
96
+ opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
97
+ """
98
+ self.url_format = _get_tile_url_format(
99
+ ee_object, _validate_vis_params(vis_params)
100
+ )
101
+ super().__init__(
102
+ tiles=self.url_format,
103
+ attr="Google Earth Engine",
104
+ name=name,
105
+ overlay=True,
106
+ control=True,
107
+ show=shown,
108
+ opacity=opacity,
109
+ max_zoom=24,
110
+ **kwargs,
111
+ )
112
+
113
+
114
+ class EELeafletTileLayer(ipyleaflet.TileLayer):
115
+ """An ipyleaflet TileLayer that shows an EE object."""
116
+
117
+ EE_TYPES = (
118
+ ee.Geometry,
119
+ ee.Feature,
120
+ ee.FeatureCollection,
121
+ ee.Image,
122
+ ee.ImageCollection,
123
+ )
124
+
125
+ def __init__(
126
+ self,
127
+ ee_object,
128
+ vis_params=None,
129
+ name="Layer untitled",
130
+ shown=True,
131
+ opacity=1.0,
132
+ **kwargs,
133
+ ):
134
+ """Initialize the ipyleaflet tile layer.
135
+
136
+ Args:
137
+ ee_object (Collection|Feature|Image|MapId): The object to add to the map.
138
+ vis_params (dict, optional): The visualization parameters. Defaults to None.
139
+ name (str, optional): The name of the layer. Defaults to 'Layer untitled'.
140
+ shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
141
+ opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
142
+ """
143
+ self._ee_object = ee_object
144
+ self.url_format = _get_tile_url_format(
145
+ ee_object, _validate_vis_params(vis_params)
146
+ )
147
+ super().__init__(
148
+ url=self.url_format,
149
+ attribution="Google Earth Engine",
150
+ name=name,
151
+ opacity=opacity,
152
+ visible=shown,
153
+ max_zoom=24,
154
+ **kwargs,
155
+ )
156
+
157
+ @lru_cache()
158
+ def _calculate_vis_stats(self, *, bounds, bands):
159
+ """Calculate stats used for visualization parameters.
160
+
161
+ Stats are calculated consistently with the Code Editor visualization parameters,
162
+ and are cached to avoid recomputing for the same bounds and bands.
163
+
164
+ Args:
165
+ bounds (ee.Geometry|ee.Feature|ee.FeatureCollection): The bounds to sample.
166
+ bands (tuple): The bands to sample.
167
+
168
+ Returns:
169
+ tuple: The minimum, maximum, standard deviation, and mean values across the
170
+ specified bands.
171
+ """
172
+ stat_reducer = (ee.Reducer.minMax()
173
+ .combine(ee.Reducer.mean().unweighted(), sharedInputs=True)
174
+ .combine(ee.Reducer.stdDev(), sharedInputs=True))
175
+
176
+ stats = self._ee_object.select(bands).reduceRegion(
177
+ reducer=stat_reducer,
178
+ geometry=bounds,
179
+ bestEffort=True,
180
+ maxPixels=10_000,
181
+ crs="SR-ORG:6627",
182
+ scale=1,
183
+ ).getInfo()
184
+
185
+ mins, maxs, stds, means = [
186
+ {v for k, v in stats.items() if k.endswith(stat) and v is not None}
187
+ for stat in ('_min', '_max', '_stdDev', '_mean')
188
+ ]
189
+ if any(len(vals) == 0 for vals in (mins, maxs, stds, means)):
190
+ raise ValueError('No unmasked pixels were sampled.')
191
+
192
+ min_val = min(mins)
193
+ max_val = max(maxs)
194
+ std_dev = sum(stds) / len(stds)
195
+ mean = sum(means) / len(means)
196
+
197
+ return (min_val, max_val, std_dev, mean)
198
+
199
+ def calculate_vis_minmax(self, *, bounds, bands=None, percent=None, sigma=None):
200
+ """Calculate the min and max clip values for visualization.
201
+
202
+ Args:
203
+ bounds (ee.Geometry|ee.Feature|ee.FeatureCollection): The bounds to sample.
204
+ bands (list, optional): The bands to sample. If None, all bands are used.
205
+ percent (float, optional): The percent to use when stretching.
206
+ sigma (float, optional): The number of standard deviations to use when
207
+ stretching.
208
+
209
+ Returns:
210
+ tuple: The minimum and maximum values to clip to.
211
+ """
212
+ bands = self._ee_object.bandNames() if bands is None else tuple(bands)
213
+ try:
214
+ min_val, max_val, std, mean = self._calculate_vis_stats(
215
+ bounds=bounds, bands=bands
216
+ )
217
+ except ValueError:
218
+ return (0, 0)
219
+
220
+ if sigma is not None:
221
+ stretch_min = mean - sigma * std
222
+ stretch_max = mean + sigma * std
223
+ elif percent is not None:
224
+ x = (max_val - min_val) * (1 - percent)
225
+ stretch_min = min_val + x
226
+ stretch_max = max_val - x
227
+ else:
228
+ stretch_min = min_val
229
+ stretch_max = max_val
230
+
231
+ return (stretch_min, stretch_max)
geeltermap/geeltermap.py CHANGED
@@ -23,6 +23,8 @@ from .common import *
23
23
  from .legends import builtin_legends
24
24
  from .osm import *
25
25
  from .plot import *
26
+ from . import map_widgets
27
+
26
28
 
27
29
 
28
30
  basemaps = Box(xyz_to_leaflet(), frozen_box=True)