id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
12,438 | import os
import warnings
from typing import Optional, Any, Dict
import ee
import ipyleaflet
import ipywidgets as widgets
from box import Box
from bqplot import pyplot as plt
from IPython.display import display
from .basemaps import get_xyz_dict, xyz_to_leaflet
from .common import *
from .conversion import *
from .ee_tile_layers import *
from . import core
from . import map_widgets
from . import toolbar
from .plot import *
from .timelapse import *
from .legends import builtin_legends
from . import examples
class Map(core.Map):
"""The Map class inherits the core Map class. The arguments you can pass to the Map initialization
can be found at https://ipyleaflet.readthedocs.io/en/latest/map_and_basemaps/map.html.
By default, the Map will add Google Maps as the basemap. Set add_google_map = False
to use OpenStreetMap as the basemap.
Returns:
object: ipyleaflet map object.
"""
# Map attributes for drawing features
def draw_control(self):
return self.get_draw_control()
def draw_control_lite(self):
return self.get_draw_control()
def draw_features(self):
return self._draw_control.features if self._draw_control else []
def draw_last_feature(self):
return self._draw_control.last_feature if self._draw_control else None
def draw_layer(self):
return self._draw_control.layer if self._draw_control else None
def user_roi(self):
return self._draw_control.last_geometry if self._draw_control else None
def user_rois(self):
return self._draw_control.collection if self._draw_control else None
def __init__(self, **kwargs):
"""Initialize a map object. The following additional parameters can be passed in addition to the ipyleaflet.Map parameters:
Args:
ee_initialize (bool, optional): Whether or not to initialize ee. Defaults to True.
center (list, optional): Center of the map (lat, lon). Defaults to [20, 0].
zoom (int, optional): Zoom level of the map. Defaults to 2.
height (str, optional): Height of the map. Defaults to "600px".
width (str, optional): Width of the map. Defaults to "100%".
basemap (str, optional): Name of the basemap to add to the map. Defaults to "ROADMAP". Other options include "ROADMAP", "SATELLITE", "TERRAIN".
add_google_map (bool, optional): Whether to add Google Maps to the map. Defaults to True.
sandbox_path (str, optional): The path to a sandbox folder for voila web app. Defaults to None.
lite_mode (bool, optional): Whether to enable lite mode, which only displays zoom control on the map. Defaults to False.
data_ctrl (bool, optional): Whether to add the data control to the map. Defaults to True.
zoom_ctrl (bool, optional): Whether to add the zoom control to the map. Defaults to True.
fullscreen_ctrl (bool, optional): Whether to add the fullscreen control to the map. Defaults to True.
search_ctrl (bool, optional): Whether to add the search control to the map. Defaults to True.
draw_ctrl (bool, optional): Whether to add the draw control to the map. Defaults to True.
scale_ctrl (bool, optional): Whether to add the scale control to the map. Defaults to True.
measure_ctrl (bool, optional): Whether to add the measure control to the map. Defaults to True.
toolbar_ctrl (bool, optional): Whether to add the toolbar control to the map. Defaults to True.
layer_ctrl (bool, optional): Whether to add the layer control to the map. Defaults to False.
attribution_ctrl (bool, optional): Whether to add the attribution control to the map. Defaults to True.
**kwargs: Additional keyword arguments for ipyleaflet.Map.
"""
warnings.filterwarnings("ignore")
if isinstance(kwargs.get("height"), int):
kwargs["height"] = str(kwargs["height"]) + "px"
if isinstance(kwargs.get("width"), int):
kwargs["width"] = str(kwargs["width"]) + "px"
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 24
# Use any basemap available through the basemap module, such as 'ROADMAP', 'OpenTopoMap'
if "basemap" in kwargs:
kwargs["basemap"] = check_basemap(kwargs["basemap"])
if kwargs["basemap"] in basemaps.keys():
kwargs["basemap"] = get_basemap(kwargs["basemap"])
kwargs["add_google_map"] = False
else:
kwargs.pop("basemap")
self._xyz_dict = get_xyz_dict()
self.baseclass = "ipyleaflet"
self._USER_AGENT_PREFIX = "geemap"
self.kwargs = kwargs
super().__init__(**kwargs)
if kwargs.get("height"):
self.layout.height = kwargs.get("height")
# sandbox path for Voila app to restrict access to system directories.
if "sandbox_path" not in kwargs:
self.sandbox_path = None
else:
if os.path.exists(os.path.abspath(kwargs["sandbox_path"])):
self.sandbox_path = kwargs["sandbox_path"]
else:
print("The sandbox path is invalid.")
self.sandbox_path = None
# Add Google Maps as the default basemap
if kwargs.get("add_google_map", False):
self.add_basemap("ROADMAP")
# ipyleaflet built-in layer control
self.layer_control = None
if "ee_initialize" not in kwargs:
kwargs["ee_initialize"] = True
# Default reducer to use
if kwargs["ee_initialize"]:
self.roi_reducer = ee.Reducer.mean()
self.roi_reducer_scale = None
def _control_config(self):
if self.kwargs.get("lite_mode"):
return {"topleft": ["zoom_control"]}
topleft = []
bottomleft = []
topright = []
bottomright = []
for control in ["data_ctrl", "zoom_ctrl", "fullscreen_ctrl", "draw_ctrl"]:
if self.kwargs.get(control, True):
topleft.append(control)
for control in ["scale_ctrl", "measure_ctrl"]:
if self.kwargs.get(control, True):
bottomleft.append(control)
for control in ["toolbar_ctrl"]:
if self.kwargs.get(control, True):
topright.append(control)
for control in ["attribution_control"]:
if self.kwargs.get(control, True):
bottomright.append(control)
return {
"topleft": topleft,
"bottomleft": bottomleft,
"topright": topright,
"bottomright": bottomright,
}
def ee_layer_names(self):
warnings.warn(
"ee_layer_names is deprecated. Use ee_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_layers.keys()
def ee_layer_dict(self):
warnings.warn(
"ee_layer_dict is deprecated. Use ee_layers instead.", DeprecationWarning
)
return self.ee_layers
def ee_raster_layer_names(self):
warnings.warn(
"ee_raster_layer_names is deprecated. Use self.ee_raster_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_raster_layers.keys()
def ee_vector_layer_names(self):
warnings.warn(
"ee_vector_layer_names is deprecated. Use self.ee_vector_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_vector_layers.keys()
def ee_raster_layers(self):
return dict(filter(self._raster_filter, self.ee_layers.items()))
def ee_vector_layers(self):
return dict(filter(self._vector_filter, self.ee_layers.items()))
def _raster_filter(self, pair):
return isinstance(pair[1]["ee_object"], (ee.Image, ee.ImageCollection))
def _vector_filter(self, pair):
return isinstance(
pair[1]["ee_object"], (ee.Geometry, ee.Feature, ee.FeatureCollection)
)
def add(self, obj, position="topright", **kwargs):
"""Adds a layer or control to the map.
Args:
object (object): The layer or control to add to the map.
"""
if isinstance(obj, str):
basemap = check_basemap(obj)
if basemap in basemaps.keys():
super().add(get_basemap(basemap))
return
if not isinstance(obj, str):
super().add(obj, position=position, **kwargs)
return
obj = obj.lower()
backward_compatibilities = {
"zoom_ctrl": "zoom_control",
"fullscreen_ctrl": "fullscreen_control",
"scale_ctrl": "scale_control",
"toolbar_ctrl": "toolbar",
"draw_ctrl": "draw_control",
}
obj = backward_compatibilities.get(obj, obj)
if obj == "data_ctrl":
data_widget = toolbar.SearchDataGUI(self)
data_control = ipyleaflet.WidgetControl(
widget=data_widget, position=position
)
self.add(data_control)
elif obj == "search_ctrl":
self.add_search_control(position=position)
elif obj == "measure_ctrl":
measure = ipyleaflet.MeasureControl(
position=position,
active_color="orange",
primary_length_unit="kilometers",
)
self.add(measure, position=position)
elif obj == "layer_ctrl":
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control, position=position)
else:
super().add(obj, position=position, **kwargs)
def add_controls(self, controls, position="topleft"):
"""Adds a list of controls to the map.
Args:
controls (list): A list of controls to add to the map.
position (str, optional): The position of the controls on the map. Defaults to 'topleft'.
"""
if not isinstance(controls, list):
controls = [controls]
for control in controls:
self.add(control, position)
def set_options(self, mapTypeId="HYBRID", **kwargs):
"""Adds Google basemap and controls to the ipyleaflet map.
Args:
mapTypeId (str, optional): A mapTypeId to set the basemap to. Can be one of "ROADMAP", "SATELLITE",
"HYBRID" or "TERRAIN" to select one of the standard Google Maps API map types. Defaults to 'HYBRID'.
"""
try:
self.add(mapTypeId)
except Exception:
raise ValueError(
'Google basemaps can only be one of "ROADMAP", "SATELLITE", "HYBRID" or "TERRAIN".'
)
setOptions = set_options
def add_ee_layer(
self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0
):
"""Adds a given EE object to the map as a layer.
Args:
ee_object (Collection|Feature|Image|MapId): The object to add to the map.
vis_params (dict, optional): The visualization parameters. Defaults to {}.
name (str, optional): The name of the layer. Defaults to 'Layer N'.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
"""
has_plot_dropdown = (
hasattr(self, "_plot_dropdown_widget")
and self._plot_dropdown_widget is not None
)
ee_layer = self.ee_layers.get(name, {})
layer = ee_layer.get("ee_layer", None)
if layer is not None:
if isinstance(ee_layer["ee_object"], (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(
self.ee_raster_layers.keys()
)
super().add_layer(ee_object, vis_params, name, shown, opacity)
if isinstance(ee_object, (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(self.ee_raster_layers.keys())
tile_layer = self.ee_layers.get(name, {}).get("ee_layer", None)
if tile_layer:
arc_add_layer(tile_layer.url_format, name, shown, opacity)
addLayer = add_ee_layer
def remove_ee_layer(self, name):
"""Removes an Earth Engine layer.
Args:
name (str): The name of the Earth Engine layer to remove.
"""
if name in self.ee_layers:
ee_layer = self.ee_layers[name]["ee_layer"]
self.ee_layers.pop(name, None)
if ee_layer in self.layers:
self.remove_layer(ee_layer)
def set_center(self, lon, lat, zoom=None):
"""Centers the map view at a given coordinates with the given zoom level.
Args:
lon (float): The longitude of the center, in degrees.
lat (float): The latitude of the center, in degrees.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to None.
"""
super().set_center(lon, lat, zoom)
if is_arcpy():
arc_zoom_to_extent(lon, lat, lon, lat)
setCenter = set_center
def center_object(self, ee_object, zoom=None):
"""Centers the map view on a given object.
Args:
ee_object (Element|Geometry): An Earth Engine object to center on a geometry, image or feature.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to None.
"""
super().center_object(ee_object, zoom)
if is_arcpy():
bds = self.bounds
arc_zoom_to_extent(bds[0][1], bds[0][0], bds[1][1], bds[1][0])
centerObject = center_object
def zoom_to_bounds(self, bounds):
"""Zooms to a bounding box in the form of [minx, miny, maxx, maxy].
Args:
bounds (list | tuple): A list/tuple containing minx, miny, maxx, maxy values for the bounds.
"""
# The ipyleaflet fit_bounds method takes lat/lon bounds in the form [[south, west], [north, east]].
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def get_scale(self):
"""Returns the approximate pixel scale of the current map view, in meters.
Returns:
float: Map resolution in meters.
"""
return super().get_scale()
getScale = get_scale
def add_basemap(self, basemap="ROADMAP", show=True, **kwargs):
"""Adds a basemap to the map.
Args:
basemap (str, optional): Can be one of string from basemaps. Defaults to 'ROADMAP'.
visible (bool, optional): Whether the basemap is visible or not. Defaults to True.
**kwargs: Keyword arguments for the TileLayer.
"""
import xyzservices
try:
layer_names = self.get_layer_names()
map_dict = {
"ROADMAP": "Esri.WorldStreetMap",
"SATELLITE": "Esri.WorldImagery",
"TERRAIN": "Esri.WorldTopoMap",
"HYBRID": "Esri.WorldImagery",
}
if isinstance(basemap, str):
if basemap.upper() in map_dict:
if basemap in os.environ:
if "name" in kwargs:
kwargs["name"] = basemap
basemap = os.environ[basemap]
else:
basemap = map_dict[basemap.upper()]
if isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
url = basemap.build_url()
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
max_zoom = basemap["max_zoom"]
else:
max_zoom = 22
layer = ipyleaflet.TileLayer(
url=url,
name=name,
max_zoom=max_zoom,
attribution=attribution,
visible=show,
**kwargs,
)
self.add(layer)
arc_add_layer(url, name)
elif basemap in basemaps and basemaps[basemap].name not in layer_names:
self.add(basemap)
self.layers[-1].visible = show
arc_add_layer(basemaps[basemap].url, basemap)
elif basemap in basemaps and basemaps[basemap].name in layer_names:
print(f"{basemap} has been already added before.")
elif basemap.startswith("http"):
self.add_tile_layer(url=basemap, shown=show, **kwargs)
else:
print(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
except Exception as e:
raise ValueError(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
def get_layer_names(self):
"""Gets layer names as a list.
Returns:
list: A list of layer names.
"""
layer_names = []
for layer in list(self.layers):
if len(layer.name) > 0:
layer_names.append(layer.name)
return layer_names
def find_layer(self, name):
"""Finds layer by name
Args:
name (str): Name of the layer to find.
Returns:
object: ipyleaflet layer object.
"""
layers = self.layers
for layer in layers:
if layer.name == name:
return layer
return None
def show_layer(self, name, show=True):
"""Shows or hides a layer on the map.
Args:
name (str): Name of the layer to show/hide.
show (bool, optional): Whether to show or hide the layer. Defaults to True.
"""
layer = self.find_layer(name)
if layer is not None:
layer.visible = show
def find_layer_index(self, name):
"""Finds layer index by name
Args:
name (str): Name of the layer to find.
Returns:
int: Index of the layer with the specified name
"""
layers = self.layers
for index, layer in enumerate(layers):
if layer.name == name:
return index
return -1
def layer_opacity(self, name, opacity=1.0):
"""Changes layer opacity.
Args:
name (str): The name of the layer to change opacity.
opacity (float, optional): The opacity value to set. Defaults to 1.0.
"""
layer = self.find_layer(name)
try:
layer.opacity = opacity
except Exception as e:
raise Exception(e)
def add_tile_layer(
self,
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
name="Untitled",
attribution="",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a TileLayer to the map.
Args:
url (str, optional): The URL of the tile layer. Defaults to 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'.
name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
tile_layer = ipyleaflet.TileLayer(
url=url,
name=name,
attribution=attribution,
opacity=opacity,
visible=shown,
**kwargs,
)
self.add(tile_layer)
except Exception as e:
print("Failed to add the specified TileLayer.")
raise Exception(e)
def set_plot_options(
self,
add_marker_cluster=False,
sample_scale=None,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Sets plotting options.
Args:
add_marker_cluster (bool, optional): Whether to add a marker cluster. Defaults to False.
sample_scale (float, optional): A nominal scale in meters of the projection to sample in . Defaults to None.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
plot_options_dict = {}
plot_options_dict["add_marker_cluster"] = add_marker_cluster
plot_options_dict["sample_scale"] = sample_scale
plot_options_dict["plot_type"] = plot_type
plot_options_dict["overlay"] = overlay
plot_options_dict["position"] = position
plot_options_dict["min_width"] = min_width
plot_options_dict["max_width"] = max_width
plot_options_dict["min_height"] = min_height
plot_options_dict["max_height"] = max_height
for key in kwargs:
plot_options_dict[key] = kwargs[key]
self._plot_options = plot_options_dict
if not hasattr(self, "_plot_marker_cluster"):
self._plot_marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
if add_marker_cluster and (self._plot_marker_cluster not in self.layers):
self.add(self._plot_marker_cluster)
def plot(
self,
x,
y,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Creates a plot based on x-array and y-array data.
Args:
x (numpy.ndarray or list): The x-coordinates of the plotted line.
y (numpy.ndarray or list): The y-coordinates of the plotted line.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
if hasattr(self, "_plot_widget") and self._plot_widget is not None:
plot_widget = self._plot_widget
else:
plot_widget = widgets.Output(
layout={"border": "1px solid black", "max_width": "500px"}
)
plot_control = ipyleaflet.WidgetControl(
widget=plot_widget,
position=position,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
)
self._plot_widget = plot_widget
self._plot_control = plot_control
self.add(plot_control)
if max_width is None:
max_width = 500
if max_height is None:
max_height = 300
if (plot_type is None) and ("markers" not in kwargs):
kwargs["markers"] = "circle"
with plot_widget:
try:
fig = plt.figure(1, **kwargs)
if max_width is not None:
fig.layout.width = str(max_width) + "px"
if max_height is not None:
fig.layout.height = str(max_height) + "px"
plot_widget.outputs = ()
if not overlay:
plt.clear()
if plot_type is None:
if "marker" not in kwargs:
kwargs["marker"] = "circle"
plt.plot(x, y, **kwargs)
elif plot_type == "bar":
plt.bar(x, y, **kwargs)
elif plot_type == "scatter":
plt.scatter(x, y, **kwargs)
elif plot_type == "hist":
plt.hist(y, **kwargs)
plt.show()
except Exception as e:
print("Failed to create plot.")
raise Exception(e)
def add_layer_control(self, position="topright"):
"""Adds a layer control to the map.
Args:
position (str, optional): _description_. Defaults to "topright".
"""
if self.layer_control is None:
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control)
addLayerControl = add_layer_control
def add_legend(
self,
title="Legend",
legend_dict=None,
keys=None,
colors=None,
position="bottomright",
builtin_legend=None,
layer_name=None,
add_header=True,
widget_args={},
**kwargs,
):
"""Adds a customized basemap to the map.
Args:
title (str, optional): Title of the legend. Defaults to 'Legend'.
legend_dict (dict, optional): A dictionary containing legend items
as keys and color as values. If provided, keys and
colors will be ignored. Defaults to None.
keys (list, optional): A list of legend keys. Defaults to None.
colors (list, optional): A list of legend colors. Defaults to None.
position (str, optional): Position of the legend. Defaults to
'bottomright'.
builtin_legend (str, optional): Name of the builtin legend to add
to the map. Defaults to None.
add_header (bool, optional): Whether the legend can be closed or
not. Defaults to True.
widget_args (dict, optional): Additional arguments passed to the
widget_template() function. Defaults to {}.
"""
try:
legend = map_widgets.Legend(
title,
legend_dict,
keys,
colors,
position,
builtin_legend,
add_header,
widget_args,
**kwargs,
)
legend_control = ipyleaflet.WidgetControl(widget=legend, position=position)
self._legend_widget = legend
self._legend = legend_control
self.add(legend_control)
if not hasattr(self, "legends"):
setattr(self, "legends", [legend_control])
else:
self.legends.append(legend_control)
if layer_name in self.ee_layers:
self.ee_layers[layer_name]["legend"] = legend_control
except Exception as e:
raise Exception(e)
def add_colorbar(
self,
vis_params=None,
cmap="gray",
discrete=False,
label=None,
orientation="horizontal",
position="bottomright",
transparent_bg=False,
layer_name=None,
font_size=9,
axis_off=False,
max_width=None,
**kwargs,
):
"""Add a matplotlib colorbar to the map
Args:
vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
label (str, optional): Label for the colorbar. Defaults to None.
orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.
font_size (int, optional): Font size for the colorbar. Defaults to 9.
axis_off (bool, optional): Whether to turn off the axis. Defaults to False.
max_width (str, optional): Maximum width of the colorbar in pixels. Defaults to None.
Raises:
TypeError: If the vis_params is not a dictionary.
ValueError: If the orientation is not either horizontal or vertical.
TypeError: If the provided min value is not scalar type.
TypeError: If the provided max value is not scalar type.
TypeError: If the provided opacity value is not scalar type.
TypeError: If cmap or palette is not provided.
"""
colorbar = map_widgets.Colorbar(
vis_params,
cmap,
discrete,
label,
orientation,
transparent_bg,
font_size,
axis_off,
max_width,
**kwargs,
)
colormap_ctrl = ipyleaflet.WidgetControl(
widget=colorbar, position=position, transparent_bg=transparent_bg
)
self._colorbar = colormap_ctrl
if layer_name in self.ee_layers:
if "colorbar" in self.ee_layers[layer_name]:
self.remove_control(self.ee_layers[layer_name]["colorbar"])
self.ee_layers[layer_name]["colorbar"] = colormap_ctrl
if not hasattr(self, "colorbars"):
self.colorbars = [colormap_ctrl]
else:
self.colorbars.append(colormap_ctrl)
self.add(colormap_ctrl)
def remove_colorbar(self):
"""Remove colorbar from the map."""
if hasattr(self, "_colorbar") and self._colorbar is not None:
self.remove_control(self._colorbar)
def remove_colorbars(self):
"""Remove all colorbars from the map."""
if hasattr(self, "colorbars"):
for colorbar in self.colorbars:
if colorbar in self.controls:
self.remove_control(colorbar)
def remove_legend(self):
"""Remove legend from the map."""
if hasattr(self, "_legend") and self._legend is not None:
if self._legend in self.controls:
self.remove_control(self._legend)
def remove_legends(self):
"""Remove all legends from the map."""
if hasattr(self, "legends"):
for legend in self.legends:
if legend in self.controls:
self.remove_control(legend)
def create_vis_widget(self, layer_dict):
"""Create a GUI for changing layer visualization parameters interactively.
Args:
layer_dict (dict): A dict containing information about the layer. It is an element from Map.ee_layers.
"""
self._add_layer_editor(position="topright", layer_dict=layer_dict)
def add_inspector(
self,
names=None,
visible=True,
decimals=2,
position="topright",
opened=True,
show_close_button=True,
):
"""Add the Inspector GUI to the map.
Args:
names (str | list, optional): The names of the layers to be included. Defaults to None.
visible (bool, optional): Whether to inspect visible layers only. Defaults to True.
decimals (int, optional): The number of decimal places to round the coordinates. Defaults to 2.
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
"""
super()._add_inspector(
position,
names=names,
visible=visible,
decimals=decimals,
opened=opened,
show_close_button=show_close_button,
)
def add_layer_manager(
self, position="topright", opened=True, show_close_button=True
):
"""Add the Layer Manager to the map.
Args:
position (str, optional): The position of the Layer Manager. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
super()._add_layer_manager(position)
if layer_manager := self._layer_manager:
layer_manager.collapsed = not opened
layer_manager.close_button_hidden = not show_close_button
def _on_basemap_changed(self, basemap_name):
if basemap_name not in self.get_layer_names():
self.add_basemap(basemap_name)
if basemap_name in self._xyz_dict:
if "bounds" in self._xyz_dict[basemap_name]:
bounds = self._xyz_dict[basemap_name]["bounds"]
bounds = [bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]]
self.zoom_to_bounds(bounds)
def add_basemap_widget(self, value="OpenStreetMap", position="topright"):
"""Add the Basemap GUI to the map.
Args:
value (str): The default value from basemaps to select. Defaults to "OpenStreetMap".
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
"""
super()._add_basemap_selector(
position, basemaps=list(basemaps.keys()), value=value
)
if basemap_selector := self._basemap_selector:
basemap_selector.on_basemap_changed = self._on_basemap_changed
def add_draw_control(self, position="topleft"):
"""Add a draw control to the map
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add("draw_control", position=position)
def add_draw_control_lite(self, position="topleft"):
"""Add a lite version draw control to the map for the plotting tool.
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add(
"draw_control",
position=position,
marker={},
rectangle={"shapeOptions": {"color": "#3388ff"}},
circle={"shapeOptions": {"color": "#3388ff"}},
circlemarker={},
polyline={},
polygon={},
edit=False,
remove=False,
)
def add_toolbar(self, position="topright", **kwargs):
"""Add a toolbar to the map.
Args:
position (str, optional): The position of the toolbar. Defaults to "topright".
"""
self.add("toolbar", position, **kwargs)
def _toolbar_main_tools(self):
return toolbar.main_tools
def _toolbar_extra_tools(self):
return toolbar.extra_tools
def add_plot_gui(self, position="topright", **kwargs):
"""Adds the plot widget to the map.
Args:
position (str, optional): Position of the widget. Defaults to "topright".
"""
from .toolbar import ee_plot_gui
ee_plot_gui(self, position, **kwargs)
def add_gui(
self, name, position="topright", opened=True, show_close_button=True, **kwargs
):
"""Add a GUI to the map.
Args:
name (str): The name of the GUI. Options include "layer_manager", "inspector", "plot", and "timelapse".
position (str, optional): The position of the GUI. Defaults to "topright".
opened (bool, optional): Whether the GUI is opened. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
name = name.lower()
if name == "layer_manager":
self.add_layer_manager(position, opened, show_close_button, **kwargs)
elif name == "inspector":
self.add_inspector(
position=position,
opened=opened,
show_close_button=show_close_button,
**kwargs,
)
elif name == "plot":
self.add_plot_gui(position, **kwargs)
elif name == "timelapse":
from .toolbar import timelapse_gui
timelapse_gui(self, **kwargs)
# ******************************************************************************#
# The classes and functions above are the core features of the geemap package. #
# The Earth Engine team and the geemap community will maintain these features. #
# ******************************************************************************#
# ******************************************************************************#
# The classes and functions below are the extra features of the geemap package. #
# The geemap community will maintain these features. #
# ******************************************************************************#
def draw_layer_on_top(self):
"""Move user-drawn feature layer to the top of all layers."""
draw_layer_index = self.find_layer_index(name="Drawn Features")
if draw_layer_index > -1 and draw_layer_index < (len(self.layers) - 1):
layers = list(self.layers)
layers = (
layers[0:draw_layer_index]
+ layers[(draw_layer_index + 1) :]
+ [layers[draw_layer_index]]
)
self.layers = layers
def add_marker(self, location, **kwargs):
"""Adds a marker to the map. More info about marker at https://ipyleaflet.readthedocs.io/en/latest/api_reference/marker.html.
Args:
location (list | tuple): The location of the marker in the format of [lat, lng].
**kwargs: Keyword arguments for the marker.
"""
if isinstance(location, list):
location = tuple(location)
if isinstance(location, tuple):
marker = ipyleaflet.Marker(location=location, **kwargs)
self.add(marker)
else:
raise TypeError("The location must be a list or a tuple.")
def add_wms_layer(
self,
url,
layers,
name=None,
attribution="",
format="image/png",
transparent=True,
opacity=1.0,
shown=True,
**kwargs,
):
"""Add a WMS layer to the map.
Args:
url (str): The URL of the WMS web service.
layers (str): Comma-separated list of WMS layers to show.
name (str, optional): The layer name to use on the layer control. Defaults to None.
attribution (str, optional): The attribution of the data layer. Defaults to ''.
format (str, optional): WMS image format (use ‘image/png’ for layers with transparency). Defaults to 'image/png'.
transparent (bool, optional): If True, the WMS service will return images with transparency. Defaults to True.
opacity (float, optional): The opacity of the layer. Defaults to 1.0.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
if name is None:
name = str(layers)
try:
wms_layer = ipyleaflet.WMSLayer(
url=url,
layers=layers,
name=name,
attribution=attribution,
format=format,
transparent=transparent,
opacity=opacity,
visible=shown,
**kwargs,
)
self.add(wms_layer)
except Exception as e:
print("Failed to add the specified WMS TileLayer.")
raise Exception(e)
def zoom_to_me(self, zoom=14, add_marker=True):
"""Zoom to the current device location.
Args:
zoom (int, optional): Zoom level. Defaults to 14.
add_marker (bool, optional): Whether to add a marker of the current device location. Defaults to True.
"""
lat, lon = get_current_latlon()
self.set_center(lon, lat, zoom)
if add_marker:
marker = ipyleaflet.Marker(
location=(lat, lon),
draggable=False,
name="Device location",
)
self.add(marker)
def zoom_to_gdf(self, gdf):
"""Zooms to the bounding box of a GeoPandas GeoDataFrame.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
"""
bounds = gdf.total_bounds
self.zoom_to_bounds(bounds)
def get_bounds(self, asGeoJSON=False):
"""Returns the bounds of the current map view, as a list in the format [west, south, east, north] in degrees.
Args:
asGeoJSON (bool, optional): If true, returns map bounds as GeoJSON. Defaults to False.
Returns:
list | dict: A list in the format [west, south, east, north] in degrees.
"""
bounds = self.bounds
coords = [bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]]
if asGeoJSON:
return ee.Geometry.BBox(
bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]
).getInfo()
else:
return coords
getBounds = get_bounds
def add_cog_layer(
self,
url,
name="Untitled",
attribution="",
opacity=1.0,
shown=True,
bands=None,
titiler_endpoint=None,
**kwargs,
):
"""Adds a COG TileLayer to the map.
Args:
url (str): The URL of the COG tile layer.
name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
bands (list, optional): A list of bands to use for the layer. Defaults to None.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
**kwargs: Arbitrary keyword arguments, including bidx, expression, nodata, unscale, resampling, rescale, color_formula, colormap, colormap_name, return_mask. See https://developmentseed.org/titiler/endpoints/cog/ and https://cogeotiff.github.io/rio-tiler/colormap/. To select a certain bands, use bidx=[1, 2, 3]
"""
tile_url = cog_tile(url, bands, titiler_endpoint, **kwargs)
bounds = cog_bounds(url, titiler_endpoint)
self.add_tile_layer(tile_url, name, attribution, opacity, shown)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
params = {
"url": url,
"titizer_endpoint": titiler_endpoint,
"bounds": bounds,
"type": "COG",
}
self.cog_layer_dict[name] = params
def add_cog_mosaic(self, **kwargs):
raise NotImplementedError(
"This function is no longer supported.See https://github.com/giswqs/leafmap/issues/180."
)
def add_stac_layer(
self,
url=None,
collection=None,
item=None,
assets=None,
bands=None,
titiler_endpoint=None,
name="STAC Layer",
attribution="",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a STAC TileLayer to the map.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.
name (str, optional): The layer name to use for the layer. Defaults to 'STAC Layer'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
tile_url = stac_tile(
url, collection, item, assets, bands, titiler_endpoint, **kwargs
)
bounds = stac_bounds(url, collection, item, titiler_endpoint)
self.add_tile_layer(tile_url, name, attribution, opacity, shown)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
if assets is None and bands is not None:
assets = bands
params = {
"url": url,
"collection": collection,
"item": item,
"assets": assets,
"bounds": bounds,
"titiler_endpoint": titiler_endpoint,
"type": "STAC",
}
self.cog_layer_dict[name] = params
def add_minimap(self, zoom=5, position="bottomright"):
"""Adds a minimap (overview) to the ipyleaflet map.
Args:
zoom (int, optional): Initial map zoom level. Defaults to 5.
position (str, optional): Position of the minimap. Defaults to "bottomright".
"""
minimap = ipyleaflet.Map(
zoom_control=False,
attribution_control=False,
zoom=zoom,
center=self.center,
layers=[get_basemap("ROADMAP")],
)
minimap.layout.width = "150px"
minimap.layout.height = "150px"
ipyleaflet.link((minimap, "center"), (self, "center"))
minimap_control = ipyleaflet.WidgetControl(widget=minimap, position=position)
self.add(minimap_control)
def marker_cluster(self):
"""Adds a marker cluster to the map and returns a list of ee.Feature, which can be accessed using Map.ee_marker_cluster.
Returns:
object: a list of ee.Feature
"""
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
self.ee_markers = []
self.add(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get("coordinates")
if kwargs.get("type") == "click":
coordinates.append(latlon)
geom = ee.Geometry.Point(latlon[1], latlon[0])
feature = ee.Feature(geom)
self.ee_markers.append(feature)
self.last_click = latlon
self.all_clicks = coordinates
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
elif kwargs.get("type") == "mousemove":
pass
# cursor style: https://www.w3schools.com/cssref/pr_class_cursor.asp
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def plot_demo(
self,
iterations=20,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""A demo of interactive plotting using random pixel coordinates.
Args:
iterations (int, optional): How many iterations to run for the demo. Defaults to 20.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
import numpy as np
import time
if hasattr(self, "random_marker") and self.random_marker is not None:
self.remove_layer(self.random_marker)
image = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003").select([0, 1, 2, 3, 4, 6])
self.addLayer(
image,
{"bands": ["B4", "B3", "B2"], "gamma": 1.4},
"LANDSAT/LE7_TOA_5YEAR/1999_2003",
)
self.setCenter(-50.078877, 25.190030, 3)
band_names = image.bandNames().getInfo()
# band_count = len(band_names)
latitudes = np.random.uniform(30, 48, size=iterations)
longitudes = np.random.uniform(-121, -76, size=iterations)
marker = ipyleaflet.Marker(location=(0, 0))
self.random_marker = marker
self.add(marker)
for i in range(iterations):
try:
coordinate = ee.Geometry.Point([longitudes[i], latitudes[i]])
dict_values = image.sample(coordinate).first().toDictionary().getInfo()
band_values = list(dict_values.values())
title = "{}/{}: Spectral signature at ({}, {})".format(
i + 1,
iterations,
round(latitudes[i], 2),
round(longitudes[i], 2),
)
marker.location = (latitudes[i], longitudes[i])
self.plot(
band_names,
band_values,
plot_type=plot_type,
overlay=overlay,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
title=title,
**kwargs,
)
time.sleep(0.3)
except Exception as e:
raise Exception(e)
def plot_raster(
self,
ee_object=None,
sample_scale=None,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Interactive plotting of Earth Engine data by clicking on the map.
Args:
ee_object (object, optional): The ee.Image or ee.ImageCollection to sample. Defaults to None.
sample_scale (float, optional): A nominal scale in meters of the projection to sample in. Defaults to None.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
if hasattr(self, "_plot_control") and self._plot_control is not None:
del self._plot_widget
if self._plot_control in self.controls:
self.remove_control(self._plot_control)
if hasattr(self, "random_marker") and self.random_marker is not None:
self.remove_layer(self.random_marker)
plot_widget = widgets.Output(layout={"border": "1px solid black"})
plot_control = ipyleaflet.WidgetControl(
widget=plot_widget,
position=position,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
)
self._plot_widget = plot_widget
self._plot_control = plot_control
self.add(plot_control)
self.default_style = {"cursor": "crosshair"}
msg = "The plot function can only be used on ee.Image or ee.ImageCollection with more than one band."
if (ee_object is None) and len(self.ee_raster_layers) > 0:
ee_object = self.ee_raster_layers.values()[-1]["ee_object"]
if isinstance(ee_object, ee.ImageCollection):
ee_object = ee_object.mosaic()
elif isinstance(ee_object, ee.ImageCollection):
ee_object = ee_object.mosaic()
elif not isinstance(ee_object, ee.Image):
print(msg)
return
if sample_scale is None:
sample_scale = self.getScale()
if max_width is None:
max_width = 500
band_names = ee_object.bandNames().getInfo()
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
self.add(marker_cluster)
def handle_interaction(**kwargs2):
latlon = kwargs2.get("coordinates")
if kwargs2.get("type") == "click":
try:
coordinates.append(latlon)
self.last_click = latlon
self.all_clicks = coordinates
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
self.default_style = {"cursor": "wait"}
xy = ee.Geometry.Point(latlon[::-1])
dict_values = (
ee_object.sample(xy, scale=sample_scale)
.first()
.toDictionary()
.getInfo()
)
band_values = list(dict_values.values())
self.plot(
band_names,
band_values,
plot_type=plot_type,
overlay=overlay,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
**kwargs,
)
self.default_style = {"cursor": "crosshair"}
except Exception as e:
if self._plot_widget is not None:
with self._plot_widget:
self._plot_widget.outputs = ()
print("No data for the clicked location.")
else:
print(e)
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def add_marker_cluster(self, event="click", add_marker=True):
"""Captures user inputs and add markers to the map.
Args:
event (str, optional): [description]. Defaults to 'click'.
add_marker (bool, optional): If True, add markers to the map. Defaults to True.
Returns:
object: a marker cluster.
"""
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
if add_marker:
self.add(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get("coordinates")
if event == "click" and kwargs.get("type") == "click":
coordinates.append(latlon)
self.last_click = latlon
self.all_clicks = coordinates
if add_marker:
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
elif kwargs.get("type") == "mousemove":
pass
# cursor style: https://www.w3schools.com/cssref/pr_class_cursor.asp
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def set_control_visibility(
self, layerControl=True, fullscreenControl=True, latLngPopup=True
):
"""Sets the visibility of the controls on the map.
Args:
layerControl (bool, optional): Whether to show the control that allows the user to toggle layers on/off. Defaults to True.
fullscreenControl (bool, optional): Whether to show the control that allows the user to make the map full-screen. Defaults to True.
latLngPopup (bool, optional): Whether to show the control that pops up the Lat/lon when the user clicks on the map. Defaults to True.
"""
pass
setControlVisibility = set_control_visibility
def split_map(
self,
left_layer="OpenTopoMap",
right_layer="Esri.WorldTopoMap",
zoom_control=True,
fullscreen_control=True,
layer_control=True,
add_close_button=False,
close_button_position="topright",
left_label=None,
right_label=None,
left_position="bottomleft",
right_position="bottomright",
widget_layout=None,
**kwargs,
):
"""Adds split map.
Args:
left_layer (str, optional): The layer tile layer. Defaults to 'OpenTopoMap'.
right_layer (str, optional): The right tile layer. Defaults to 'Esri.WorldTopoMap'.
zoom_control (bool, optional): Whether to show the zoom control. Defaults to True.
fullscreen_control (bool, optional): Whether to show the full screen control. Defaults to True.
layer_control (bool, optional): Whether to show the layer control. Defaults to True.
add_close_button (bool, optional): Whether to add a close button. Defaults to False.
close_button_position (str, optional): The position of the close button. Defaults to 'topright'.
left_label (str, optional): The label for the left map. Defaults to None.
right_label (str, optional): The label for the right map. Defaults to None.
left_position (str, optional): The position of the left label. Defaults to 'bottomleft'.
right_position (str, optional): The position of the right label. Defaults to 'bottomright'.
widget_layout (str, optional): The layout of the label widget, such as ipywidgets.Layout(padding="0px 4px 0px 4px"). Defaults to None.
kwargs: Other arguments for ipyleaflet.TileLayer.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
controls = self.controls
layers = self.layers
self.clear_controls()
if zoom_control:
self.add(ipyleaflet.ZoomControl())
if fullscreen_control:
self.add(ipyleaflet.FullScreenControl())
if left_label is not None:
left_name = left_label
else:
left_name = "Left Layer"
if right_label is not None:
right_name = right_label
else:
right_name = "Right Layer"
if "attribution" not in kwargs:
kwargs["attribution"] = " "
if left_layer in basemaps.keys():
left_layer = get_basemap(left_layer)
elif isinstance(left_layer, str):
if left_layer.startswith("http") and left_layer.endswith(".tif"):
url = cog_tile(left_layer)
left_layer = ipyleaflet.TileLayer(
url=url,
name=left_name,
**kwargs,
)
else:
left_layer = ipyleaflet.TileLayer(
url=left_layer,
name=left_name,
**kwargs,
)
elif isinstance(left_layer, ipyleaflet.TileLayer):
pass
else:
raise ValueError(
f"left_layer must be one of the following: {', '.join(basemaps.keys())} or a string url to a tif file."
)
if right_layer in basemaps.keys():
right_layer = get_basemap(right_layer)
elif isinstance(right_layer, str):
if right_layer.startswith("http") and right_layer.endswith(".tif"):
url = cog_tile(right_layer)
right_layer = ipyleaflet.TileLayer(
url=url,
name=right_name,
**kwargs,
)
else:
right_layer = ipyleaflet.TileLayer(
url=right_layer,
name=right_name,
**kwargs,
)
elif isinstance(right_layer, ipyleaflet.TileLayer):
pass
else:
raise ValueError(
f"right_layer must be one of the following: {', '.join(basemaps.keys())} or a string url to a tif file."
)
control = ipyleaflet.SplitMapControl(
left_layer=left_layer, right_layer=right_layer
)
self.add(control)
self.dragging = False
if left_label is not None:
if widget_layout is None:
widget_layout = widgets.Layout(padding="0px 4px 0px 4px")
left_widget = widgets.HTML(value=left_label, layout=widget_layout)
left_control = ipyleaflet.WidgetControl(
widget=left_widget, position=left_position
)
self.add(left_control)
if right_label is not None:
if widget_layout is None:
widget_layout = widgets.Layout(padding="0px 4px 0px 4px")
right_widget = widgets.HTML(value=right_label, layout=widget_layout)
right_control = ipyleaflet.WidgetControl(
widget=right_widget, position=right_position
)
self.add(right_control)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close split-panel map",
icon="times",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
def close_btn_click(change):
if left_label is not None:
self.remove_control(left_control)
if right_label is not None:
self.remove_control(right_control)
if change["new"]:
self.controls = controls
self.layers = layers[:-1]
self.add(layers[-1])
self.dragging = True
close_button.observe(close_btn_click, "value")
close_control = ipyleaflet.WidgetControl(
widget=close_button, position=close_button_position
)
if add_close_button:
self.add(close_control)
if layer_control:
self.addLayerControl()
except Exception as e:
print("The provided layers are invalid!")
raise ValueError(e)
def ts_inspector(
self,
left_ts,
left_names=None,
left_vis={},
left_index=0,
right_ts=None,
right_names=None,
right_vis=None,
right_index=-1,
width="130px",
date_format="YYYY-MM-dd",
add_close_button=False,
**kwargs,
):
"""Creates a split-panel map for inspecting timeseries images.
Args:
left_ts (object): An ee.ImageCollection to show on the left panel.
left_names (list): A list of names to show under the left dropdown.
left_vis (dict, optional): Visualization parameters for the left layer. Defaults to {}.
left_index (int, optional): The index of the left layer to show. Defaults to 0.
right_ts (object): An ee.ImageCollection to show on the right panel.
right_names (list): A list of names to show under the right dropdown.
right_vis (dict, optional): Visualization parameters for the right layer. Defaults to {}.
right_index (int, optional): The index of the right layer to show. Defaults to -1.
width (str, optional): The width of the dropdown list. Defaults to '130px'.
date_format (str, optional): The date format to show in the dropdown. Defaults to 'YYYY-MM-dd'.
add_close_button (bool, optional): Whether to show the close button. Defaults to False.
"""
controls = self.controls
layers = self.layers
if left_names is None:
left_names = image_dates(left_ts, date_format=date_format).getInfo()
if right_ts is None:
right_ts = left_ts
if right_names is None:
right_names = left_names
if right_vis is None:
right_vis = left_vis
left_count = int(left_ts.size().getInfo())
right_count = int(right_ts.size().getInfo())
if left_count != len(left_names):
print(
"The number of images in left_ts must match the number of layer names in left_names."
)
return
if right_count != len(right_names):
print(
"The number of images in right_ts must match the number of layer names in right_names."
)
return
left_layer = ipyleaflet.TileLayer(
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
attribution="Esri",
name="Esri.WorldStreetMap",
)
right_layer = ipyleaflet.TileLayer(
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
attribution="Esri",
name="Esri.WorldStreetMap",
)
self.clear_controls()
left_dropdown = widgets.Dropdown(options=left_names, value=None)
right_dropdown = widgets.Dropdown(options=right_names, value=None)
left_dropdown.layout.max_width = width
right_dropdown.layout.max_width = width
left_control = ipyleaflet.WidgetControl(
widget=left_dropdown, position="topleft"
)
right_control = ipyleaflet.WidgetControl(
widget=right_dropdown, position="topright"
)
self.add(left_control)
self.add(right_control)
self.add(ipyleaflet.ZoomControl(position="topleft"))
self.add(ipyleaflet.ScaleControl(position="bottomleft"))
self.add(ipyleaflet.FullScreenControl())
def left_dropdown_change(change):
left_dropdown_index = left_dropdown.index
if left_dropdown_index is not None and left_dropdown_index >= 0:
try:
if isinstance(left_ts, ee.ImageCollection):
left_image = left_ts.toList(left_ts.size()).get(
left_dropdown_index
)
elif isinstance(left_ts, ee.List):
left_image = left_ts.get(left_dropdown_index)
else:
print("The left_ts argument must be an ImageCollection.")
return
if isinstance(left_image, ee.ImageCollection):
left_image = ee.Image(left_image.mosaic())
elif isinstance(left_image, ee.Image):
pass
else:
left_image = ee.Image(left_image)
left_image = EELeafletTileLayer(
left_image, left_vis, left_names[left_dropdown_index]
)
left_layer.url = left_image.url
except Exception as e:
print(e)
return
left_dropdown.observe(left_dropdown_change, names="value")
def right_dropdown_change(change):
right_dropdown_index = right_dropdown.index
if right_dropdown_index is not None and right_dropdown_index >= 0:
try:
if isinstance(right_ts, ee.ImageCollection):
right_image = right_ts.toList(left_ts.size()).get(
right_dropdown_index
)
elif isinstance(right_ts, ee.List):
right_image = right_ts.get(right_dropdown_index)
else:
print("The left_ts argument must be an ImageCollection.")
return
if isinstance(right_image, ee.ImageCollection):
right_image = ee.Image(right_image.mosaic())
elif isinstance(right_image, ee.Image):
pass
else:
right_image = ee.Image(right_image)
right_image = EELeafletTileLayer(
right_image,
right_vis,
right_names[right_dropdown_index],
)
right_layer.url = right_image.url
except Exception as e:
print(e)
return
right_dropdown.observe(right_dropdown_change, names="value")
if left_index is not None:
left_dropdown.value = left_names[left_index]
if right_index is not None:
right_dropdown.value = right_names[right_index]
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
# button_style="primary",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
def close_btn_click(change):
if change["new"]:
self.controls = controls
self.clear_layers()
self.layers = layers
close_button.observe(close_btn_click, "value")
close_control = ipyleaflet.WidgetControl(
widget=close_button, position="bottomright"
)
try:
split_control = ipyleaflet.SplitMapControl(
left_layer=left_layer, right_layer=right_layer
)
self.add(split_control)
self.dragging = False
if add_close_button:
self.add(close_control)
except Exception as e:
raise Exception(e)
def basemap_demo(self):
"""A demo for using geemap basemaps."""
dropdown = widgets.Dropdown(
options=list(basemaps.keys()),
value="HYBRID",
description="Basemaps",
)
def on_click(change):
basemap_name = change["new"]
old_basemap = self.layers[-1]
self.substitute_layer(old_basemap, get_basemap(basemaps[basemap_name]))
dropdown.observe(on_click, "value")
basemap_control = ipyleaflet.WidgetControl(widget=dropdown, position="topright")
self.add(basemap_control)
def add_colorbar_branca(
self,
colors,
vmin=0,
vmax=1.0,
index=None,
caption="",
categorical=False,
step=None,
height="45px",
transparent_bg=False,
position="bottomright",
layer_name=None,
**kwargs,
):
"""Add a branca colorbar to the map.
Args:
colors (list): The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)
vmin (int, optional): The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.
vmax (float, optional): The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.
index (list, optional):The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.
caption (str, optional): The caption for the colormap. Defaults to "".
categorical (bool, optional): Whether or not to create a categorical colormap. Defaults to False.
step (int, optional): The step to split the LinearColormap into a StepColormap. Defaults to None.
height (str, optional): The height of the colormap widget. Defaults to "45px".
transparent_bg (bool, optional): Whether to use transparent background for the colormap widget. Defaults to True.
position (str, optional): The position for the colormap widget. Defaults to "bottomright".
layer_name (str, optional): Layer name of the colorbar to be associated with. Defaults to None.
"""
from branca.colormap import LinearColormap
output = widgets.Output()
output.layout.height = height
if "width" in kwargs:
output.layout.width = kwargs["width"]
if isinstance(colors, Box):
try:
colors = list(colors["default"])
except Exception as e:
print("The provided color list is invalid.")
raise Exception(e)
if all(len(color) == 6 for color in colors):
colors = ["#" + color for color in colors]
colormap = LinearColormap(
colors=colors, index=index, vmin=vmin, vmax=vmax, caption=caption
)
if categorical:
if step is not None:
colormap = colormap.to_step(step)
elif index is not None:
colormap = colormap.to_step(len(index) - 1)
else:
colormap = colormap.to_step(3)
colormap_ctrl = ipyleaflet.WidgetControl(
widget=output,
position=position,
transparent_bg=transparent_bg,
**kwargs,
)
with output:
output.outputs = ()
display(colormap)
self._colorbar = colormap_ctrl
self.add(colormap_ctrl)
if not hasattr(self, "colorbars"):
self.colorbars = [colormap_ctrl]
else:
self.colorbars.append(colormap_ctrl)
if layer_name in self.ee_layers:
self.ee_layers[layer_name]["colorbar"] = colormap_ctrl
def image_overlay(self, url, bounds, name):
"""Overlays an image from the Internet or locally on the map.
Args:
url (str): http URL or local file path to the image.
bounds (tuple): bounding box of the image in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).
name (str): name of the layer to show on the layer control.
"""
from base64 import b64encode
from io import BytesIO
from PIL import Image, ImageSequence
try:
if not url.startswith("http"):
if not os.path.exists(url):
print("The provided file does not exist.")
return
ext = os.path.splitext(url)[1][1:] # file extension
image = Image.open(url)
f = BytesIO()
if ext.lower() == "gif":
frames = []
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(image):
frame = frame.convert("RGBA")
b = BytesIO()
frame.save(b, format="gif")
frame = Image.open(b)
frames.append(frame)
frames[0].save(
f,
format="GIF",
save_all=True,
append_images=frames[1:],
loop=0,
)
else:
image.save(f, ext)
data = b64encode(f.getvalue())
data = data.decode("ascii")
url = "data:image/{};base64,".format(ext) + data
img = ipyleaflet.ImageOverlay(url=url, bounds=bounds, name=name)
self.add(img)
except Exception as e:
print(e)
def video_overlay(self, url, bounds, name="Video"):
"""Overlays a video from the Internet on the map.
Args:
url (str): http URL of the video, such as "https://www.mapbox.com/bites/00188/patricia_nasa.webm"
bounds (tuple): bounding box of the video in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).
name (str): name of the layer to show on the layer control.
"""
try:
video = ipyleaflet.VideoOverlay(url=url, bounds=bounds, name=name)
self.add(video)
except Exception as e:
print(e)
def add_landsat_ts_gif(
self,
layer_name="Timelapse",
roi=None,
label=None,
start_year=1984,
end_year=2021,
start_date="06-10",
end_date="09-20",
bands=["NIR", "Red", "Green"],
vis_params=None,
dimensions=768,
frames_per_second=10,
font_size=30,
font_color="white",
add_progress_bar=True,
progress_bar_color="white",
progress_bar_height=5,
out_gif=None,
download=False,
apply_fmask=True,
nd_bands=None,
nd_threshold=0,
nd_palette=["black", "blue"],
):
"""Adds a Landsat timelapse to the map.
Args:
layer_name (str, optional): Layer name to show under the layer control. Defaults to 'Timelapse'.
roi (object, optional): Region of interest to create the timelapse. Defaults to None.
label (str, optional): A label to show on the GIF, such as place name. Defaults to None.
start_year (int, optional): Starting year for the timelapse. Defaults to 1984.
end_year (int, optional): Ending year for the timelapse. Defaults to 2021.
start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'.
end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'.
bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green'].
vis_params (dict, optional): Visualization parameters. Defaults to None.
dimensions (int, optional): a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768.
frames_per_second (int, optional): Animation speed. Defaults to 10.
font_size (int, optional): Font size of the animated text and label. Defaults to 30.
font_color (str, optional): Font color of the animated text and label. Defaults to 'black'.
add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True.
progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'.
progress_bar_height (int, optional): Height of the progress bar. Defaults to 5.
out_gif (str, optional): File path to the output animated GIF. Defaults to None.
download (bool, optional): Whether to download the gif. Defaults to False.
apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking.
nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1).
nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band.
nd_palette (str, optional): The color palette to use for displaying the normalized difference band.
"""
try:
if roi is None:
if self.draw_last_feature is not None:
feature = self.draw_last_feature
roi = feature.geometry()
else:
roi = ee.Geometry.Polygon(
[
[
[-115.471773, 35.892718],
[-115.471773, 36.409454],
[-114.271283, 36.409454],
[-114.271283, 35.892718],
[-115.471773, 35.892718],
]
],
None,
False,
)
elif isinstance(roi, ee.Feature) or isinstance(roi, ee.FeatureCollection):
roi = roi.geometry()
elif isinstance(roi, ee.Geometry):
pass
else:
print("The provided roi is invalid. It must be an ee.Geometry")
return
geojson = ee_to_geojson(roi)
bounds = minimum_bounding_box(geojson)
geojson = adjust_longitude(geojson)
roi = ee.Geometry(geojson)
in_gif = landsat_timelapse(
roi=roi,
out_gif=out_gif,
start_year=start_year,
end_year=end_year,
start_date=start_date,
end_date=end_date,
bands=bands,
vis_params=vis_params,
dimensions=dimensions,
frames_per_second=frames_per_second,
apply_fmask=apply_fmask,
nd_bands=nd_bands,
nd_threshold=nd_threshold,
nd_palette=nd_palette,
font_size=font_size,
font_color=font_color,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
in_nd_gif = in_gif.replace(".gif", "_nd.gif")
if nd_bands is not None:
add_text_to_gif(
in_nd_gif,
in_nd_gif,
xy=("2%", "2%"),
text_sequence=start_year,
font_size=font_size,
font_color=font_color,
duration=int(1000 / frames_per_second),
add_progress_bar=add_progress_bar,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
if label is not None:
add_text_to_gif(
in_gif,
in_gif,
xy=("2%", "90%"),
text_sequence=label,
font_size=font_size,
font_color=font_color,
duration=int(1000 / frames_per_second),
add_progress_bar=add_progress_bar,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
# if nd_bands is not None:
# add_text_to_gif(in_nd_gif, in_nd_gif, xy=('2%', '90%'), text_sequence=label,
# font_size=font_size, font_color=font_color, duration=int(1000 / frames_per_second), add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height)
if is_tool("ffmpeg"):
reduce_gif_size(in_gif)
if nd_bands is not None:
reduce_gif_size(in_nd_gif)
print("Adding GIF to the map ...")
self.image_overlay(url=in_gif, bounds=bounds, name=layer_name)
if nd_bands is not None:
self.image_overlay(
url=in_nd_gif, bounds=bounds, name=layer_name + " ND"
)
print("The timelapse has been added to the map.")
if download:
link = create_download_link(
in_gif,
title="Click here to download the Landsat timelapse: ",
)
display(link)
if nd_bands is not None:
link2 = create_download_link(
in_nd_gif,
title="Click here to download the Normalized Difference Index timelapse: ",
)
display(link2)
except Exception as e:
raise Exception(e)
def to_html(
self,
filename=None,
title="My Map",
width="100%",
height="880px",
add_layer_control=True,
**kwargs,
):
"""Saves the map as an HTML file.
Args:
filename (str, optional): The output file path to the HTML file.
title (str, optional): The title of the HTML file. Defaults to 'My Map'.
width (str, optional): The width of the map in pixels or percentage. Defaults to '100%'.
height (str, optional): The height of the map in pixels. Defaults to '880px'.
add_layer_control (bool, optional): Whether to add the LayersControl. Defaults to True.
"""
try:
save = True
if filename is not None:
if not filename.endswith(".html"):
raise ValueError("The output file extension must be html.")
filename = os.path.abspath(filename)
out_dir = os.path.dirname(filename)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
filename = os.path.abspath(random_string() + ".html")
save = False
if add_layer_control and self.layer_control is None:
layer_control = ipyleaflet.LayersControl(position="topright")
self.layer_control = layer_control
self.add(layer_control)
before_width = self.layout.width
before_height = self.layout.height
if not isinstance(width, str):
print("width must be a string.")
return
elif width.endswith("px") or width.endswith("%"):
pass
else:
print("width must end with px or %")
return
if not isinstance(height, str):
print("height must be a string.")
return
elif not height.endswith("px"):
print("height must end with px")
return
self.layout.width = width
self.layout.height = height
self.save(filename, title=title, **kwargs)
self.layout.width = before_width
self.layout.height = before_height
if not save:
out_html = ""
with open(filename) as f:
lines = f.readlines()
out_html = "".join(lines)
os.remove(filename)
return out_html
except Exception as e:
raise Exception(e)
def to_image(self, filename=None, monitor=1):
"""Saves the map as a PNG or JPG image.
Args:
filename (str, optional): The output file path to the image. Defaults to None.
monitor (int, optional): The monitor to take the screenshot. Defaults to 1.
"""
self.screenshot = None
if filename is None:
filename = os.path.join(os.getcwd(), "my_map.png")
if filename.endswith(".png") or filename.endswith(".jpg"):
pass
else:
print("The output file must be a PNG or JPG image.")
return
work_dir = os.path.dirname(filename)
if not os.path.exists(work_dir):
os.makedirs(work_dir)
screenshot = screen_capture(filename, monitor)
self.screenshot = screenshot
def toolbar_reset(self):
"""Reset the toolbar so that no tool is selected."""
if hasattr(self, "_toolbar"):
self._toolbar.reset()
def add_raster(
self,
source,
indexes=None,
colormap=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name="Raster",
zoom_to_layer=True,
visible=True,
array_args={},
**kwargs,
):
"""Add a local raster dataset to the map.
If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer) and
if the raster does not render properly, try installing jupyter-server-proxy using `pip install jupyter-server-proxy`,
then running the following code before calling this function. For more info, see https://bit.ly/3JbmF93.
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}'
Args:
source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.
indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None.
colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to 'Raster'.
zoom_to_layer (bool, optional): Whether to zoom to the extent of the layer. Defaults to True.
visible (bool, optional): Whether the layer is visible. Defaults to True.
array_args (dict, optional): Additional arguments to pass to `array_to_memory_file` when reading the raster. Defaults to {}.
"""
import numpy as np
import xarray as xr
if isinstance(source, np.ndarray) or isinstance(source, xr.DataArray):
source = array_to_image(source, **array_args)
tile_layer, tile_client = get_local_tile_layer(
source,
indexes=indexes,
colormap=colormap,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
return_client=True,
**kwargs,
)
tile_layer.visible = visible
self.add(tile_layer)
bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax]
bounds = (
bounds[2],
bounds[0],
bounds[3],
bounds[1],
) # [minx, miny, maxx, maxy]
if zoom_to_layer:
self.zoom_to_bounds(bounds)
arc_add_layer(tile_layer.url, layer_name, True, 1.0)
if zoom_to_layer:
arc_zoom_to_extent(bounds[0], bounds[1], bounds[2], bounds[3])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
params = {
"tile_layer": tile_layer,
"tile_client": tile_client,
"indexes": indexes,
"band_names": tile_client.band_names,
"bounds": bounds,
"type": "LOCAL",
}
self.cog_layer_dict[layer_name] = params
def add_remote_tile(
self,
source,
band=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name=None,
**kwargs,
):
"""Add a remote Cloud Optimized GeoTIFF (COG) to the map.
Args:
source (str): The path to the remote Cloud Optimized GeoTIFF.
band (int, optional): The band to use. Band indexing starts at 1. Defaults to None.
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to None.
"""
if isinstance(source, str) and source.startswith("http"):
self.add_raster(
source,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
**kwargs,
)
else:
raise Exception("The source must be a URL.")
def remove_draw_control(self):
"""Removes the draw control from the map"""
self.remove("draw_control")
def remove_drawn_features(self):
"""Removes user-drawn geometries from the map"""
if self._draw_control is not None:
self._draw_control.reset()
if "Drawn Features" in self.ee_layers:
self.ee_layers.pop("Drawn Features")
def remove_last_drawn(self):
"""Removes last user-drawn geometry from the map"""
if self._draw_control is not None:
if self._draw_control.count == 1:
self.remove_drawn_features()
elif self._draw_control.count:
self._draw_control.remove_geometry(self._draw_control.geometries[-1])
if hasattr(self, "_chart_values"):
self._chart_values = self._chart_values[:-1]
if hasattr(self, "_chart_points"):
self._chart_points = self._chart_points[:-1]
# self._chart_labels = None
def extract_values_to_points(self, filename):
"""Exports pixel values to a csv file based on user-drawn geometries.
Args:
filename (str): The output file path to the csv file or shapefile.
"""
import csv
filename = os.path.abspath(filename)
allowed_formats = ["csv", "shp"]
ext = filename[-3:]
if ext not in allowed_formats:
print(
"The output file must be one of the following: {}".format(
", ".join(allowed_formats)
)
)
return
out_dir = os.path.dirname(filename)
out_csv = filename[:-3] + "csv"
out_shp = filename[:-3] + "shp"
if not os.path.exists(out_dir):
os.makedirs(out_dir)
count = len(self._chart_points)
out_list = []
if count > 0:
header = ["id", "longitude", "latitude"] + self._chart_labels
out_list.append(header)
for i in range(0, count):
id = i + 1
line = [id] + self._chart_points[i] + self._chart_values[i]
out_list.append(line)
with open(out_csv, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(out_list)
if ext == "csv":
print(f"The csv file has been saved to: {out_csv}")
else:
csv_to_shp(out_csv, out_shp)
print(f"The shapefile has been saved to: {out_shp}")
def add_styled_vector(
self,
ee_object,
column,
palette,
layer_name="Untitled",
shown=True,
opacity=1.0,
**kwargs,
):
"""Adds a styled vector to the map.
Args:
ee_object (object): An ee.FeatureCollection.
column (str): The column name to use for styling.
palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling.
layer_name (str, optional): The name to be used for the new layer. Defaults to "Untitled".
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): The opacity of the layer. Defaults to 1.0.
"""
if isinstance(palette, str):
from .colormaps import get_palette
count = ee_object.size().getInfo()
palette = get_palette(palette, count)
styled_vector = vector_styling(ee_object, column, palette, **kwargs)
self.addLayer(
styled_vector.style(**{"styleProperty": "style"}),
{},
layer_name,
shown,
opacity,
)
def add_shp(
self,
in_shp,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
):
"""Adds a shapefile to the map.
Args:
in_shp (str): The input file path to the shapefile.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the shapefile. Defaults to "utf-8".
Raises:
FileNotFoundError: The provided shapefile could not be found.
"""
in_shp = os.path.abspath(in_shp)
if not os.path.exists(in_shp):
raise FileNotFoundError("The provided shapefile could not be found.")
geojson = shp_to_geojson(in_shp)
self.add_geojson(
geojson,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
add_shapefile = add_shp
def add_geojson(
self,
in_geojson,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
):
"""Adds a GeoJSON file to the map.
Args:
in_geojson (str | dict): The file path or http URL to the input GeoJSON or a dictionary containing the geojson.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the GeoJSON file. Defaults to "utf-8".
Raises:
FileNotFoundError: The provided GeoJSON file could not be found.
"""
import json
import random
import requests
import warnings
warnings.filterwarnings("ignore")
style_callback_only = False
if len(style) == 0 and style_callback is not None:
style_callback_only = True
try:
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
in_geojson = github_raw_url(in_geojson)
data = requests.get(in_geojson).json()
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError(
"The provided GeoJSON file could not be found."
)
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
else:
raise TypeError("The input geojson must be a type of str or dict.")
except Exception as e:
raise Exception(e)
if not style:
style = {
# "stroke": True,
"color": "#000000",
"weight": 1,
"opacity": 1,
# "fill": True,
# "fillColor": "#ffffff",
"fillOpacity": 0.1,
# "dashArray": "9"
# "clickable": True,
}
elif "weight" not in style:
style["weight"] = 1
if not hover_style:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
def random_color(feature):
return {
"color": "black",
"fillColor": random.choice(fill_colors),
}
toolbar_button = widgets.ToggleButton(
value=True,
tooltip="Toolbar",
icon="info",
layout=widgets.Layout(
width="28px", height="28px", padding="0px 0px 0px 4px"
),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
# button_style="primary",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
html = widgets.HTML()
html.layout.margin = "0px 10px 0px 10px"
html.layout.max_height = "250px"
html.layout.max_width = "250px"
output_widget = widgets.VBox(
[widgets.HBox([toolbar_button, close_button]), html]
)
info_control = ipyleaflet.WidgetControl(
widget=output_widget, position="bottomright"
)
if info_mode in ["on_hover", "on_click"]:
self.add(info_control)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
output_widget.children = [
widgets.VBox([widgets.HBox([toolbar_button, close_button]), html])
]
else:
output_widget.children = [widgets.HBox([toolbar_button, close_button])]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if info_control in self.controls:
self.remove_control(info_control)
output_widget.close()
close_button.observe(close_btn_click, "value")
def update_html(feature, **kwargs):
value = [
"<b>{}: </b>{}<br>".format(prop, feature["properties"][prop])
for prop in feature["properties"].keys()
][:-1]
value = """{}""".format("".join(value))
html.value = value
if style_callback is None:
style_callback = random_color
if style_callback_only:
geojson = ipyleaflet.GeoJSON(
data=data,
hover_style=hover_style,
style_callback=style_callback,
name=layer_name,
)
else:
geojson = ipyleaflet.GeoJSON(
data=data,
style=style,
hover_style=hover_style,
style_callback=style_callback,
name=layer_name,
)
if info_mode == "on_hover":
geojson.on_hover(update_html)
elif info_mode == "on_click":
geojson.on_click(update_html)
self.add(geojson)
self.geojson_layers.append(geojson)
if not hasattr(self, "json_layer_dict"):
self.json_layer_dict = {}
params = {
"data": geojson,
"style": style,
"hover_style": hover_style,
"style_callback": style_callback,
}
self.json_layer_dict[layer_name] = params
def add_kml(
self,
in_kml,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds a GeoJSON file to the map.
Args:
in_kml (str): The input file path to the KML.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
Raises:
FileNotFoundError: The provided KML file could not be found.
"""
if isinstance(in_kml, str) and in_kml.startswith("http"):
in_kml = github_raw_url(in_kml)
in_kml = download_file(in_kml)
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The provided KML file could not be found.")
self.add_vector(
in_kml,
layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
def add_vector(
self,
filename,
layer_name="Untitled",
to_ee=False,
bbox=None,
mask=None,
rows=None,
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
**kwargs,
):
"""Adds any geopandas-supported vector dataset to the map.
Args:
filename (str): Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).
layer_name (str, optional): The layer name to use. Defaults to "Untitled".
to_ee (bool, optional): Whether to convert the GeoJSON to ee.FeatureCollection. Defaults to False.
bbox (tuple | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.
mask (dict | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.
rows (int or slice, optional): Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding to use to read the file. Defaults to "utf-8".
"""
if not filename.startswith("http"):
filename = os.path.abspath(filename)
else:
filename = github_raw_url(filename)
if to_ee:
fc = vector_to_ee(
filename,
bbox=bbox,
mask=mask,
rows=rows,
geodesic=True,
**kwargs,
)
self.addLayer(fc, {}, layer_name)
else:
ext = os.path.splitext(filename)[1].lower()
if ext == ".shp":
self.add_shapefile(
filename,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
elif ext in [".json", ".geojson"]:
self.add_geojson(
filename,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
else:
geojson = vector_to_geojson(
filename,
bbox=bbox,
mask=mask,
rows=rows,
epsg="4326",
**kwargs,
)
self.add_geojson(
geojson,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
def add_osm(
self,
query,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
which_result=None,
by_osmid=False,
buffer_dist=None,
to_ee=False,
geodesic=True,
):
"""Adds OSM data to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
to_ee (bool, optional): Whether to convert the csv to an ee.FeatureCollection.
geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected.
"""
gdf = osm_to_gdf(
query, which_result=which_result, by_osmid=by_osmid, buffer_dist=buffer_dist
)
geojson = gdf.__geo_interface__
if to_ee:
fc = geojson_to_ee(geojson, geodesic=geodesic)
self.addLayer(fc, {}, layer_name)
self.zoomToObject(fc)
else:
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
bounds = gdf.bounds.iloc[0]
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def add_osm_from_geocode(
self,
query,
which_result=None,
by_osmid=False,
buffer_dist=None,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM data of place(s) by name or ID to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_geocode
gdf = osm_gdf_from_geocode(
query, which_result=which_result, by_osmid=by_osmid, buffer_dist=buffer_dist
)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_address(
self,
address,
tags,
dist=1000,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within some distance N, S, E, W of address to the map.
Args:
address (str): The address to geocode and use as the central point around which to get the geometries.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
dist (int, optional): Distance in meters. Defaults to 1000.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_address
gdf = osm_gdf_from_address(address, tags, dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_place(
self,
query,
tags,
which_result=None,
buffer_dist=None,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within boundaries of geocodable place(s) to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_place
gdf = osm_gdf_from_place(query, tags, which_result, buffer_dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_point(
self,
center_point,
tags,
dist=1000,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within some distance N, S, E, W of a point to the map.
Args:
center_point (tuple): The (lat, lng) center point around which to get the geometries.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
dist (int, optional): Distance in meters. Defaults to 1000.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_point
gdf = osm_gdf_from_point(center_point, tags, dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_polygon(
self,
polygon,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within boundaries of a (multi)polygon to the map.
Args:
polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_polygon
gdf = osm_gdf_from_polygon(polygon, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_bbox(
self,
north,
south,
east,
west,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within a N, S, E, W bounding box to the map.
Args:
north (float): Northern latitude of bounding box.
south (float): Southern latitude of bounding box.
east (float): Eastern longitude of bounding box.
west (float): Western longitude of bounding box.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_bbox
gdf = osm_gdf_from_bbox(north, south, east, west, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_view(
self,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within the current map view to the map.
Args:
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_bbox
bounds = self.bounds
if len(bounds) == 0:
bounds = (
(40.74824858675827, -73.98933637940563),
(40.75068694343106, -73.98364473187601),
)
north, south, east, west = (
bounds[1][0],
bounds[0][0],
bounds[1][1],
bounds[0][1],
)
gdf = osm_gdf_from_bbox(north, south, east, west, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_gdf(
self,
gdf,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
zoom_to_layer=True,
encoding="utf-8",
):
"""Adds a GeoDataFrame to the map.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
zoom_to_layer (bool, optional): Whether to zoom to the layer.
encoding (str, optional): The encoding of the GeoDataFrame. Defaults to "utf-8".
"""
data = gdf_to_geojson(gdf, epsg="4326")
self.add_geojson(
data,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
if zoom_to_layer:
import numpy as np
bounds = gdf.to_crs(epsg="4326").bounds
west = np.min(bounds["minx"])
south = np.min(bounds["miny"])
east = np.max(bounds["maxx"])
north = np.max(bounds["maxy"])
self.fit_bounds([[south, east], [north, west]])
def add_gdf_from_postgis(
self,
sql,
con,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
zoom_to_layer=True,
**kwargs,
):
"""Reads a PostGIS database and returns data as a GeoDataFrame to be added to the map.
Args:
sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database.
con (sqlalchemy.engine.Engine): Active connection to the database to query.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
zoom_to_layer (bool, optional): Whether to zoom to the layer.
"""
gdf = read_postgis(sql, con, **kwargs)
gdf = gdf.to_crs("epsg:4326")
self.add_gdf(
gdf,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
zoom_to_layer,
)
def add_time_slider(
self,
ee_object,
vis_params={},
region=None,
layer_name="Time series",
labels=None,
time_interval=1,
position="bottomright",
slider_length="150px",
date_format="YYYY-MM-dd",
opacity=1.0,
**kwargs,
):
"""Adds a time slider to the map.
Args:
ee_object (ee.Image | ee.ImageCollection): The Image or ImageCollection to visualize.
vis_params (dict, optional): Visualization parameters to use for visualizing image. Defaults to {}.
region (ee.Geometry | ee.FeatureCollection): The region to visualize.
layer_name (str, optional): The layer name to be used. Defaults to "Time series".
labels (list, optional): The list of labels to be used for the time series. Defaults to None.
time_interval (int, optional): Time interval in seconds. Defaults to 1.
position (str, optional): Position to place the time slider, can be any of ['topleft', 'topright', 'bottomleft', 'bottomright']. Defaults to "bottomright".
slider_length (str, optional): Length of the time slider. Defaults to "150px".
date_format (str, optional): The date format to use. Defaults to 'YYYY-MM-dd'.
opacity (float, optional): The opacity of layers. Defaults to 1.0.
Raises:
TypeError: If the ee_object is not ee.Image | ee.ImageCollection.
"""
import threading
if isinstance(ee_object, ee.Image):
if region is not None:
if isinstance(region, ee.Geometry):
ee_object = ee_object.clip(region)
elif isinstance(region, ee.FeatureCollection):
ee_object = ee_object.clipToCollection(region)
if layer_name not in self.ee_layers:
self.addLayer(ee_object, {}, layer_name, False, opacity)
band_names = ee_object.bandNames()
ee_object = ee.ImageCollection(
ee_object.bandNames().map(lambda b: ee_object.select([b]))
)
if labels is not None:
if len(labels) != int(ee_object.size().getInfo()):
raise ValueError(
"The length of labels must be equal to the number of bands in the image."
)
else:
labels = band_names.getInfo()
elif isinstance(ee_object, ee.ImageCollection):
if region is not None:
if isinstance(region, ee.Geometry):
ee_object = ee_object.map(lambda img: img.clip(region))
elif isinstance(region, ee.FeatureCollection):
ee_object = ee_object.map(lambda img: img.clipToCollection(region))
if labels is not None:
if len(labels) != int(ee_object.size().getInfo()):
raise ValueError(
"The length of labels must be equal to the number of images in the ImageCollection."
)
else:
labels = (
ee_object.aggregate_array("system:time_start")
.map(lambda d: ee.Date(d).format(date_format))
.getInfo()
)
else:
raise TypeError("The ee_object must be an ee.Image or ee.ImageCollection")
# if labels is not None:
# size = len(labels)
# else:
# size = ee_object.size().getInfo()
# labels = [str(i) for i in range(1, size + 1)]
first = ee.Image(ee_object.first())
if layer_name not in self.ee_layers:
self.addLayer(ee_object.toBands(), {}, layer_name, False, opacity)
self.addLayer(first, vis_params, "Image X", True, opacity)
slider = widgets.IntSlider(
min=1,
max=len(labels),
readout=False,
continuous_update=False,
layout=widgets.Layout(width=slider_length),
)
label = widgets.Label(
value=labels[0], layout=widgets.Layout(padding="0px 5px 0px 5px")
)
play_btn = widgets.Button(
icon="play",
tooltip="Play the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
pause_btn = widgets.Button(
icon="pause",
tooltip="Pause the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
close_btn = widgets.Button(
icon="times",
tooltip="Close the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
play_chk = widgets.Checkbox(value=False)
slider_widget = widgets.HBox([slider, label, play_btn, pause_btn, close_btn])
def play_click(b):
import time
play_chk.value = True
def work(slider):
while play_chk.value:
if slider.value < len(labels):
slider.value += 1
else:
slider.value = 1
time.sleep(time_interval)
thread = threading.Thread(target=work, args=(slider,))
thread.start()
def pause_click(b):
play_chk.value = False
play_btn.on_click(play_click)
pause_btn.on_click(pause_click)
def slider_changed(change):
self.default_style = {"cursor": "wait"}
index = slider.value - 1
label.value = labels[index]
image = ee.Image(ee_object.toList(ee_object.size()).get(index))
if layer_name not in self.ee_layers:
self.addLayer(ee_object.toBands(), {}, layer_name, False, opacity)
self.addLayer(image, vis_params, "Image X", True, opacity)
self.default_style = {"cursor": "default"}
slider.observe(slider_changed, "value")
def close_click(b):
play_chk.value = False
self.toolbar_reset()
self.remove_ee_layer("Image X")
self.remove_ee_layer(layer_name)
if self.slider_ctrl is not None and self.slider_ctrl in self.controls:
self.remove_control(self.slider_ctrl)
slider_widget.close()
close_btn.on_click(close_click)
slider_ctrl = ipyleaflet.WidgetControl(widget=slider_widget, position=position)
self.add(slider_ctrl)
self.slider_ctrl = slider_ctrl
def add_xy_data(
self,
in_csv,
x="longitude",
y="latitude",
label=None,
layer_name="Marker cluster",
to_ee=False,
):
"""Adds points from a CSV file containing lat/lon information and display data on the map.
Args:
in_csv (str): The file path to the input CSV file.
x (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
y (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
label (str, optional): The name of the column containing label information to used for marker popup. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to "Marker cluster".
to_ee (bool, optional): Whether to convert the csv to an ee.FeatureCollection.
Raises:
FileNotFoundError: The specified input csv does not exist.
ValueError: The specified x column does not exist.
ValueError: The specified y column does not exist.
ValueError: The specified label column does not exist.
"""
import pandas as pd
if not in_csv.startswith("http") and (not os.path.exists(in_csv)):
raise FileNotFoundError("The specified input csv does not exist.")
df = pd.read_csv(in_csv)
col_names = df.columns.values.tolist()
if x not in col_names:
raise ValueError(f"x must be one of the following: {', '.join(col_names)}")
if y not in col_names:
raise ValueError(f"y must be one of the following: {', '.join(col_names)}")
if label is not None and (label not in col_names):
raise ValueError(
f"label must be one of the following: {', '.join(col_names)}"
)
self.default_style = {"cursor": "wait"}
if to_ee:
fc = csv_to_ee(in_csv, latitude=y, longitude=x)
self.addLayer(fc, {}, layer_name)
else:
points = list(zip(df[y], df[x]))
if label is not None:
labels = df[label]
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
)
for index, point in enumerate(points)
]
else:
markers = [
ipyleaflet.Marker(location=point, draggable=False)
for point in points
]
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
self.default_style = {"cursor": "default"}
def add_points_from_xy(
self,
data,
x="longitude",
y="latitude",
popup=None,
layer_name="Marker Cluster",
color_column=None,
marker_colors=None,
icon_colors=["white"],
icon_names=["info"],
spin=False,
add_legend=True,
**kwargs,
):
"""Adds a marker cluster to the map.
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
popup (list, optional): A list of column names to be used as the popup. Defaults to None.
layer_name (str, optional): The name of the layer. Defaults to "Marker Cluster".
color_column (str, optional): The column name for the color values. Defaults to None.
marker_colors (list, optional): A list of colors to be used for the markers. Defaults to None.
icon_colors (list, optional): A list of colors to be used for the icons. Defaults to ['white'].
icon_names (list, optional): A list of names to be used for the icons. More icons can be found at https://fontawesome.com/v4/icons. Defaults to ['info'].
spin (bool, optional): If True, the icon will spin. Defaults to False.
add_legend (bool, optional): If True, a legend will be added to the map. Defaults to True.
"""
import pandas as pd
data = github_raw_url(data)
color_options = [
"red",
"blue",
"green",
"purple",
"orange",
"darkred",
"lightred",
"beige",
"darkblue",
"darkgreen",
"cadetblue",
"darkpurple",
"white",
"pink",
"lightblue",
"lightgreen",
"gray",
"black",
"lightgray",
]
if isinstance(data, pd.DataFrame):
df = data
elif not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data)
df = points_from_xy(df, x, y)
col_names = df.columns.values.tolist()
if color_column is not None and color_column not in col_names:
raise ValueError(
f"The color column {color_column} does not exist in the dataframe."
)
if color_column is not None:
items = list(set(df[color_column]))
else:
items = None
if color_column is not None and marker_colors is None:
if len(items) > len(color_options):
raise ValueError(
f"The number of unique values in the color column {color_column} is greater than the number of available colors."
)
else:
marker_colors = color_options[: len(items)]
elif color_column is not None and marker_colors is not None:
if len(items) != len(marker_colors):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if items is not None:
if len(icon_colors) == 1:
icon_colors = icon_colors * len(items)
elif len(items) != len(icon_colors):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if len(icon_names) == 1:
icon_names = icon_names * len(items)
elif len(items) != len(icon_names):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if "geometry" in col_names:
col_names.remove("geometry")
if popup is not None:
if isinstance(popup, str) and (popup not in col_names):
raise ValueError(
f"popup must be one of the following: {', '.join(col_names)}"
)
elif isinstance(popup, list) and (
not all(item in col_names for item in popup)
):
raise ValueError(
f"All popup items must be select from: {', '.join(col_names)}"
)
else:
popup = col_names
df["x"] = df.geometry.x
df["y"] = df.geometry.y
points = list(zip(df["y"], df["x"]))
if popup is not None:
if isinstance(popup, str):
labels = df[popup]
markers = []
for index, point in enumerate(points):
if items is not None:
marker_color = marker_colors[
items.index(df[color_column][index])
]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
icon=marker_icon,
)
markers.append(marker)
elif isinstance(popup, list):
labels = []
for i in range(len(points)):
label = ""
for item in popup:
label = (
label
+ "<b>"
+ str(item)
+ "</b>"
+ ": "
+ str(df[item][i])
+ "<br>"
)
labels.append(label)
df["popup"] = labels
markers = []
for index, point in enumerate(points):
if items is not None:
marker_color = marker_colors[
items.index(df[color_column][index])
]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(labels[index]),
icon=marker_icon,
)
markers.append(marker)
else:
markers = []
for point in points:
if items is not None:
marker_color = marker_colors[items.index(df[color_column][index])]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point, draggable=False, icon=marker_icon
)
markers.append(marker)
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
if items is not None and add_legend:
marker_colors = [check_color(c) for c in marker_colors]
self.add_legend(
title=color_column.title(), colors=marker_colors, keys=items
)
self.default_style = {"cursor": "default"}
def add_circle_markers_from_xy(
self,
data,
x="longitude",
y="latitude",
radius=10,
popup=None,
**kwargs,
):
"""Adds a marker cluster to the map. For a list of options, see https://ipyleaflet.readthedocs.io/en/latest/api_reference/circle_marker.html
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
radius (int, optional): The radius of the circle. Defaults to 10.
popup (list, optional): A list of column names to be used as the popup. Defaults to None.
"""
import pandas as pd
data = github_raw_url(data)
if isinstance(data, pd.DataFrame):
df = data
elif not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data)
col_names = df.columns.values.tolist()
if popup is None:
popup = col_names
if not isinstance(popup, list):
popup = [popup]
if x not in col_names:
raise ValueError(f"x must be one of the following: {', '.join(col_names)}")
if y not in col_names:
raise ValueError(f"y must be one of the following: {', '.join(col_names)}")
for row in df.itertuples():
html = ""
for p in popup:
html = html + "<b>" + p + "</b>" + ": " + str(getattr(row, p)) + "<br>"
popup_html = widgets.HTML(html)
marker = ipyleaflet.CircleMarker(
location=[getattr(row, y), getattr(row, x)],
radius=radius,
popup=popup_html,
**kwargs,
)
super().add(marker)
def add_planet_by_month(
self, year=2016, month=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
"""Adds a Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
"""
layer = planet_tile_by_month(year, month, name, api_key, token_name)
self.add(layer)
def add_planet_by_quarter(
self, year=2016, quarter=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
"""Adds a Planet global mosaic by quarter to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
"""
layer = planet_tile_by_quarter(year, quarter, name, api_key, token_name)
self.add(layer)
def to_streamlit(self, width=None, height=600, scrolling=False, **kwargs):
"""Renders map figure in a Streamlit app.
Args:
width (int, optional): Width of the map. Defaults to None.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): If True, show a scrollbar when the content is larger than the iframe. Otherwise, do not show a scrollbar. Defaults to False.
Returns:
streamlit.components: components.html object.
"""
try:
import streamlit.components.v1 as components
# if responsive:
# make_map_responsive = """
# <style>
# [title~="st.iframe"] { width: 100%}
# </style>
# """
# st.markdown(make_map_responsive, unsafe_allow_html=True)
return components.html(
self.to_html(), width=width, height=height, scrolling=scrolling
)
except Exception as e:
raise Exception(e)
def add_point_layer(
self, filename, popup=None, layer_name="Marker Cluster", **kwargs
):
"""Adds a point layer to the map with a popup attribute.
Args:
filename (str): str, http url, path object or file-like object. Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO)
popup (str | list, optional): Column name(s) to be used for popup. Defaults to None.
layer_name (str, optional): A layer name to use. Defaults to "Marker Cluster".
Raises:
ValueError: If the specified column name does not exist.
ValueError: If the specified column names do not exist.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
self.default_style = {"cursor": "wait"}
if not filename.startswith("http"):
filename = os.path.abspath(filename)
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(filename, driver="KML", **kwargs)
else:
gdf = gpd.read_file(filename, **kwargs)
df = gdf.to_crs(epsg="4326")
col_names = df.columns.values.tolist()
if popup is not None:
if isinstance(popup, str) and (popup not in col_names):
raise ValueError(
f"popup must be one of the following: {', '.join(col_names)}"
)
elif isinstance(popup, list) and (
not all(item in col_names for item in popup)
):
raise ValueError(
f"All popup items must be select from: {', '.join(col_names)}"
)
df["x"] = df.geometry.x
df["y"] = df.geometry.y
points = list(zip(df["y"], df["x"]))
if popup is not None:
if isinstance(popup, str):
labels = df[popup]
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
)
for index, point in enumerate(points)
]
elif isinstance(popup, list):
labels = []
for i in range(len(points)):
label = ""
for item in popup:
label = label + str(item) + ": " + str(df[item][i]) + "<br>"
labels.append(label)
df["popup"] = labels
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(labels[index]),
)
for index, point in enumerate(points)
]
else:
markers = [
ipyleaflet.Marker(location=point, draggable=False) for point in points
]
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
self.default_style = {"cursor": "default"}
def add_census_data(self, wms, layer, census_dict=None, **kwargs):
"""Adds a census data layer to the map.
Args:
wms (str): The wms to use. For example, "Current", "ACS 2021", "Census 2020". See the complete list at https://tigerweb.geo.census.gov/tigerwebmain/TIGERweb_wms.html
layer (str): The layer name to add to the map.
census_dict (dict, optional): A dictionary containing census data. Defaults to None. It can be obtained from the get_census_dict() function.
"""
try:
if census_dict is None:
census_dict = get_census_dict()
if wms not in census_dict.keys():
raise ValueError(
f"The provided WMS is invalid. It must be one of {census_dict.keys()}"
)
layers = census_dict[wms]["layers"]
if layer not in layers:
raise ValueError(
f"The layer name is not valid. It must be one of {layers}"
)
url = census_dict[wms]["url"]
if "name" not in kwargs:
kwargs["name"] = layer
if "attribution" not in kwargs:
kwargs["attribution"] = "U.S. Census Bureau"
if "format" not in kwargs:
kwargs["format"] = "image/png"
if "transparent" not in kwargs:
kwargs["transparent"] = True
self.add_wms_layer(url, layer, **kwargs)
except Exception as e:
raise Exception(e)
def add_xyz_service(self, provider, **kwargs):
"""Add a XYZ tile layer to the map.
Args:
provider (str): A tile layer name starts with xyz or qms. For example, xyz.OpenTopoMap,
Raises:
ValueError: The provider is not valid. It must start with xyz or qms.
"""
import xyzservices.providers as xyz
from xyzservices import TileProvider
if provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
url = xyz_provider.build_url()
attribution = xyz_provider.attribution
if attribution.strip() == "":
attribution = " "
self.add_tile_layer(url, name, attribution)
elif provider.startswith("qms"):
name = provider[4:]
qms_provider = TileProvider.from_qms(name)
url = qms_provider.build_url()
attribution = qms_provider.attribution
if attribution.strip() == "":
attribution = " "
self.add_tile_layer(url, name, attribution)
else:
raise ValueError(
f"The provider {provider} is not valid. It must start with xyz or qms."
)
def add_heatmap(
self,
data,
latitude="latitude",
longitude="longitude",
value="value",
name="Heat map",
radius=25,
**kwargs,
):
"""Adds a heat map to the map. Reference: https://ipyleaflet.readthedocs.io/en/latest/api_reference/heatmap.html
Args:
data (str | list | pd.DataFrame): File path or HTTP URL to the input file or a list of data points in the format of [[x1, y1, z1], [x2, y2, z2]]. For example, https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/world_cities.csv
latitude (str, optional): The column name of latitude. Defaults to "latitude".
longitude (str, optional): The column name of longitude. Defaults to "longitude".
value (str, optional): The column name of values. Defaults to "value".
name (str, optional): Layer name to use. Defaults to "Heat map".
radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25.
Raises:
ValueError: If data is not a list.
"""
import pandas as pd
from ipyleaflet import Heatmap
try:
if isinstance(data, str):
df = pd.read_csv(data)
data = df[[latitude, longitude, value]].values.tolist()
elif isinstance(data, pd.DataFrame):
data = data[[latitude, longitude, value]].values.tolist()
elif isinstance(data, list):
pass
else:
raise ValueError("data must be a list, a DataFrame, or a file path.")
heatmap = Heatmap(locations=data, radius=radius, name=name, **kwargs)
self.add(heatmap)
except Exception as e:
raise Exception(e)
def add_labels(
self,
data,
column,
font_size="12pt",
font_color="black",
font_family="arial",
font_weight="normal",
x="longitude",
y="latitude",
draggable=True,
layer_name="Labels",
**kwargs,
):
"""Adds a label layer to the map. Reference: https://ipyleaflet.readthedocs.io/en/latest/api_reference/divicon.html
Args:
data (pd.DataFrame | ee.FeatureCollection): The input data to label.
column (str): The column name of the data to label.
font_size (str, optional): The font size of the labels. Defaults to "12pt".
font_color (str, optional): The font color of the labels. Defaults to "black".
font_family (str, optional): The font family of the labels. Defaults to "arial".
font_weight (str, optional): The font weight of the labels, can be normal, bold. Defaults to "normal".
x (str, optional): The column name of the longitude. Defaults to "longitude".
y (str, optional): The column name of the latitude. Defaults to "latitude".
draggable (bool, optional): Whether the labels are draggable. Defaults to True.
layer_name (str, optional): Layer name to use. Defaults to "Labels".
"""
import warnings
import pandas as pd
warnings.filterwarnings("ignore")
if isinstance(data, ee.FeatureCollection):
centroids = vector_centroids(data)
df = ee_to_df(centroids)
elif isinstance(data, pd.DataFrame):
df = data
elif isinstance(data, str):
ext = os.path.splitext(data)[1]
if ext == ".csv":
df = pd.read_csv(data)
elif ext in [".geojson", ".json", ".shp", ".gpkg"]:
try:
import geopandas as gpd
df = gpd.read_file(data)
df[x] = df.centroid.x
df[y] = df.centroid.y
except Exception as _:
print("geopandas is required to read geojson.")
return
else:
raise ValueError("data must be a DataFrame or an ee.FeatureCollection.")
if column not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
if x not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
if y not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
try:
size = int(font_size.replace("pt", ""))
except:
raise ValueError("font_size must be something like '10pt'")
labels = []
for index in df.index:
html = f'<div style="font-size: {font_size};color:{font_color};font-family:{font_family};font-weight: {font_weight}">{df[column][index]}</div>'
marker = ipyleaflet.Marker(
location=[df[y][index], df[x][index]],
icon=ipyleaflet.DivIcon(
icon_size=(1, 1),
icon_anchor=(size, size),
html=html,
**kwargs,
),
draggable=draggable,
)
labels.append(marker)
layer_group = ipyleaflet.LayerGroup(layers=labels, name=layer_name)
self.add(layer_group)
self.labels = layer_group
def remove_labels(self):
"""Removes all labels from the map."""
if hasattr(self, "labels"):
self.remove_layer(self.labels)
delattr(self, "labels")
def add_netcdf(
self,
filename,
variables=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name="NetCDF layer",
shift_lon=True,
lat="lat",
lon="lon",
**kwargs,
):
"""Generate an ipyleaflet/folium TileLayer from a netCDF file.
If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer),
try adding to following two lines to the beginning of the notebook if the raster does not render properly.
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}'
Args:
filename (str): File path or HTTP URL to the netCDF file.
variables (int, optional): The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted.
port (str, optional): The port to use for the server. Defaults to "default".
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to "netCDF layer".
shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True.
lat (str, optional): Name of the latitude variable. Defaults to 'lat'.
lon (str, optional): Name of the longitude variable. Defaults to 'lon'.
"""
tif, vars = netcdf_to_tif(
filename, shift_lon=shift_lon, lat=lat, lon=lon, return_vars=True
)
if variables is None:
if len(vars) >= 3:
band_idx = [1, 2, 3]
else:
band_idx = [1]
else:
if not set(variables).issubset(set(vars)):
raise ValueError(f"The variables must be a subset of {vars}.")
else:
band_idx = [vars.index(v) + 1 for v in variables]
self.add_raster(
tif,
band=band_idx,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
**kwargs,
)
def add_velocity(
self,
data,
zonal_speed,
meridional_speed,
latitude_dimension="lat",
longitude_dimension="lon",
level_dimension="lev",
level_index=0,
time_index=0,
velocity_scale=0.01,
max_velocity=20,
display_options={},
name="Velocity",
):
"""Add a velocity layer to the map.
Args:
data (str | xr.Dataset): The data to use for the velocity layer. It can be a file path to a NetCDF file or an xarray Dataset.
zonal_speed (str): Name of the zonal speed in the dataset. See https://en.wikipedia.org/wiki/Zonal_and_meridional_flow.
meridional_speed (str): Name of the meridional speed in the dataset. See https://en.wikipedia.org/wiki/Zonal_and_meridional_flow.
latitude_dimension (str, optional): Name of the latitude dimension in the dataset. Defaults to 'lat'.
longitude_dimension (str, optional): Name of the longitude dimension in the dataset. Defaults to 'lon'.
level_dimension (str, optional): Name of the level dimension in the dataset. Defaults to 'lev'.
level_index (int, optional): The index of the level dimension to display. Defaults to 0.
time_index (int, optional): The index of the time dimension to display. Defaults to 0.
velocity_scale (float, optional): The scale of the velocity. Defaults to 0.01.
max_velocity (int, optional): The maximum velocity to display. Defaults to 20.
display_options (dict, optional): The display options for the velocity layer. Defaults to {}. See https://bit.ly/3uf8t6w.
name (str, optional): Layer name to use . Defaults to 'Velocity'.
Raises:
ImportError: If the xarray package is not installed.
ValueError: If the data is not a NetCDF file or an xarray Dataset.
"""
try:
import xarray as xr
from ipyleaflet.velocity import Velocity
except ImportError:
raise ImportError(
"The xarray package is required to add a velocity layer. "
"Please install it with `pip install xarray`."
)
if isinstance(data, str):
if data.startswith("http"):
data = download_file(data)
ds = xr.open_dataset(data)
elif isinstance(data, xr.Dataset):
ds = data
else:
raise ValueError("The data must be a file path or xarray dataset.")
coords = list(ds.coords.keys())
# Rasterio does not handle time or levels. So we must drop them
if "time" in coords:
ds = ds.isel(time=time_index, drop=True)
params = {level_dimension: level_index}
if level_dimension in coords:
ds = ds.isel(drop=True, **params)
wind = Velocity(
data=ds,
zonal_speed=zonal_speed,
meridional_speed=meridional_speed,
latitude_dimension=latitude_dimension,
longitude_dimension=longitude_dimension,
velocity_scale=velocity_scale,
max_velocity=max_velocity,
display_options=display_options,
name=name,
)
self.add(wind)
def add_data(
self,
data,
column,
colors=None,
labels=None,
cmap=None,
scheme="Quantiles",
k=5,
add_legend=True,
legend_title=None,
legend_kwds=None,
classification_kwds=None,
layer_name="Untitled",
style=None,
hover_style=None,
style_callback=None,
info_mode="on_hover",
encoding="utf-8",
**kwargs,
):
"""Add vector data to the map with a variety of classification schemes.
Args:
data (str | pd.DataFrame | gpd.GeoDataFrame): The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe.
column (str): The column to classify.
cmap (str, optional): The name of a colormap recognized by matplotlib. Defaults to None.
colors (list, optional): A list of colors to use for the classification. Defaults to None.
labels (list, optional): A list of labels to use for the legend. Defaults to None.
scheme (str, optional): Name of a choropleth classification scheme (requires mapclassify).
Name of a choropleth classification scheme (requires mapclassify).
A mapclassify.MapClassifier object will be used
under the hood. Supported are all schemes provided by mapclassify (e.g.
'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled',
'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced',
'JenksCaspallSampled', 'MaxP', 'MaximumBreaks',
'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean',
'UserDefined'). Arguments can be passed in classification_kwds.
k (int, optional): Number of classes (ignored if scheme is None or if column is categorical). Default to 5.
legend_kwds (dict, optional): Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or `matplotlib.pyplot.colorbar`. Defaults to None.
Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or
Additional accepted keywords when `scheme` is specified:
fmt : string
A formatting specification for the bin edges of the classes in the
legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``.
labels : list-like
A list of legend labels to override the auto-generated labblels.
Needs to have the same number of elements as the number of
classes (`k`).
interval : boolean (default False)
An option to control brackets from mapclassify legend.
If True, open/closed interval brackets are shown in the legend.
classification_kwds (dict, optional): Keyword arguments to pass to mapclassify. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to None.
style is a dictionary of the following form:
style = {
"stroke": False,
"color": "#ff0000",
"weight": 1,
"opacity": 1,
"fill": True,
"fillColor": "#ffffff",
"fillOpacity": 1.0,
"dashArray": "9"
"clickable": True,
}
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
hover_style is a dictionary of the following form:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
style_callback is a function that takes the feature as argument and should return a dictionary of the following form:
style_callback = lambda feat: {"fillColor": feat["properties"]["color"]}
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the GeoJSON file. Defaults to "utf-8".
"""
gdf, legend_dict = classify(
data=data,
column=column,
cmap=cmap,
colors=colors,
labels=labels,
scheme=scheme,
k=k,
legend_kwds=legend_kwds,
classification_kwds=classification_kwds,
)
if legend_title is None:
legend_title = column
if style is None:
style = {
# "stroke": False,
# "color": "#ff0000",
"weight": 1,
"opacity": 1,
# "fill": True,
# "fillColor": "#ffffff",
"fillOpacity": 1.0,
# "dashArray": "9"
# "clickable": True,
}
if colors is not None:
style["color"] = "#000000"
if hover_style is None:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
if style_callback is None:
style_callback = lambda feat: {"fillColor": feat["properties"]["color"]}
self.add_gdf(
gdf,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
info_mode=info_mode,
encoding=encoding,
**kwargs,
)
if add_legend:
self.add_legend(title=legend_title, legend_dict=legend_dict)
def user_roi_coords(self, decimals=4):
"""Return the bounding box of the ROI as a list of coordinates.
Args:
decimals (int, optional): Number of decimals to round the coordinates to. Defaults to 4.
"""
return bbox_coords(self.user_roi, decimals=decimals)
def add_widget(
self,
content,
position="bottomright",
add_header=False,
opened=True,
show_close_button=True,
widget_icon="gear",
close_button_icon="times",
widget_args={},
close_button_args={},
display_widget=None,
**kwargs,
):
"""Add a widget (e.g., text, HTML, figure) to the map.
Args:
content (str | ipywidgets.Widget | object): The widget to add.
position (str, optional): The position of the widget. Defaults to "bottomright".
add_header (bool, optional): Whether to add a header with close buttons to the widget. Defaults to False.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
widget_icon (str, optional): The icon name for the toolbar button. Defaults to 'gear'.
close_button_icon (str, optional): The icon name for the close button. Defaults to "times".
widget_args (dict, optional): Additional arguments to pass to the toolbar button. Defaults to {}.
close_button_args (dict, optional): Additional arguments to pass to the close button. Defaults to {}.
display_widget (ipywidgets.Widget, optional): The widget to be displayed when the toolbar is clicked.
**kwargs: Additional arguments to pass to the HTML or Output widgets
"""
allowed_positions = ["topleft", "topright", "bottomleft", "bottomright"]
if position not in allowed_positions:
raise Exception(f"position must be one of {allowed_positions}")
if "layout" not in kwargs:
kwargs["layout"] = widgets.Layout(padding="0px 4px 0px 4px")
try:
if add_header:
if isinstance(content, str):
widget = widgets.HTML(value=content, **kwargs)
else:
widget = content
widget_template(
widget,
opened,
show_close_button,
widget_icon,
close_button_icon,
widget_args,
close_button_args,
display_widget,
self,
position,
)
else:
if isinstance(content, str):
widget = widgets.HTML(value=content, **kwargs)
else:
widget = widgets.Output(**kwargs)
with widget:
display(content)
control = ipyleaflet.WidgetControl(widget=widget, position=position)
self.add(control)
except Exception as e:
raise Exception(f"Error adding widget: {e}")
def add_image(self, image, position="bottomright", **kwargs):
"""Add an image to the map.
Args:
image (str | ipywidgets.Image): The image to add.
position (str, optional): The position of the image, can be one of "topleft",
"topright", "bottomleft", "bottomright". Defaults to "bottomright".
"""
if isinstance(image, str):
if image.startswith("http"):
image = widgets.Image(value=requests.get(image).content, **kwargs)
elif os.path.exists(image):
with open(image, "rb") as f:
image = widgets.Image(value=f.read(), **kwargs)
elif isinstance(image, widgets.Image):
pass
else:
raise Exception("Invalid image")
self.add_widget(image, position=position, **kwargs)
def add_html(self, html, position="bottomright", **kwargs):
"""Add HTML to the map.
Args:
html (str): The HTML to add.
position (str, optional): The position of the HTML, can be one of "topleft",
"topright", "bottomleft", "bottomright". Defaults to "bottomright".
"""
self.add_widget(html, position=position, **kwargs)
def add_text(
self,
text,
fontsize=20,
fontcolor="black",
bold=False,
padding="5px",
background=True,
bg_color="white",
border_radius="5px",
position="bottomright",
**kwargs,
):
"""Add text to the map.
Args:
text (str): The text to add.
fontsize (int, optional): The font size. Defaults to 20.
fontcolor (str, optional): The font color. Defaults to "black".
bold (bool, optional): Whether to use bold font. Defaults to False.
padding (str, optional): The padding. Defaults to "5px".
background (bool, optional): Whether to use background. Defaults to True.
bg_color (str, optional): The background color. Defaults to "white".
border_radius (str, optional): The border radius. Defaults to "5px".
position (str, optional): The position of the widget. Defaults to "bottomright".
"""
if background:
text = f"""<div style="font-size: {fontsize}px; color: {fontcolor}; font-weight: {'bold' if bold else 'normal'};
padding: {padding}; background-color: {bg_color};
border-radius: {border_radius};">{text}</div>"""
else:
text = f"""<div style="font-size: {fontsize}px; color: {fontcolor}; font-weight: {'bold' if bold else 'normal'};
padding: {padding};">{text}</div>"""
self.add_html(text, position=position, **kwargs)
def to_gradio(self, width="100%", height="500px", **kwargs):
"""Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as
attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190
Args:
width (str, optional): The width of the map. Defaults to '100%'.
height (str, optional): The height of the map. Defaults to '500px'.
Returns:
str: The HTML string to use in Gradio.
"""
print(
"The ipyleaflet plotting backend does not support this function. Please use the folium backend instead."
)
def add_search_control(
self,
marker=None,
url=None,
zoom=5,
property_name="display_name",
position="topleft",
):
"""Add a search control to the map.
Args:
marker (ipyleaflet.Marker, optional): The marker to use. Defaults to None.
url (str, optional): The URL to use for the search. Defaults to None.
zoom (int, optional): The zoom level to use. Defaults to 5.
property_name (str, optional): The property name to use. Defaults to "display_name".
position (str, optional): The position of the widget. Defaults to "topleft".
"""
if marker is None:
marker = ipyleaflet.Marker(
icon=ipyleaflet.AwesomeIcon(
name="check", marker_color="green", icon_color="darkgreen"
)
)
if url is None:
url = "https://nominatim.openstreetmap.org/search?format=json&q={s}"
search = ipyleaflet.SearchControl(
position=position,
url=url,
zoom=zoom,
property_name=property_name,
marker=marker,
)
self.add(search)
def layer_to_image(
self,
layer_name: str,
output: Optional[str] = None,
crs: str = "EPSG:3857",
scale: Optional[int] = None,
region: Optional[ee.Geometry] = None,
vis_params: Optional[Dict] = None,
**kwargs: Any,
) -> None:
"""
Converts a specific layer from Earth Engine to an image file.
Args:
layer_name (str): The name of the layer to convert.
output (str): The output file path for the image. Defaults to None.
crs (str, optional): The coordinate reference system (CRS) of the output image. Defaults to "EPSG:3857".
scale (int, optional): The scale of the output image. Defaults to None.
region (ee.Geometry, optional): The region of interest for the conversion. Defaults to None.
vis_params (dict, optional): The visualization parameters. Defaults to None.
**kwargs: Additional keyword arguments to pass to the `download_ee_image` function.
Returns:
None
"""
if region is None:
b = self.bounds
west, south, east, north = b[0][1], b[0][0], b[1][1], b[1][0]
region = ee.Geometry.BBox(west, south, east, north)
if scale is None:
scale = int(self.get_scale())
if layer_name not in self.ee_layers.keys():
raise ValueError(f"Layer {layer_name} does not exist.")
if output is None:
output = layer_name + ".tif"
layer = self.ee_layers[layer_name]
ee_object = layer["ee_object"]
if vis_params is None:
vis_params = layer["vis_params"]
image = ee_object.visualize(**vis_params)
if not output.endswith(".tif"):
geotiff = output + ".tif"
else:
geotiff = output
download_ee_image(image, geotiff, region, crs=crs, scale=scale, **kwargs)
if not output.endswith(".tif"):
geotiff_to_image(geotiff, output)
os.remove(geotiff)
import ipyleaflet
The provided code snippet includes necessary dependencies for implementing the `linked_maps` function. Write a Python function `def linked_maps( rows=2, cols=2, height="400px", ee_objects=[], vis_params=[], labels=[], label_position="topright", **kwargs, )` to solve the following problem:
Create linked maps of Earth Engine data layers. Args: rows (int, optional): The number of rows of maps to create. Defaults to 2. cols (int, optional): The number of columns of maps to create. Defaults to 2. height (str, optional): The height of each map in pixels. Defaults to "400px". ee_objects (list, optional): The list of Earth Engine objects to use for each map. Defaults to []. vis_params (list, optional): The list of visualization parameters to use for each map. Defaults to []. labels (list, optional): The list of labels to show on the map. Defaults to []. label_position (str, optional): The position of the label, can be [topleft, topright, bottomleft, bottomright]. Defaults to "topright". Raises: ValueError: If the length of ee_objects is not equal to rows*cols. ValueError: If the length of vis_params is not equal to rows*cols. ValueError: If the length of labels is not equal to rows*cols. Returns: ipywidget: A GridspecLayout widget.
Here is the function:
def linked_maps(
rows=2,
cols=2,
height="400px",
ee_objects=[],
vis_params=[],
labels=[],
label_position="topright",
**kwargs,
):
"""Create linked maps of Earth Engine data layers.
Args:
rows (int, optional): The number of rows of maps to create. Defaults to 2.
cols (int, optional): The number of columns of maps to create. Defaults to 2.
height (str, optional): The height of each map in pixels. Defaults to "400px".
ee_objects (list, optional): The list of Earth Engine objects to use for each map. Defaults to [].
vis_params (list, optional): The list of visualization parameters to use for each map. Defaults to [].
labels (list, optional): The list of labels to show on the map. Defaults to [].
label_position (str, optional): The position of the label, can be [topleft, topright, bottomleft, bottomright]. Defaults to "topright".
Raises:
ValueError: If the length of ee_objects is not equal to rows*cols.
ValueError: If the length of vis_params is not equal to rows*cols.
ValueError: If the length of labels is not equal to rows*cols.
Returns:
ipywidget: A GridspecLayout widget.
"""
grid = widgets.GridspecLayout(rows, cols, grid_gap="0px")
count = rows * cols
maps = []
if len(ee_objects) > 0:
if len(ee_objects) == 1:
ee_objects = ee_objects * count
elif len(ee_objects) < count:
raise ValueError(f"The length of ee_objects must be equal to {count}.")
if len(vis_params) > 0:
if len(vis_params) == 1:
vis_params = vis_params * count
elif len(vis_params) < count:
raise ValueError(f"The length of vis_params must be equal to {count}.")
if len(labels) > 0:
if len(labels) == 1:
labels = labels * count
elif len(labels) < count:
raise ValueError(f"The length of labels must be equal to {count}.")
for i in range(rows):
for j in range(cols):
index = i * rows + j
m = Map(
height=height,
lite_mode=True,
add_google_map=False,
layout=widgets.Layout(margin="0px", padding="0px"),
**kwargs,
)
if len(ee_objects) > 0:
m.addLayer(ee_objects[index], vis_params[index], labels[index])
if len(labels) > 0:
label = widgets.Label(
labels[index], layout=widgets.Layout(padding="0px 5px 0px 5px")
)
control = ipyleaflet.WidgetControl(
widget=label, position=label_position
)
m.add(control)
maps.append(m)
widgets.jslink((maps[0], "center"), (m, "center"))
widgets.jslink((maps[0], "zoom"), (m, "zoom"))
output = widgets.Output()
with output:
display(m)
grid[i, j] = output
return grid | Create linked maps of Earth Engine data layers. Args: rows (int, optional): The number of rows of maps to create. Defaults to 2. cols (int, optional): The number of columns of maps to create. Defaults to 2. height (str, optional): The height of each map in pixels. Defaults to "400px". ee_objects (list, optional): The list of Earth Engine objects to use for each map. Defaults to []. vis_params (list, optional): The list of visualization parameters to use for each map. Defaults to []. labels (list, optional): The list of labels to show on the map. Defaults to []. label_position (str, optional): The position of the label, can be [topleft, topright, bottomleft, bottomright]. Defaults to "topright". Raises: ValueError: If the length of ee_objects is not equal to rows*cols. ValueError: If the length of vis_params is not equal to rows*cols. ValueError: If the length of labels is not equal to rows*cols. Returns: ipywidget: A GridspecLayout widget. |
12,439 | import os
import warnings
from typing import Optional, Any, Dict
import ee
import ipyleaflet
import ipywidgets as widgets
from box import Box
from bqplot import pyplot as plt
from IPython.display import display
from .basemaps import get_xyz_dict, xyz_to_leaflet
from .common import *
from .conversion import *
from .ee_tile_layers import *
from . import core
from . import map_widgets
from . import toolbar
from .plot import *
from .timelapse import *
from .legends import builtin_legends
from . import examples
basemaps = Box(xyz_to_leaflet(), frozen_box=True)
class Map(core.Map):
"""The Map class inherits the core Map class. The arguments you can pass to the Map initialization
can be found at https://ipyleaflet.readthedocs.io/en/latest/map_and_basemaps/map.html.
By default, the Map will add Google Maps as the basemap. Set add_google_map = False
to use OpenStreetMap as the basemap.
Returns:
object: ipyleaflet map object.
"""
# Map attributes for drawing features
def draw_control(self):
return self.get_draw_control()
def draw_control_lite(self):
return self.get_draw_control()
def draw_features(self):
return self._draw_control.features if self._draw_control else []
def draw_last_feature(self):
return self._draw_control.last_feature if self._draw_control else None
def draw_layer(self):
return self._draw_control.layer if self._draw_control else None
def user_roi(self):
return self._draw_control.last_geometry if self._draw_control else None
def user_rois(self):
return self._draw_control.collection if self._draw_control else None
def __init__(self, **kwargs):
"""Initialize a map object. The following additional parameters can be passed in addition to the ipyleaflet.Map parameters:
Args:
ee_initialize (bool, optional): Whether or not to initialize ee. Defaults to True.
center (list, optional): Center of the map (lat, lon). Defaults to [20, 0].
zoom (int, optional): Zoom level of the map. Defaults to 2.
height (str, optional): Height of the map. Defaults to "600px".
width (str, optional): Width of the map. Defaults to "100%".
basemap (str, optional): Name of the basemap to add to the map. Defaults to "ROADMAP". Other options include "ROADMAP", "SATELLITE", "TERRAIN".
add_google_map (bool, optional): Whether to add Google Maps to the map. Defaults to True.
sandbox_path (str, optional): The path to a sandbox folder for voila web app. Defaults to None.
lite_mode (bool, optional): Whether to enable lite mode, which only displays zoom control on the map. Defaults to False.
data_ctrl (bool, optional): Whether to add the data control to the map. Defaults to True.
zoom_ctrl (bool, optional): Whether to add the zoom control to the map. Defaults to True.
fullscreen_ctrl (bool, optional): Whether to add the fullscreen control to the map. Defaults to True.
search_ctrl (bool, optional): Whether to add the search control to the map. Defaults to True.
draw_ctrl (bool, optional): Whether to add the draw control to the map. Defaults to True.
scale_ctrl (bool, optional): Whether to add the scale control to the map. Defaults to True.
measure_ctrl (bool, optional): Whether to add the measure control to the map. Defaults to True.
toolbar_ctrl (bool, optional): Whether to add the toolbar control to the map. Defaults to True.
layer_ctrl (bool, optional): Whether to add the layer control to the map. Defaults to False.
attribution_ctrl (bool, optional): Whether to add the attribution control to the map. Defaults to True.
**kwargs: Additional keyword arguments for ipyleaflet.Map.
"""
warnings.filterwarnings("ignore")
if isinstance(kwargs.get("height"), int):
kwargs["height"] = str(kwargs["height"]) + "px"
if isinstance(kwargs.get("width"), int):
kwargs["width"] = str(kwargs["width"]) + "px"
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 24
# Use any basemap available through the basemap module, such as 'ROADMAP', 'OpenTopoMap'
if "basemap" in kwargs:
kwargs["basemap"] = check_basemap(kwargs["basemap"])
if kwargs["basemap"] in basemaps.keys():
kwargs["basemap"] = get_basemap(kwargs["basemap"])
kwargs["add_google_map"] = False
else:
kwargs.pop("basemap")
self._xyz_dict = get_xyz_dict()
self.baseclass = "ipyleaflet"
self._USER_AGENT_PREFIX = "geemap"
self.kwargs = kwargs
super().__init__(**kwargs)
if kwargs.get("height"):
self.layout.height = kwargs.get("height")
# sandbox path for Voila app to restrict access to system directories.
if "sandbox_path" not in kwargs:
self.sandbox_path = None
else:
if os.path.exists(os.path.abspath(kwargs["sandbox_path"])):
self.sandbox_path = kwargs["sandbox_path"]
else:
print("The sandbox path is invalid.")
self.sandbox_path = None
# Add Google Maps as the default basemap
if kwargs.get("add_google_map", False):
self.add_basemap("ROADMAP")
# ipyleaflet built-in layer control
self.layer_control = None
if "ee_initialize" not in kwargs:
kwargs["ee_initialize"] = True
# Default reducer to use
if kwargs["ee_initialize"]:
self.roi_reducer = ee.Reducer.mean()
self.roi_reducer_scale = None
def _control_config(self):
if self.kwargs.get("lite_mode"):
return {"topleft": ["zoom_control"]}
topleft = []
bottomleft = []
topright = []
bottomright = []
for control in ["data_ctrl", "zoom_ctrl", "fullscreen_ctrl", "draw_ctrl"]:
if self.kwargs.get(control, True):
topleft.append(control)
for control in ["scale_ctrl", "measure_ctrl"]:
if self.kwargs.get(control, True):
bottomleft.append(control)
for control in ["toolbar_ctrl"]:
if self.kwargs.get(control, True):
topright.append(control)
for control in ["attribution_control"]:
if self.kwargs.get(control, True):
bottomright.append(control)
return {
"topleft": topleft,
"bottomleft": bottomleft,
"topright": topright,
"bottomright": bottomright,
}
def ee_layer_names(self):
warnings.warn(
"ee_layer_names is deprecated. Use ee_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_layers.keys()
def ee_layer_dict(self):
warnings.warn(
"ee_layer_dict is deprecated. Use ee_layers instead.", DeprecationWarning
)
return self.ee_layers
def ee_raster_layer_names(self):
warnings.warn(
"ee_raster_layer_names is deprecated. Use self.ee_raster_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_raster_layers.keys()
def ee_vector_layer_names(self):
warnings.warn(
"ee_vector_layer_names is deprecated. Use self.ee_vector_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_vector_layers.keys()
def ee_raster_layers(self):
return dict(filter(self._raster_filter, self.ee_layers.items()))
def ee_vector_layers(self):
return dict(filter(self._vector_filter, self.ee_layers.items()))
def _raster_filter(self, pair):
return isinstance(pair[1]["ee_object"], (ee.Image, ee.ImageCollection))
def _vector_filter(self, pair):
return isinstance(
pair[1]["ee_object"], (ee.Geometry, ee.Feature, ee.FeatureCollection)
)
def add(self, obj, position="topright", **kwargs):
"""Adds a layer or control to the map.
Args:
object (object): The layer or control to add to the map.
"""
if isinstance(obj, str):
basemap = check_basemap(obj)
if basemap in basemaps.keys():
super().add(get_basemap(basemap))
return
if not isinstance(obj, str):
super().add(obj, position=position, **kwargs)
return
obj = obj.lower()
backward_compatibilities = {
"zoom_ctrl": "zoom_control",
"fullscreen_ctrl": "fullscreen_control",
"scale_ctrl": "scale_control",
"toolbar_ctrl": "toolbar",
"draw_ctrl": "draw_control",
}
obj = backward_compatibilities.get(obj, obj)
if obj == "data_ctrl":
data_widget = toolbar.SearchDataGUI(self)
data_control = ipyleaflet.WidgetControl(
widget=data_widget, position=position
)
self.add(data_control)
elif obj == "search_ctrl":
self.add_search_control(position=position)
elif obj == "measure_ctrl":
measure = ipyleaflet.MeasureControl(
position=position,
active_color="orange",
primary_length_unit="kilometers",
)
self.add(measure, position=position)
elif obj == "layer_ctrl":
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control, position=position)
else:
super().add(obj, position=position, **kwargs)
def add_controls(self, controls, position="topleft"):
"""Adds a list of controls to the map.
Args:
controls (list): A list of controls to add to the map.
position (str, optional): The position of the controls on the map. Defaults to 'topleft'.
"""
if not isinstance(controls, list):
controls = [controls]
for control in controls:
self.add(control, position)
def set_options(self, mapTypeId="HYBRID", **kwargs):
"""Adds Google basemap and controls to the ipyleaflet map.
Args:
mapTypeId (str, optional): A mapTypeId to set the basemap to. Can be one of "ROADMAP", "SATELLITE",
"HYBRID" or "TERRAIN" to select one of the standard Google Maps API map types. Defaults to 'HYBRID'.
"""
try:
self.add(mapTypeId)
except Exception:
raise ValueError(
'Google basemaps can only be one of "ROADMAP", "SATELLITE", "HYBRID" or "TERRAIN".'
)
setOptions = set_options
def add_ee_layer(
self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0
):
"""Adds a given EE object to the map as a layer.
Args:
ee_object (Collection|Feature|Image|MapId): The object to add to the map.
vis_params (dict, optional): The visualization parameters. Defaults to {}.
name (str, optional): The name of the layer. Defaults to 'Layer N'.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
"""
has_plot_dropdown = (
hasattr(self, "_plot_dropdown_widget")
and self._plot_dropdown_widget is not None
)
ee_layer = self.ee_layers.get(name, {})
layer = ee_layer.get("ee_layer", None)
if layer is not None:
if isinstance(ee_layer["ee_object"], (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(
self.ee_raster_layers.keys()
)
super().add_layer(ee_object, vis_params, name, shown, opacity)
if isinstance(ee_object, (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(self.ee_raster_layers.keys())
tile_layer = self.ee_layers.get(name, {}).get("ee_layer", None)
if tile_layer:
arc_add_layer(tile_layer.url_format, name, shown, opacity)
addLayer = add_ee_layer
def remove_ee_layer(self, name):
"""Removes an Earth Engine layer.
Args:
name (str): The name of the Earth Engine layer to remove.
"""
if name in self.ee_layers:
ee_layer = self.ee_layers[name]["ee_layer"]
self.ee_layers.pop(name, None)
if ee_layer in self.layers:
self.remove_layer(ee_layer)
def set_center(self, lon, lat, zoom=None):
"""Centers the map view at a given coordinates with the given zoom level.
Args:
lon (float): The longitude of the center, in degrees.
lat (float): The latitude of the center, in degrees.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to None.
"""
super().set_center(lon, lat, zoom)
if is_arcpy():
arc_zoom_to_extent(lon, lat, lon, lat)
setCenter = set_center
def center_object(self, ee_object, zoom=None):
"""Centers the map view on a given object.
Args:
ee_object (Element|Geometry): An Earth Engine object to center on a geometry, image or feature.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to None.
"""
super().center_object(ee_object, zoom)
if is_arcpy():
bds = self.bounds
arc_zoom_to_extent(bds[0][1], bds[0][0], bds[1][1], bds[1][0])
centerObject = center_object
def zoom_to_bounds(self, bounds):
"""Zooms to a bounding box in the form of [minx, miny, maxx, maxy].
Args:
bounds (list | tuple): A list/tuple containing minx, miny, maxx, maxy values for the bounds.
"""
# The ipyleaflet fit_bounds method takes lat/lon bounds in the form [[south, west], [north, east]].
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def get_scale(self):
"""Returns the approximate pixel scale of the current map view, in meters.
Returns:
float: Map resolution in meters.
"""
return super().get_scale()
getScale = get_scale
def add_basemap(self, basemap="ROADMAP", show=True, **kwargs):
"""Adds a basemap to the map.
Args:
basemap (str, optional): Can be one of string from basemaps. Defaults to 'ROADMAP'.
visible (bool, optional): Whether the basemap is visible or not. Defaults to True.
**kwargs: Keyword arguments for the TileLayer.
"""
import xyzservices
try:
layer_names = self.get_layer_names()
map_dict = {
"ROADMAP": "Esri.WorldStreetMap",
"SATELLITE": "Esri.WorldImagery",
"TERRAIN": "Esri.WorldTopoMap",
"HYBRID": "Esri.WorldImagery",
}
if isinstance(basemap, str):
if basemap.upper() in map_dict:
if basemap in os.environ:
if "name" in kwargs:
kwargs["name"] = basemap
basemap = os.environ[basemap]
else:
basemap = map_dict[basemap.upper()]
if isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
url = basemap.build_url()
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
max_zoom = basemap["max_zoom"]
else:
max_zoom = 22
layer = ipyleaflet.TileLayer(
url=url,
name=name,
max_zoom=max_zoom,
attribution=attribution,
visible=show,
**kwargs,
)
self.add(layer)
arc_add_layer(url, name)
elif basemap in basemaps and basemaps[basemap].name not in layer_names:
self.add(basemap)
self.layers[-1].visible = show
arc_add_layer(basemaps[basemap].url, basemap)
elif basemap in basemaps and basemaps[basemap].name in layer_names:
print(f"{basemap} has been already added before.")
elif basemap.startswith("http"):
self.add_tile_layer(url=basemap, shown=show, **kwargs)
else:
print(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
except Exception as e:
raise ValueError(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
def get_layer_names(self):
"""Gets layer names as a list.
Returns:
list: A list of layer names.
"""
layer_names = []
for layer in list(self.layers):
if len(layer.name) > 0:
layer_names.append(layer.name)
return layer_names
def find_layer(self, name):
"""Finds layer by name
Args:
name (str): Name of the layer to find.
Returns:
object: ipyleaflet layer object.
"""
layers = self.layers
for layer in layers:
if layer.name == name:
return layer
return None
def show_layer(self, name, show=True):
"""Shows or hides a layer on the map.
Args:
name (str): Name of the layer to show/hide.
show (bool, optional): Whether to show or hide the layer. Defaults to True.
"""
layer = self.find_layer(name)
if layer is not None:
layer.visible = show
def find_layer_index(self, name):
"""Finds layer index by name
Args:
name (str): Name of the layer to find.
Returns:
int: Index of the layer with the specified name
"""
layers = self.layers
for index, layer in enumerate(layers):
if layer.name == name:
return index
return -1
def layer_opacity(self, name, opacity=1.0):
"""Changes layer opacity.
Args:
name (str): The name of the layer to change opacity.
opacity (float, optional): The opacity value to set. Defaults to 1.0.
"""
layer = self.find_layer(name)
try:
layer.opacity = opacity
except Exception as e:
raise Exception(e)
def add_tile_layer(
self,
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
name="Untitled",
attribution="",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a TileLayer to the map.
Args:
url (str, optional): The URL of the tile layer. Defaults to 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'.
name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
tile_layer = ipyleaflet.TileLayer(
url=url,
name=name,
attribution=attribution,
opacity=opacity,
visible=shown,
**kwargs,
)
self.add(tile_layer)
except Exception as e:
print("Failed to add the specified TileLayer.")
raise Exception(e)
def set_plot_options(
self,
add_marker_cluster=False,
sample_scale=None,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Sets plotting options.
Args:
add_marker_cluster (bool, optional): Whether to add a marker cluster. Defaults to False.
sample_scale (float, optional): A nominal scale in meters of the projection to sample in . Defaults to None.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
plot_options_dict = {}
plot_options_dict["add_marker_cluster"] = add_marker_cluster
plot_options_dict["sample_scale"] = sample_scale
plot_options_dict["plot_type"] = plot_type
plot_options_dict["overlay"] = overlay
plot_options_dict["position"] = position
plot_options_dict["min_width"] = min_width
plot_options_dict["max_width"] = max_width
plot_options_dict["min_height"] = min_height
plot_options_dict["max_height"] = max_height
for key in kwargs:
plot_options_dict[key] = kwargs[key]
self._plot_options = plot_options_dict
if not hasattr(self, "_plot_marker_cluster"):
self._plot_marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
if add_marker_cluster and (self._plot_marker_cluster not in self.layers):
self.add(self._plot_marker_cluster)
def plot(
self,
x,
y,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Creates a plot based on x-array and y-array data.
Args:
x (numpy.ndarray or list): The x-coordinates of the plotted line.
y (numpy.ndarray or list): The y-coordinates of the plotted line.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
if hasattr(self, "_plot_widget") and self._plot_widget is not None:
plot_widget = self._plot_widget
else:
plot_widget = widgets.Output(
layout={"border": "1px solid black", "max_width": "500px"}
)
plot_control = ipyleaflet.WidgetControl(
widget=plot_widget,
position=position,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
)
self._plot_widget = plot_widget
self._plot_control = plot_control
self.add(plot_control)
if max_width is None:
max_width = 500
if max_height is None:
max_height = 300
if (plot_type is None) and ("markers" not in kwargs):
kwargs["markers"] = "circle"
with plot_widget:
try:
fig = plt.figure(1, **kwargs)
if max_width is not None:
fig.layout.width = str(max_width) + "px"
if max_height is not None:
fig.layout.height = str(max_height) + "px"
plot_widget.outputs = ()
if not overlay:
plt.clear()
if plot_type is None:
if "marker" not in kwargs:
kwargs["marker"] = "circle"
plt.plot(x, y, **kwargs)
elif plot_type == "bar":
plt.bar(x, y, **kwargs)
elif plot_type == "scatter":
plt.scatter(x, y, **kwargs)
elif plot_type == "hist":
plt.hist(y, **kwargs)
plt.show()
except Exception as e:
print("Failed to create plot.")
raise Exception(e)
def add_layer_control(self, position="topright"):
"""Adds a layer control to the map.
Args:
position (str, optional): _description_. Defaults to "topright".
"""
if self.layer_control is None:
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control)
addLayerControl = add_layer_control
def add_legend(
self,
title="Legend",
legend_dict=None,
keys=None,
colors=None,
position="bottomright",
builtin_legend=None,
layer_name=None,
add_header=True,
widget_args={},
**kwargs,
):
"""Adds a customized basemap to the map.
Args:
title (str, optional): Title of the legend. Defaults to 'Legend'.
legend_dict (dict, optional): A dictionary containing legend items
as keys and color as values. If provided, keys and
colors will be ignored. Defaults to None.
keys (list, optional): A list of legend keys. Defaults to None.
colors (list, optional): A list of legend colors. Defaults to None.
position (str, optional): Position of the legend. Defaults to
'bottomright'.
builtin_legend (str, optional): Name of the builtin legend to add
to the map. Defaults to None.
add_header (bool, optional): Whether the legend can be closed or
not. Defaults to True.
widget_args (dict, optional): Additional arguments passed to the
widget_template() function. Defaults to {}.
"""
try:
legend = map_widgets.Legend(
title,
legend_dict,
keys,
colors,
position,
builtin_legend,
add_header,
widget_args,
**kwargs,
)
legend_control = ipyleaflet.WidgetControl(widget=legend, position=position)
self._legend_widget = legend
self._legend = legend_control
self.add(legend_control)
if not hasattr(self, "legends"):
setattr(self, "legends", [legend_control])
else:
self.legends.append(legend_control)
if layer_name in self.ee_layers:
self.ee_layers[layer_name]["legend"] = legend_control
except Exception as e:
raise Exception(e)
def add_colorbar(
self,
vis_params=None,
cmap="gray",
discrete=False,
label=None,
orientation="horizontal",
position="bottomright",
transparent_bg=False,
layer_name=None,
font_size=9,
axis_off=False,
max_width=None,
**kwargs,
):
"""Add a matplotlib colorbar to the map
Args:
vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
label (str, optional): Label for the colorbar. Defaults to None.
orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.
font_size (int, optional): Font size for the colorbar. Defaults to 9.
axis_off (bool, optional): Whether to turn off the axis. Defaults to False.
max_width (str, optional): Maximum width of the colorbar in pixels. Defaults to None.
Raises:
TypeError: If the vis_params is not a dictionary.
ValueError: If the orientation is not either horizontal or vertical.
TypeError: If the provided min value is not scalar type.
TypeError: If the provided max value is not scalar type.
TypeError: If the provided opacity value is not scalar type.
TypeError: If cmap or palette is not provided.
"""
colorbar = map_widgets.Colorbar(
vis_params,
cmap,
discrete,
label,
orientation,
transparent_bg,
font_size,
axis_off,
max_width,
**kwargs,
)
colormap_ctrl = ipyleaflet.WidgetControl(
widget=colorbar, position=position, transparent_bg=transparent_bg
)
self._colorbar = colormap_ctrl
if layer_name in self.ee_layers:
if "colorbar" in self.ee_layers[layer_name]:
self.remove_control(self.ee_layers[layer_name]["colorbar"])
self.ee_layers[layer_name]["colorbar"] = colormap_ctrl
if not hasattr(self, "colorbars"):
self.colorbars = [colormap_ctrl]
else:
self.colorbars.append(colormap_ctrl)
self.add(colormap_ctrl)
def remove_colorbar(self):
"""Remove colorbar from the map."""
if hasattr(self, "_colorbar") and self._colorbar is not None:
self.remove_control(self._colorbar)
def remove_colorbars(self):
"""Remove all colorbars from the map."""
if hasattr(self, "colorbars"):
for colorbar in self.colorbars:
if colorbar in self.controls:
self.remove_control(colorbar)
def remove_legend(self):
"""Remove legend from the map."""
if hasattr(self, "_legend") and self._legend is not None:
if self._legend in self.controls:
self.remove_control(self._legend)
def remove_legends(self):
"""Remove all legends from the map."""
if hasattr(self, "legends"):
for legend in self.legends:
if legend in self.controls:
self.remove_control(legend)
def create_vis_widget(self, layer_dict):
"""Create a GUI for changing layer visualization parameters interactively.
Args:
layer_dict (dict): A dict containing information about the layer. It is an element from Map.ee_layers.
"""
self._add_layer_editor(position="topright", layer_dict=layer_dict)
def add_inspector(
self,
names=None,
visible=True,
decimals=2,
position="topright",
opened=True,
show_close_button=True,
):
"""Add the Inspector GUI to the map.
Args:
names (str | list, optional): The names of the layers to be included. Defaults to None.
visible (bool, optional): Whether to inspect visible layers only. Defaults to True.
decimals (int, optional): The number of decimal places to round the coordinates. Defaults to 2.
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
"""
super()._add_inspector(
position,
names=names,
visible=visible,
decimals=decimals,
opened=opened,
show_close_button=show_close_button,
)
def add_layer_manager(
self, position="topright", opened=True, show_close_button=True
):
"""Add the Layer Manager to the map.
Args:
position (str, optional): The position of the Layer Manager. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
super()._add_layer_manager(position)
if layer_manager := self._layer_manager:
layer_manager.collapsed = not opened
layer_manager.close_button_hidden = not show_close_button
def _on_basemap_changed(self, basemap_name):
if basemap_name not in self.get_layer_names():
self.add_basemap(basemap_name)
if basemap_name in self._xyz_dict:
if "bounds" in self._xyz_dict[basemap_name]:
bounds = self._xyz_dict[basemap_name]["bounds"]
bounds = [bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]]
self.zoom_to_bounds(bounds)
def add_basemap_widget(self, value="OpenStreetMap", position="topright"):
"""Add the Basemap GUI to the map.
Args:
value (str): The default value from basemaps to select. Defaults to "OpenStreetMap".
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
"""
super()._add_basemap_selector(
position, basemaps=list(basemaps.keys()), value=value
)
if basemap_selector := self._basemap_selector:
basemap_selector.on_basemap_changed = self._on_basemap_changed
def add_draw_control(self, position="topleft"):
"""Add a draw control to the map
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add("draw_control", position=position)
def add_draw_control_lite(self, position="topleft"):
"""Add a lite version draw control to the map for the plotting tool.
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add(
"draw_control",
position=position,
marker={},
rectangle={"shapeOptions": {"color": "#3388ff"}},
circle={"shapeOptions": {"color": "#3388ff"}},
circlemarker={},
polyline={},
polygon={},
edit=False,
remove=False,
)
def add_toolbar(self, position="topright", **kwargs):
"""Add a toolbar to the map.
Args:
position (str, optional): The position of the toolbar. Defaults to "topright".
"""
self.add("toolbar", position, **kwargs)
def _toolbar_main_tools(self):
return toolbar.main_tools
def _toolbar_extra_tools(self):
return toolbar.extra_tools
def add_plot_gui(self, position="topright", **kwargs):
"""Adds the plot widget to the map.
Args:
position (str, optional): Position of the widget. Defaults to "topright".
"""
from .toolbar import ee_plot_gui
ee_plot_gui(self, position, **kwargs)
def add_gui(
self, name, position="topright", opened=True, show_close_button=True, **kwargs
):
"""Add a GUI to the map.
Args:
name (str): The name of the GUI. Options include "layer_manager", "inspector", "plot", and "timelapse".
position (str, optional): The position of the GUI. Defaults to "topright".
opened (bool, optional): Whether the GUI is opened. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
name = name.lower()
if name == "layer_manager":
self.add_layer_manager(position, opened, show_close_button, **kwargs)
elif name == "inspector":
self.add_inspector(
position=position,
opened=opened,
show_close_button=show_close_button,
**kwargs,
)
elif name == "plot":
self.add_plot_gui(position, **kwargs)
elif name == "timelapse":
from .toolbar import timelapse_gui
timelapse_gui(self, **kwargs)
# ******************************************************************************#
# The classes and functions above are the core features of the geemap package. #
# The Earth Engine team and the geemap community will maintain these features. #
# ******************************************************************************#
# ******************************************************************************#
# The classes and functions below are the extra features of the geemap package. #
# The geemap community will maintain these features. #
# ******************************************************************************#
def draw_layer_on_top(self):
"""Move user-drawn feature layer to the top of all layers."""
draw_layer_index = self.find_layer_index(name="Drawn Features")
if draw_layer_index > -1 and draw_layer_index < (len(self.layers) - 1):
layers = list(self.layers)
layers = (
layers[0:draw_layer_index]
+ layers[(draw_layer_index + 1) :]
+ [layers[draw_layer_index]]
)
self.layers = layers
def add_marker(self, location, **kwargs):
"""Adds a marker to the map. More info about marker at https://ipyleaflet.readthedocs.io/en/latest/api_reference/marker.html.
Args:
location (list | tuple): The location of the marker in the format of [lat, lng].
**kwargs: Keyword arguments for the marker.
"""
if isinstance(location, list):
location = tuple(location)
if isinstance(location, tuple):
marker = ipyleaflet.Marker(location=location, **kwargs)
self.add(marker)
else:
raise TypeError("The location must be a list or a tuple.")
def add_wms_layer(
self,
url,
layers,
name=None,
attribution="",
format="image/png",
transparent=True,
opacity=1.0,
shown=True,
**kwargs,
):
"""Add a WMS layer to the map.
Args:
url (str): The URL of the WMS web service.
layers (str): Comma-separated list of WMS layers to show.
name (str, optional): The layer name to use on the layer control. Defaults to None.
attribution (str, optional): The attribution of the data layer. Defaults to ''.
format (str, optional): WMS image format (use ‘image/png’ for layers with transparency). Defaults to 'image/png'.
transparent (bool, optional): If True, the WMS service will return images with transparency. Defaults to True.
opacity (float, optional): The opacity of the layer. Defaults to 1.0.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
if name is None:
name = str(layers)
try:
wms_layer = ipyleaflet.WMSLayer(
url=url,
layers=layers,
name=name,
attribution=attribution,
format=format,
transparent=transparent,
opacity=opacity,
visible=shown,
**kwargs,
)
self.add(wms_layer)
except Exception as e:
print("Failed to add the specified WMS TileLayer.")
raise Exception(e)
def zoom_to_me(self, zoom=14, add_marker=True):
"""Zoom to the current device location.
Args:
zoom (int, optional): Zoom level. Defaults to 14.
add_marker (bool, optional): Whether to add a marker of the current device location. Defaults to True.
"""
lat, lon = get_current_latlon()
self.set_center(lon, lat, zoom)
if add_marker:
marker = ipyleaflet.Marker(
location=(lat, lon),
draggable=False,
name="Device location",
)
self.add(marker)
def zoom_to_gdf(self, gdf):
"""Zooms to the bounding box of a GeoPandas GeoDataFrame.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
"""
bounds = gdf.total_bounds
self.zoom_to_bounds(bounds)
def get_bounds(self, asGeoJSON=False):
"""Returns the bounds of the current map view, as a list in the format [west, south, east, north] in degrees.
Args:
asGeoJSON (bool, optional): If true, returns map bounds as GeoJSON. Defaults to False.
Returns:
list | dict: A list in the format [west, south, east, north] in degrees.
"""
bounds = self.bounds
coords = [bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]]
if asGeoJSON:
return ee.Geometry.BBox(
bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]
).getInfo()
else:
return coords
getBounds = get_bounds
def add_cog_layer(
self,
url,
name="Untitled",
attribution="",
opacity=1.0,
shown=True,
bands=None,
titiler_endpoint=None,
**kwargs,
):
"""Adds a COG TileLayer to the map.
Args:
url (str): The URL of the COG tile layer.
name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
bands (list, optional): A list of bands to use for the layer. Defaults to None.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
**kwargs: Arbitrary keyword arguments, including bidx, expression, nodata, unscale, resampling, rescale, color_formula, colormap, colormap_name, return_mask. See https://developmentseed.org/titiler/endpoints/cog/ and https://cogeotiff.github.io/rio-tiler/colormap/. To select a certain bands, use bidx=[1, 2, 3]
"""
tile_url = cog_tile(url, bands, titiler_endpoint, **kwargs)
bounds = cog_bounds(url, titiler_endpoint)
self.add_tile_layer(tile_url, name, attribution, opacity, shown)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
params = {
"url": url,
"titizer_endpoint": titiler_endpoint,
"bounds": bounds,
"type": "COG",
}
self.cog_layer_dict[name] = params
def add_cog_mosaic(self, **kwargs):
raise NotImplementedError(
"This function is no longer supported.See https://github.com/giswqs/leafmap/issues/180."
)
def add_stac_layer(
self,
url=None,
collection=None,
item=None,
assets=None,
bands=None,
titiler_endpoint=None,
name="STAC Layer",
attribution="",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a STAC TileLayer to the map.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.
name (str, optional): The layer name to use for the layer. Defaults to 'STAC Layer'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
tile_url = stac_tile(
url, collection, item, assets, bands, titiler_endpoint, **kwargs
)
bounds = stac_bounds(url, collection, item, titiler_endpoint)
self.add_tile_layer(tile_url, name, attribution, opacity, shown)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
if assets is None and bands is not None:
assets = bands
params = {
"url": url,
"collection": collection,
"item": item,
"assets": assets,
"bounds": bounds,
"titiler_endpoint": titiler_endpoint,
"type": "STAC",
}
self.cog_layer_dict[name] = params
def add_minimap(self, zoom=5, position="bottomright"):
"""Adds a minimap (overview) to the ipyleaflet map.
Args:
zoom (int, optional): Initial map zoom level. Defaults to 5.
position (str, optional): Position of the minimap. Defaults to "bottomright".
"""
minimap = ipyleaflet.Map(
zoom_control=False,
attribution_control=False,
zoom=zoom,
center=self.center,
layers=[get_basemap("ROADMAP")],
)
minimap.layout.width = "150px"
minimap.layout.height = "150px"
ipyleaflet.link((minimap, "center"), (self, "center"))
minimap_control = ipyleaflet.WidgetControl(widget=minimap, position=position)
self.add(minimap_control)
def marker_cluster(self):
"""Adds a marker cluster to the map and returns a list of ee.Feature, which can be accessed using Map.ee_marker_cluster.
Returns:
object: a list of ee.Feature
"""
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
self.ee_markers = []
self.add(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get("coordinates")
if kwargs.get("type") == "click":
coordinates.append(latlon)
geom = ee.Geometry.Point(latlon[1], latlon[0])
feature = ee.Feature(geom)
self.ee_markers.append(feature)
self.last_click = latlon
self.all_clicks = coordinates
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
elif kwargs.get("type") == "mousemove":
pass
# cursor style: https://www.w3schools.com/cssref/pr_class_cursor.asp
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def plot_demo(
self,
iterations=20,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""A demo of interactive plotting using random pixel coordinates.
Args:
iterations (int, optional): How many iterations to run for the demo. Defaults to 20.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
import numpy as np
import time
if hasattr(self, "random_marker") and self.random_marker is not None:
self.remove_layer(self.random_marker)
image = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003").select([0, 1, 2, 3, 4, 6])
self.addLayer(
image,
{"bands": ["B4", "B3", "B2"], "gamma": 1.4},
"LANDSAT/LE7_TOA_5YEAR/1999_2003",
)
self.setCenter(-50.078877, 25.190030, 3)
band_names = image.bandNames().getInfo()
# band_count = len(band_names)
latitudes = np.random.uniform(30, 48, size=iterations)
longitudes = np.random.uniform(-121, -76, size=iterations)
marker = ipyleaflet.Marker(location=(0, 0))
self.random_marker = marker
self.add(marker)
for i in range(iterations):
try:
coordinate = ee.Geometry.Point([longitudes[i], latitudes[i]])
dict_values = image.sample(coordinate).first().toDictionary().getInfo()
band_values = list(dict_values.values())
title = "{}/{}: Spectral signature at ({}, {})".format(
i + 1,
iterations,
round(latitudes[i], 2),
round(longitudes[i], 2),
)
marker.location = (latitudes[i], longitudes[i])
self.plot(
band_names,
band_values,
plot_type=plot_type,
overlay=overlay,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
title=title,
**kwargs,
)
time.sleep(0.3)
except Exception as e:
raise Exception(e)
def plot_raster(
self,
ee_object=None,
sample_scale=None,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Interactive plotting of Earth Engine data by clicking on the map.
Args:
ee_object (object, optional): The ee.Image or ee.ImageCollection to sample. Defaults to None.
sample_scale (float, optional): A nominal scale in meters of the projection to sample in. Defaults to None.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
if hasattr(self, "_plot_control") and self._plot_control is not None:
del self._plot_widget
if self._plot_control in self.controls:
self.remove_control(self._plot_control)
if hasattr(self, "random_marker") and self.random_marker is not None:
self.remove_layer(self.random_marker)
plot_widget = widgets.Output(layout={"border": "1px solid black"})
plot_control = ipyleaflet.WidgetControl(
widget=plot_widget,
position=position,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
)
self._plot_widget = plot_widget
self._plot_control = plot_control
self.add(plot_control)
self.default_style = {"cursor": "crosshair"}
msg = "The plot function can only be used on ee.Image or ee.ImageCollection with more than one band."
if (ee_object is None) and len(self.ee_raster_layers) > 0:
ee_object = self.ee_raster_layers.values()[-1]["ee_object"]
if isinstance(ee_object, ee.ImageCollection):
ee_object = ee_object.mosaic()
elif isinstance(ee_object, ee.ImageCollection):
ee_object = ee_object.mosaic()
elif not isinstance(ee_object, ee.Image):
print(msg)
return
if sample_scale is None:
sample_scale = self.getScale()
if max_width is None:
max_width = 500
band_names = ee_object.bandNames().getInfo()
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
self.add(marker_cluster)
def handle_interaction(**kwargs2):
latlon = kwargs2.get("coordinates")
if kwargs2.get("type") == "click":
try:
coordinates.append(latlon)
self.last_click = latlon
self.all_clicks = coordinates
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
self.default_style = {"cursor": "wait"}
xy = ee.Geometry.Point(latlon[::-1])
dict_values = (
ee_object.sample(xy, scale=sample_scale)
.first()
.toDictionary()
.getInfo()
)
band_values = list(dict_values.values())
self.plot(
band_names,
band_values,
plot_type=plot_type,
overlay=overlay,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
**kwargs,
)
self.default_style = {"cursor": "crosshair"}
except Exception as e:
if self._plot_widget is not None:
with self._plot_widget:
self._plot_widget.outputs = ()
print("No data for the clicked location.")
else:
print(e)
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def add_marker_cluster(self, event="click", add_marker=True):
"""Captures user inputs and add markers to the map.
Args:
event (str, optional): [description]. Defaults to 'click'.
add_marker (bool, optional): If True, add markers to the map. Defaults to True.
Returns:
object: a marker cluster.
"""
coordinates = []
markers = []
marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
self.last_click = []
self.all_clicks = []
if add_marker:
self.add(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get("coordinates")
if event == "click" and kwargs.get("type") == "click":
coordinates.append(latlon)
self.last_click = latlon
self.all_clicks = coordinates
if add_marker:
markers.append(ipyleaflet.Marker(location=latlon))
marker_cluster.markers = markers
elif kwargs.get("type") == "mousemove":
pass
# cursor style: https://www.w3schools.com/cssref/pr_class_cursor.asp
self.default_style = {"cursor": "crosshair"}
self.on_interaction(handle_interaction)
def set_control_visibility(
self, layerControl=True, fullscreenControl=True, latLngPopup=True
):
"""Sets the visibility of the controls on the map.
Args:
layerControl (bool, optional): Whether to show the control that allows the user to toggle layers on/off. Defaults to True.
fullscreenControl (bool, optional): Whether to show the control that allows the user to make the map full-screen. Defaults to True.
latLngPopup (bool, optional): Whether to show the control that pops up the Lat/lon when the user clicks on the map. Defaults to True.
"""
pass
setControlVisibility = set_control_visibility
def split_map(
self,
left_layer="OpenTopoMap",
right_layer="Esri.WorldTopoMap",
zoom_control=True,
fullscreen_control=True,
layer_control=True,
add_close_button=False,
close_button_position="topright",
left_label=None,
right_label=None,
left_position="bottomleft",
right_position="bottomright",
widget_layout=None,
**kwargs,
):
"""Adds split map.
Args:
left_layer (str, optional): The layer tile layer. Defaults to 'OpenTopoMap'.
right_layer (str, optional): The right tile layer. Defaults to 'Esri.WorldTopoMap'.
zoom_control (bool, optional): Whether to show the zoom control. Defaults to True.
fullscreen_control (bool, optional): Whether to show the full screen control. Defaults to True.
layer_control (bool, optional): Whether to show the layer control. Defaults to True.
add_close_button (bool, optional): Whether to add a close button. Defaults to False.
close_button_position (str, optional): The position of the close button. Defaults to 'topright'.
left_label (str, optional): The label for the left map. Defaults to None.
right_label (str, optional): The label for the right map. Defaults to None.
left_position (str, optional): The position of the left label. Defaults to 'bottomleft'.
right_position (str, optional): The position of the right label. Defaults to 'bottomright'.
widget_layout (str, optional): The layout of the label widget, such as ipywidgets.Layout(padding="0px 4px 0px 4px"). Defaults to None.
kwargs: Other arguments for ipyleaflet.TileLayer.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
controls = self.controls
layers = self.layers
self.clear_controls()
if zoom_control:
self.add(ipyleaflet.ZoomControl())
if fullscreen_control:
self.add(ipyleaflet.FullScreenControl())
if left_label is not None:
left_name = left_label
else:
left_name = "Left Layer"
if right_label is not None:
right_name = right_label
else:
right_name = "Right Layer"
if "attribution" not in kwargs:
kwargs["attribution"] = " "
if left_layer in basemaps.keys():
left_layer = get_basemap(left_layer)
elif isinstance(left_layer, str):
if left_layer.startswith("http") and left_layer.endswith(".tif"):
url = cog_tile(left_layer)
left_layer = ipyleaflet.TileLayer(
url=url,
name=left_name,
**kwargs,
)
else:
left_layer = ipyleaflet.TileLayer(
url=left_layer,
name=left_name,
**kwargs,
)
elif isinstance(left_layer, ipyleaflet.TileLayer):
pass
else:
raise ValueError(
f"left_layer must be one of the following: {', '.join(basemaps.keys())} or a string url to a tif file."
)
if right_layer in basemaps.keys():
right_layer = get_basemap(right_layer)
elif isinstance(right_layer, str):
if right_layer.startswith("http") and right_layer.endswith(".tif"):
url = cog_tile(right_layer)
right_layer = ipyleaflet.TileLayer(
url=url,
name=right_name,
**kwargs,
)
else:
right_layer = ipyleaflet.TileLayer(
url=right_layer,
name=right_name,
**kwargs,
)
elif isinstance(right_layer, ipyleaflet.TileLayer):
pass
else:
raise ValueError(
f"right_layer must be one of the following: {', '.join(basemaps.keys())} or a string url to a tif file."
)
control = ipyleaflet.SplitMapControl(
left_layer=left_layer, right_layer=right_layer
)
self.add(control)
self.dragging = False
if left_label is not None:
if widget_layout is None:
widget_layout = widgets.Layout(padding="0px 4px 0px 4px")
left_widget = widgets.HTML(value=left_label, layout=widget_layout)
left_control = ipyleaflet.WidgetControl(
widget=left_widget, position=left_position
)
self.add(left_control)
if right_label is not None:
if widget_layout is None:
widget_layout = widgets.Layout(padding="0px 4px 0px 4px")
right_widget = widgets.HTML(value=right_label, layout=widget_layout)
right_control = ipyleaflet.WidgetControl(
widget=right_widget, position=right_position
)
self.add(right_control)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close split-panel map",
icon="times",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
def close_btn_click(change):
if left_label is not None:
self.remove_control(left_control)
if right_label is not None:
self.remove_control(right_control)
if change["new"]:
self.controls = controls
self.layers = layers[:-1]
self.add(layers[-1])
self.dragging = True
close_button.observe(close_btn_click, "value")
close_control = ipyleaflet.WidgetControl(
widget=close_button, position=close_button_position
)
if add_close_button:
self.add(close_control)
if layer_control:
self.addLayerControl()
except Exception as e:
print("The provided layers are invalid!")
raise ValueError(e)
def ts_inspector(
self,
left_ts,
left_names=None,
left_vis={},
left_index=0,
right_ts=None,
right_names=None,
right_vis=None,
right_index=-1,
width="130px",
date_format="YYYY-MM-dd",
add_close_button=False,
**kwargs,
):
"""Creates a split-panel map for inspecting timeseries images.
Args:
left_ts (object): An ee.ImageCollection to show on the left panel.
left_names (list): A list of names to show under the left dropdown.
left_vis (dict, optional): Visualization parameters for the left layer. Defaults to {}.
left_index (int, optional): The index of the left layer to show. Defaults to 0.
right_ts (object): An ee.ImageCollection to show on the right panel.
right_names (list): A list of names to show under the right dropdown.
right_vis (dict, optional): Visualization parameters for the right layer. Defaults to {}.
right_index (int, optional): The index of the right layer to show. Defaults to -1.
width (str, optional): The width of the dropdown list. Defaults to '130px'.
date_format (str, optional): The date format to show in the dropdown. Defaults to 'YYYY-MM-dd'.
add_close_button (bool, optional): Whether to show the close button. Defaults to False.
"""
controls = self.controls
layers = self.layers
if left_names is None:
left_names = image_dates(left_ts, date_format=date_format).getInfo()
if right_ts is None:
right_ts = left_ts
if right_names is None:
right_names = left_names
if right_vis is None:
right_vis = left_vis
left_count = int(left_ts.size().getInfo())
right_count = int(right_ts.size().getInfo())
if left_count != len(left_names):
print(
"The number of images in left_ts must match the number of layer names in left_names."
)
return
if right_count != len(right_names):
print(
"The number of images in right_ts must match the number of layer names in right_names."
)
return
left_layer = ipyleaflet.TileLayer(
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
attribution="Esri",
name="Esri.WorldStreetMap",
)
right_layer = ipyleaflet.TileLayer(
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
attribution="Esri",
name="Esri.WorldStreetMap",
)
self.clear_controls()
left_dropdown = widgets.Dropdown(options=left_names, value=None)
right_dropdown = widgets.Dropdown(options=right_names, value=None)
left_dropdown.layout.max_width = width
right_dropdown.layout.max_width = width
left_control = ipyleaflet.WidgetControl(
widget=left_dropdown, position="topleft"
)
right_control = ipyleaflet.WidgetControl(
widget=right_dropdown, position="topright"
)
self.add(left_control)
self.add(right_control)
self.add(ipyleaflet.ZoomControl(position="topleft"))
self.add(ipyleaflet.ScaleControl(position="bottomleft"))
self.add(ipyleaflet.FullScreenControl())
def left_dropdown_change(change):
left_dropdown_index = left_dropdown.index
if left_dropdown_index is not None and left_dropdown_index >= 0:
try:
if isinstance(left_ts, ee.ImageCollection):
left_image = left_ts.toList(left_ts.size()).get(
left_dropdown_index
)
elif isinstance(left_ts, ee.List):
left_image = left_ts.get(left_dropdown_index)
else:
print("The left_ts argument must be an ImageCollection.")
return
if isinstance(left_image, ee.ImageCollection):
left_image = ee.Image(left_image.mosaic())
elif isinstance(left_image, ee.Image):
pass
else:
left_image = ee.Image(left_image)
left_image = EELeafletTileLayer(
left_image, left_vis, left_names[left_dropdown_index]
)
left_layer.url = left_image.url
except Exception as e:
print(e)
return
left_dropdown.observe(left_dropdown_change, names="value")
def right_dropdown_change(change):
right_dropdown_index = right_dropdown.index
if right_dropdown_index is not None and right_dropdown_index >= 0:
try:
if isinstance(right_ts, ee.ImageCollection):
right_image = right_ts.toList(left_ts.size()).get(
right_dropdown_index
)
elif isinstance(right_ts, ee.List):
right_image = right_ts.get(right_dropdown_index)
else:
print("The left_ts argument must be an ImageCollection.")
return
if isinstance(right_image, ee.ImageCollection):
right_image = ee.Image(right_image.mosaic())
elif isinstance(right_image, ee.Image):
pass
else:
right_image = ee.Image(right_image)
right_image = EELeafletTileLayer(
right_image,
right_vis,
right_names[right_dropdown_index],
)
right_layer.url = right_image.url
except Exception as e:
print(e)
return
right_dropdown.observe(right_dropdown_change, names="value")
if left_index is not None:
left_dropdown.value = left_names[left_index]
if right_index is not None:
right_dropdown.value = right_names[right_index]
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
# button_style="primary",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
def close_btn_click(change):
if change["new"]:
self.controls = controls
self.clear_layers()
self.layers = layers
close_button.observe(close_btn_click, "value")
close_control = ipyleaflet.WidgetControl(
widget=close_button, position="bottomright"
)
try:
split_control = ipyleaflet.SplitMapControl(
left_layer=left_layer, right_layer=right_layer
)
self.add(split_control)
self.dragging = False
if add_close_button:
self.add(close_control)
except Exception as e:
raise Exception(e)
def basemap_demo(self):
"""A demo for using geemap basemaps."""
dropdown = widgets.Dropdown(
options=list(basemaps.keys()),
value="HYBRID",
description="Basemaps",
)
def on_click(change):
basemap_name = change["new"]
old_basemap = self.layers[-1]
self.substitute_layer(old_basemap, get_basemap(basemaps[basemap_name]))
dropdown.observe(on_click, "value")
basemap_control = ipyleaflet.WidgetControl(widget=dropdown, position="topright")
self.add(basemap_control)
def add_colorbar_branca(
self,
colors,
vmin=0,
vmax=1.0,
index=None,
caption="",
categorical=False,
step=None,
height="45px",
transparent_bg=False,
position="bottomright",
layer_name=None,
**kwargs,
):
"""Add a branca colorbar to the map.
Args:
colors (list): The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)
vmin (int, optional): The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.
vmax (float, optional): The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.
index (list, optional):The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.
caption (str, optional): The caption for the colormap. Defaults to "".
categorical (bool, optional): Whether or not to create a categorical colormap. Defaults to False.
step (int, optional): The step to split the LinearColormap into a StepColormap. Defaults to None.
height (str, optional): The height of the colormap widget. Defaults to "45px".
transparent_bg (bool, optional): Whether to use transparent background for the colormap widget. Defaults to True.
position (str, optional): The position for the colormap widget. Defaults to "bottomright".
layer_name (str, optional): Layer name of the colorbar to be associated with. Defaults to None.
"""
from branca.colormap import LinearColormap
output = widgets.Output()
output.layout.height = height
if "width" in kwargs:
output.layout.width = kwargs["width"]
if isinstance(colors, Box):
try:
colors = list(colors["default"])
except Exception as e:
print("The provided color list is invalid.")
raise Exception(e)
if all(len(color) == 6 for color in colors):
colors = ["#" + color for color in colors]
colormap = LinearColormap(
colors=colors, index=index, vmin=vmin, vmax=vmax, caption=caption
)
if categorical:
if step is not None:
colormap = colormap.to_step(step)
elif index is not None:
colormap = colormap.to_step(len(index) - 1)
else:
colormap = colormap.to_step(3)
colormap_ctrl = ipyleaflet.WidgetControl(
widget=output,
position=position,
transparent_bg=transparent_bg,
**kwargs,
)
with output:
output.outputs = ()
display(colormap)
self._colorbar = colormap_ctrl
self.add(colormap_ctrl)
if not hasattr(self, "colorbars"):
self.colorbars = [colormap_ctrl]
else:
self.colorbars.append(colormap_ctrl)
if layer_name in self.ee_layers:
self.ee_layers[layer_name]["colorbar"] = colormap_ctrl
def image_overlay(self, url, bounds, name):
"""Overlays an image from the Internet or locally on the map.
Args:
url (str): http URL or local file path to the image.
bounds (tuple): bounding box of the image in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).
name (str): name of the layer to show on the layer control.
"""
from base64 import b64encode
from io import BytesIO
from PIL import Image, ImageSequence
try:
if not url.startswith("http"):
if not os.path.exists(url):
print("The provided file does not exist.")
return
ext = os.path.splitext(url)[1][1:] # file extension
image = Image.open(url)
f = BytesIO()
if ext.lower() == "gif":
frames = []
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(image):
frame = frame.convert("RGBA")
b = BytesIO()
frame.save(b, format="gif")
frame = Image.open(b)
frames.append(frame)
frames[0].save(
f,
format="GIF",
save_all=True,
append_images=frames[1:],
loop=0,
)
else:
image.save(f, ext)
data = b64encode(f.getvalue())
data = data.decode("ascii")
url = "data:image/{};base64,".format(ext) + data
img = ipyleaflet.ImageOverlay(url=url, bounds=bounds, name=name)
self.add(img)
except Exception as e:
print(e)
def video_overlay(self, url, bounds, name="Video"):
"""Overlays a video from the Internet on the map.
Args:
url (str): http URL of the video, such as "https://www.mapbox.com/bites/00188/patricia_nasa.webm"
bounds (tuple): bounding box of the video in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -100)).
name (str): name of the layer to show on the layer control.
"""
try:
video = ipyleaflet.VideoOverlay(url=url, bounds=bounds, name=name)
self.add(video)
except Exception as e:
print(e)
def add_landsat_ts_gif(
self,
layer_name="Timelapse",
roi=None,
label=None,
start_year=1984,
end_year=2021,
start_date="06-10",
end_date="09-20",
bands=["NIR", "Red", "Green"],
vis_params=None,
dimensions=768,
frames_per_second=10,
font_size=30,
font_color="white",
add_progress_bar=True,
progress_bar_color="white",
progress_bar_height=5,
out_gif=None,
download=False,
apply_fmask=True,
nd_bands=None,
nd_threshold=0,
nd_palette=["black", "blue"],
):
"""Adds a Landsat timelapse to the map.
Args:
layer_name (str, optional): Layer name to show under the layer control. Defaults to 'Timelapse'.
roi (object, optional): Region of interest to create the timelapse. Defaults to None.
label (str, optional): A label to show on the GIF, such as place name. Defaults to None.
start_year (int, optional): Starting year for the timelapse. Defaults to 1984.
end_year (int, optional): Ending year for the timelapse. Defaults to 2021.
start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'.
end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'.
bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green'].
vis_params (dict, optional): Visualization parameters. Defaults to None.
dimensions (int, optional): a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768.
frames_per_second (int, optional): Animation speed. Defaults to 10.
font_size (int, optional): Font size of the animated text and label. Defaults to 30.
font_color (str, optional): Font color of the animated text and label. Defaults to 'black'.
add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True.
progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'.
progress_bar_height (int, optional): Height of the progress bar. Defaults to 5.
out_gif (str, optional): File path to the output animated GIF. Defaults to None.
download (bool, optional): Whether to download the gif. Defaults to False.
apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking.
nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1).
nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band.
nd_palette (str, optional): The color palette to use for displaying the normalized difference band.
"""
try:
if roi is None:
if self.draw_last_feature is not None:
feature = self.draw_last_feature
roi = feature.geometry()
else:
roi = ee.Geometry.Polygon(
[
[
[-115.471773, 35.892718],
[-115.471773, 36.409454],
[-114.271283, 36.409454],
[-114.271283, 35.892718],
[-115.471773, 35.892718],
]
],
None,
False,
)
elif isinstance(roi, ee.Feature) or isinstance(roi, ee.FeatureCollection):
roi = roi.geometry()
elif isinstance(roi, ee.Geometry):
pass
else:
print("The provided roi is invalid. It must be an ee.Geometry")
return
geojson = ee_to_geojson(roi)
bounds = minimum_bounding_box(geojson)
geojson = adjust_longitude(geojson)
roi = ee.Geometry(geojson)
in_gif = landsat_timelapse(
roi=roi,
out_gif=out_gif,
start_year=start_year,
end_year=end_year,
start_date=start_date,
end_date=end_date,
bands=bands,
vis_params=vis_params,
dimensions=dimensions,
frames_per_second=frames_per_second,
apply_fmask=apply_fmask,
nd_bands=nd_bands,
nd_threshold=nd_threshold,
nd_palette=nd_palette,
font_size=font_size,
font_color=font_color,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
in_nd_gif = in_gif.replace(".gif", "_nd.gif")
if nd_bands is not None:
add_text_to_gif(
in_nd_gif,
in_nd_gif,
xy=("2%", "2%"),
text_sequence=start_year,
font_size=font_size,
font_color=font_color,
duration=int(1000 / frames_per_second),
add_progress_bar=add_progress_bar,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
if label is not None:
add_text_to_gif(
in_gif,
in_gif,
xy=("2%", "90%"),
text_sequence=label,
font_size=font_size,
font_color=font_color,
duration=int(1000 / frames_per_second),
add_progress_bar=add_progress_bar,
progress_bar_color=progress_bar_color,
progress_bar_height=progress_bar_height,
)
# if nd_bands is not None:
# add_text_to_gif(in_nd_gif, in_nd_gif, xy=('2%', '90%'), text_sequence=label,
# font_size=font_size, font_color=font_color, duration=int(1000 / frames_per_second), add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height)
if is_tool("ffmpeg"):
reduce_gif_size(in_gif)
if nd_bands is not None:
reduce_gif_size(in_nd_gif)
print("Adding GIF to the map ...")
self.image_overlay(url=in_gif, bounds=bounds, name=layer_name)
if nd_bands is not None:
self.image_overlay(
url=in_nd_gif, bounds=bounds, name=layer_name + " ND"
)
print("The timelapse has been added to the map.")
if download:
link = create_download_link(
in_gif,
title="Click here to download the Landsat timelapse: ",
)
display(link)
if nd_bands is not None:
link2 = create_download_link(
in_nd_gif,
title="Click here to download the Normalized Difference Index timelapse: ",
)
display(link2)
except Exception as e:
raise Exception(e)
def to_html(
self,
filename=None,
title="My Map",
width="100%",
height="880px",
add_layer_control=True,
**kwargs,
):
"""Saves the map as an HTML file.
Args:
filename (str, optional): The output file path to the HTML file.
title (str, optional): The title of the HTML file. Defaults to 'My Map'.
width (str, optional): The width of the map in pixels or percentage. Defaults to '100%'.
height (str, optional): The height of the map in pixels. Defaults to '880px'.
add_layer_control (bool, optional): Whether to add the LayersControl. Defaults to True.
"""
try:
save = True
if filename is not None:
if not filename.endswith(".html"):
raise ValueError("The output file extension must be html.")
filename = os.path.abspath(filename)
out_dir = os.path.dirname(filename)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
filename = os.path.abspath(random_string() + ".html")
save = False
if add_layer_control and self.layer_control is None:
layer_control = ipyleaflet.LayersControl(position="topright")
self.layer_control = layer_control
self.add(layer_control)
before_width = self.layout.width
before_height = self.layout.height
if not isinstance(width, str):
print("width must be a string.")
return
elif width.endswith("px") or width.endswith("%"):
pass
else:
print("width must end with px or %")
return
if not isinstance(height, str):
print("height must be a string.")
return
elif not height.endswith("px"):
print("height must end with px")
return
self.layout.width = width
self.layout.height = height
self.save(filename, title=title, **kwargs)
self.layout.width = before_width
self.layout.height = before_height
if not save:
out_html = ""
with open(filename) as f:
lines = f.readlines()
out_html = "".join(lines)
os.remove(filename)
return out_html
except Exception as e:
raise Exception(e)
def to_image(self, filename=None, monitor=1):
"""Saves the map as a PNG or JPG image.
Args:
filename (str, optional): The output file path to the image. Defaults to None.
monitor (int, optional): The monitor to take the screenshot. Defaults to 1.
"""
self.screenshot = None
if filename is None:
filename = os.path.join(os.getcwd(), "my_map.png")
if filename.endswith(".png") or filename.endswith(".jpg"):
pass
else:
print("The output file must be a PNG or JPG image.")
return
work_dir = os.path.dirname(filename)
if not os.path.exists(work_dir):
os.makedirs(work_dir)
screenshot = screen_capture(filename, monitor)
self.screenshot = screenshot
def toolbar_reset(self):
"""Reset the toolbar so that no tool is selected."""
if hasattr(self, "_toolbar"):
self._toolbar.reset()
def add_raster(
self,
source,
indexes=None,
colormap=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name="Raster",
zoom_to_layer=True,
visible=True,
array_args={},
**kwargs,
):
"""Add a local raster dataset to the map.
If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer) and
if the raster does not render properly, try installing jupyter-server-proxy using `pip install jupyter-server-proxy`,
then running the following code before calling this function. For more info, see https://bit.ly/3JbmF93.
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}'
Args:
source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.
indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None.
colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to 'Raster'.
zoom_to_layer (bool, optional): Whether to zoom to the extent of the layer. Defaults to True.
visible (bool, optional): Whether the layer is visible. Defaults to True.
array_args (dict, optional): Additional arguments to pass to `array_to_memory_file` when reading the raster. Defaults to {}.
"""
import numpy as np
import xarray as xr
if isinstance(source, np.ndarray) or isinstance(source, xr.DataArray):
source = array_to_image(source, **array_args)
tile_layer, tile_client = get_local_tile_layer(
source,
indexes=indexes,
colormap=colormap,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
return_client=True,
**kwargs,
)
tile_layer.visible = visible
self.add(tile_layer)
bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax]
bounds = (
bounds[2],
bounds[0],
bounds[3],
bounds[1],
) # [minx, miny, maxx, maxy]
if zoom_to_layer:
self.zoom_to_bounds(bounds)
arc_add_layer(tile_layer.url, layer_name, True, 1.0)
if zoom_to_layer:
arc_zoom_to_extent(bounds[0], bounds[1], bounds[2], bounds[3])
if not hasattr(self, "cog_layer_dict"):
self.cog_layer_dict = {}
params = {
"tile_layer": tile_layer,
"tile_client": tile_client,
"indexes": indexes,
"band_names": tile_client.band_names,
"bounds": bounds,
"type": "LOCAL",
}
self.cog_layer_dict[layer_name] = params
def add_remote_tile(
self,
source,
band=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name=None,
**kwargs,
):
"""Add a remote Cloud Optimized GeoTIFF (COG) to the map.
Args:
source (str): The path to the remote Cloud Optimized GeoTIFF.
band (int, optional): The band to use. Band indexing starts at 1. Defaults to None.
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to None.
"""
if isinstance(source, str) and source.startswith("http"):
self.add_raster(
source,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
**kwargs,
)
else:
raise Exception("The source must be a URL.")
def remove_draw_control(self):
"""Removes the draw control from the map"""
self.remove("draw_control")
def remove_drawn_features(self):
"""Removes user-drawn geometries from the map"""
if self._draw_control is not None:
self._draw_control.reset()
if "Drawn Features" in self.ee_layers:
self.ee_layers.pop("Drawn Features")
def remove_last_drawn(self):
"""Removes last user-drawn geometry from the map"""
if self._draw_control is not None:
if self._draw_control.count == 1:
self.remove_drawn_features()
elif self._draw_control.count:
self._draw_control.remove_geometry(self._draw_control.geometries[-1])
if hasattr(self, "_chart_values"):
self._chart_values = self._chart_values[:-1]
if hasattr(self, "_chart_points"):
self._chart_points = self._chart_points[:-1]
# self._chart_labels = None
def extract_values_to_points(self, filename):
"""Exports pixel values to a csv file based on user-drawn geometries.
Args:
filename (str): The output file path to the csv file or shapefile.
"""
import csv
filename = os.path.abspath(filename)
allowed_formats = ["csv", "shp"]
ext = filename[-3:]
if ext not in allowed_formats:
print(
"The output file must be one of the following: {}".format(
", ".join(allowed_formats)
)
)
return
out_dir = os.path.dirname(filename)
out_csv = filename[:-3] + "csv"
out_shp = filename[:-3] + "shp"
if not os.path.exists(out_dir):
os.makedirs(out_dir)
count = len(self._chart_points)
out_list = []
if count > 0:
header = ["id", "longitude", "latitude"] + self._chart_labels
out_list.append(header)
for i in range(0, count):
id = i + 1
line = [id] + self._chart_points[i] + self._chart_values[i]
out_list.append(line)
with open(out_csv, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(out_list)
if ext == "csv":
print(f"The csv file has been saved to: {out_csv}")
else:
csv_to_shp(out_csv, out_shp)
print(f"The shapefile has been saved to: {out_shp}")
def add_styled_vector(
self,
ee_object,
column,
palette,
layer_name="Untitled",
shown=True,
opacity=1.0,
**kwargs,
):
"""Adds a styled vector to the map.
Args:
ee_object (object): An ee.FeatureCollection.
column (str): The column name to use for styling.
palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling.
layer_name (str, optional): The name to be used for the new layer. Defaults to "Untitled".
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): The opacity of the layer. Defaults to 1.0.
"""
if isinstance(palette, str):
from .colormaps import get_palette
count = ee_object.size().getInfo()
palette = get_palette(palette, count)
styled_vector = vector_styling(ee_object, column, palette, **kwargs)
self.addLayer(
styled_vector.style(**{"styleProperty": "style"}),
{},
layer_name,
shown,
opacity,
)
def add_shp(
self,
in_shp,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
):
"""Adds a shapefile to the map.
Args:
in_shp (str): The input file path to the shapefile.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the shapefile. Defaults to "utf-8".
Raises:
FileNotFoundError: The provided shapefile could not be found.
"""
in_shp = os.path.abspath(in_shp)
if not os.path.exists(in_shp):
raise FileNotFoundError("The provided shapefile could not be found.")
geojson = shp_to_geojson(in_shp)
self.add_geojson(
geojson,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
add_shapefile = add_shp
def add_geojson(
self,
in_geojson,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
):
"""Adds a GeoJSON file to the map.
Args:
in_geojson (str | dict): The file path or http URL to the input GeoJSON or a dictionary containing the geojson.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the GeoJSON file. Defaults to "utf-8".
Raises:
FileNotFoundError: The provided GeoJSON file could not be found.
"""
import json
import random
import requests
import warnings
warnings.filterwarnings("ignore")
style_callback_only = False
if len(style) == 0 and style_callback is not None:
style_callback_only = True
try:
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
in_geojson = github_raw_url(in_geojson)
data = requests.get(in_geojson).json()
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError(
"The provided GeoJSON file could not be found."
)
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
else:
raise TypeError("The input geojson must be a type of str or dict.")
except Exception as e:
raise Exception(e)
if not style:
style = {
# "stroke": True,
"color": "#000000",
"weight": 1,
"opacity": 1,
# "fill": True,
# "fillColor": "#ffffff",
"fillOpacity": 0.1,
# "dashArray": "9"
# "clickable": True,
}
elif "weight" not in style:
style["weight"] = 1
if not hover_style:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
def random_color(feature):
return {
"color": "black",
"fillColor": random.choice(fill_colors),
}
toolbar_button = widgets.ToggleButton(
value=True,
tooltip="Toolbar",
icon="info",
layout=widgets.Layout(
width="28px", height="28px", padding="0px 0px 0px 4px"
),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
# button_style="primary",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 4px"
),
)
html = widgets.HTML()
html.layout.margin = "0px 10px 0px 10px"
html.layout.max_height = "250px"
html.layout.max_width = "250px"
output_widget = widgets.VBox(
[widgets.HBox([toolbar_button, close_button]), html]
)
info_control = ipyleaflet.WidgetControl(
widget=output_widget, position="bottomright"
)
if info_mode in ["on_hover", "on_click"]:
self.add(info_control)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
output_widget.children = [
widgets.VBox([widgets.HBox([toolbar_button, close_button]), html])
]
else:
output_widget.children = [widgets.HBox([toolbar_button, close_button])]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if info_control in self.controls:
self.remove_control(info_control)
output_widget.close()
close_button.observe(close_btn_click, "value")
def update_html(feature, **kwargs):
value = [
"<b>{}: </b>{}<br>".format(prop, feature["properties"][prop])
for prop in feature["properties"].keys()
][:-1]
value = """{}""".format("".join(value))
html.value = value
if style_callback is None:
style_callback = random_color
if style_callback_only:
geojson = ipyleaflet.GeoJSON(
data=data,
hover_style=hover_style,
style_callback=style_callback,
name=layer_name,
)
else:
geojson = ipyleaflet.GeoJSON(
data=data,
style=style,
hover_style=hover_style,
style_callback=style_callback,
name=layer_name,
)
if info_mode == "on_hover":
geojson.on_hover(update_html)
elif info_mode == "on_click":
geojson.on_click(update_html)
self.add(geojson)
self.geojson_layers.append(geojson)
if not hasattr(self, "json_layer_dict"):
self.json_layer_dict = {}
params = {
"data": geojson,
"style": style,
"hover_style": hover_style,
"style_callback": style_callback,
}
self.json_layer_dict[layer_name] = params
def add_kml(
self,
in_kml,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds a GeoJSON file to the map.
Args:
in_kml (str): The input file path to the KML.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
Raises:
FileNotFoundError: The provided KML file could not be found.
"""
if isinstance(in_kml, str) and in_kml.startswith("http"):
in_kml = github_raw_url(in_kml)
in_kml = download_file(in_kml)
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The provided KML file could not be found.")
self.add_vector(
in_kml,
layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
def add_vector(
self,
filename,
layer_name="Untitled",
to_ee=False,
bbox=None,
mask=None,
rows=None,
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
encoding="utf-8",
**kwargs,
):
"""Adds any geopandas-supported vector dataset to the map.
Args:
filename (str): Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).
layer_name (str, optional): The layer name to use. Defaults to "Untitled".
to_ee (bool, optional): Whether to convert the GeoJSON to ee.FeatureCollection. Defaults to False.
bbox (tuple | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.
mask (dict | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.
rows (int or slice, optional): Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding to use to read the file. Defaults to "utf-8".
"""
if not filename.startswith("http"):
filename = os.path.abspath(filename)
else:
filename = github_raw_url(filename)
if to_ee:
fc = vector_to_ee(
filename,
bbox=bbox,
mask=mask,
rows=rows,
geodesic=True,
**kwargs,
)
self.addLayer(fc, {}, layer_name)
else:
ext = os.path.splitext(filename)[1].lower()
if ext == ".shp":
self.add_shapefile(
filename,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
elif ext in [".json", ".geojson"]:
self.add_geojson(
filename,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
else:
geojson = vector_to_geojson(
filename,
bbox=bbox,
mask=mask,
rows=rows,
epsg="4326",
**kwargs,
)
self.add_geojson(
geojson,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
def add_osm(
self,
query,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
which_result=None,
by_osmid=False,
buffer_dist=None,
to_ee=False,
geodesic=True,
):
"""Adds OSM data to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
to_ee (bool, optional): Whether to convert the csv to an ee.FeatureCollection.
geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected.
"""
gdf = osm_to_gdf(
query, which_result=which_result, by_osmid=by_osmid, buffer_dist=buffer_dist
)
geojson = gdf.__geo_interface__
if to_ee:
fc = geojson_to_ee(geojson, geodesic=geodesic)
self.addLayer(fc, {}, layer_name)
self.zoomToObject(fc)
else:
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
bounds = gdf.bounds.iloc[0]
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def add_osm_from_geocode(
self,
query,
which_result=None,
by_osmid=False,
buffer_dist=None,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM data of place(s) by name or ID to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_geocode
gdf = osm_gdf_from_geocode(
query, which_result=which_result, by_osmid=by_osmid, buffer_dist=buffer_dist
)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_address(
self,
address,
tags,
dist=1000,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within some distance N, S, E, W of address to the map.
Args:
address (str): The address to geocode and use as the central point around which to get the geometries.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
dist (int, optional): Distance in meters. Defaults to 1000.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_address
gdf = osm_gdf_from_address(address, tags, dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_place(
self,
query,
tags,
which_result=None,
buffer_dist=None,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within boundaries of geocodable place(s) to the map.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_place
gdf = osm_gdf_from_place(query, tags, which_result, buffer_dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_point(
self,
center_point,
tags,
dist=1000,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within some distance N, S, E, W of a point to the map.
Args:
center_point (tuple): The (lat, lng) center point around which to get the geometries.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
dist (int, optional): Distance in meters. Defaults to 1000.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_point
gdf = osm_gdf_from_point(center_point, tags, dist)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_polygon(
self,
polygon,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within boundaries of a (multi)polygon to the map.
Args:
polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_polygon
gdf = osm_gdf_from_polygon(polygon, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_bbox(
self,
north,
south,
east,
west,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within a N, S, E, W bounding box to the map.
Args:
north (float): Northern latitude of bounding box.
south (float): Southern latitude of bounding box.
east (float): Eastern longitude of bounding box.
west (float): Western longitude of bounding box.
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_bbox
gdf = osm_gdf_from_bbox(north, south, east, west, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_osm_from_view(
self,
tags,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
):
"""Adds OSM entities within the current map view to the map.
Args:
tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
"""
from .osm import osm_gdf_from_bbox
bounds = self.bounds
if len(bounds) == 0:
bounds = (
(40.74824858675827, -73.98933637940563),
(40.75068694343106, -73.98364473187601),
)
north, south, east, west = (
bounds[1][0],
bounds[0][0],
bounds[1][1],
bounds[0][1],
)
gdf = osm_gdf_from_bbox(north, south, east, west, tags)
geojson = gdf.__geo_interface__
self.add_geojson(
geojson,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
fill_colors=fill_colors,
info_mode=info_mode,
)
self.zoom_to_gdf(gdf)
def add_gdf(
self,
gdf,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
zoom_to_layer=True,
encoding="utf-8",
):
"""Adds a GeoDataFrame to the map.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
zoom_to_layer (bool, optional): Whether to zoom to the layer.
encoding (str, optional): The encoding of the GeoDataFrame. Defaults to "utf-8".
"""
data = gdf_to_geojson(gdf, epsg="4326")
self.add_geojson(
data,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
encoding,
)
if zoom_to_layer:
import numpy as np
bounds = gdf.to_crs(epsg="4326").bounds
west = np.min(bounds["minx"])
south = np.min(bounds["miny"])
east = np.max(bounds["maxx"])
north = np.max(bounds["maxy"])
self.fit_bounds([[south, east], [north, west]])
def add_gdf_from_postgis(
self,
sql,
con,
layer_name="Untitled",
style={},
hover_style={},
style_callback=None,
fill_colors=["black"],
info_mode="on_hover",
zoom_to_layer=True,
**kwargs,
):
"""Reads a PostGIS database and returns data as a GeoDataFrame to be added to the map.
Args:
sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database.
con (sqlalchemy.engine.Engine): Active connection to the database to query.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to {}.
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
fill_colors (list, optional): The random colors to use for filling polygons. Defaults to ["black"].
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
zoom_to_layer (bool, optional): Whether to zoom to the layer.
"""
gdf = read_postgis(sql, con, **kwargs)
gdf = gdf.to_crs("epsg:4326")
self.add_gdf(
gdf,
layer_name,
style,
hover_style,
style_callback,
fill_colors,
info_mode,
zoom_to_layer,
)
def add_time_slider(
self,
ee_object,
vis_params={},
region=None,
layer_name="Time series",
labels=None,
time_interval=1,
position="bottomright",
slider_length="150px",
date_format="YYYY-MM-dd",
opacity=1.0,
**kwargs,
):
"""Adds a time slider to the map.
Args:
ee_object (ee.Image | ee.ImageCollection): The Image or ImageCollection to visualize.
vis_params (dict, optional): Visualization parameters to use for visualizing image. Defaults to {}.
region (ee.Geometry | ee.FeatureCollection): The region to visualize.
layer_name (str, optional): The layer name to be used. Defaults to "Time series".
labels (list, optional): The list of labels to be used for the time series. Defaults to None.
time_interval (int, optional): Time interval in seconds. Defaults to 1.
position (str, optional): Position to place the time slider, can be any of ['topleft', 'topright', 'bottomleft', 'bottomright']. Defaults to "bottomright".
slider_length (str, optional): Length of the time slider. Defaults to "150px".
date_format (str, optional): The date format to use. Defaults to 'YYYY-MM-dd'.
opacity (float, optional): The opacity of layers. Defaults to 1.0.
Raises:
TypeError: If the ee_object is not ee.Image | ee.ImageCollection.
"""
import threading
if isinstance(ee_object, ee.Image):
if region is not None:
if isinstance(region, ee.Geometry):
ee_object = ee_object.clip(region)
elif isinstance(region, ee.FeatureCollection):
ee_object = ee_object.clipToCollection(region)
if layer_name not in self.ee_layers:
self.addLayer(ee_object, {}, layer_name, False, opacity)
band_names = ee_object.bandNames()
ee_object = ee.ImageCollection(
ee_object.bandNames().map(lambda b: ee_object.select([b]))
)
if labels is not None:
if len(labels) != int(ee_object.size().getInfo()):
raise ValueError(
"The length of labels must be equal to the number of bands in the image."
)
else:
labels = band_names.getInfo()
elif isinstance(ee_object, ee.ImageCollection):
if region is not None:
if isinstance(region, ee.Geometry):
ee_object = ee_object.map(lambda img: img.clip(region))
elif isinstance(region, ee.FeatureCollection):
ee_object = ee_object.map(lambda img: img.clipToCollection(region))
if labels is not None:
if len(labels) != int(ee_object.size().getInfo()):
raise ValueError(
"The length of labels must be equal to the number of images in the ImageCollection."
)
else:
labels = (
ee_object.aggregate_array("system:time_start")
.map(lambda d: ee.Date(d).format(date_format))
.getInfo()
)
else:
raise TypeError("The ee_object must be an ee.Image or ee.ImageCollection")
# if labels is not None:
# size = len(labels)
# else:
# size = ee_object.size().getInfo()
# labels = [str(i) for i in range(1, size + 1)]
first = ee.Image(ee_object.first())
if layer_name not in self.ee_layers:
self.addLayer(ee_object.toBands(), {}, layer_name, False, opacity)
self.addLayer(first, vis_params, "Image X", True, opacity)
slider = widgets.IntSlider(
min=1,
max=len(labels),
readout=False,
continuous_update=False,
layout=widgets.Layout(width=slider_length),
)
label = widgets.Label(
value=labels[0], layout=widgets.Layout(padding="0px 5px 0px 5px")
)
play_btn = widgets.Button(
icon="play",
tooltip="Play the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
pause_btn = widgets.Button(
icon="pause",
tooltip="Pause the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
close_btn = widgets.Button(
icon="times",
tooltip="Close the time slider",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
play_chk = widgets.Checkbox(value=False)
slider_widget = widgets.HBox([slider, label, play_btn, pause_btn, close_btn])
def play_click(b):
import time
play_chk.value = True
def work(slider):
while play_chk.value:
if slider.value < len(labels):
slider.value += 1
else:
slider.value = 1
time.sleep(time_interval)
thread = threading.Thread(target=work, args=(slider,))
thread.start()
def pause_click(b):
play_chk.value = False
play_btn.on_click(play_click)
pause_btn.on_click(pause_click)
def slider_changed(change):
self.default_style = {"cursor": "wait"}
index = slider.value - 1
label.value = labels[index]
image = ee.Image(ee_object.toList(ee_object.size()).get(index))
if layer_name not in self.ee_layers:
self.addLayer(ee_object.toBands(), {}, layer_name, False, opacity)
self.addLayer(image, vis_params, "Image X", True, opacity)
self.default_style = {"cursor": "default"}
slider.observe(slider_changed, "value")
def close_click(b):
play_chk.value = False
self.toolbar_reset()
self.remove_ee_layer("Image X")
self.remove_ee_layer(layer_name)
if self.slider_ctrl is not None and self.slider_ctrl in self.controls:
self.remove_control(self.slider_ctrl)
slider_widget.close()
close_btn.on_click(close_click)
slider_ctrl = ipyleaflet.WidgetControl(widget=slider_widget, position=position)
self.add(slider_ctrl)
self.slider_ctrl = slider_ctrl
def add_xy_data(
self,
in_csv,
x="longitude",
y="latitude",
label=None,
layer_name="Marker cluster",
to_ee=False,
):
"""Adds points from a CSV file containing lat/lon information and display data on the map.
Args:
in_csv (str): The file path to the input CSV file.
x (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
y (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
label (str, optional): The name of the column containing label information to used for marker popup. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to "Marker cluster".
to_ee (bool, optional): Whether to convert the csv to an ee.FeatureCollection.
Raises:
FileNotFoundError: The specified input csv does not exist.
ValueError: The specified x column does not exist.
ValueError: The specified y column does not exist.
ValueError: The specified label column does not exist.
"""
import pandas as pd
if not in_csv.startswith("http") and (not os.path.exists(in_csv)):
raise FileNotFoundError("The specified input csv does not exist.")
df = pd.read_csv(in_csv)
col_names = df.columns.values.tolist()
if x not in col_names:
raise ValueError(f"x must be one of the following: {', '.join(col_names)}")
if y not in col_names:
raise ValueError(f"y must be one of the following: {', '.join(col_names)}")
if label is not None and (label not in col_names):
raise ValueError(
f"label must be one of the following: {', '.join(col_names)}"
)
self.default_style = {"cursor": "wait"}
if to_ee:
fc = csv_to_ee(in_csv, latitude=y, longitude=x)
self.addLayer(fc, {}, layer_name)
else:
points = list(zip(df[y], df[x]))
if label is not None:
labels = df[label]
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
)
for index, point in enumerate(points)
]
else:
markers = [
ipyleaflet.Marker(location=point, draggable=False)
for point in points
]
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
self.default_style = {"cursor": "default"}
def add_points_from_xy(
self,
data,
x="longitude",
y="latitude",
popup=None,
layer_name="Marker Cluster",
color_column=None,
marker_colors=None,
icon_colors=["white"],
icon_names=["info"],
spin=False,
add_legend=True,
**kwargs,
):
"""Adds a marker cluster to the map.
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
popup (list, optional): A list of column names to be used as the popup. Defaults to None.
layer_name (str, optional): The name of the layer. Defaults to "Marker Cluster".
color_column (str, optional): The column name for the color values. Defaults to None.
marker_colors (list, optional): A list of colors to be used for the markers. Defaults to None.
icon_colors (list, optional): A list of colors to be used for the icons. Defaults to ['white'].
icon_names (list, optional): A list of names to be used for the icons. More icons can be found at https://fontawesome.com/v4/icons. Defaults to ['info'].
spin (bool, optional): If True, the icon will spin. Defaults to False.
add_legend (bool, optional): If True, a legend will be added to the map. Defaults to True.
"""
import pandas as pd
data = github_raw_url(data)
color_options = [
"red",
"blue",
"green",
"purple",
"orange",
"darkred",
"lightred",
"beige",
"darkblue",
"darkgreen",
"cadetblue",
"darkpurple",
"white",
"pink",
"lightblue",
"lightgreen",
"gray",
"black",
"lightgray",
]
if isinstance(data, pd.DataFrame):
df = data
elif not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data)
df = points_from_xy(df, x, y)
col_names = df.columns.values.tolist()
if color_column is not None and color_column not in col_names:
raise ValueError(
f"The color column {color_column} does not exist in the dataframe."
)
if color_column is not None:
items = list(set(df[color_column]))
else:
items = None
if color_column is not None and marker_colors is None:
if len(items) > len(color_options):
raise ValueError(
f"The number of unique values in the color column {color_column} is greater than the number of available colors."
)
else:
marker_colors = color_options[: len(items)]
elif color_column is not None and marker_colors is not None:
if len(items) != len(marker_colors):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if items is not None:
if len(icon_colors) == 1:
icon_colors = icon_colors * len(items)
elif len(items) != len(icon_colors):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if len(icon_names) == 1:
icon_names = icon_names * len(items)
elif len(items) != len(icon_names):
raise ValueError(
f"The number of unique values in the color column {color_column} is not equal to the number of available colors."
)
if "geometry" in col_names:
col_names.remove("geometry")
if popup is not None:
if isinstance(popup, str) and (popup not in col_names):
raise ValueError(
f"popup must be one of the following: {', '.join(col_names)}"
)
elif isinstance(popup, list) and (
not all(item in col_names for item in popup)
):
raise ValueError(
f"All popup items must be select from: {', '.join(col_names)}"
)
else:
popup = col_names
df["x"] = df.geometry.x
df["y"] = df.geometry.y
points = list(zip(df["y"], df["x"]))
if popup is not None:
if isinstance(popup, str):
labels = df[popup]
markers = []
for index, point in enumerate(points):
if items is not None:
marker_color = marker_colors[
items.index(df[color_column][index])
]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
icon=marker_icon,
)
markers.append(marker)
elif isinstance(popup, list):
labels = []
for i in range(len(points)):
label = ""
for item in popup:
label = (
label
+ "<b>"
+ str(item)
+ "</b>"
+ ": "
+ str(df[item][i])
+ "<br>"
)
labels.append(label)
df["popup"] = labels
markers = []
for index, point in enumerate(points):
if items is not None:
marker_color = marker_colors[
items.index(df[color_column][index])
]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(labels[index]),
icon=marker_icon,
)
markers.append(marker)
else:
markers = []
for point in points:
if items is not None:
marker_color = marker_colors[items.index(df[color_column][index])]
icon_name = icon_names[items.index(df[color_column][index])]
icon_color = icon_colors[items.index(df[color_column][index])]
marker_icon = ipyleaflet.AwesomeIcon(
name=icon_name,
marker_color=marker_color,
icon_color=icon_color,
spin=spin,
)
else:
marker_icon = None
marker = ipyleaflet.Marker(
location=point, draggable=False, icon=marker_icon
)
markers.append(marker)
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
if items is not None and add_legend:
marker_colors = [check_color(c) for c in marker_colors]
self.add_legend(
title=color_column.title(), colors=marker_colors, keys=items
)
self.default_style = {"cursor": "default"}
def add_circle_markers_from_xy(
self,
data,
x="longitude",
y="latitude",
radius=10,
popup=None,
**kwargs,
):
"""Adds a marker cluster to the map. For a list of options, see https://ipyleaflet.readthedocs.io/en/latest/api_reference/circle_marker.html
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
radius (int, optional): The radius of the circle. Defaults to 10.
popup (list, optional): A list of column names to be used as the popup. Defaults to None.
"""
import pandas as pd
data = github_raw_url(data)
if isinstance(data, pd.DataFrame):
df = data
elif not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data)
col_names = df.columns.values.tolist()
if popup is None:
popup = col_names
if not isinstance(popup, list):
popup = [popup]
if x not in col_names:
raise ValueError(f"x must be one of the following: {', '.join(col_names)}")
if y not in col_names:
raise ValueError(f"y must be one of the following: {', '.join(col_names)}")
for row in df.itertuples():
html = ""
for p in popup:
html = html + "<b>" + p + "</b>" + ": " + str(getattr(row, p)) + "<br>"
popup_html = widgets.HTML(html)
marker = ipyleaflet.CircleMarker(
location=[getattr(row, y), getattr(row, x)],
radius=radius,
popup=popup_html,
**kwargs,
)
super().add(marker)
def add_planet_by_month(
self, year=2016, month=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
"""Adds a Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
"""
layer = planet_tile_by_month(year, month, name, api_key, token_name)
self.add(layer)
def add_planet_by_quarter(
self, year=2016, quarter=1, name=None, api_key=None, token_name="PLANET_API_KEY"
):
"""Adds a Planet global mosaic by quarter to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
"""
layer = planet_tile_by_quarter(year, quarter, name, api_key, token_name)
self.add(layer)
def to_streamlit(self, width=None, height=600, scrolling=False, **kwargs):
"""Renders map figure in a Streamlit app.
Args:
width (int, optional): Width of the map. Defaults to None.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): If True, show a scrollbar when the content is larger than the iframe. Otherwise, do not show a scrollbar. Defaults to False.
Returns:
streamlit.components: components.html object.
"""
try:
import streamlit.components.v1 as components
# if responsive:
# make_map_responsive = """
# <style>
# [title~="st.iframe"] { width: 100%}
# </style>
# """
# st.markdown(make_map_responsive, unsafe_allow_html=True)
return components.html(
self.to_html(), width=width, height=height, scrolling=scrolling
)
except Exception as e:
raise Exception(e)
def add_point_layer(
self, filename, popup=None, layer_name="Marker Cluster", **kwargs
):
"""Adds a point layer to the map with a popup attribute.
Args:
filename (str): str, http url, path object or file-like object. Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO)
popup (str | list, optional): Column name(s) to be used for popup. Defaults to None.
layer_name (str, optional): A layer name to use. Defaults to "Marker Cluster".
Raises:
ValueError: If the specified column name does not exist.
ValueError: If the specified column names do not exist.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
self.default_style = {"cursor": "wait"}
if not filename.startswith("http"):
filename = os.path.abspath(filename)
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(filename, driver="KML", **kwargs)
else:
gdf = gpd.read_file(filename, **kwargs)
df = gdf.to_crs(epsg="4326")
col_names = df.columns.values.tolist()
if popup is not None:
if isinstance(popup, str) and (popup not in col_names):
raise ValueError(
f"popup must be one of the following: {', '.join(col_names)}"
)
elif isinstance(popup, list) and (
not all(item in col_names for item in popup)
):
raise ValueError(
f"All popup items must be select from: {', '.join(col_names)}"
)
df["x"] = df.geometry.x
df["y"] = df.geometry.y
points = list(zip(df["y"], df["x"]))
if popup is not None:
if isinstance(popup, str):
labels = df[popup]
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(str(labels[index])),
)
for index, point in enumerate(points)
]
elif isinstance(popup, list):
labels = []
for i in range(len(points)):
label = ""
for item in popup:
label = label + str(item) + ": " + str(df[item][i]) + "<br>"
labels.append(label)
df["popup"] = labels
markers = [
ipyleaflet.Marker(
location=point,
draggable=False,
popup=widgets.HTML(labels[index]),
)
for index, point in enumerate(points)
]
else:
markers = [
ipyleaflet.Marker(location=point, draggable=False) for point in points
]
marker_cluster = ipyleaflet.MarkerCluster(markers=markers, name=layer_name)
self.add(marker_cluster)
self.default_style = {"cursor": "default"}
def add_census_data(self, wms, layer, census_dict=None, **kwargs):
"""Adds a census data layer to the map.
Args:
wms (str): The wms to use. For example, "Current", "ACS 2021", "Census 2020". See the complete list at https://tigerweb.geo.census.gov/tigerwebmain/TIGERweb_wms.html
layer (str): The layer name to add to the map.
census_dict (dict, optional): A dictionary containing census data. Defaults to None. It can be obtained from the get_census_dict() function.
"""
try:
if census_dict is None:
census_dict = get_census_dict()
if wms not in census_dict.keys():
raise ValueError(
f"The provided WMS is invalid. It must be one of {census_dict.keys()}"
)
layers = census_dict[wms]["layers"]
if layer not in layers:
raise ValueError(
f"The layer name is not valid. It must be one of {layers}"
)
url = census_dict[wms]["url"]
if "name" not in kwargs:
kwargs["name"] = layer
if "attribution" not in kwargs:
kwargs["attribution"] = "U.S. Census Bureau"
if "format" not in kwargs:
kwargs["format"] = "image/png"
if "transparent" not in kwargs:
kwargs["transparent"] = True
self.add_wms_layer(url, layer, **kwargs)
except Exception as e:
raise Exception(e)
def add_xyz_service(self, provider, **kwargs):
"""Add a XYZ tile layer to the map.
Args:
provider (str): A tile layer name starts with xyz or qms. For example, xyz.OpenTopoMap,
Raises:
ValueError: The provider is not valid. It must start with xyz or qms.
"""
import xyzservices.providers as xyz
from xyzservices import TileProvider
if provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
url = xyz_provider.build_url()
attribution = xyz_provider.attribution
if attribution.strip() == "":
attribution = " "
self.add_tile_layer(url, name, attribution)
elif provider.startswith("qms"):
name = provider[4:]
qms_provider = TileProvider.from_qms(name)
url = qms_provider.build_url()
attribution = qms_provider.attribution
if attribution.strip() == "":
attribution = " "
self.add_tile_layer(url, name, attribution)
else:
raise ValueError(
f"The provider {provider} is not valid. It must start with xyz or qms."
)
def add_heatmap(
self,
data,
latitude="latitude",
longitude="longitude",
value="value",
name="Heat map",
radius=25,
**kwargs,
):
"""Adds a heat map to the map. Reference: https://ipyleaflet.readthedocs.io/en/latest/api_reference/heatmap.html
Args:
data (str | list | pd.DataFrame): File path or HTTP URL to the input file or a list of data points in the format of [[x1, y1, z1], [x2, y2, z2]]. For example, https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/world_cities.csv
latitude (str, optional): The column name of latitude. Defaults to "latitude".
longitude (str, optional): The column name of longitude. Defaults to "longitude".
value (str, optional): The column name of values. Defaults to "value".
name (str, optional): Layer name to use. Defaults to "Heat map".
radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25.
Raises:
ValueError: If data is not a list.
"""
import pandas as pd
from ipyleaflet import Heatmap
try:
if isinstance(data, str):
df = pd.read_csv(data)
data = df[[latitude, longitude, value]].values.tolist()
elif isinstance(data, pd.DataFrame):
data = data[[latitude, longitude, value]].values.tolist()
elif isinstance(data, list):
pass
else:
raise ValueError("data must be a list, a DataFrame, or a file path.")
heatmap = Heatmap(locations=data, radius=radius, name=name, **kwargs)
self.add(heatmap)
except Exception as e:
raise Exception(e)
def add_labels(
self,
data,
column,
font_size="12pt",
font_color="black",
font_family="arial",
font_weight="normal",
x="longitude",
y="latitude",
draggable=True,
layer_name="Labels",
**kwargs,
):
"""Adds a label layer to the map. Reference: https://ipyleaflet.readthedocs.io/en/latest/api_reference/divicon.html
Args:
data (pd.DataFrame | ee.FeatureCollection): The input data to label.
column (str): The column name of the data to label.
font_size (str, optional): The font size of the labels. Defaults to "12pt".
font_color (str, optional): The font color of the labels. Defaults to "black".
font_family (str, optional): The font family of the labels. Defaults to "arial".
font_weight (str, optional): The font weight of the labels, can be normal, bold. Defaults to "normal".
x (str, optional): The column name of the longitude. Defaults to "longitude".
y (str, optional): The column name of the latitude. Defaults to "latitude".
draggable (bool, optional): Whether the labels are draggable. Defaults to True.
layer_name (str, optional): Layer name to use. Defaults to "Labels".
"""
import warnings
import pandas as pd
warnings.filterwarnings("ignore")
if isinstance(data, ee.FeatureCollection):
centroids = vector_centroids(data)
df = ee_to_df(centroids)
elif isinstance(data, pd.DataFrame):
df = data
elif isinstance(data, str):
ext = os.path.splitext(data)[1]
if ext == ".csv":
df = pd.read_csv(data)
elif ext in [".geojson", ".json", ".shp", ".gpkg"]:
try:
import geopandas as gpd
df = gpd.read_file(data)
df[x] = df.centroid.x
df[y] = df.centroid.y
except Exception as _:
print("geopandas is required to read geojson.")
return
else:
raise ValueError("data must be a DataFrame or an ee.FeatureCollection.")
if column not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
if x not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
if y not in df.columns:
raise ValueError(f"column must be one of {', '.join(df.columns)}.")
try:
size = int(font_size.replace("pt", ""))
except:
raise ValueError("font_size must be something like '10pt'")
labels = []
for index in df.index:
html = f'<div style="font-size: {font_size};color:{font_color};font-family:{font_family};font-weight: {font_weight}">{df[column][index]}</div>'
marker = ipyleaflet.Marker(
location=[df[y][index], df[x][index]],
icon=ipyleaflet.DivIcon(
icon_size=(1, 1),
icon_anchor=(size, size),
html=html,
**kwargs,
),
draggable=draggable,
)
labels.append(marker)
layer_group = ipyleaflet.LayerGroup(layers=labels, name=layer_name)
self.add(layer_group)
self.labels = layer_group
def remove_labels(self):
"""Removes all labels from the map."""
if hasattr(self, "labels"):
self.remove_layer(self.labels)
delattr(self, "labels")
def add_netcdf(
self,
filename,
variables=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name="NetCDF layer",
shift_lon=True,
lat="lat",
lon="lon",
**kwargs,
):
"""Generate an ipyleaflet/folium TileLayer from a netCDF file.
If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer),
try adding to following two lines to the beginning of the notebook if the raster does not render properly.
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}'
Args:
filename (str): File path or HTTP URL to the netCDF file.
variables (int, optional): The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted.
port (str, optional): The port to use for the server. Defaults to "default".
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to "netCDF layer".
shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True.
lat (str, optional): Name of the latitude variable. Defaults to 'lat'.
lon (str, optional): Name of the longitude variable. Defaults to 'lon'.
"""
tif, vars = netcdf_to_tif(
filename, shift_lon=shift_lon, lat=lat, lon=lon, return_vars=True
)
if variables is None:
if len(vars) >= 3:
band_idx = [1, 2, 3]
else:
band_idx = [1]
else:
if not set(variables).issubset(set(vars)):
raise ValueError(f"The variables must be a subset of {vars}.")
else:
band_idx = [vars.index(v) + 1 for v in variables]
self.add_raster(
tif,
band=band_idx,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
**kwargs,
)
def add_velocity(
self,
data,
zonal_speed,
meridional_speed,
latitude_dimension="lat",
longitude_dimension="lon",
level_dimension="lev",
level_index=0,
time_index=0,
velocity_scale=0.01,
max_velocity=20,
display_options={},
name="Velocity",
):
"""Add a velocity layer to the map.
Args:
data (str | xr.Dataset): The data to use for the velocity layer. It can be a file path to a NetCDF file or an xarray Dataset.
zonal_speed (str): Name of the zonal speed in the dataset. See https://en.wikipedia.org/wiki/Zonal_and_meridional_flow.
meridional_speed (str): Name of the meridional speed in the dataset. See https://en.wikipedia.org/wiki/Zonal_and_meridional_flow.
latitude_dimension (str, optional): Name of the latitude dimension in the dataset. Defaults to 'lat'.
longitude_dimension (str, optional): Name of the longitude dimension in the dataset. Defaults to 'lon'.
level_dimension (str, optional): Name of the level dimension in the dataset. Defaults to 'lev'.
level_index (int, optional): The index of the level dimension to display. Defaults to 0.
time_index (int, optional): The index of the time dimension to display. Defaults to 0.
velocity_scale (float, optional): The scale of the velocity. Defaults to 0.01.
max_velocity (int, optional): The maximum velocity to display. Defaults to 20.
display_options (dict, optional): The display options for the velocity layer. Defaults to {}. See https://bit.ly/3uf8t6w.
name (str, optional): Layer name to use . Defaults to 'Velocity'.
Raises:
ImportError: If the xarray package is not installed.
ValueError: If the data is not a NetCDF file or an xarray Dataset.
"""
try:
import xarray as xr
from ipyleaflet.velocity import Velocity
except ImportError:
raise ImportError(
"The xarray package is required to add a velocity layer. "
"Please install it with `pip install xarray`."
)
if isinstance(data, str):
if data.startswith("http"):
data = download_file(data)
ds = xr.open_dataset(data)
elif isinstance(data, xr.Dataset):
ds = data
else:
raise ValueError("The data must be a file path or xarray dataset.")
coords = list(ds.coords.keys())
# Rasterio does not handle time or levels. So we must drop them
if "time" in coords:
ds = ds.isel(time=time_index, drop=True)
params = {level_dimension: level_index}
if level_dimension in coords:
ds = ds.isel(drop=True, **params)
wind = Velocity(
data=ds,
zonal_speed=zonal_speed,
meridional_speed=meridional_speed,
latitude_dimension=latitude_dimension,
longitude_dimension=longitude_dimension,
velocity_scale=velocity_scale,
max_velocity=max_velocity,
display_options=display_options,
name=name,
)
self.add(wind)
def add_data(
self,
data,
column,
colors=None,
labels=None,
cmap=None,
scheme="Quantiles",
k=5,
add_legend=True,
legend_title=None,
legend_kwds=None,
classification_kwds=None,
layer_name="Untitled",
style=None,
hover_style=None,
style_callback=None,
info_mode="on_hover",
encoding="utf-8",
**kwargs,
):
"""Add vector data to the map with a variety of classification schemes.
Args:
data (str | pd.DataFrame | gpd.GeoDataFrame): The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe.
column (str): The column to classify.
cmap (str, optional): The name of a colormap recognized by matplotlib. Defaults to None.
colors (list, optional): A list of colors to use for the classification. Defaults to None.
labels (list, optional): A list of labels to use for the legend. Defaults to None.
scheme (str, optional): Name of a choropleth classification scheme (requires mapclassify).
Name of a choropleth classification scheme (requires mapclassify).
A mapclassify.MapClassifier object will be used
under the hood. Supported are all schemes provided by mapclassify (e.g.
'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled',
'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced',
'JenksCaspallSampled', 'MaxP', 'MaximumBreaks',
'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean',
'UserDefined'). Arguments can be passed in classification_kwds.
k (int, optional): Number of classes (ignored if scheme is None or if column is categorical). Default to 5.
legend_kwds (dict, optional): Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or `matplotlib.pyplot.colorbar`. Defaults to None.
Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or
Additional accepted keywords when `scheme` is specified:
fmt : string
A formatting specification for the bin edges of the classes in the
legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``.
labels : list-like
A list of legend labels to override the auto-generated labblels.
Needs to have the same number of elements as the number of
classes (`k`).
interval : boolean (default False)
An option to control brackets from mapclassify legend.
If True, open/closed interval brackets are shown in the legend.
classification_kwds (dict, optional): Keyword arguments to pass to mapclassify. Defaults to None.
layer_name (str, optional): The layer name to be used.. Defaults to "Untitled".
style (dict, optional): A dictionary specifying the style to be used. Defaults to None.
style is a dictionary of the following form:
style = {
"stroke": False,
"color": "#ff0000",
"weight": 1,
"opacity": 1,
"fill": True,
"fillColor": "#ffffff",
"fillOpacity": 1.0,
"dashArray": "9"
"clickable": True,
}
hover_style (dict, optional): Hover style dictionary. Defaults to {}.
hover_style is a dictionary of the following form:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
style_callback (function, optional): Styling function that is called for each feature, and should return the feature style. This styling function takes the feature as argument. Defaults to None.
style_callback is a function that takes the feature as argument and should return a dictionary of the following form:
style_callback = lambda feat: {"fillColor": feat["properties"]["color"]}
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
encoding (str, optional): The encoding of the GeoJSON file. Defaults to "utf-8".
"""
gdf, legend_dict = classify(
data=data,
column=column,
cmap=cmap,
colors=colors,
labels=labels,
scheme=scheme,
k=k,
legend_kwds=legend_kwds,
classification_kwds=classification_kwds,
)
if legend_title is None:
legend_title = column
if style is None:
style = {
# "stroke": False,
# "color": "#ff0000",
"weight": 1,
"opacity": 1,
# "fill": True,
# "fillColor": "#ffffff",
"fillOpacity": 1.0,
# "dashArray": "9"
# "clickable": True,
}
if colors is not None:
style["color"] = "#000000"
if hover_style is None:
hover_style = {"weight": style["weight"] + 1, "fillOpacity": 0.5}
if style_callback is None:
style_callback = lambda feat: {"fillColor": feat["properties"]["color"]}
self.add_gdf(
gdf,
layer_name=layer_name,
style=style,
hover_style=hover_style,
style_callback=style_callback,
info_mode=info_mode,
encoding=encoding,
**kwargs,
)
if add_legend:
self.add_legend(title=legend_title, legend_dict=legend_dict)
def user_roi_coords(self, decimals=4):
"""Return the bounding box of the ROI as a list of coordinates.
Args:
decimals (int, optional): Number of decimals to round the coordinates to. Defaults to 4.
"""
return bbox_coords(self.user_roi, decimals=decimals)
def add_widget(
self,
content,
position="bottomright",
add_header=False,
opened=True,
show_close_button=True,
widget_icon="gear",
close_button_icon="times",
widget_args={},
close_button_args={},
display_widget=None,
**kwargs,
):
"""Add a widget (e.g., text, HTML, figure) to the map.
Args:
content (str | ipywidgets.Widget | object): The widget to add.
position (str, optional): The position of the widget. Defaults to "bottomright".
add_header (bool, optional): Whether to add a header with close buttons to the widget. Defaults to False.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
widget_icon (str, optional): The icon name for the toolbar button. Defaults to 'gear'.
close_button_icon (str, optional): The icon name for the close button. Defaults to "times".
widget_args (dict, optional): Additional arguments to pass to the toolbar button. Defaults to {}.
close_button_args (dict, optional): Additional arguments to pass to the close button. Defaults to {}.
display_widget (ipywidgets.Widget, optional): The widget to be displayed when the toolbar is clicked.
**kwargs: Additional arguments to pass to the HTML or Output widgets
"""
allowed_positions = ["topleft", "topright", "bottomleft", "bottomright"]
if position not in allowed_positions:
raise Exception(f"position must be one of {allowed_positions}")
if "layout" not in kwargs:
kwargs["layout"] = widgets.Layout(padding="0px 4px 0px 4px")
try:
if add_header:
if isinstance(content, str):
widget = widgets.HTML(value=content, **kwargs)
else:
widget = content
widget_template(
widget,
opened,
show_close_button,
widget_icon,
close_button_icon,
widget_args,
close_button_args,
display_widget,
self,
position,
)
else:
if isinstance(content, str):
widget = widgets.HTML(value=content, **kwargs)
else:
widget = widgets.Output(**kwargs)
with widget:
display(content)
control = ipyleaflet.WidgetControl(widget=widget, position=position)
self.add(control)
except Exception as e:
raise Exception(f"Error adding widget: {e}")
def add_image(self, image, position="bottomright", **kwargs):
"""Add an image to the map.
Args:
image (str | ipywidgets.Image): The image to add.
position (str, optional): The position of the image, can be one of "topleft",
"topright", "bottomleft", "bottomright". Defaults to "bottomright".
"""
if isinstance(image, str):
if image.startswith("http"):
image = widgets.Image(value=requests.get(image).content, **kwargs)
elif os.path.exists(image):
with open(image, "rb") as f:
image = widgets.Image(value=f.read(), **kwargs)
elif isinstance(image, widgets.Image):
pass
else:
raise Exception("Invalid image")
self.add_widget(image, position=position, **kwargs)
def add_html(self, html, position="bottomright", **kwargs):
"""Add HTML to the map.
Args:
html (str): The HTML to add.
position (str, optional): The position of the HTML, can be one of "topleft",
"topright", "bottomleft", "bottomright". Defaults to "bottomright".
"""
self.add_widget(html, position=position, **kwargs)
def add_text(
self,
text,
fontsize=20,
fontcolor="black",
bold=False,
padding="5px",
background=True,
bg_color="white",
border_radius="5px",
position="bottomright",
**kwargs,
):
"""Add text to the map.
Args:
text (str): The text to add.
fontsize (int, optional): The font size. Defaults to 20.
fontcolor (str, optional): The font color. Defaults to "black".
bold (bool, optional): Whether to use bold font. Defaults to False.
padding (str, optional): The padding. Defaults to "5px".
background (bool, optional): Whether to use background. Defaults to True.
bg_color (str, optional): The background color. Defaults to "white".
border_radius (str, optional): The border radius. Defaults to "5px".
position (str, optional): The position of the widget. Defaults to "bottomright".
"""
if background:
text = f"""<div style="font-size: {fontsize}px; color: {fontcolor}; font-weight: {'bold' if bold else 'normal'};
padding: {padding}; background-color: {bg_color};
border-radius: {border_radius};">{text}</div>"""
else:
text = f"""<div style="font-size: {fontsize}px; color: {fontcolor}; font-weight: {'bold' if bold else 'normal'};
padding: {padding};">{text}</div>"""
self.add_html(text, position=position, **kwargs)
def to_gradio(self, width="100%", height="500px", **kwargs):
"""Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as
attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190
Args:
width (str, optional): The width of the map. Defaults to '100%'.
height (str, optional): The height of the map. Defaults to '500px'.
Returns:
str: The HTML string to use in Gradio.
"""
print(
"The ipyleaflet plotting backend does not support this function. Please use the folium backend instead."
)
def add_search_control(
self,
marker=None,
url=None,
zoom=5,
property_name="display_name",
position="topleft",
):
"""Add a search control to the map.
Args:
marker (ipyleaflet.Marker, optional): The marker to use. Defaults to None.
url (str, optional): The URL to use for the search. Defaults to None.
zoom (int, optional): The zoom level to use. Defaults to 5.
property_name (str, optional): The property name to use. Defaults to "display_name".
position (str, optional): The position of the widget. Defaults to "topleft".
"""
if marker is None:
marker = ipyleaflet.Marker(
icon=ipyleaflet.AwesomeIcon(
name="check", marker_color="green", icon_color="darkgreen"
)
)
if url is None:
url = "https://nominatim.openstreetmap.org/search?format=json&q={s}"
search = ipyleaflet.SearchControl(
position=position,
url=url,
zoom=zoom,
property_name=property_name,
marker=marker,
)
self.add(search)
def layer_to_image(
self,
layer_name: str,
output: Optional[str] = None,
crs: str = "EPSG:3857",
scale: Optional[int] = None,
region: Optional[ee.Geometry] = None,
vis_params: Optional[Dict] = None,
**kwargs: Any,
) -> None:
"""
Converts a specific layer from Earth Engine to an image file.
Args:
layer_name (str): The name of the layer to convert.
output (str): The output file path for the image. Defaults to None.
crs (str, optional): The coordinate reference system (CRS) of the output image. Defaults to "EPSG:3857".
scale (int, optional): The scale of the output image. Defaults to None.
region (ee.Geometry, optional): The region of interest for the conversion. Defaults to None.
vis_params (dict, optional): The visualization parameters. Defaults to None.
**kwargs: Additional keyword arguments to pass to the `download_ee_image` function.
Returns:
None
"""
if region is None:
b = self.bounds
west, south, east, north = b[0][1], b[0][0], b[1][1], b[1][0]
region = ee.Geometry.BBox(west, south, east, north)
if scale is None:
scale = int(self.get_scale())
if layer_name not in self.ee_layers.keys():
raise ValueError(f"Layer {layer_name} does not exist.")
if output is None:
output = layer_name + ".tif"
layer = self.ee_layers[layer_name]
ee_object = layer["ee_object"]
if vis_params is None:
vis_params = layer["vis_params"]
image = ee_object.visualize(**vis_params)
if not output.endswith(".tif"):
geotiff = output + ".tif"
else:
geotiff = output
download_ee_image(image, geotiff, region, crs=crs, scale=scale, **kwargs)
if not output.endswith(".tif"):
geotiff_to_image(geotiff, output)
os.remove(geotiff)
import ipywidgets as widgets
import ipyleaflet
The provided code snippet includes necessary dependencies for implementing the `ts_inspector` function. Write a Python function `def ts_inspector( layers_dict=None, left_name=None, right_name=None, width="120px", center=[40, -100], zoom=4, **kwargs, )` to solve the following problem:
Creates a time series inspector. Args: layers_dict (dict, optional): A dictionary of layers to be shown on the map. Defaults to None. left_name (str, optional): A name for the left layer. Defaults to None. right_name (str, optional): A name for the right layer. Defaults to None. width (str, optional): Width of the dropdown list. Defaults to "120px". center (list, optional): Center of the map. Defaults to [40, -100]. zoom (int, optional): Zoom level of the map. Defaults to 4. Returns: leafmap.Map: The Map instance.
Here is the function:
def ts_inspector(
layers_dict=None,
left_name=None,
right_name=None,
width="120px",
center=[40, -100],
zoom=4,
**kwargs,
):
"""Creates a time series inspector.
Args:
layers_dict (dict, optional): A dictionary of layers to be shown on the map. Defaults to None.
left_name (str, optional): A name for the left layer. Defaults to None.
right_name (str, optional): A name for the right layer. Defaults to None.
width (str, optional): Width of the dropdown list. Defaults to "120px".
center (list, optional): Center of the map. Defaults to [40, -100].
zoom (int, optional): Zoom level of the map. Defaults to 4.
Returns:
leafmap.Map: The Map instance.
"""
import ipywidgets as widgets
add_zoom = True
add_fullscreen = True
if "toolbar_control" not in kwargs:
kwargs["toolbar_control"] = False
if "draw_control" not in kwargs:
kwargs["draw_control"] = False
if "measure_control" not in kwargs:
kwargs["measure_control"] = False
if "zoom_control" not in kwargs:
kwargs["zoom_control"] = False
else:
add_zoom = kwargs["zoom_control"]
if "fullscreen_control" not in kwargs:
kwargs["fullscreen_control"] = False
else:
add_fullscreen = kwargs["fullscreen_control"]
if layers_dict is None:
layers_dict = {}
keys = dict(basemaps).keys()
for key in keys:
if basemaps[key]["type"] == "wms":
pass
else:
layers_dict[key] = basemaps[key]
keys = list(layers_dict.keys())
if left_name is None:
left_name = keys[0]
if right_name is None:
right_name = keys[-1]
left_layer = layers_dict[left_name]
right_layer = layers_dict[right_name]
m = Map(center=center, zoom=zoom, **kwargs)
control = ipyleaflet.SplitMapControl(left_layer=left_layer, right_layer=right_layer)
m.add(control)
m.dragging = False
left_dropdown = widgets.Dropdown(
options=keys, value=left_name, layout=widgets.Layout(width=width)
)
left_control = ipyleaflet.WidgetControl(widget=left_dropdown, position="topleft")
m.add(left_control)
right_dropdown = widgets.Dropdown(
options=keys, value=right_name, layout=widgets.Layout(width=width)
)
right_control = ipyleaflet.WidgetControl(widget=right_dropdown, position="topright")
m.add(right_control)
if add_zoom:
m.add(ipyleaflet.ZoomControl())
if add_fullscreen:
m.add(ipyleaflet.FullScreenControl())
split_control = None
for ctrl in m.controls:
if isinstance(ctrl, ipyleaflet.SplitMapControl):
split_control = ctrl
break
def left_change(change):
split_control.left_layer.url = layers_dict[left_dropdown.value].url
left_dropdown.observe(left_change, "value")
def right_change(change):
split_control.right_layer.url = layers_dict[right_dropdown.value].url
right_dropdown.observe(right_change, "value")
return m | Creates a time series inspector. Args: layers_dict (dict, optional): A dictionary of layers to be shown on the map. Defaults to None. left_name (str, optional): A name for the left layer. Defaults to None. right_name (str, optional): A name for the right layer. Defaults to None. width (str, optional): Width of the dropdown list. Defaults to "120px". center (list, optional): Center of the map. Defaults to [40, -100]. zoom (int, optional): Zoom level of the map. Defaults to 4. Returns: leafmap.Map: The Map instance. |
12,440 | import os
import warnings
from typing import Optional, Any, Dict
import ee
import ipyleaflet
import ipywidgets as widgets
from box import Box
from bqplot import pyplot as plt
from IPython.display import display
from .basemaps import get_xyz_dict, xyz_to_leaflet
from .common import *
from .conversion import *
from .ee_tile_layers import *
from . import core
from . import map_widgets
from . import toolbar
from .plot import *
from .timelapse import *
from .legends import builtin_legends
from . import examples
basemaps = Box(xyz_to_leaflet(), frozen_box=True)
import ipyleaflet
The provided code snippet includes necessary dependencies for implementing the `get_basemap` function. Write a Python function `def get_basemap(name)` to solve the following problem:
Gets a basemap tile layer by name. Args: name (str): The name of the basemap. Returns: ipylealfet.TileLayer | ipyleaflet.WMSLayer: The basemap layer.
Here is the function:
def get_basemap(name):
"""Gets a basemap tile layer by name.
Args:
name (str): The name of the basemap.
Returns:
ipylealfet.TileLayer | ipyleaflet.WMSLayer: The basemap layer.
"""
if isinstance(name, str):
if name in basemaps.keys():
basemap = basemaps[name]
if basemap["type"] in ["xyz", "normal", "grau"]:
layer = ipyleaflet.TileLayer(
url=basemap["url"],
name=basemap["name"],
max_zoom=24,
attribution=basemap["attribution"],
)
elif basemap["type"] == "wms":
layer = ipyleaflet.WMSLayer(
url=basemap["url"],
layers=basemap["layers"],
name=basemap["name"],
attribution=basemap["attribution"],
format=basemap["format"],
transparent=basemap["transparent"],
)
return layer
else:
raise ValueError(
"Basemap must be a string. Please choose from: "
+ str(list(basemaps.keys()))
)
else:
raise ValueError(
"Basemap must be a string. Please choose from: "
+ str(list(basemaps.keys()))
) | Gets a basemap tile layer by name. Args: name (str): The name of the basemap. Returns: ipylealfet.TileLayer | ipyleaflet.WMSLayer: The basemap layer. |
12,441 | import pandas as pd
import plotly.express as px
from .common import *
def github_raw_url(url):
"""Get the raw URL for a GitHub file.
Args:
url (str): The GitHub URL.
Returns:
str: The raw URL.
"""
if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url:
url = url.replace("github.com", "raw.githubusercontent.com").replace(
"blob/", "", 1
)
return url
def get_direct_url(url):
"""Get the direct URL for a given URL.
Args:
url (str): The URL to get the direct URL for.
Returns:
str: The direct URL.
"""
if not isinstance(url, str):
raise ValueError("url must be a string.")
if not url.startswith("http"):
raise ValueError("url must start with http.")
r = requests.head(url, allow_redirects=True)
return r.url
The provided code snippet includes necessary dependencies for implementing the `bar_chart` function. Write a Python function `def bar_chart( data=None, x=None, y=None, color=None, descending=True, sort_column=None, max_rows=None, x_label=None, y_label=None, title=None, legend_title=None, width=None, height=500, layout_args={}, **kwargs, )` to solve the following problem:
Create a bar chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to True. sort_column (str, optional): The column to sort the data. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. legend_title (str, optional): Title for the legend. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object.
Here is the function:
def bar_chart(
data=None,
x=None,
y=None,
color=None,
descending=True,
sort_column=None,
max_rows=None,
x_label=None,
y_label=None,
title=None,
legend_title=None,
width=None,
height=500,
layout_args={},
**kwargs,
):
"""Create a bar chart with plotly.express,
Args:
data: DataFrame | array-like | dict | str (local file path or HTTP URL)
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the x axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the y axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
descending (bool, optional): Whether to sort the data in descending order. Defaults to True.
sort_column (str, optional): The column to sort the data. Defaults to None.
max_rows (int, optional): Maximum number of rows to display. Defaults to None.
x_label (str, optional): Label for the x axis. Defaults to None.
y_label (str, optional): Label for the y axis. Defaults to None.
title (str, optional): Title for the plot. Defaults to None.
legend_title (str, optional): Title for the legend. Defaults to None.
width (int, optional): Width of the plot in pixels. Defaults to None.
height (int, optional): Height of the plot in pixels. Defaults to 500.
layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(),
such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None.
**kwargs: Any additional arguments to pass to plotly.express.bar(), such as:
pattern_shape: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign pattern shapes to marks.
facet_row: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the vertical direction.
facet_col: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the horizontal direction.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this
width, so that the column facets span multiple rows. Ignored if 0, and
forced to 0 if `facet_row` or a `marginal` is set.
facet_row_spacing: float between 0 and 1
Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7
when facet_col_wrap is used.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units Default is 0.02.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: list of str or int, or Series or array-like, or dict
Either a list of names of columns in `data_frame`, or pandas Series, or
array_like objects or a dict with column names as keys, with values
True (for default formatting) False (in order to remove this column
from hover information), or a formatting string, for example ':.3f' or
'|%a' or list-like data to appear in the hover tooltip or tuples with a
bool or formatting string as first element, and list-like data to
appear in hover as second element Values from these columns appear as
extra data in the hover tooltip.
custom_data: list of str or int, or Series or array-like
Either names of columns in `data_frame`, or pandas Series, or
array_like objects Values from these columns are extra data, to be used
in widgets or Dash callbacks for example. This data is not user-visible
but is included in events emitted by the figure (lasso selection etc.)
text: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in the
figure as text labels.
base: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position the base of the bar.
error_x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars. If `error_x_minus` is `None`, error bars will
be symmetrical, otherwise `error_x` is used for the positive direction
only.
error_x_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars in the negative direction. Ignored if `error_x`
is `None`.
error_y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars. If `error_y_minus` is `None`, error bars will
be symmetrical, otherwise `error_y` is used for the positive direction
only.
error_y_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars in the negative direction. Ignored if `error_y`
is `None`.
animation_frame: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to animation frames.
animation_group: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
provide object-constancy across animation frames: rows with matching
`animation_group`s will be treated as if they describe the same object
in each frame.
category_orders: dict with str keys and list of str values (default `{}`)
By default, in Python 3.6+, the order of categorical values in axes,
legends and facets depends on the order in which these values are first
encountered in `data_frame` (and no order is guaranteed by default in
Python below 3.6). This parameter is used to force a specific ordering
of values per column. The keys of this dict should correspond to column
names, and the values should be lists of strings corresponding to the
specific display order desired.
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
color_continuous_scale: list of str
Strings should define valid CSS-colors This list is used to build a
continuous color scale when the column denoted by `color` contains
numeric data. Various useful color scales are available in the
`plotly.express.colors` submodules, specifically
`plotly.express.colors.sequential`, `plotly.express.colors.diverging`
and `plotly.express.colors.cyclical`.
pattern_shape_sequence: list of str
Strings should define valid plotly.js patterns-shapes. When
`pattern_shape` is set, values in that column are assigned patterns-
shapes by cycling through `pattern_shape_sequence` in the order
described in `category_orders`, unless the value of `pattern_shape` is
a key in `pattern_shape_map`.
pattern_shape_map: dict with str keys and str values (default `{}`)
Strings values define plotly.js patterns-shapes. Used to override
`pattern_shape_sequences` to assign a specific patterns-shapes to lines
corresponding with specific values. Keys in `pattern_shape_map` should
be values in the column denoted by `pattern_shape`. Alternatively, if
the values of `pattern_shape` are valid patterns-shapes names, the
string `'identity'` may be passed to cause them to be used directly.
range_color: list of two numbers
If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint: number (default `None`)
If set, computes the bounds of the continuous color scale to have the
desired midpoint. Setting this value is recommended when using
`plotly.express.colors.diverging` color scales as the inputs to
`color_continuous_scale`.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
orientation: str, one of `'h'` for horizontal or `'v'` for vertical.
(default `'v'` if `x` and `y` are provided and both continuous or both
categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and
`y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is
provided)
barmode: str (default `'relative'`)
One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode,
bars are stacked above zero for positive values and below zero for
negative values. In `'overlay'` mode, bars are drawn on top of one
another. In `'group'` mode, bars are placed beside each other.
log_x: boolean (default `False`)
If `True`, the x-axis is log-scaled in cartesian coordinates.
log_y: boolean (default `False`)
If `True`, the y-axis is log-scaled in cartesian coordinates.
range_x: list of two numbers
If provided, overrides auto-scaling on the x-axis in cartesian
coordinates.
range_y: list of two numbers
If provided, overrides auto-scaling on the y-axis in cartesian
coordinates.
text_auto: bool or string (default `False`)
If `True` or a string, the x or y or z values will be displayed as
text, depending on the orientation A string like `'.2f'` will be
interpreted as a `texttemplate` numeric formatting directive.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
Returns:
plotly.graph_objs._figure.Figure: A plotly figure object.
"""
if isinstance(data, str):
if data.startswith("http"):
data = github_raw_url(data)
data = get_direct_url(data)
try:
data = pd.read_csv(data)
except Exception as e:
raise ValueError(f"Could not read data from {data}. {e}")
if not isinstance(data, pd.DataFrame):
raise ValueError(
"data must be a pandas DataFrame, a string or an ee.FeatureCollection."
)
if descending is not None:
if sort_column is None:
if isinstance(y, str):
sort_column = y
elif isinstance(y, list):
sort_column = y[0]
data.sort_values([sort_column, x], ascending=not (descending), inplace=True)
if "barmode" not in kwargs:
kwargs["barmode"] = "group"
if isinstance(max_rows, int):
data = data.head(max_rows)
if "labels" in kwargs:
labels = kwargs["labels"]
kwargs.pop("labels")
else:
labels = {}
if x_label is not None:
labels[x] = x_label
if y_label is not None:
if isinstance(y, str):
labels[y] = y_label
elif isinstance(y, list):
labels[y[0]] = y_label
if isinstance(legend_title, str):
if "legend" not in layout_args:
layout_args["legend"] = {}
layout_args["legend"]["title"] = legend_title
try:
fig = px.bar(
data,
x=x,
y=y,
color=color,
labels=labels,
title=title,
width=width,
height=height,
**kwargs,
)
if isinstance(layout_args, dict):
fig.update_layout(**layout_args)
return fig
except Exception as e:
raise ValueError(f"Could not create bar plot. {e}") | Create a bar chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to True. sort_column (str, optional): The column to sort the data. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. legend_title (str, optional): Title for the legend. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object. |
12,442 | import pandas as pd
import plotly.express as px
from .common import *
def github_raw_url(url):
"""Get the raw URL for a GitHub file.
Args:
url (str): The GitHub URL.
Returns:
str: The raw URL.
"""
if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url:
url = url.replace("github.com", "raw.githubusercontent.com").replace(
"blob/", "", 1
)
return url
def get_direct_url(url):
"""Get the direct URL for a given URL.
Args:
url (str): The URL to get the direct URL for.
Returns:
str: The direct URL.
"""
if not isinstance(url, str):
raise ValueError("url must be a string.")
if not url.startswith("http"):
raise ValueError("url must start with http.")
r = requests.head(url, allow_redirects=True)
return r.url
The provided code snippet includes necessary dependencies for implementing the `line_chart` function. Write a Python function `def line_chart( data=None, x=None, y=None, color=None, descending=None, max_rows=None, x_label=None, y_label=None, title=None, legend_title=None, width=None, height=500, layout_args={}, **kwargs, )` to solve the following problem:
Create a line chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. legend_title (str, optional): Title for the legend. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object.
Here is the function:
def line_chart(
data=None,
x=None,
y=None,
color=None,
descending=None,
max_rows=None,
x_label=None,
y_label=None,
title=None,
legend_title=None,
width=None,
height=500,
layout_args={},
**kwargs,
):
"""Create a line chart with plotly.express,
Args:
data: DataFrame | array-like | dict | str (local file path or HTTP URL)
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the x axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the y axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
descending (bool, optional): Whether to sort the data in descending order. Defaults to None.
max_rows (int, optional): Maximum number of rows to display. Defaults to None.
x_label (str, optional): Label for the x axis. Defaults to None.
y_label (str, optional): Label for the y axis. Defaults to None.
title (str, optional): Title for the plot. Defaults to None.
legend_title (str, optional): Title for the legend. Defaults to None.
width (int, optional): Width of the plot in pixels. Defaults to None.
height (int, optional): Height of the plot in pixels. Defaults to 500.
layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(),
such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None.
**kwargs: Any additional arguments to pass to plotly.express.bar(), such as:
pattern_shape: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign pattern shapes to marks.
facet_row: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the vertical direction.
facet_col: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the horizontal direction.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this
width, so that the column facets span multiple rows. Ignored if 0, and
forced to 0 if `facet_row` or a `marginal` is set.
facet_row_spacing: float between 0 and 1
Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7
when facet_col_wrap is used.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units Default is 0.02.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: list of str or int, or Series or array-like, or dict
Either a list of names of columns in `data_frame`, or pandas Series, or
array_like objects or a dict with column names as keys, with values
True (for default formatting) False (in order to remove this column
from hover information), or a formatting string, for example ':.3f' or
'|%a' or list-like data to appear in the hover tooltip or tuples with a
bool or formatting string as first element, and list-like data to
appear in hover as second element Values from these columns appear as
extra data in the hover tooltip.
custom_data: list of str or int, or Series or array-like
Either names of columns in `data_frame`, or pandas Series, or
array_like objects Values from these columns are extra data, to be used
in widgets or Dash callbacks for example. This data is not user-visible
but is included in events emitted by the figure (lasso selection etc.)
text: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in the
figure as text labels.
base: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position the base of the bar.
error_x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars. If `error_x_minus` is `None`, error bars will
be symmetrical, otherwise `error_x` is used for the positive direction
only.
error_x_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars in the negative direction. Ignored if `error_x`
is `None`.
error_y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars. If `error_y_minus` is `None`, error bars will
be symmetrical, otherwise `error_y` is used for the positive direction
only.
error_y_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars in the negative direction. Ignored if `error_y`
is `None`.
animation_frame: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to animation frames.
animation_group: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
provide object-constancy across animation frames: rows with matching
`animation_group`s will be treated as if they describe the same object
in each frame.
category_orders: dict with str keys and list of str values (default `{}`)
By default, in Python 3.6+, the order of categorical values in axes,
legends and facets depends on the order in which these values are first
encountered in `data_frame` (and no order is guaranteed by default in
Python below 3.6). This parameter is used to force a specific ordering
of values per column. The keys of this dict should correspond to column
names, and the values should be lists of strings corresponding to the
specific display order desired.
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
color_continuous_scale: list of str
Strings should define valid CSS-colors This list is used to build a
continuous color scale when the column denoted by `color` contains
numeric data. Various useful color scales are available in the
`plotly.express.colors` submodules, specifically
`plotly.express.colors.sequential`, `plotly.express.colors.diverging`
and `plotly.express.colors.cyclical`.
pattern_shape_sequence: list of str
Strings should define valid plotly.js patterns-shapes. When
`pattern_shape` is set, values in that column are assigned patterns-
shapes by cycling through `pattern_shape_sequence` in the order
described in `category_orders`, unless the value of `pattern_shape` is
a key in `pattern_shape_map`.
pattern_shape_map: dict with str keys and str values (default `{}`)
Strings values define plotly.js patterns-shapes. Used to override
`pattern_shape_sequences` to assign a specific patterns-shapes to lines
corresponding with specific values. Keys in `pattern_shape_map` should
be values in the column denoted by `pattern_shape`. Alternatively, if
the values of `pattern_shape` are valid patterns-shapes names, the
string `'identity'` may be passed to cause them to be used directly.
range_color: list of two numbers
If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint: number (default `None`)
If set, computes the bounds of the continuous color scale to have the
desired midpoint. Setting this value is recommended when using
`plotly.express.colors.diverging` color scales as the inputs to
`color_continuous_scale`.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
orientation: str, one of `'h'` for horizontal or `'v'` for vertical.
(default `'v'` if `x` and `y` are provided and both continuous or both
categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and
`y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is
provided)
barmode: str (default `'relative'`)
One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode,
bars are stacked above zero for positive values and below zero for
negative values. In `'overlay'` mode, bars are drawn on top of one
another. In `'group'` mode, bars are placed beside each other.
log_x: boolean (default `False`)
If `True`, the x-axis is log-scaled in cartesian coordinates.
log_y: boolean (default `False`)
If `True`, the y-axis is log-scaled in cartesian coordinates.
range_x: list of two numbers
If provided, overrides auto-scaling on the x-axis in cartesian
coordinates.
range_y: list of two numbers
If provided, overrides auto-scaling on the y-axis in cartesian
coordinates.
text_auto: bool or string (default `False`)
If `True` or a string, the x or y or z values will be displayed as
text, depending on the orientation A string like `'.2f'` will be
interpreted as a `texttemplate` numeric formatting directive.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
Returns:
plotly.graph_objs._figure.Figure: A plotly figure object.
"""
if isinstance(data, str):
if data.startswith("http"):
data = github_raw_url(data)
data = get_direct_url(data)
try:
data = pd.read_csv(data)
except Exception as e:
raise ValueError(f"Could not read data from {data}. {e}")
if not isinstance(data, pd.DataFrame):
raise ValueError(
"data must be a pandas DataFrame, a string or an ee.FeatureCollection."
)
if descending is not None:
data.sort_values([y, x], ascending=not (descending), inplace=True)
if isinstance(max_rows, int):
data = data.head(max_rows)
if "labels" in kwargs:
labels = kwargs["labels"]
kwargs.pop("labels")
else:
labels = {}
if x_label is not None:
labels[x] = x_label
if y_label is not None:
labels[y] = y_label
if isinstance(legend_title, str):
if "legend" not in layout_args:
layout_args["legend"] = {}
layout_args["legend"]["title"] = legend_title
try:
fig = px.line(
data,
x=x,
y=y,
color=color,
labels=labels,
title=title,
width=width,
height=height,
**kwargs,
)
if isinstance(layout_args, dict):
fig.update_layout(**layout_args)
return fig
except Exception as e:
raise ValueError(f"Could not create bar plot. {e}") | Create a line chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. legend_title (str, optional): Title for the legend. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object. |
12,443 | import pandas as pd
import plotly.express as px
from .common import *
def github_raw_url(url):
"""Get the raw URL for a GitHub file.
Args:
url (str): The GitHub URL.
Returns:
str: The raw URL.
"""
if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url:
url = url.replace("github.com", "raw.githubusercontent.com").replace(
"blob/", "", 1
)
return url
def get_direct_url(url):
"""Get the direct URL for a given URL.
Args:
url (str): The URL to get the direct URL for.
Returns:
str: The direct URL.
"""
if not isinstance(url, str):
raise ValueError("url must be a string.")
if not url.startswith("http"):
raise ValueError("url must start with http.")
r = requests.head(url, allow_redirects=True)
return r.url
The provided code snippet includes necessary dependencies for implementing the `histogram` function. Write a Python function `def histogram( data=None, x=None, y=None, color=None, descending=None, max_rows=None, x_label=None, y_label=None, title=None, width=None, height=500, layout_args={}, **kwargs, )` to solve the following problem:
Create a line chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object.
Here is the function:
def histogram(
data=None,
x=None,
y=None,
color=None,
descending=None,
max_rows=None,
x_label=None,
y_label=None,
title=None,
width=None,
height=500,
layout_args={},
**kwargs,
):
"""Create a line chart with plotly.express,
Args:
data: DataFrame | array-like | dict | str (local file path or HTTP URL)
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the x axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the y axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
descending (bool, optional): Whether to sort the data in descending order. Defaults to None.
max_rows (int, optional): Maximum number of rows to display. Defaults to None.
x_label (str, optional): Label for the x axis. Defaults to None.
y_label (str, optional): Label for the y axis. Defaults to None.
title (str, optional): Title for the plot. Defaults to None.
width (int, optional): Width of the plot in pixels. Defaults to None.
height (int, optional): Height of the plot in pixels. Defaults to 500.
layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(),
such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None.
**kwargs: Any additional arguments to pass to plotly.express.bar(), such as:
pattern_shape: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign pattern shapes to marks.
facet_row: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the vertical direction.
facet_col: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the horizontal direction.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this
width, so that the column facets span multiple rows. Ignored if 0, and
forced to 0 if `facet_row` or a `marginal` is set.
facet_row_spacing: float between 0 and 1
Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7
when facet_col_wrap is used.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units Default is 0.02.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: list of str or int, or Series or array-like, or dict
Either a list of names of columns in `data_frame`, or pandas Series, or
array_like objects or a dict with column names as keys, with values
True (for default formatting) False (in order to remove this column
from hover information), or a formatting string, for example ':.3f' or
'|%a' or list-like data to appear in the hover tooltip or tuples with a
bool or formatting string as first element, and list-like data to
appear in hover as second element Values from these columns appear as
extra data in the hover tooltip.
custom_data: list of str or int, or Series or array-like
Either names of columns in `data_frame`, or pandas Series, or
array_like objects Values from these columns are extra data, to be used
in widgets or Dash callbacks for example. This data is not user-visible
but is included in events emitted by the figure (lasso selection etc.)
text: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in the
figure as text labels.
base: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position the base of the bar.
error_x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars. If `error_x_minus` is `None`, error bars will
be symmetrical, otherwise `error_x` is used for the positive direction
only.
error_x_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars in the negative direction. Ignored if `error_x`
is `None`.
error_y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars. If `error_y_minus` is `None`, error bars will
be symmetrical, otherwise `error_y` is used for the positive direction
only.
error_y_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars in the negative direction. Ignored if `error_y`
is `None`.
animation_frame: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to animation frames.
animation_group: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
provide object-constancy across animation frames: rows with matching
`animation_group`s will be treated as if they describe the same object
in each frame.
category_orders: dict with str keys and list of str values (default `{}`)
By default, in Python 3.6+, the order of categorical values in axes,
legends and facets depends on the order in which these values are first
encountered in `data_frame` (and no order is guaranteed by default in
Python below 3.6). This parameter is used to force a specific ordering
of values per column. The keys of this dict should correspond to column
names, and the values should be lists of strings corresponding to the
specific display order desired.
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
color_continuous_scale: list of str
Strings should define valid CSS-colors This list is used to build a
continuous color scale when the column denoted by `color` contains
numeric data. Various useful color scales are available in the
`plotly.express.colors` submodules, specifically
`plotly.express.colors.sequential`, `plotly.express.colors.diverging`
and `plotly.express.colors.cyclical`.
pattern_shape_sequence: list of str
Strings should define valid plotly.js patterns-shapes. When
`pattern_shape` is set, values in that column are assigned patterns-
shapes by cycling through `pattern_shape_sequence` in the order
described in `category_orders`, unless the value of `pattern_shape` is
a key in `pattern_shape_map`.
pattern_shape_map: dict with str keys and str values (default `{}`)
Strings values define plotly.js patterns-shapes. Used to override
`pattern_shape_sequences` to assign a specific patterns-shapes to lines
corresponding with specific values. Keys in `pattern_shape_map` should
be values in the column denoted by `pattern_shape`. Alternatively, if
the values of `pattern_shape` are valid patterns-shapes names, the
string `'identity'` may be passed to cause them to be used directly.
range_color: list of two numbers
If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint: number (default `None`)
If set, computes the bounds of the continuous color scale to have the
desired midpoint. Setting this value is recommended when using
`plotly.express.colors.diverging` color scales as the inputs to
`color_continuous_scale`.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
orientation: str, one of `'h'` for horizontal or `'v'` for vertical.
(default `'v'` if `x` and `y` are provided and both continuous or both
categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and
`y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is
provided)
barmode: str (default `'relative'`)
One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode,
bars are stacked above zero for positive values and below zero for
negative values. In `'overlay'` mode, bars are drawn on top of one
another. In `'group'` mode, bars are placed beside each other.
log_x: boolean (default `False`)
If `True`, the x-axis is log-scaled in cartesian coordinates.
log_y: boolean (default `False`)
If `True`, the y-axis is log-scaled in cartesian coordinates.
range_x: list of two numbers
If provided, overrides auto-scaling on the x-axis in cartesian
coordinates.
range_y: list of two numbers
If provided, overrides auto-scaling on the y-axis in cartesian
coordinates.
text_auto: bool or string (default `False`)
If `True` or a string, the x or y or z values will be displayed as
text, depending on the orientation A string like `'.2f'` will be
interpreted as a `texttemplate` numeric formatting directive.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
Returns:
plotly.graph_objs._figure.Figure: A plotly figure object.
"""
if isinstance(data, str):
if data.startswith("http"):
data = github_raw_url(data)
data = get_direct_url(data)
try:
data = pd.read_csv(data)
except Exception as e:
raise ValueError(f"Could not read data from {data}. {e}")
if not isinstance(data, pd.DataFrame):
raise ValueError(
"data must be a pandas DataFrame, a string or an ee.FeatureCollection."
)
if descending is not None:
data.sort_values([y, x], ascending=not (descending), inplace=True)
if isinstance(max_rows, int):
data = data.head(max_rows)
if "labels" in kwargs:
labels = kwargs["labels"]
else:
labels = {}
if x_label is not None:
labels[x] = x_label
if y_label is not None:
labels[y] = y_label
try:
fig = px.histogram(
data,
x=x,
y=y,
color=color,
labels=labels,
title=title,
width=width,
height=height,
**kwargs,
)
if isinstance(layout_args, dict):
fig.update_layout(**layout_args)
return fig
except Exception as e:
raise ValueError(f"Could not create bar plot. {e}") | Create a line chart with plotly.express, Args: data: DataFrame | array-like | dict | str (local file path or HTTP URL) This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either `x` or `y` can optionally be a list of column references or array_likes, in which case the data will be treated as if it were 'wide' rather than 'long'. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. descending (bool, optional): Whether to sort the data in descending order. Defaults to None. max_rows (int, optional): Maximum number of rows to display. Defaults to None. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), such as {'title':'Plot Title', 'title_x':0.5}. Defaults to None. **kwargs: Any additional arguments to pass to plotly.express.bar(), such as: pattern_shape: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign pattern shapes to marks. facet_row: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction. facet_col: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction. facet_col_wrap: int Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if `facet_row` or a `marginal` is set. facet_row_spacing: float between 0 and 1 Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used. facet_col_spacing: float between 0 and 1 Spacing between facet columns, in paper units Default is 0.02. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) text: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels. base: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to position the base of the bar. error_x: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars. If `error_x_minus` is `None`, error bars will be symmetrical, otherwise `error_x` is used for the positive direction only. error_x_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size x-axis error bars in the negative direction. Ignored if `error_x` is `None`. error_y: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars. If `error_y_minus` is `None`, error bars will be symmetrical, otherwise `error_y` is used for the positive direction only. error_y_minus: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to size y-axis error bars in the negative direction. Ignored if `error_y` is `None`. animation_frame: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames. animation_group: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching `animation_group`s will be treated as if they describe the same object in each frame. category_orders: dict with str keys and list of str values (default `{}`) By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in `data_frame` (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired. labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. color_continuous_scale: list of str Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by `color` contains numeric data. Various useful color scales are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.sequential`, `plotly.express.colors.diverging` and `plotly.express.colors.cyclical`. pattern_shape_sequence: list of str Strings should define valid plotly.js patterns-shapes. When `pattern_shape` is set, values in that column are assigned patterns- shapes by cycling through `pattern_shape_sequence` in the order described in `category_orders`, unless the value of `pattern_shape` is a key in `pattern_shape_map`. pattern_shape_map: dict with str keys and str values (default `{}`) Strings values define plotly.js patterns-shapes. Used to override `pattern_shape_sequences` to assign a specific patterns-shapes to lines corresponding with specific values. Keys in `pattern_shape_map` should be values in the column denoted by `pattern_shape`. Alternatively, if the values of `pattern_shape` are valid patterns-shapes names, the string `'identity'` may be passed to cause them to be used directly. range_color: list of two numbers If provided, overrides auto-scaling on the continuous color scale. color_continuous_midpoint: number (default `None`) If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when using `plotly.express.colors.diverging` color scales as the inputs to `color_continuous_scale`. opacity: float Value between 0 and 1. Sets the opacity for markers. orientation: str, one of `'h'` for horizontal or `'v'` for vertical. (default `'v'` if `x` and `y` are provided and both continuous or both categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and `y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is provided) barmode: str (default `'relative'`) One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode, bars are stacked above zero for positive values and below zero for negative values. In `'overlay'` mode, bars are drawn on top of one another. In `'group'` mode, bars are placed beside each other. log_x: boolean (default `False`) If `True`, the x-axis is log-scaled in cartesian coordinates. log_y: boolean (default `False`) If `True`, the y-axis is log-scaled in cartesian coordinates. range_x: list of two numbers If provided, overrides auto-scaling on the x-axis in cartesian coordinates. range_y: list of two numbers If provided, overrides auto-scaling on the y-axis in cartesian coordinates. text_auto: bool or string (default `False`) If `True` or a string, the x or y or z values will be displayed as text, depending on the orientation A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. Returns: plotly.graph_objs._figure.Figure: A plotly figure object. |
12,444 | import pandas as pd
import plotly.express as px
from .common import *
def github_raw_url(url):
"""Get the raw URL for a GitHub file.
Args:
url (str): The GitHub URL.
Returns:
str: The raw URL.
"""
if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url:
url = url.replace("github.com", "raw.githubusercontent.com").replace(
"blob/", "", 1
)
return url
def get_direct_url(url):
"""Get the direct URL for a given URL.
Args:
url (str): The URL to get the direct URL for.
Returns:
str: The direct URL.
"""
if not isinstance(url, str):
raise ValueError("url must be a string.")
if not url.startswith("http"):
raise ValueError("url must start with http.")
r = requests.head(url, allow_redirects=True)
return r.url
The provided code snippet includes necessary dependencies for implementing the `pie_chart` function. Write a Python function `def pie_chart( data, names=None, values=None, descending=True, max_rows=None, other_label=None, color=None, color_discrete_sequence=None, color_discrete_map=None, hover_name=None, hover_data=None, custom_data=None, labels=None, title=None, legend_title=None, template=None, width=None, height=None, opacity=None, hole=None, layout_args={}, **kwargs, )` to solve the following problem:
Create a plotly pie chart. Args: data: DataFrame or array-like or dict This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. names: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used as labels for sectors. values: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to set values associated to sectors. descending (bool, optional): Whether to sort the data in descending order. Defaults to True. max_rows (int, optional): Maximum number of rows to display. Defaults to None. other_label (str, optional): Label for the "other" category. Defaults to None. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. title: str The figure title. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. width: int (default `None`) The figure width in pixels. height: int (default `None`) The figure height in pixels. opacity: float Value between 0 and 1. Sets the opacity for markers. hole: float Sets the fraction of the radius to cut out of the pie.Use this to make a donut chart. Returns: plotly.graph_objs._figure.Figure: A plotly figure object.
Here is the function:
def pie_chart(
data,
names=None,
values=None,
descending=True,
max_rows=None,
other_label=None,
color=None,
color_discrete_sequence=None,
color_discrete_map=None,
hover_name=None,
hover_data=None,
custom_data=None,
labels=None,
title=None,
legend_title=None,
template=None,
width=None,
height=None,
opacity=None,
hole=None,
layout_args={},
**kwargs,
):
"""Create a plotly pie chart.
Args:
data: DataFrame or array-like or dict
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
names: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used as
labels for sectors.
values: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
set values associated to sectors.
descending (bool, optional): Whether to sort the data in descending order. Defaults to True.
max_rows (int, optional): Maximum number of rows to display. Defaults to None.
other_label (str, optional): Label for the "other" category. Defaults to None.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: list of str or int, or Series or array-like, or dict
Either a list of names of columns in `data_frame`, or pandas Series, or
array_like objects or a dict with column names as keys, with values
True (for default formatting) False (in order to remove this column
from hover information), or a formatting string, for example ':.3f' or
'|%a' or list-like data to appear in the hover tooltip or tuples with a
bool or formatting string as first element, and list-like data to
appear in hover as second element Values from these columns appear as
extra data in the hover tooltip.
custom_data: list of str or int, or Series or array-like
Either names of columns in `data_frame`, or pandas Series, or
array_like objects Values from these columns are extra data, to be used
in widgets or Dash callbacks for example. This data is not user-visible
but is included in events emitted by the figure (lasso selection etc.)
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
title: str
The figure title.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
width: int (default `None`)
The figure width in pixels.
height: int (default `None`)
The figure height in pixels.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
hole: float
Sets the fraction of the radius to cut out of the pie.Use this to make
a donut chart.
Returns:
plotly.graph_objs._figure.Figure: A plotly figure object.
"""
if isinstance(data, str):
if data.startswith("http"):
data = github_raw_url(data)
data = get_direct_url(data)
try:
data = pd.read_csv(data)
except Exception as e:
raise ValueError(f"Could not read data from {data}. {e}")
if not isinstance(data, pd.DataFrame):
raise ValueError(
"data must be a pandas DataFrame, a string or an ee.FeatureCollection."
)
if descending is not None and isinstance(values, str):
data.sort_values([values], ascending=not (descending), inplace=True)
if other_label is None:
other_label = "Other"
if max_rows is not None and isinstance(names, str) and isinstance(values, str):
max_rows = min(len(data), max_rows) - 2
value = data.iloc[max_rows][values]
data.loc[data[values] < value, names] = other_label
if isinstance(legend_title, str):
if "legend" not in layout_args:
layout_args["legend"] = {}
layout_args["legend"]["title"] = legend_title
try:
fig = px.pie(
data_frame=data,
names=names,
values=values,
color=color,
color_discrete_sequence=color_discrete_sequence,
color_discrete_map=color_discrete_map,
hover_name=hover_name,
hover_data=hover_data,
custom_data=custom_data,
labels=labels,
title=title,
template=template,
width=width,
height=height,
opacity=opacity,
hole=hole,
**kwargs,
)
if isinstance(layout_args, dict):
fig.update_layout(**layout_args)
return fig
except Exception as e:
raise Exception(f"Could not create pie chart. {e}") | Create a plotly pie chart. Args: data: DataFrame or array-like or dict This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments. names: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used as labels for sectors. values: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to set values associated to sectors. descending (bool, optional): Whether to sort the data in descending order. Defaults to True. max_rows (int, optional): Maximum number of rows to display. Defaults to None. other_label (str, optional): Label for the "other" category. Defaults to None. color: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. color_discrete_sequence: list of str Strings should define valid CSS-colors. When `color` is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through `color_discrete_sequence` in the order described in `category_orders`, unless the value of `color` is a key in `color_discrete_map`. Various useful color sequences are available in the `plotly.express.colors` submodules, specifically `plotly.express.colors.qualitative`. color_discrete_map: dict with str keys and str values (default `{}`) String values should define valid CSS-colors Used to override `color_discrete_sequence` to assign a specific colors to marks corresponding with specific values. Keys in `color_discrete_map` should be values in the column denoted by `color`. Alternatively, if the values of `color` are valid colors, the string `'identity'` may be passed to cause them to be used directly. hover_name: str or int or Series or array-like Either a name of a column in `data_frame`, or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip. hover_data: list of str or int, or Series or array-like, or dict Either a list of names of columns in `data_frame`, or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ':.3f' or '|%a' or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. custom_data: list of str or int, or Series or array-like Either names of columns in `data_frame`, or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.) labels: dict with str keys and str values (default `{}`) By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed. title: str The figure title. template: str or dict or plotly.graph_objects.layout.Template instance The figure template name (must be a key in plotly.io.templates) or definition. width: int (default `None`) The figure width in pixels. height: int (default `None`) The figure height in pixels. opacity: float Value between 0 and 1. Sets the opacity for markers. hole: float Sets the fraction of the radius to cut out of the pie.Use this to make a donut chart. Returns: plotly.graph_objs._figure.Figure: A plotly figure object. |
12,445 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from box import Box
The provided code snippet includes necessary dependencies for implementing the `get_colorbar` function. Write a Python function `def get_colorbar( colors, vmin=0, vmax=1, width=6.0, height=0.4, orientation="horizontal", discrete=False, return_fig=False, )` to solve the following problem:
Creates a colorbar based on custom colors. Args: colors (list): A list of hex colors. vmin (float, optional): The minimum value range. Defaults to 0. vmax (float, optional): The maximum value range. Defaults to 1.0. width (float, optional): The width of the colormap. Defaults to 6.0. height (float, optional): The height of the colormap. Defaults to 0.4. orientation (str, optional): The orientation of the colormap. Defaults to "horizontal". discrete (bool, optional): Whether to create a discrete colormap. return_fig (bool, optional): Whether to return the figure. Defaults to False.
Here is the function:
def get_colorbar(
colors,
vmin=0,
vmax=1,
width=6.0,
height=0.4,
orientation="horizontal",
discrete=False,
return_fig=False,
):
"""Creates a colorbar based on custom colors.
Args:
colors (list): A list of hex colors.
vmin (float, optional): The minimum value range. Defaults to 0.
vmax (float, optional): The maximum value range. Defaults to 1.0.
width (float, optional): The width of the colormap. Defaults to 6.0.
height (float, optional): The height of the colormap. Defaults to 0.4.
orientation (str, optional): The orientation of the colormap. Defaults to "horizontal".
discrete (bool, optional): Whether to create a discrete colormap.
return_fig (bool, optional): Whether to return the figure. Defaults to False.
"""
hexcodes = [i if i[0] == "#" else "#" + i for i in colors]
fig, ax = plt.subplots(figsize=(width, height))
if discrete:
cmap = mpl.colors.ListedColormap(hexcodes)
vals = np.linspace(vmin, vmax, cmap.N + 1)
norm = mpl.colors.BoundaryNorm(vals, cmap.N)
else:
cmap = mpl.colors.LinearSegmentedColormap.from_list("custom", hexcodes, N=256)
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
mpl.colorbar.ColorbarBase(ax, norm=norm, cmap=cmap, orientation=orientation)
if return_fig:
return fig
else:
plt.show() | Creates a colorbar based on custom colors. Args: colors (list): A list of hex colors. vmin (float, optional): The minimum value range. Defaults to 0. vmax (float, optional): The maximum value range. Defaults to 1.0. width (float, optional): The width of the colormap. Defaults to 6.0. height (float, optional): The height of the colormap. Defaults to 0.4. orientation (str, optional): The orientation of the colormap. Defaults to "horizontal". discrete (bool, optional): Whether to create a discrete colormap. return_fig (bool, optional): Whether to return the figure. Defaults to False. |
12,446 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from box import Box
The provided code snippet includes necessary dependencies for implementing the `plot_colormap` function. Write a Python function `def plot_colormap( cmap, width=8.0, height=0.4, orientation="horizontal", vmin=0, vmax=1.0, axis_off=True, show_name=False, font_size=12, return_fig=False, )` to solve the following problem:
Plot a matplotlib colormap. Args: cmap (str): The name of the colormap. width (float, optional): The width of the colormap. Defaults to 8.0. height (float, optional): The height of the colormap. Defaults to 0.4. orientation (str, optional): The orientation of the colormap. Defaults to "horizontal". vmin (float, optional): The minimum value range. Defaults to 0. vmax (float, optional): The maximum value range. Defaults to 1.0. axis_off (bool, optional): Whether to turn axis off. Defaults to True. show_name (bool, optional): Whether to show the colormap name. Defaults to False. font_size (int, optional): Font size of the text. Defaults to 12. return_fig (bool, optional): Whether to return the figure. Defaults to False.
Here is the function:
def plot_colormap(
cmap,
width=8.0,
height=0.4,
orientation="horizontal",
vmin=0,
vmax=1.0,
axis_off=True,
show_name=False,
font_size=12,
return_fig=False,
):
"""Plot a matplotlib colormap.
Args:
cmap (str): The name of the colormap.
width (float, optional): The width of the colormap. Defaults to 8.0.
height (float, optional): The height of the colormap. Defaults to 0.4.
orientation (str, optional): The orientation of the colormap. Defaults to "horizontal".
vmin (float, optional): The minimum value range. Defaults to 0.
vmax (float, optional): The maximum value range. Defaults to 1.0.
axis_off (bool, optional): Whether to turn axis off. Defaults to True.
show_name (bool, optional): Whether to show the colormap name. Defaults to False.
font_size (int, optional): Font size of the text. Defaults to 12.
return_fig (bool, optional): Whether to return the figure. Defaults to False.
"""
fig, ax = plt.subplots(figsize=(width, height))
col_map = mpl.colormaps[cmap]
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
mpl.colorbar.ColorbarBase(ax, norm=norm, cmap=col_map, orientation=orientation)
if axis_off:
ax.set_axis_off()
if show_name:
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3] / 2.0
fig.text(x_text, y_text, cmap, va="center", ha="right", fontsize=font_size)
if return_fig:
return fig
else:
plt.show() | Plot a matplotlib colormap. Args: cmap (str): The name of the colormap. width (float, optional): The width of the colormap. Defaults to 8.0. height (float, optional): The height of the colormap. Defaults to 0.4. orientation (str, optional): The orientation of the colormap. Defaults to "horizontal". vmin (float, optional): The minimum value range. Defaults to 0. vmax (float, optional): The maximum value range. Defaults to 1.0. axis_off (bool, optional): Whether to turn axis off. Defaults to True. show_name (bool, optional): Whether to show the colormap name. Defaults to False. font_size (int, optional): Font size of the text. Defaults to 12. return_fig (bool, optional): Whether to return the figure. Defaults to False. |
12,447 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from box import Box
def list_colormaps(add_extra=False, lowercase=False):
"""List all available colormaps. See a complete lost of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.
Returns:
list: The list of colormap names.
"""
result = plt.colormaps()
if add_extra:
result += ["dem", "ndvi", "ndwi"]
if lowercase:
result = [i.lower() for i in result]
result.sort()
return result
The provided code snippet includes necessary dependencies for implementing the `plot_colormaps` function. Write a Python function `def plot_colormaps(width=8.0, height=0.4)` to solve the following problem:
Plot all available colormaps. Args: width (float, optional): Width of the colormap. Defaults to 8.0. height (float, optional): Height of the colormap. Defaults to 0.4.
Here is the function:
def plot_colormaps(width=8.0, height=0.4):
"""Plot all available colormaps.
Args:
width (float, optional): Width of the colormap. Defaults to 8.0.
height (float, optional): Height of the colormap. Defaults to 0.4.
"""
cmap_list = list_colormaps()
nrows = len(cmap_list)
fig, axes = plt.subplots(nrows=nrows, figsize=(width, height * nrows))
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
for ax, name in zip(axes, cmap_list):
ax.imshow(gradient, aspect="auto", cmap=mpl.colormaps[name])
ax.set_axis_off()
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3] / 2.0
fig.text(x_text, y_text, name, va="center", ha="right", fontsize=12)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
plt.show() | Plot all available colormaps. Args: width (float, optional): Width of the colormap. Defaults to 8.0. height (float, optional): Height of the colormap. Defaults to 0.4. |
12,448 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
class Feature_ByFeature(BarChart):
"""A object to define variables and get_data method."""
def __init__(
self, features, xProperty, yProperties, name="feature.byFeature", **kwargs
):
default_labels = yProperties
super().__init__(features, default_labels, name, **kwargs)
self.x_data, self.y_data = self.get_data(xProperty, yProperties)
def get_data(self, xProperty, yProperties):
x_data = list(self.df[xProperty])
y_data = list(self.df[yProperties].values.T)
return x_data, y_data
The provided code snippet includes necessary dependencies for implementing the `feature_byFeature` function. Write a Python function `def feature_byFeature( features: ee.FeatureCollection, xProperty: str, yProperties: list, **kwargs )` to solve the following problem:
Generates a Chart from a set of features. Plots the value of one or more properties for each feature. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature Args: features (ee.FeatureCollection): The feature collection to generate a chart from. xProperty (str): Features labeled by xProperty. yProperties (list): Values of yProperties. Raises: Exception: Errors when creating the chart.
Here is the function:
def feature_byFeature(
features: ee.FeatureCollection, xProperty: str, yProperties: list, **kwargs
):
"""Generates a Chart from a set of features. Plots the value of one or more properties for each feature.
Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature
Args:
features (ee.FeatureCollection): The feature collection to generate a chart from.
xProperty (str): Features labeled by xProperty.
yProperties (list): Values of yProperties.
Raises:
Exception: Errors when creating the chart.
"""
bar = Feature_ByFeature(
features=features, xProperty=xProperty, yProperties=yProperties, **kwargs
)
try:
bar.plot_chart()
except Exception as e:
raise Exception(e) | Generates a Chart from a set of features. Plots the value of one or more properties for each feature. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature Args: features (ee.FeatureCollection): The feature collection to generate a chart from. xProperty (str): Features labeled by xProperty. yProperties (list): Values of yProperties. Raises: Exception: Errors when creating the chart. |
12,449 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
class Feature_ByProperty(BarChart):
"""A object to define variables and get_data method."""
def __init__(
self, features, xProperties, seriesProperty, name="feature.byProperty", **kwargs
):
default_labels = None
super().__init__(features, default_labels, name, **kwargs)
if "labels" in kwargs:
raise Exception("Please remove labels in kwargs and try again.")
self.labels = list(self.df[seriesProperty])
self.x_data, self.y_data = self.get_data(xProperties)
def get_data(self, xProperties):
if isinstance(xProperties, list):
x_data = xProperties
y_data = self.df[xProperties].values
elif isinstance(xProperties, dict):
x_data = list(xProperties.values())
y_data = self.df[list(xProperties.keys())].values
else:
raise Exception("xProperties must be a list or dictionary.")
return x_data, y_data
The provided code snippet includes necessary dependencies for implementing the `feature_byProperty` function. Write a Python function `def feature_byProperty( features: ee.FeatureCollection, xProperties: Union[list, dict], seriesProperty: str, **kwargs, )` to solve the following problem:
Generates a Chart from a set of features. Plots property values of one or more features. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty Args: features (ee.FeatureCollection): The features to include in the chart. xProperties (list | dict): One of (1) a list of properties to be plotted on the x-axis; or (2) a (property, label) dictionary specifying labels for properties to be used as values on the x-axis. seriesProperty (str): The name of the property used to label each feature in the legend. Raises: Exception: If the provided xProperties is not a list or dict. Exception: If the chart fails to create.
Here is the function:
def feature_byProperty(
features: ee.FeatureCollection,
xProperties: Union[list, dict],
seriesProperty: str,
**kwargs,
):
"""Generates a Chart from a set of features. Plots property values of one or more features.
Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty
Args:
features (ee.FeatureCollection): The features to include in the chart.
xProperties (list | dict): One of (1) a list of properties to be plotted on the x-axis; or
(2) a (property, label) dictionary specifying labels for properties to be used as values on the x-axis.
seriesProperty (str): The name of the property used to label each feature in the legend.
Raises:
Exception: If the provided xProperties is not a list or dict.
Exception: If the chart fails to create.
"""
bar = Feature_ByProperty(
features=features,
xProperties=xProperties,
seriesProperty=seriesProperty,
**kwargs,
)
try:
bar.plot_chart()
except Exception as e:
raise Exception(e) | Generates a Chart from a set of features. Plots property values of one or more features. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty Args: features (ee.FeatureCollection): The features to include in the chart. xProperties (list | dict): One of (1) a list of properties to be plotted on the x-axis; or (2) a (property, label) dictionary specifying labels for properties to be used as values on the x-axis. seriesProperty (str): The name of the property used to label each feature in the legend. Raises: Exception: If the provided xProperties is not a list or dict. Exception: If the chart fails to create. |
12,450 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
class Feature_Groups(BarChart):
"""A object to define variables and get_data method."""
def __init__(
self,
features,
xProperty,
yProperty,
seriesProperty,
name="feature.groups",
type="stacked",
**kwargs,
):
df = ee_to_df(features)
self.unique_series_values = df[seriesProperty].unique().tolist()
default_labels = [str(x) for x in self.unique_series_values]
self.yProperty = yProperty
super().__init__(features, default_labels, name, type, **kwargs)
self.new_column_names = self.get_column_names(seriesProperty, yProperty)
self.x_data, self.y_data = self.get_data(xProperty, self.new_column_names)
def get_column_names(self, seriesProperty, yProperty):
new_column_names = []
for value in self.unique_series_values:
sample_filter = (self.df[seriesProperty] == value).map({True: 1, False: 0})
column_name = str(yProperty) + "_" + str(value)
self.df[column_name] = self.df[yProperty] * sample_filter
new_column_names.append(column_name)
return new_column_names
def get_data(self, xProperty, new_column_names):
x_data = list(self.df[xProperty])
y_data = [self.df[x] for x in new_column_names]
return x_data, y_data
The provided code snippet includes necessary dependencies for implementing the `feature_groups` function. Write a Python function `def feature_groups(features, xProperty, yProperty, seriesProperty, **kwargs)` to solve the following problem:
Generates a Chart from a set of features. Plots the value of one property for each feature. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups Args: features (ee.FeatureCollection): The feature collection to make a chart from. xProperty (str): Features labeled by xProperty. yProperty (str): Features labeled by yProperty. seriesProperty (str): The property used to label each feature in the legend. Raises: Exception: Errors when creating the chart.
Here is the function:
def feature_groups(features, xProperty, yProperty, seriesProperty, **kwargs):
"""Generates a Chart from a set of features.
Plots the value of one property for each feature.
Reference:
https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups
Args:
features (ee.FeatureCollection): The feature collection to make a chart from.
xProperty (str): Features labeled by xProperty.
yProperty (str): Features labeled by yProperty.
seriesProperty (str): The property used to label each feature in the legend.
Raises:
Exception: Errors when creating the chart.
"""
bar = Feature_Groups(
features=features,
xProperty=xProperty,
yProperty=yProperty,
seriesProperty=seriesProperty,
**kwargs,
)
try:
bar.plot_chart()
except Exception as e:
raise Exception(e) | Generates a Chart from a set of features. Plots the value of one property for each feature. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups Args: features (ee.FeatureCollection): The feature collection to make a chart from. xProperty (str): Features labeled by xProperty. yProperty (str): Features labeled by yProperty. seriesProperty (str): The property used to label each feature in the legend. Raises: Exception: Errors when creating the chart. |
12,451 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
The provided code snippet includes necessary dependencies for implementing the `feature_histogram` function. Write a Python function `def feature_histogram( features, property, maxBuckets=None, minBucketWidth=None, show=True, **kwargs )` to solve the following problem:
Generates a Chart from a set of features. Computes and plots a histogram of the given property. - X-axis = Histogram buckets (of property value). - Y-axis = Frequency Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturehistogram Args: features (ee.FeatureCollection): The features to include in the chart. property (str): The name of the property to generate the histogram for. maxBuckets (int, optional): The maximum number of buckets (bins) to use when building a histogram; will be rounded up to a power of 2. minBucketWidth (float, optional): The minimum histogram bucket width, or null to allow any power of 2. show (bool, optional): Whether to show the chart. If not, it will return the bqplot chart object, which can be used to retrieve data for the chart. Defaults to True. Raises: Exception: If the provided xProperties is not a list or dict. Exception: If the chart fails to create.
Here is the function:
def feature_histogram(
features, property, maxBuckets=None, minBucketWidth=None, show=True, **kwargs
):
"""
Generates a Chart from a set of features.
Computes and plots a histogram of the given property.
- X-axis = Histogram buckets (of property value).
- Y-axis = Frequency
Reference:
https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturehistogram
Args:
features (ee.FeatureCollection): The features to include in the chart.
property (str): The name of the property to generate the histogram for.
maxBuckets (int, optional): The maximum number of buckets (bins) to use when building a histogram;
will be rounded up to a power of 2.
minBucketWidth (float, optional): The minimum histogram bucket width, or null to allow any power of 2.
show (bool, optional): Whether to show the chart. If not, it will return the bqplot chart object, which can be used to retrieve data for the chart. Defaults to True.
Raises:
Exception: If the provided xProperties is not a list or dict.
Exception: If the chart fails to create.
"""
import math
if not isinstance(features, ee.FeatureCollection):
raise Exception("features must be an ee.FeatureCollection")
first = features.first()
props = first.propertyNames().getInfo()
if property not in props:
raise Exception(
f"property {property} not found. Available properties: {', '.join(props)}"
)
def nextPowerOf2(n):
return pow(2, math.ceil(math.log2(n)))
def grow_bin(bin_size, ref):
while bin_size < ref:
bin_size *= 2
return bin_size
try:
raw_data = pd.to_numeric(
pd.Series(features.aggregate_array(property).getInfo())
)
y_data = raw_data.tolist()
if "ylim" in kwargs:
min_value = kwargs["ylim"][0]
max_value = kwargs["ylim"][1]
else:
min_value = raw_data.min()
max_value = raw_data.max()
data_range = max_value - min_value
if not maxBuckets:
initial_bin_size = nextPowerOf2(data_range / pow(2, 8))
if minBucketWidth:
if minBucketWidth < initial_bin_size:
bin_size = grow_bin(minBucketWidth, initial_bin_size)
else:
bin_size = minBucketWidth
else:
bin_size = initial_bin_size
else:
initial_bin_size = math.ceil(data_range / nextPowerOf2(maxBuckets))
if minBucketWidth:
if minBucketWidth < initial_bin_size:
bin_size = grow_bin(minBucketWidth, initial_bin_size)
else:
bin_size = minBucketWidth
else:
bin_size = initial_bin_size
start_bins = (math.floor(min_value / bin_size) * bin_size) - (bin_size / 2)
end_bins = (math.ceil(max_value / bin_size) * bin_size) + (bin_size / 2)
if start_bins < min_value:
y_data.append(start_bins)
else:
y_data[y_data.index(min_value)] = start_bins
if end_bins > max_value:
y_data.append(end_bins)
else:
y_data[y_data.index(max_value)] = end_bins
num_bins = math.floor((end_bins - start_bins) / bin_size)
if "title" not in kwargs:
title = ""
else:
title = kwargs["title"]
fig = plt.figure(title=title)
if "width" in kwargs:
fig.layout.width = kwargs["width"]
if "height" in kwargs:
fig.layout.height = kwargs["height"]
if "xlabel" not in kwargs:
xlabel = ""
else:
xlabel = kwargs["xlabel"]
if "ylabel" not in kwargs:
ylabel = ""
else:
ylabel = kwargs["ylabel"]
histogram = plt.hist(
sample=y_data,
bins=num_bins,
axes_options={"count": {"label": ylabel}, "sample": {"label": xlabel}},
)
if "colors" in kwargs:
histogram.colors = kwargs["colors"]
if "stroke" in kwargs:
histogram.stroke = kwargs["stroke"]
else:
histogram.stroke = "#ffffff00"
if "stroke_width" in kwargs:
histogram.stroke_width = kwargs["stroke_width"]
else:
histogram.stroke_width = 0
if ("xlabel" in kwargs) and ("ylabel" in kwargs):
histogram.tooltip = Tooltip(
fields=["midpoint", "count"],
labels=[kwargs["xlabel"], kwargs["ylabel"]],
)
else:
histogram.tooltip = Tooltip(fields=["midpoint", "count"])
if show:
plt.show()
else:
return histogram
except Exception as e:
raise Exception(e) | Generates a Chart from a set of features. Computes and plots a histogram of the given property. - X-axis = Histogram buckets (of property value). - Y-axis = Frequency Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturehistogram Args: features (ee.FeatureCollection): The features to include in the chart. property (str): The name of the property to generate the histogram for. maxBuckets (int, optional): The maximum number of buckets (bins) to use when building a histogram; will be rounded up to a power of 2. minBucketWidth (float, optional): The minimum histogram bucket width, or null to allow any power of 2. show (bool, optional): Whether to show the chart. If not, it will return the bqplot chart object, which can be used to retrieve data for the chart. Defaults to True. Raises: Exception: If the provided xProperties is not a list or dict. Exception: If the chart fails to create. |
12,452 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_byClass(
image, classBand, region, reducer, scale, classLabels, xLabels, **kwargs
):
# TODO
pass | null |
12,453 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_byRegion(image, regions, reducer, scale, xProperty, **kwargs):
# TODO
pass | null |
12,454 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_doySeries(
imageCollection,
region,
regionReducer,
scale,
yearReducer,
startDay,
endDay,
**kwargs,
):
# TODO
pass | null |
12,455 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_doySeriesByRegion(
imageCollection,
bandName,
regions,
regionReducer,
scale,
yearReducer,
seriesProperty,
startDay,
endDay,
**kwargs,
):
# TODO
pass | null |
12,456 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_doySeriesByYear(
imageCollection,
bandName,
region,
regionReducer,
scale,
sameDayReducer,
startDay,
endDay,
**kwargs,
):
# TODO
pass | null |
12,457 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_histogram(
image, region, scale, maxBuckets, minBucketWidth, maxRaw, maxPixels, **kwargs
):
# TODO
pass | null |
12,458 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_regions(image, regions, reducer, scale, seriesProperty, xLabels, **kwargs):
# TODO
pass | null |
12,459 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_series(imageCollection, region, reducer, scale, xProperty, **kwargs):
# TODO
pass | null |
12,460 | import ee
import pandas as pd
import numpy as np
from bqplot import Tooltip
from bqplot import pyplot as plt
from .common import ee_to_df, zonal_stats
from typing import Union
def image_seriesByRegion(
imageCollection, regions, reducer, band, scale, xProperty, seriesProperty, **kwargs
):
# TODO
pass | null |
12,461 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
The provided code snippet includes necessary dependencies for implementing the `tool_template` function. Write a Python function `def tool_template(m=None, opened=True)` to solve the following problem:
Create a toolbar widget. Args: m (geemap.Map, optional): The geemap.Map instance. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True.
Here is the function:
def tool_template(m=None, opened=True):
"""Create a toolbar widget.
Args:
m (geemap.Map, optional): The geemap.Map instance. Defaults to None.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
"""
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gear",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
checkbox = widgets.Checkbox(
description="Checkbox",
indent=False,
layout=widgets.Layout(padding=padding, width=widget_width),
)
dropdown = widgets.Dropdown(
options=["Option 1", "Option 2", "Option 3"],
value=None,
description="Dropdown:",
layout=widgets.Layout(width=widget_width, padding=padding),
style={"description_width": "initial"},
)
int_slider = widgets.IntSlider(
min=1,
max=100,
description="Int Slider: ",
readout=False,
continuous_update=True,
layout=widgets.Layout(width="220px", padding=padding),
style={"description_width": "initial"},
)
int_slider_label = widgets.Label(str(int_slider.value))
def update_int_slider(change):
int_slider_label.value = str(change["new"])
int_slider.observe(update_int_slider, "value")
float_slider = widgets.FloatSlider(
min=1,
max=100,
description="Float Slider: ",
readout=False,
continuous_update=True,
layout=widgets.Layout(width="210px", padding=padding),
style={"description_width": "initial"},
)
float_slider_label = widgets.Label(str(float_slider.value))
def update_float_slider(change):
float_slider_label.value = str(change["new"])
float_slider.observe(update_float_slider, "value")
color = widgets.ColorPicker(
concise=False,
description="Color:",
value="white",
style={"description_width": "initial"},
layout=widgets.Layout(width=widget_width, padding=padding),
)
text = widgets.Text(
value="",
description="Textbox:",
placeholder="Placeholder",
style={"description_width": "initial"},
layout=widgets.Layout(width=widget_width, padding=padding),
)
textarea = widgets.Textarea(
placeholder="Placeholder",
layout=widgets.Layout(width=widget_width, padding=padding),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
checkbox,
widgets.HBox([int_slider, int_slider_label]),
widgets.HBox([float_slider, float_slider_label]),
dropdown,
text,
color,
textarea,
buttons,
output,
]
# toolbar_event = ipyevents.Event(
# source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
# )
# def handle_toolbar_event(event):
# if event["type"] == "mouseenter":
# toolbar_widget.children = [toolbar_header, toolbar_footer]
# elif event["type"] == "mouseleave":
# if not toolbar_button.value:
# toolbar_widget.children = [toolbar_button]
# toolbar_button.value = False
# close_button.value = False
# toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Apply":
with output:
output.outputs = ()
print("Running ...")
elif change["new"] == "Reset":
textarea.value = ""
output.outputs = ()
elif change["new"] == "Close":
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = opened
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
else:
return toolbar_widget | Create a toolbar widget. Args: m (geemap.Map, optional): The geemap.Map instance. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. |
12,462 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
The provided code snippet includes necessary dependencies for implementing the `tool_header_template` function. Write a Python function `def tool_header_template(m=None, opened=True, show_close_button=True)` to solve the following problem:
Create a toolbar widget. Args: m (geemap.Map, optional): The geemap.Map instance. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. show_close_button (bool, optional): Whether to show the close button. Defaults to True.
Here is the function:
def tool_header_template(m=None, opened=True, show_close_button=True):
"""Create a toolbar widget.
Args:
m (geemap.Map, optional): The geemap.Map instance. Defaults to None.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gear",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
if show_close_button:
toolbar_header.children = [close_button, toolbar_button]
else:
toolbar_header.children = [toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
buttons,
output,
]
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Apply":
with output:
output.outputs = ()
print("Running ...")
elif change["new"] == "Reset":
output.outputs = ()
elif change["new"] == "Close":
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = opened
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
else:
return toolbar_widget | Create a toolbar widget. Args: m (geemap.Map, optional): The geemap.Map instance. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. show_close_button (bool, optional): Whether to show the close button. Defaults to True. |
12,463 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def split_basemaps(
m, layers_dict=None, left_name=None, right_name=None, width="120px", **kwargs
):
from .geemap import basemaps
controls = m.controls
layers = m.layers
m.layers = [m.layers[0]]
m.clear_controls()
add_zoom = True
add_fullscreen = True
if layers_dict is None:
layers_dict = {}
keys = dict(basemaps).keys()
for key in keys:
if isinstance(basemaps[key], ipyleaflet.WMSLayer):
pass
else:
layers_dict[key] = basemaps[key]
keys = list(layers_dict.keys())
if left_name is None:
left_name = keys[0]
if right_name is None:
right_name = keys[-1]
left_layer = layers_dict[left_name]
right_layer = layers_dict[right_name]
control = ipyleaflet.SplitMapControl(left_layer=left_layer, right_layer=right_layer)
m.add_control(control)
m.dragging = False
left_dropdown = widgets.Dropdown(
options=keys, value=left_name, layout=widgets.Layout(width=width)
)
left_control = ipyleaflet.WidgetControl(widget=left_dropdown, position="topleft")
m.add_control(left_control)
right_dropdown = widgets.Dropdown(
options=keys, value=right_name, layout=widgets.Layout(width=width)
)
right_control = ipyleaflet.WidgetControl(widget=right_dropdown, position="topright")
m.add_control(right_control)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
# button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
def close_btn_click(change):
if change["new"]:
m.controls = controls
m.layers = layers
close_button.observe(close_btn_click, "value")
close_control = ipyleaflet.WidgetControl(
widget=close_button, position="bottomright"
)
m.add_control(close_control)
if add_zoom:
m.add_control(ipyleaflet.ZoomControl())
if add_fullscreen:
m.add_control(ipyleaflet.FullScreenControl())
m.add_control(ipyleaflet.ScaleControl(position="bottomleft"))
split_control = None
for ctrl in m.controls:
if isinstance(ctrl, ipyleaflet.SplitMapControl):
split_control = ctrl
break
def left_change(change):
split_control.left_layer.url = layers_dict[left_dropdown.value].url
left_dropdown.observe(left_change, "value")
def right_change(change):
split_control.right_layer.url = layers_dict[right_dropdown.value].url
right_dropdown.observe(right_change, "value")
def planet_tiles(api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"):
"""Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
catalog = {}
quarterly = planet_quarterly_tiles(api_key, token_name, tile_format)
monthly = planet_monthly_tiles(api_key, token_name, tile_format)
for key in quarterly:
catalog[key] = quarterly[key]
for key in monthly:
catalog[key] = monthly[key]
return catalog
def _split_basemaps_tool_callback(map, selected, _):
if selected:
try:
split_basemaps(map, layers_dict=planet_tiles())
except Exception as e:
print(e)
return | null |
12,464 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def _open_help_page_callback(map, selected, _):
del map
if selected:
import webbrowser
webbrowser.open_new_tab("https://geemap.org") | null |
12,465 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
The provided code snippet includes necessary dependencies for implementing the `_cleanup_toolbar_item` function. Write a Python function `def _cleanup_toolbar_item(func)` to solve the following problem:
Wraps a toolbar item callback to clean up the widget when unselected.
Here is the function:
def _cleanup_toolbar_item(func):
"""Wraps a toolbar item callback to clean up the widget when unselected."""
# The callback should construct the widget and return an object that
# contains a "cleanup" property, a function that removes the widget from the
# map. The decorator will handle construction and cleanup, and will also
# un-toggle the associated toolbar item.
def wrapper(map, selected, item):
if selected:
item.control = func(map, selected, item)
if not hasattr(item.control, "toggle_off"):
setattr(item.control, "toggle_off", item.toggle_off)
if hasattr(item.control, "cleanup"):
cleanup = item.control.cleanup
def cleanup_and_toggle_off():
cleanup()
item.toggle_off()
# Ensures that when cleanup() is invoked on the widget, for
# example by a close button on the widget, the toggle is
# also turned off.
item.control.cleanup = cleanup_and_toggle_off
elif item.control and hasattr(item.control, "cleanup"):
item.control.cleanup()
return wrapper | Wraps a toolbar item callback to clean up the widget when unselected. |
12,466 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def _inspector_tool_callback(map, selected, item):
del selected, item # Unused.
map.add_inspector()
return map._inspector | null |
12,467 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def ee_plot_gui(m, position="topright", **kwargs):
def _plotting_tool_callback(map, selected, item):
del selected, item # Unused.
ee_plot_gui(map)
return map._plot_dropdown_control | null |
12,468 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def timelapse_gui(m=None):
def _timelapse_tool_callback(map, selected, item):
del selected, item # Unused.
timelapse_gui(map)
return map.tool_control | null |
12,469 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def convert_js2py(m):
"""A widget for converting Earth Engine JavaScript to Python.
Args:
m (object): geemap.Map
"""
full_widget = widgets.VBox(layout=widgets.Layout(width="465px", height="350px"))
text_widget = widgets.Textarea(
placeholder="Paste your Earth Engine JavaScript into this textbox and click the Convert button below to convert the Javascript to Python",
layout=widgets.Layout(width="455px", height="310px"),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Convert", "Clear", "Close"],
tooltips=["Convert", "Clear", "Close"],
button_style="primary",
)
buttons.style.button_width = "128px"
def cleanup():
if m._convert_ctrl is not None and m._convert_ctrl in m.controls:
m.remove_control(m._convert_ctrl)
full_widget.close()
def button_clicked(change):
if change["new"] == "Convert":
from .conversion import create_new_cell, js_snippet_to_py
if len(text_widget.value) > 0:
out_lines = js_snippet_to_py(
text_widget.value,
add_new_cell=False,
import_ee=False,
import_geemap=False,
show_map=False,
)
if len(out_lines) > 0 and len(out_lines[0].strip()) == 0:
out_lines = out_lines[1:]
prefix = "# The code has been copied to the clipboard. \n# Press Ctrl+V to in a code cell to paste it.\n"
text_widget.value = "".join([prefix] + out_lines)
create_code_cell("".join(out_lines))
elif change["new"] == "Clear":
text_widget.value = ""
elif change["new"] == "Close":
m._convert_ctrl.cleanup()
buttons.value = None
buttons.observe(button_clicked, "value")
full_widget.children = [text_widget, buttons]
widget_control = ipyleaflet.WidgetControl(widget=full_widget, position="topright")
widget_control.cleanup = cleanup
m.add_control(widget_control)
m._convert_ctrl = widget_control
def _convert_js_tool_callback(map, selected, item):
del selected, item # Unused.
convert_js2py(map)
return map._convert_ctrl | null |
12,470 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def _basemap_tool_callback(map, selected, item):
del selected, item # Unused.
map.add_basemap_widget()
return map._basemap_selector | null |
12,471 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def open_data_widget(m):
"""A widget for opening local vector/raster data.
Args:
m (object): geemap.Map
"""
padding = "0px 0px 0px 5px"
style = {"description_width": "initial"}
tool_output = widgets.Output()
tool_output_ctrl = ipyleaflet.WidgetControl(widget=tool_output, position="topright")
if (
hasattr(m, "_tool_output_ctrl")
and m._tool_output_ctrl is not None
and m._tool_output_ctrl in m.controls
):
m.remove_control(m._tool_output_ctrl)
file_type = widgets.ToggleButtons(
options=["Shapefile", "GeoJSON", "CSV", "Vector", "Raster"],
tooltips=[
"Open a shapefile",
"Open a GeoJSON file",
"Open a vector dataset",
"Create points from CSV",
"Open a vector dataset",
"Open a raster dataset",
],
)
file_type.style.button_width = "88px"
filepath = widgets.Text(
value="",
description="File path or http URL:",
tooltip="Enter a file path or http URL to vector data",
style=style,
layout=widgets.Layout(width="454px", padding=padding),
)
http_widget = widgets.HBox()
file_chooser = FileChooser(
os.getcwd(), sandbox_path=m.sandbox_path, layout=widgets.Layout(width="454px")
)
file_chooser.filter_pattern = "*.shp"
file_chooser.use_dir_icons = True
style = {"description_width": "initial"}
layer_name = widgets.Text(
value="Shapefile",
description="Enter a layer name:",
tooltip="Enter a layer name for the selected file",
style=style,
layout=widgets.Layout(width="454px", padding="0px 0px 0px 5px"),
)
longitude = widgets.Dropdown(
options=[],
value=None,
description="Longitude:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
latitude = widgets.Dropdown(
options=[],
value=None,
description="Latitude:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
label = widgets.Dropdown(
options=[],
value=None,
description="Label:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
csv_widget = widgets.HBox()
convert_bool = widgets.Checkbox(
description="Convert to ee.FeatureCollection?",
indent=False,
layout=widgets.Layout(padding="0px 0px 0px 5px"),
)
convert_hbox = widgets.HBox([convert_bool])
ok_cancel = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
# ok_cancel.style.button_width = "133px"
bands = widgets.Text(
value=None,
description="Band:",
tooltip="Enter a list of band indices",
style=style,
layout=widgets.Layout(width="150px", padding=padding),
)
vmin = widgets.Text(
value=None,
description="vmin:",
tooltip="Minimum value of the raster to visualize",
style=style,
layout=widgets.Layout(width="148px"),
)
vmax = widgets.Text(
value=None,
description="vmax:",
tooltip="Maximum value of the raster to visualize",
style=style,
layout=widgets.Layout(width="148px"),
)
nodata = widgets.Text(
value=None,
description="Nodata:",
tooltip="Nodata the raster to visualize",
style=style,
layout=widgets.Layout(width="150px", padding=padding),
)
palette = widgets.Dropdown(
options=[],
value=None,
description="palette:",
layout=widgets.Layout(width="300px"),
style=style,
)
raster_options = widgets.VBox()
main_widget = widgets.VBox(
[
file_type,
file_chooser,
http_widget,
csv_widget,
layer_name,
convert_hbox,
raster_options,
ok_cancel,
]
)
tool_output.outputs = ()
with tool_output:
display(main_widget)
def bands_changed(change):
if change["new"] and "," in change["owner"].value:
palette.value = None
palette.disabled = True
else:
palette.disabled = False
bands.observe(bands_changed, "value")
def chooser_callback(chooser):
filepath.value = file_chooser.selected
if file_type.value == "CSV":
import pandas as pd
df = pd.read_csv(filepath.value)
col_names = df.columns.values.tolist()
longitude.options = col_names
latitude.options = col_names
label.options = col_names
if "longitude" in col_names:
longitude.value = "longitude"
if "latitude" in col_names:
latitude.value = "latitude"
if "name" in col_names:
label.value = "name"
file_chooser.register_callback(chooser_callback)
def file_type_changed(change):
ok_cancel.value = None
file_chooser.default_path = os.getcwd()
file_chooser.reset()
layer_name.value = file_type.value
csv_widget.children = []
filepath.value = ""
if change["new"] == "Shapefile":
file_chooser.filter_pattern = "*.shp"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = []
elif change["new"] == "GeoJSON":
file_chooser.filter_pattern = "*.geojson"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "Vector":
file_chooser.filter_pattern = "*.*"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "CSV":
file_chooser.filter_pattern = ["*.csv", "*.CSV"]
csv_widget.children = [longitude, latitude, label]
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "Raster":
if not hasattr(m, "_colormaps"):
from .colormaps import list_colormaps
m._colormaps = list_colormaps(add_extra=True)
file_chooser.filter_pattern = ["*.tif", "*.img"]
palette.options = m._colormaps
palette.value = None
raster_options.children = [
widgets.HBox([bands, vmin, vmax]),
widgets.HBox([nodata, palette]),
]
convert_hbox.children = []
http_widget.children = [filepath]
def cleanup():
if (
hasattr(m, "_tool_output_ctrl")
and m._tool_output_ctrl is not None
and m._tool_output_ctrl in m.controls
):
m.remove_control(m._tool_output_ctrl)
m._tool_output_ctrl = None
tool_output_ctrl.cleanup = cleanup
def ok_cancel_clicked(change):
if change["new"] == "Apply":
m.default_style = {"cursor": "wait"}
file_path = filepath.value
if file_path is not None:
ext = os.path.splitext(file_path)[1]
with tool_output:
if ext.lower() == ".shp":
if convert_bool.value:
ee_object = shp_to_ee(file_path)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_shapefile(
file_path, style={}, layer_name=layer_name.value
)
elif ext.lower() == ".geojson":
if convert_bool.value:
ee_object = geojson_to_ee(file_path)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_geojson(
file_path, style={}, layer_name=layer_name.value
)
elif ext.lower() == ".csv":
if convert_bool.value:
ee_object = csv_to_ee(
file_path, latitude.value, longitude.value
)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_xy_data(
file_path,
x=longitude.value,
y=latitude.value,
label=label.value,
layer_name=layer_name.value,
)
elif ext.lower() in [".tif", "img"] and file_type.value == "Raster":
band = None
vis_min = None
vis_max = None
vis_nodata = None
try:
if len(bands.value) > 0:
band = bands.value.split(",")
if len(vmin.value) > 0:
vis_min = float(vmin.value)
if len(vmax.value) > 0:
vis_max = float(vmax.value)
if len(nodata.value) > 0:
vis_nodata = float(nodata.value)
except Exception as _:
pass
m.add_raster(
file_path,
layer_name=layer_name.value,
band=band,
palette=palette.value,
vmin=vis_min,
vmax=vis_max,
nodata=vis_nodata,
)
else:
m.add_vector(file_path, style={}, layer_name=layer_name.value)
else:
print("Please select a file to open.")
m.default_style = {"cursor": "default"}
elif change["new"] == "Reset":
file_chooser.reset()
tool_output.outputs = ()
with tool_output:
display(main_widget)
elif change["new"] == "Close":
tool_output_ctrl.cleanup()
ok_cancel.value = None
file_type.observe(file_type_changed, names="value")
ok_cancel.observe(ok_cancel_clicked, names="value")
# file_chooser.register_callback(chooser_callback)
m.add_control(tool_output_ctrl)
m._tool_output_ctrl = tool_output_ctrl
def _open_data_tool_callback(map, selected, item):
del selected, item # Unused.
open_data_widget(map)
return map._tool_output_ctrl | null |
12,472 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def build_toolbox(tools_dict, max_width="1080px", max_height="600px"):
def _whitebox_tool_callback(map, selected, item):
del selected, item # Unused.
import whiteboxgui.whiteboxgui as wbt
tools_dict = wbt.get_wbt_dict()
wbt_toolbox = wbt.build_toolbox(
tools_dict,
max_width="800px",
max_height="500px",
sandbox_path=map.sandbox_path,
)
wbt_control = ipyleaflet.WidgetControl(widget=wbt_toolbox, position="bottomright")
setattr(wbt_control, "cleanup", lambda: map.remove_control(wbt_control))
map.whitebox = wbt_control
map.add(wbt_control)
return wbt_control | null |
12,473 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def get_tools_dict():
import pandas as pd
import pkg_resources
pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py"))
toolbox_csv = os.path.join(pkg_dir, "data/template/toolbox.csv")
df = pd.read_csv(toolbox_csv).set_index("index")
tools_dict = df.to_dict("index")
return tools_dict
def build_toolbox(tools_dict, max_width="1080px", max_height="600px"):
"""Build the GEE toolbox.
Args:
tools_dict (dict): A dictionary containing information for all tools.
max_width (str, optional): The maximum width of the widget.
max_height (str, optional): The maximum height of the widget.
Returns:
object: An ipywidget representing the toolbox.
"""
left_widget = widgets.VBox(layout=widgets.Layout(min_width="175px"))
center_widget = widgets.VBox(
layout=widgets.Layout(min_width="200px", max_width="200px")
)
right_widget = widgets.Output(
layout=widgets.Layout(width="630px", max_height=max_height)
)
full_widget = widgets.HBox(
[left_widget, center_widget, right_widget],
layout=widgets.Layout(max_width=max_width, max_height=max_height),
)
search_widget = widgets.Text(
placeholder="Search tools ...", layout=widgets.Layout(width="170px")
)
label_widget = widgets.Label(layout=widgets.Layout(width="170px"))
label_widget.value = f"{len(tools_dict)} Available Tools"
close_btn = widgets.Button(
description="Close Toolbox", icon="close", layout=widgets.Layout(width="170px")
)
categories = {}
categories["All Tools"] = []
for key in tools_dict.keys():
category = tools_dict[key]["category"]
if category not in categories.keys():
categories[category] = []
categories[category].append(tools_dict[key]["name"])
categories["All Tools"].append(tools_dict[key]["name"])
options = list(categories.keys())
all_tools = categories["All Tools"]
all_tools.sort()
category_widget = widgets.Select(
options=options, layout=widgets.Layout(width="170px", height="165px")
)
tools_widget = widgets.Select(
options=[], layout=widgets.Layout(width="195px", height="400px")
)
def category_selected(change):
if change["new"]:
selected = change["owner"].value
options = categories[selected]
options.sort()
tools_widget.options = options
label_widget.value = f"{len(options)} Available Tools"
category_widget.observe(category_selected, "value")
def tool_selected(change):
if change["new"]:
selected = change["owner"].value
tool_dict = tools_dict[selected]
with right_widget:
right_widget.outputs = ()
display(tool_gui(tool_dict, max_height=max_height))
tools_widget.observe(tool_selected, "value")
def search_changed(change):
if change["new"]:
keyword = change["owner"].value
if len(keyword) > 0:
selected_tools = []
for tool in all_tools:
if keyword.lower() in tool.lower():
selected_tools.append(tool)
if len(selected_tools) > 0:
tools_widget.options = selected_tools
label_widget.value = f"{len(selected_tools)} Available Tools"
else:
tools_widget.options = all_tools
label_widget.value = f"{len(tools_dict)} Available Tools"
search_widget.observe(search_changed, "value")
def cleanup():
full_widget.close()
full_widget.cleanup = cleanup
def close_btn_clicked(b):
full_widget.cleanup()
close_btn.on_click(close_btn_clicked)
category_widget.value = list(categories.keys())[0]
tools_widget.options = all_tools
left_widget.children = [category_widget, search_widget, label_widget, close_btn]
center_widget.children = [tools_widget]
return full_widget
def _gee_toolbox_tool_callback(map, selected, item):
del selected, item # Unused.
tools_dict = get_tools_dict()
gee_toolbox = build_toolbox(tools_dict, max_width="800px", max_height="500px")
geetoolbox_control = ipyleaflet.WidgetControl(
widget=gee_toolbox, position="bottomright"
)
map.geetoolbox = geetoolbox_control
map.add(geetoolbox_control)
return gee_toolbox | null |
12,474 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def time_slider(m=None):
def _time_slider_tool_callback(map, selected, item):
del selected, item # Unused.
time_slider(map)
return map.tool_control | null |
12,475 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def collect_samples(m):
full_widget = widgets.VBox()
layout = widgets.Layout(width="100px")
prop_label = widgets.Label(
value="Property",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
value_label = widgets.Label(
value="Value",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
color_label = widgets.Label(
value="Color",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
prop_text1 = widgets.Text(layout=layout, placeholder="Required")
value_text1 = widgets.Text(layout=layout, placeholder="Integer")
prop_text2 = widgets.Text(layout=layout, placeholder="Optional")
value_text2 = widgets.Text(layout=layout, placeholder="String")
color = widgets.ColorPicker(
concise=False,
value="#3388ff",
layout=layout,
style={"description_width": "initial"},
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Clear", "Close"],
tooltips=["Apply", "Clear", "Close"],
button_style="primary",
)
buttons.style.button_width = "99px"
old_draw_control = m.get_draw_control()
def cleanup():
if m.training_ctrl is not None and m.training_ctrl in m.controls:
m.remove_control(m.training_ctrl)
full_widget.close()
# Restore default draw control.
if old_draw_control:
old_draw_control.open()
m.substitute(m.get_draw_control(), old_draw_control)
else:
m.remove_draw_control()
def button_clicked(change):
if change["new"] == "Apply":
if len(color.value) != 7:
color.value = "#3388ff"
m.remove_draw_control()
m.add(
"draw_control",
position="topleft",
marker={"shapeOptions": {"color": color.value}, "repeatMode": False},
rectangle={"shapeOptions": {"color": color.value}, "repeatMode": False},
polygon={"shapeOptions": {"color": color.value}, "repeatMode": False},
circlemarker={},
polyline={},
edit=False,
remove=False,
)
draw_control = m.get_draw_control()
train_props = {}
if prop_text1.value != "" and value_text1.value != "":
try:
_ = int(value_text1.value)
except Exception as _:
value_text1.placeholder = "Integer only"
value_text1.value = ""
return
train_props[prop_text1.value] = int(value_text1.value)
if prop_text2.value != "" and value_text2.value != "":
train_props[prop_text2.value] = value_text2.value
if color.value != "":
train_props["color"] = color.value
# Handles draw events
def set_properties(_, geometry):
if len(train_props) > 0:
draw_control.set_geometry_properties(geometry, train_props)
draw_control.on_geometry_create(set_properties)
elif change["new"] == "Clear":
prop_text1.value = ""
value_text1.value = ""
prop_text2.value = ""
value_text2.value = ""
color.value = "#3388ff"
elif change["new"] == "Close":
m.training_ctrl.cleanup()
buttons.value = None
buttons.observe(button_clicked, "value")
full_widget.children = [
widgets.HBox([prop_label, value_label, color_label]),
widgets.HBox([prop_text1, value_text1, color]),
widgets.HBox([prop_text2, value_text2, color]),
buttons,
]
widget_control = ipyleaflet.WidgetControl(widget=full_widget, position="topright")
widget_control.cleanup = cleanup
m.add_control(widget_control)
m.training_ctrl = widget_control
def _collect_samples_tool_callback(map, selected, item):
del selected, item # Unused.
collect_samples(map)
return map.training_ctrl | null |
12,476 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def plot_transect(m=None):
def _plot_transect_tool_callback(map, selected, item):
del selected, item # Unused.
plot_transect(map)
return map.tool_control | null |
12,477 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def sankee_gui(m=None):
import sankee
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="random",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
region = widgets.Dropdown(
options=["User-drawn ROI"],
value="User-drawn ROI",
description="Region:",
layout=widgets.Layout(width=widget_width, padding=padding),
style={"description_width": "initial"},
)
def region_changed(change):
if change["new"] == "Las Vegas":
if m is not None:
las_vegas = ee.Geometry.Polygon(
[
[
[-115.01184401606046, 36.24170785506492],
[-114.98849806879484, 36.29928186470082],
[-115.25628981684171, 36.35238941394592],
[-115.34692702387296, 36.310348922031565],
[-115.37988600824796, 36.160811202271944],
[-115.30298171137296, 36.03653336474891],
[-115.25628981684171, 36.05207884201088],
[-115.26590285395109, 36.226199908103695],
[-115.19174513910734, 36.25499793268206],
]
]
)
m.addLayer(las_vegas, {}, "Las Vegas")
m.centerObject(las_vegas, 10)
region.observe(region_changed, "value")
sankee_datasets = [
sankee.datasets.NLCD,
sankee.datasets.MODIS_LC_TYPE1,
sankee.datasets.CGLS_LC100,
sankee.datasets.LCMS_LU,
sankee.datasets.LCMS_LC,
]
dataset_options = {dataset.name: dataset for dataset in sankee_datasets}
default_dataset = sankee_datasets[0]
dataset = widgets.Dropdown(
options=dataset_options.keys(),
value=default_dataset.name,
description="Dataset:",
layout=widgets.Layout(width=widget_width, padding=padding),
style={"description_width": "initial"},
)
before = widgets.Dropdown(
options=default_dataset.years,
value=default_dataset.years[0],
description="Before:",
layout=widgets.Layout(width="123px", padding=padding),
style={"description_width": "initial"},
)
after = widgets.Dropdown(
options=default_dataset.years,
value=default_dataset.years[-1],
description="After:",
layout=widgets.Layout(width="123px", padding=padding),
style={"description_width": "initial"},
)
def dataset_changed(change):
selected = dataset_options[change["new"]]
before.options = selected.years
after.options = selected.years
before.value = selected.years[0]
after.value = selected.years[-1]
dataset.observe(dataset_changed, "value")
samples = widgets.IntText(
value=1000,
description="Samples:",
placeholder="The number of samples points to randomly generate for characterizing all images",
style={"description_width": "initial"},
layout=widgets.Layout(width="133px", padding=padding),
)
classes = widgets.IntText(
value=6,
description="Classes:",
style={"description_width": "initial"},
layout=widgets.Layout(width="113px", padding=padding),
)
title = widgets.Text(
value="Land Cover Change",
description="Title:",
style={"description_width": "initial"},
layout=widgets.Layout(width=widget_width, padding=padding),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(padding=padding))
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
region,
dataset,
widgets.HBox([before, after]),
widgets.HBox([samples, classes]),
title,
buttons,
output,
]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
if m is not None:
if "Las Vegas" not in m.ee_vector_layers.keys():
region.options = ["User-drawn ROI", "Las Vegas"] + list(
m.ee_vector_layers.keys()
)
else:
region.options = ["User-drawn ROI"] + list(m.ee_vector_layers.keys())
plot_close_btn = widgets.Button(
tooltip="Close the plot",
icon="times",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 0px"
),
)
def plot_close_btn_clicked(b):
plot_widget.children = []
plot_close_btn.on_click(plot_close_btn_clicked)
plot_reset_btn = widgets.Button(
tooltip="Reset the plot",
icon="home",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 0px"
),
)
def plot_reset_btn_clicked(b):
m.sankee_plot.update_layout(
width=600,
height=250,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
plot_reset_btn.on_click(plot_reset_btn_clicked)
plot_fullscreen_btn = widgets.Button(
tooltip="Fullscreen the plot",
icon="arrows-alt",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 0px"
),
)
def plot_fullscreen_btn_clicked(b):
m.sankee_plot.update_layout(
width=1030,
height=int(m.layout.height[:-2]) - 60,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
plot_fullscreen_btn.on_click(plot_fullscreen_btn_clicked)
width_btn = widgets.Button(
tooltip="Change plot width",
icon="arrows-h",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 0px"
),
)
def width_btn_clicked(b):
m.sankee_plot.update_layout(
width=1030,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
width_btn.on_click(width_btn_clicked)
height_btn = widgets.Button(
tooltip="Change plot height",
icon="arrows-v",
layout=widgets.Layout(
height="28px", width="28px", padding="0px 0px 0px 0px"
),
)
def height_btn_clicked(b):
m.sankee_plot.update_layout(
height=int(m.layout.height[:-2]) - 60,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
height_btn.on_click(height_btn_clicked)
width_slider = widgets.IntSlider(
value=600,
min=400,
max=1030,
step=10,
description="",
readout=False,
continuous_update=False,
layout=widgets.Layout(width="100px", padding=padding),
style={"description_width": "initial"},
)
width_slider_label = widgets.Label(
"600", layout=widgets.Layout(padding="0px 10px 0px 0px")
)
jslink_slider_label(width_slider, width_slider_label)
def width_changed(change):
if change["new"]:
m.sankee_plot.update_layout(
width=width_slider.value,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
width_slider.observe(width_changed, "value")
height_slider = widgets.IntSlider(
value=250,
min=200,
max=int(m.layout.height[:-2]) - 60,
step=10,
description="",
readout=False,
continuous_update=False,
layout=widgets.Layout(width="100px", padding=padding),
style={"description_width": "initial"},
)
height_slider_label = widgets.Label("250")
jslink_slider_label(height_slider, height_slider_label)
def height_changed(change):
if change["new"]:
m.sankee_plot.update_layout(
height=height_slider.value,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
with plot_output:
plot_output.outputs = ()
display(m.sankee_plot)
height_slider.observe(height_changed, "value")
plot_output = widgets.Output()
plot_widget = widgets.VBox([plot_output])
sankee_control = ipyleaflet.WidgetControl(
widget=plot_widget, position="bottomright"
)
m.add_control(sankee_control)
m.sankee_control = sankee_control
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
close_button.value = False
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def cleanup():
toolbar_button.value = False
if m is not None:
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
if m.sankee_control is not None and m.sankee_control in m.controls:
m.remove_control(m.sankee_control)
m.sankee_control = None
toolbar_widget.close()
def close_btn_click(change):
if change["new"]:
m.tool_control.cleanup()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Apply":
with output:
output.outputs = ()
plot_output.outputs = ()
print("Running ...")
if m is not None:
selected = dataset_options[dataset.value]
before_year = before.value
after_year = after.value
image1 = selected.get_year(before_year)
image2 = selected.get_year(after_year)
if region.value != "User-drawn ROI" or (
region.value == "User-drawn ROI" and m.user_roi is not None
):
if region.value == "User-drawn ROI":
geom = m.user_roi
image1 = image1.clip(geom)
image2 = image2.clip(geom)
else:
roi_object = m.ee_layers[region.value]["ee_object"]
if region.value == "Las Vegas":
m.centerObject(roi_object, 10)
if isinstance(roi_object, ee.Geometry):
geom = roi_object
image1 = image1.clip(geom)
image2 = image2.clip(geom)
else:
roi_object = ee.FeatureCollection(roi_object)
image1 = image1.clipToCollection(roi_object)
image2 = image2.clipToCollection(roi_object)
geom = roi_object.geometry()
if len(title.value) > 0:
plot_title = title.value
else:
plot_title = None
m.default_style = {"cursor": "wait"}
plot = selected.sankify(
years=[before_year, after_year],
region=geom,
max_classes=classes.value,
n=int(samples.value),
title=plot_title,
)
output.outputs = ()
plot_output.outputs = ()
with plot_output:
plot.update_layout(
width=600,
height=250,
margin=dict(l=10, r=10, b=10, t=50, pad=5),
)
plot_widget.children = [
widgets.HBox(
[
plot_close_btn,
plot_reset_btn,
plot_fullscreen_btn,
width_btn,
width_slider,
width_slider_label,
height_btn,
height_slider,
height_slider_label,
]
),
plot_output,
]
display(plot)
m.sankee_plot = plot
m.addLayer(image1, {}, str(before_year))
m.addLayer(image2, {}, str(after_year))
m.default_style = {"cursor": "default"}
else:
with output:
output.outputs = ()
print("Draw a polygon on the map.")
elif change["new"] == "Reset":
output.outputs = ()
plot_output.outputs = ()
plot_widget.children = []
elif change["new"] == "Close":
m.tool_control.cleanup()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = True
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
toolbar_control.cleanup = cleanup
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
else:
return toolbar_widget
def _sankee_tool_callback(map, selected, item):
del selected, item # Unused.
sankee_gui(map)
return map.tool_control | null |
12,478 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def inspector_gui(m=None):
"""Generates a tool GUI template using ipywidgets.
Args:
m (geemap.Map, optional): The leaflet Map object. Defaults to None.
Returns:
ipywidgets: The tool GUI widget.
"""
import pandas as pd
widget_width = "250px"
padding = "0px 5px 0px 5px" # upper, right, bottom, left
style = {"description_width": "initial"}
if m is not None:
marker_cluster = ipyleaflet.MarkerCluster(name="Inspector Markers")
setattr(m, "pixel_values", [])
setattr(m, "marker_cluster", marker_cluster)
if not hasattr(m, "interact_mode"):
setattr(m, "interact_mode", False)
if not hasattr(m, "inspector_output"):
inspector_output = widgets.Output(
layout=widgets.Layout(
width=widget_width,
padding="0px 5px 5px 5px",
max_width=widget_width,
)
)
setattr(m, "inspector_output", inspector_output)
output = m.inspector_output
output.outputs = ()
if not hasattr(m, "inspector_add_marker"):
inspector_add_marker = widgets.Checkbox(
description="Add Marker at clicked location",
value=True,
indent=False,
layout=widgets.Layout(padding=padding, width=widget_width),
)
setattr(m, "inspector_add_marker", inspector_add_marker)
add_marker = m.inspector_add_marker
if not hasattr(m, "inspector_bands_chk"):
inspector_bands_chk = widgets.Checkbox(
description="Get pixel value for visible bands only",
indent=False,
layout=widgets.Layout(padding=padding, width=widget_width),
)
setattr(m, "inspector_bands_chk", inspector_bands_chk)
bands_chk = m.inspector_bands_chk
if not hasattr(m, "inspector_class_label"):
inspector_label = widgets.Text(
value="",
description="Class label:",
placeholder="Add a label to the marker",
style=style,
layout=widgets.Layout(width=widget_width, padding=padding),
)
setattr(m, "inspector_class_label", inspector_label)
label = m.inspector_class_label
options = []
if hasattr(m, "cog_layer_dict"):
options = list(m.cog_layer_dict.keys())
options.sort()
if len(options) == 0:
default_option = None
else:
default_option = options[0]
if not hasattr(m, "inspector_dropdown"):
inspector_dropdown = widgets.Dropdown(
options=options,
value=default_option,
description="Select a layer:",
layout=widgets.Layout(width=widget_width, padding=padding),
style=style,
)
setattr(m, "inspector_dropdown", inspector_dropdown)
dropdown = m.inspector_dropdown
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="info-circle",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Download", "Reset", "Close"],
tooltips=["Download", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
if len(options) == 0:
with output:
print("No COG/STAC layers available")
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
add_marker,
label,
dropdown,
bands_chk,
buttons,
output,
]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
def chk_change(change):
if hasattr(m, "pixel_values"):
m.pixel_values = []
if hasattr(m, "marker_cluster"):
m.marker_cluster.markers = []
output.outputs = ()
bands_chk.observe(chk_change, "value")
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
close_button.value = False
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def cleanup():
toolbar_button.value = False
if m is not None:
if hasattr(m, "inspector_mode"):
delattr(m, "inspector_mode")
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
m.default_style = {"cursor": "default"}
m.marker_cluster.markers = []
m.pixel_values = []
marker_cluster_layer = m.find_layer("Inspector Markers")
if marker_cluster_layer is not None:
m.remove_layer(marker_cluster_layer)
if hasattr(m, "pixel_values"):
delattr(m, "pixel_values")
if hasattr(m, "marker_cluster"):
delattr(m, "marker_cluster")
toolbar_widget.close()
def close_btn_click(change):
if change["new"]:
m.tool_control.cleanup()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Download":
with output:
output.outputs = ()
if len(m.pixel_values) == 0:
print(
"No pixel values available. Click on the map to start collection data."
)
else:
print("Downloading pixel values...")
df = pd.DataFrame(m.pixel_values)
temp_csv = temp_file_path("csv")
df.to_csv(temp_csv, index=False)
link = create_download_link(temp_csv)
with output:
output.outputs = ()
display(link)
elif change["new"] == "Reset":
label.value = ""
output.outputs = ()
if hasattr(m, "pixel_values"):
m.pixel_values = []
if hasattr(m, "marker_cluster"):
m.marker_cluster.markers = []
elif change["new"] == "Close":
m.tool_control.cleanup()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = True
def handle_interaction(**kwargs):
latlon = kwargs.get("coordinates")
lat = round(latlon[0], 4)
lon = round(latlon[1], 4)
if (
kwargs.get("type") == "click"
and hasattr(m, "inspector_mode")
and m.inspector_mode
):
m.default_style = {"cursor": "wait"}
with output:
output.outputs = ()
print("Getting pixel value ...")
layer_dict = m.cog_layer_dict[dropdown.value]
if layer_dict["type"] == "STAC":
if bands_chk.value:
assets = layer_dict["assets"]
else:
assets = None
result = stac_pixel_value(
lon,
lat,
layer_dict["url"],
layer_dict["collection"],
layer_dict["items"],
assets,
layer_dict["titiler_endpoint"],
verbose=False,
)
if result is not None:
with output:
output.outputs = ()
print(f"lat/lon: {lat:.4f}, {lon:.4f}\n")
for key in result:
print(f"{key}: {result[key]}")
result["latitude"] = lat
result["longitude"] = lon
result["label"] = label.value
m.pixel_values.append(result)
if add_marker.value:
markers = list(m.marker_cluster.markers)
markers.append(ipyleaflet.Marker(location=latlon))
m.marker_cluster.markers = markers
else:
with output:
output.outputs = ()
print("No pixel value available")
bounds = m.cog_layer_dict[m.inspector_dropdown.value]["bounds"]
m.zoom_to_bounds(bounds)
elif layer_dict["type"] == "COG":
result = cog_pixel_value(lon, lat, layer_dict["url"], verbose=False)
if result is not None:
with output:
output.outputs = ()
print(f"lat/lon: {lat:.4f}, {lon:.4f}\n")
for key in result:
print(f"{key}: {result[key]}")
result["latitude"] = lat
result["longitude"] = lon
result["label"] = label.value
m.pixel_values.append(result)
if add_marker.value:
markers = list(m.marker_cluster.markers)
markers.append(ipyleaflet.Marker(location=latlon))
m.marker_cluster.markers = markers
else:
with output:
output.outputs = ()
print("No pixel value available")
bounds = m.cog_layer_dict[m.inspector_dropdown.value]["bounds"]
m.zoom_to_bounds(bounds)
elif layer_dict["type"] == "LOCAL":
result = local_tile_pixel_value(
lon, lat, layer_dict["tile_client"], verbose=False
)
if result is not None:
if m.inspector_bands_chk.value:
band = m.cog_layer_dict[m.inspector_dropdown.value]["band"]
band_names = m.cog_layer_dict[m.inspector_dropdown.value][
"band_names"
]
if band is not None:
sel_bands = [band_names[b - 1] for b in band]
result = {k: v for k, v in result.items() if k in sel_bands}
with output:
output.outputs = ()
print(f"lat/lon: {lat:.4f}, {lon:.4f}\n")
for key in result:
print(f"{key}: {result[key]}")
result["latitude"] = lat
result["longitude"] = lon
result["label"] = label.value
m.pixel_values.append(result)
if add_marker.value:
markers = list(m.marker_cluster.markers)
markers.append(ipyleaflet.Marker(location=latlon))
m.marker_cluster.markers = markers
else:
with output:
output.outputs = ()
print("No pixel value available")
bounds = m.cog_layer_dict[m.inspector_dropdown.value]["bounds"]
m.zoom_to_bounds(bounds)
m.default_style = {"cursor": "crosshair"}
if m is not None:
if not hasattr(m, "marker_cluster"):
setattr(m, "marker_cluster", marker_cluster)
m.add_layer(marker_cluster)
if not m.interact_mode:
m.on_interaction(handle_interaction)
m.interact_mode = True
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
toolbar_control.cleanup = cleanup
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
if not hasattr(m, "inspector_mode"):
if hasattr(m, "cog_layer_dict"):
setattr(m, "inspector_mode", True)
else:
setattr(m, "inspector_mode", False)
else:
return toolbar_widget
def _cog_stac_inspector_callback(map, selected, item):
del selected, item # Unused.
inspector_gui(map)
return map.tool_control | null |
12,479 | import os
from dataclasses import dataclass
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from typing import Any, Callable, Optional
from .common import *
from .timelapse import *
from . import map_widgets
def plotly_tool_template(canvas):
container_widget = canvas.container_widget
map_widget = canvas.map_widget
map_width = "70%"
map_widget.layout.width = map_width
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
# style = {"description_width": "initial"}
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gears",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
with output:
print("To be implemented")
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
output,
]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
map_widget.layout.width = map_width
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
close_button.value = False
map_widget.layout.width = canvas.map_max_width
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
map_widget.layout.width = map_width
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
map_widget.layout.width = canvas.map_max_width
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
canvas.toolbar_reset()
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
toolbar_button.value = True
container_widget.children = [toolbar_widget]
def plotly_basemap_gui(canvas, map_min_width="78%", map_max_width="98%"):
"""Widget for changing basemaps.
Args:
m (object): geemap.Map.
"""
from .plotlymap import basemaps
m = canvas.map
layer_count = len(m.layout.mapbox.layers)
container_widget = canvas.container_widget
map_widget = canvas.map_widget
map_widget.layout.width = map_min_width
value = "Esri.WorldTopoMap"
m.add_basemap(value)
dropdown = widgets.Dropdown(
options=list(basemaps.keys()),
value=value,
layout=widgets.Layout(width="200px"),
)
close_btn = widgets.Button(
icon="times",
tooltip="Close the basemap widget",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
basemap_widget = widgets.HBox([dropdown, close_btn])
container_widget.children = [basemap_widget]
def on_click(change):
basemap_name = change["new"]
m.layout.mapbox.layers = m.layout.mapbox.layers[:layer_count]
m.add_basemap(basemap_name)
dropdown.observe(on_click, "value")
def close_click(change):
container_widget.children = []
basemap_widget.close()
map_widget.layout.width = map_max_width
canvas.toolbar_reset()
canvas.toolbar_button.value = False
close_btn.on_click(close_click)
def plotly_search_basemaps(canvas):
"""The widget for search XYZ tile services.
Args:
m (plotlymap.Map, optional): The Plotly Map object. Defaults to None.
Returns:
ipywidgets: The tool GUI widget.
"""
import xyzservices.providers as xyz
from xyzservices import TileProvider
m = canvas.map
container_widget = canvas.container_widget
map_widget = canvas.map_widget
map_widget.layout.width = "75%"
# map_widget.layout.width = map_min_width
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
style = {"description_width": "initial"}
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="search",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
checkbox = widgets.Checkbox(
description="Search Quick Map Services (QMS)",
indent=False,
layout=widgets.Layout(padding=padding, width=widget_width),
)
providers = widgets.Dropdown(
options=[],
value=None,
description="XYZ Tile:",
layout=widgets.Layout(width=widget_width, padding=padding),
style=style,
)
keyword = widgets.Text(
value="",
description="Search keyword:",
placeholder="OpenStreetMap",
style=style,
layout=widgets.Layout(width=widget_width, padding=padding),
)
def search_callback(change):
providers.options = []
if keyword.value != "":
tiles = search_xyz_services(keyword=keyword.value)
if checkbox.value:
tiles = tiles + search_qms(keyword=keyword.value)
providers.options = tiles
keyword.on_submit(search_callback)
buttons = widgets.ToggleButtons(
value=None,
options=["Search", "Reset", "Close"],
tooltips=["Search", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
def providers_change(change):
if change["new"] != "":
provider = change["new"]
if provider is not None:
if provider.startswith("qms"):
with output:
output.outputs = ()
print("Adding data. Please wait...")
name = provider[4:]
qms_provider = TileProvider.from_qms(name)
url = qms_provider.build_url()
attribution = qms_provider.attribution
m.add_tile_layer(url, name, attribution)
output.outputs = ()
elif provider.startswith("xyz"):
name = provider[4:]
xyz_provider = xyz.flatten()[name]
url = xyz_provider.build_url()
attribution = xyz_provider.attribution
if xyz_provider.requires_token():
with output:
output.outputs = ()
print(f"{provider} requires an API Key.")
m.add_tile_layer(url, name, attribution)
providers.observe(providers_change, "value")
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
checkbox,
keyword,
providers,
buttons,
output,
]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
close_button.value = False
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
canvas.toolbar_reset()
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Search":
providers.options = []
output.outputs = ()
if keyword.value != "":
tiles = search_xyz_services(keyword=keyword.value)
if checkbox.value:
tiles = tiles + search_qms(keyword=keyword.value)
providers.options = tiles
else:
with output:
print("Please enter a search keyword.")
elif change["new"] == "Reset":
keyword.value = ""
providers.options = []
output.outputs = ()
elif change["new"] == "Close":
canvas.toolbar_reset()
toolbar_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = True
container_widget.children = [toolbar_widget]
def plotly_whitebox_gui(canvas):
import whiteboxgui.whiteboxgui as wbt
container_widget = canvas.container_widget
map_widget = canvas.map_widget
map_width = "25%"
map_widget.layout.width = map_width
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
# style = {"description_width": "initial"}
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gears",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
tools_dict = wbt.get_wbt_dict()
wbt_toolbox = wbt.build_toolbox(
tools_dict,
max_width="800px",
max_height="500px",
sandbox_path=os.getcwd(),
)
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
wbt_toolbox,
output,
]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
map_widget.layout.width = map_width
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
close_button.value = False
map_widget.layout.width = canvas.map_max_width
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
map_widget.layout.width = map_width
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
map_widget.layout.width = canvas.map_max_width
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
canvas.toolbar_reset()
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
toolbar_button.value = True
container_widget.children = [toolbar_widget]
import math
The provided code snippet includes necessary dependencies for implementing the `plotly_toolbar` function. Write a Python function `def plotly_toolbar( canvas, )` to solve the following problem:
Creates the main toolbar and adds it to the map. Args: m (plotlymap.Map): The plotly Map object.
Here is the function:
def plotly_toolbar(
canvas,
):
"""Creates the main toolbar and adds it to the map.
Args:
m (plotlymap.Map): The plotly Map object.
"""
m = canvas.map
map_min_width = canvas.map_min_width
map_max_width = canvas.map_max_width
map_refresh = canvas.map_refresh
map_widget = canvas.map_widget
if not map_refresh:
width = int(map_min_width.replace("%", ""))
if width > 90:
map_min_width = "90%"
tools = {
"map": {
"name": "basemap",
"tooltip": "Change basemap",
},
"search": {
"name": "search_xyz",
"tooltip": "Search XYZ tile services",
},
"gears": {
"name": "whitebox",
"tooltip": "WhiteboxTools for local geoprocessing",
},
"folder-open": {
"name": "vector",
"tooltip": "Open local vector/raster data",
},
"picture-o": {
"name": "raster",
"tooltip": "Open COG/STAC dataset",
},
"question": {
"name": "help",
"tooltip": "Get help",
},
}
icons = list(tools.keys())
tooltips = [item["tooltip"] for item in list(tools.values())]
icon_width = "32px"
icon_height = "32px"
n_cols = 3
n_rows = math.ceil(len(icons) / n_cols)
toolbar_grid = widgets.GridBox(
children=[
widgets.ToggleButton(
layout=widgets.Layout(
width="auto", height="auto", padding="0px 0px 0px 4px"
),
button_style="primary",
icon=icons[i],
tooltip=tooltips[i],
)
for i in range(len(icons))
],
layout=widgets.Layout(
width="115px",
grid_template_columns=(icon_width + " ") * n_cols,
grid_template_rows=(icon_height + " ") * n_rows,
grid_gap="1px 1px",
padding="5px",
),
)
canvas.toolbar = toolbar_grid
def tool_callback(change):
if change["new"]:
current_tool = change["owner"]
for tool in toolbar_grid.children:
if tool is not current_tool:
tool.value = False
tool = change["owner"]
tool_name = tools[tool.icon]["name"]
canvas.container_widget.children = []
if tool_name == "basemap":
plotly_basemap_gui(canvas)
elif tool_name == "search_xyz":
plotly_search_basemaps(canvas)
elif tool_name == "whitebox":
plotly_whitebox_gui(canvas)
elif tool_name == "vector":
plotly_tool_template(canvas)
elif tool_name == "raster":
plotly_tool_template(canvas)
elif tool_name == "help":
import webbrowser
webbrowser.open_new_tab("https://geemap.org")
tool.value = False
else:
canvas.container_widget.children = []
map_widget.layout.width = map_max_width
for tool in toolbar_grid.children:
tool.observe(tool_callback, "value")
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="wrench",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
canvas.toolbar_button = toolbar_button
layers_button = widgets.ToggleButton(
value=False,
tooltip="Layers",
icon="server",
layout=widgets.Layout(height="28px", width="72px"),
)
canvas.layers_button = layers_button
toolbar_widget = widgets.VBox(layout=widgets.Layout(overflow="hidden"))
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox(layout=widgets.Layout(overflow="hidden"))
toolbar_header.children = [layers_button, toolbar_button]
toolbar_footer = widgets.VBox(layout=widgets.Layout(overflow="hidden"))
toolbar_footer.children = [toolbar_grid]
toolbar_event = ipyevents.Event(
source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
)
def handle_toolbar_event(event):
if event["type"] == "mouseenter":
toolbar_widget.children = [toolbar_header, toolbar_footer]
# map_widget.layout.width = "85%"
elif event["type"] == "mouseleave":
if not toolbar_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.value = False
layers_button.value = False
# map_widget.layout.width = map_max_width
toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
map_widget.layout.width = map_min_width
if map_refresh:
with map_widget:
map_widget.outputs = ()
display(m)
layers_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
canvas.toolbar_reset()
map_widget.layout.width = map_max_width
if not layers_button.value:
toolbar_widget.children = [toolbar_button]
if map_refresh:
with map_widget:
map_widget.outputs = ()
display(m)
toolbar_button.observe(toolbar_btn_click, "value")
def layers_btn_click(change):
if change["new"]:
layer_names = list(m.get_layers().keys())
layers_hbox = []
all_layers_chk = widgets.Checkbox(
value=True,
description="All layers on/off",
indent=False,
layout=widgets.Layout(height="18px", padding="0px 8px 25px 8px"),
)
all_layers_chk.layout.width = "30ex"
layers_hbox.append(all_layers_chk)
layer_chk_dict = {}
for name in layer_names:
if name in m.get_tile_layers():
index = m.find_layer_index(name)
layer = m.layout.mapbox.layers[index]
elif name in m.get_data_layers():
index = m.find_layer_index(name)
layer = m.data[index]
layer_chk = widgets.Checkbox(
value=layer.visible,
description=name,
indent=False,
layout=widgets.Layout(height="18px"),
)
layer_chk.layout.width = "25ex"
layer_chk_dict[name] = layer_chk
if hasattr(layer, "opacity"):
opacity = layer.opacity
elif hasattr(layer, "marker"):
opacity = layer.marker.opacity
else:
opacity = 1.0
layer_opacity = widgets.FloatSlider(
value=opacity,
description_tooltip=name,
min=0,
max=1,
step=0.01,
readout=False,
layout=widgets.Layout(width="80px"),
)
layer_settings = widgets.ToggleButton(
icon="gear",
tooltip=name,
layout=widgets.Layout(
width="25px", height="25px", padding="0px 0px 0px 5px"
),
)
def layer_chk_change(change):
if change["new"]:
m.set_layer_visibility(change["owner"].description, True)
else:
m.set_layer_visibility(change["owner"].description, False)
layer_chk.observe(layer_chk_change, "value")
def layer_opacity_change(change):
if change["new"]:
m.set_layer_opacity(
change["owner"].description_tooltip, change["new"]
)
layer_opacity.observe(layer_opacity_change, "value")
hbox = widgets.HBox(
[layer_chk, layer_settings, layer_opacity],
layout=widgets.Layout(padding="0px 8px 0px 8px"),
)
layers_hbox.append(hbox)
def all_layers_chk_changed(change):
if change["new"]:
for name in layer_names:
m.set_layer_visibility(name, True)
layer_chk_dict[name].value = True
else:
for name in layer_names:
m.set_layer_visibility(name, False)
layer_chk_dict[name].value = False
all_layers_chk.observe(all_layers_chk_changed, "value")
toolbar_footer.children = layers_hbox
toolbar_button.value = False
else:
toolbar_footer.children = [toolbar_grid]
layers_button.observe(layers_btn_click, "value")
return toolbar_widget | Creates the main toolbar and adds it to the map. Args: m (plotlymap.Map): The plotly Map object. |
12,480 | from playwright.sync_api import sync_playwright
import time
from sys import argv, exit, platform
import openai
import os
def print_help():
print(
"(g) to visit url\n(u) scroll up\n(d) scroll down\n(c) to click\n(t) to type\n" +
"(h) to view commands again\n(r/enter) to run suggested command\n(o) change objective"
) | null |
12,481 | from playwright.sync_api import sync_playwright
import time
from sys import argv, exit, platform
import openai
import os
prompt_template = """
You are an agent controlling a browser. You are given:
(1) an objective that you are trying to achieve
(2) the URL of your current web page
(3) a simplified text description of what's visible in the browser window (more on that below)
You can issue these commands:
SCROLL UP - scroll up one page
SCROLL DOWN - scroll down one page
CLICK X - click on a given element. You can only click on links, buttons, and inputs!
TYPE X "TEXT" - type the specified text into the input with id X
TYPESUBMIT X "TEXT" - same as TYPE above, except then it presses ENTER to submit the form
The format of the browser content is highly simplified; all formatting elements are stripped.
Interactive elements such as links, inputs, buttons are represented like this:
<link id=1>text</link>
<button id=2>text</button>
<input id=3>text</input>
Images are rendered as their alt text like this:
<img id=4 alt=""/>
Based on your given objective, issue whatever command you believe will get you closest to achieving your goal.
You always start on Google; you should submit a search query to Google that will take you to the best page for
achieving your objective. And then interact with that page to achieve your objective.
If you find yourself on Google and there are no search results displayed yet, you should probably issue a command
like "TYPESUBMIT 7 "search query"" to get to a more useful page.
Then, if you find yourself on a Google search results page, you might issue the command "CLICK 24" to click
on the first link in the search results. (If your previous command was a TYPESUBMIT your next command should
probably be a CLICK.)
Don't try to interact with elements that you can't see.
Here are some examples:
EXAMPLE 1:
==================================================
CURRENT BROWSER CONTENT:
------------------
<link id=1>About</link>
<link id=2>Store</link>
<link id=3>Gmail</link>
<link id=4>Images</link>
<link id=5>(Google apps)</link>
<link id=6>Sign in</link>
<img id=7 alt="(Google)"/>
<input id=8 alt="Search"></input>
<button id=9>(Search by voice)</button>
<button id=10>(Google Search)</button>
<button id=11>(I'm Feeling Lucky)</button>
<link id=12>Advertising</link>
<link id=13>Business</link>
<link id=14>How Search works</link>
<link id=15>Carbon neutral since 2007</link>
<link id=16>Privacy</link>
<link id=17>Terms</link>
<text id=18>Settings</text>
------------------
OBJECTIVE: Find a 2 bedroom house for sale in Anchorage AK for under $750k
CURRENT URL: https://www.google.com/
YOUR COMMAND:
TYPESUBMIT 8 "anchorage redfin"
==================================================
EXAMPLE 2:
==================================================
CURRENT BROWSER CONTENT:
------------------
<link id=1>About</link>
<link id=2>Store</link>
<link id=3>Gmail</link>
<link id=4>Images</link>
<link id=5>(Google apps)</link>
<link id=6>Sign in</link>
<img id=7 alt="(Google)"/>
<input id=8 alt="Search"></input>
<button id=9>(Search by voice)</button>
<button id=10>(Google Search)</button>
<button id=11>(I'm Feeling Lucky)</button>
<link id=12>Advertising</link>
<link id=13>Business</link>
<link id=14>How Search works</link>
<link id=15>Carbon neutral since 2007</link>
<link id=16>Privacy</link>
<link id=17>Terms</link>
<text id=18>Settings</text>
------------------
OBJECTIVE: Make a reservation for 4 at Dorsia at 8pm
CURRENT URL: https://www.google.com/
YOUR COMMAND:
TYPESUBMIT 8 "dorsia nyc opentable"
==================================================
EXAMPLE 3:
==================================================
CURRENT BROWSER CONTENT:
------------------
<button id=1>For Businesses</button>
<button id=2>Mobile</button>
<button id=3>Help</button>
<button id=4 alt="Language Picker">EN</button>
<link id=5>OpenTable logo</link>
<button id=6 alt ="search">Search</button>
<text id=7>Find your table for any occasion</text>
<button id=8>(Date selector)</button>
<text id=9>Sep 28, 2022</text>
<text id=10>7:00 PM</text>
<text id=11>2 people</text>
<input id=12 alt="Location, Restaurant, or Cuisine"></input>
<button id=13>Let’s go</button>
<text id=14>It looks like you're in Peninsula. Not correct?</text>
<button id=15>Get current location</button>
<button id=16>Next</button>
------------------
OBJECTIVE: Make a reservation for 4 for dinner at Dorsia in New York City at 8pm
CURRENT URL: https://www.opentable.com/
YOUR COMMAND:
TYPESUBMIT 12 "dorsia new york city"
==================================================
The current browser content, objective, and current URL follow. Reply with your next command to the browser.
CURRENT BROWSER CONTENT:
------------------
$browser_content
------------------
OBJECTIVE: $objective
CURRENT URL: $url
PREVIOUS COMMAND: $previous_command
YOUR COMMAND:
"""
def get_gpt_command(objective, url, previous_command, browser_content):
prompt = prompt_template
prompt = prompt.replace("$objective", objective)
prompt = prompt.replace("$url", url[:100])
prompt = prompt.replace("$previous_command", previous_command)
prompt = prompt.replace("$browser_content", browser_content[:4500])
response = openai.Completion.create(model="text-davinci-002", prompt=prompt, temperature=0.5, best_of=10, n=3, max_tokens=50)
return response.choices[0].text | null |
12,482 | from playwright.sync_api import sync_playwright
import time
from sys import argv, exit, platform
import openai
import os
def run_cmd(cmd):
cmd = cmd.split("\n")[0]
if cmd.startswith("SCROLL UP"):
_crawler.scroll("up")
elif cmd.startswith("SCROLL DOWN"):
_crawler.scroll("down")
elif cmd.startswith("CLICK"):
commasplit = cmd.split(",")
id = commasplit[0].split(" ")[1]
_crawler.click(id)
elif cmd.startswith("TYPE"):
spacesplit = cmd.split(" ")
id = spacesplit[1]
text = spacesplit[2:]
text = " ".join(text)
# Strip leading and trailing double quotes
text = text[1:-1]
if cmd.startswith("TYPESUBMIT"):
text += '\n'
_crawler.type(id, text)
time.sleep(2) | null |
12,483 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `write_hdf5` function. Write a Python function `def write_hdf5(file, tensor, key = 'tensor')` to solve the following problem:
Write a simple tensor, i.e. numpy array ,to HDF5. :param file: path to file to write :type file: str :param tensor: tensor to write :type tensor: numpy.ndarray :param key: key to use for tensor :type key: str
Here is the function:
def write_hdf5(file, tensor, key = 'tensor'):
"""
Write a simple tensor, i.e. numpy array ,to HDF5.
:param file: path to file to write
:type file: str
:param tensor: tensor to write
:type tensor: numpy.ndarray
:param key: key to use for tensor
:type key: str
"""
assert type(tensor) == np.ndarray, 'expects numpy.ndarray'
h5f = h5py.File(file, 'w')
chunks = list(tensor.shape)
if len(chunks) > 2:
chunks[2] = 1
if len(chunks) > 3:
chunks[3] = 1
if len(chunks) > 4:
chunks[4] = 1
h5f.create_dataset(key, data = tensor, chunks = tuple(chunks), compression = 'gzip')
h5f.close() | Write a simple tensor, i.e. numpy array ,to HDF5. :param file: path to file to write :type file: str :param tensor: tensor to write :type tensor: numpy.ndarray :param key: key to use for tensor :type key: str |
12,484 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `read_hdf5` function. Write a Python function `def read_hdf5(file, key = 'tensor')` to solve the following problem:
Read a tensor, i.e. numpy array, from HDF5. :param file: path to file to read :type file: str :param key: key to read :type key: str :return: tensor :rtype: numpy.ndarray
Here is the function:
def read_hdf5(file, key = 'tensor'):
"""
Read a tensor, i.e. numpy array, from HDF5.
:param file: path to file to read
:type file: str
:param key: key to read
:type key: str
:return: tensor
:rtype: numpy.ndarray
"""
assert os.path.exists(file), 'file %s not found' % file
h5f = h5py.File(file, 'r')
assert key in h5f.keys(), 'key %s not found in file %s' % (key, file)
tensor = h5f[key][()]
h5f.close()
return tensor | Read a tensor, i.e. numpy array, from HDF5. :param file: path to file to read :type file: str :param key: key to read :type key: str :return: tensor :rtype: numpy.ndarray |
12,485 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `write_off` function. Write a Python function `def write_off(file, vertices, faces)` to solve the following problem:
Writes the given vertices and faces to OFF. :param vertices: vertices as tuples of (x, y, z) coordinates :type vertices: [(float)] :param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...) :type faces: [(int)]
Here is the function:
def write_off(file, vertices, faces):
"""
Writes the given vertices and faces to OFF.
:param vertices: vertices as tuples of (x, y, z) coordinates
:type vertices: [(float)]
:param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...)
:type faces: [(int)]
"""
num_vertices = len(vertices)
num_faces = len(faces)
assert num_vertices > 0
assert num_faces > 0
with open(file, 'w') as fp:
fp.write('OFF\n')
fp.write(str(num_vertices) + ' ' + str(num_faces) + ' 0\n')
for vertex in vertices:
assert len(vertex) == 3, 'invalid vertex with %d dimensions found (%s)' % (len(vertex), file)
fp.write(str(vertex[0]) + ' ' + str(vertex[1]) + ' ' + str(vertex[2]) + '\n')
for face in faces:
assert face[0] == 3, 'only triangular faces supported (%s)' % file
assert len(face) == 4, 'faces need to have 3 vertices, but found %d (%s)' % (len(face), file)
for i in range(len(face)):
assert face[i] >= 0 and face[i] < num_vertices, 'invalid vertex index %d (of %d vertices) (%s)' % (face[i], num_vertices, file)
fp.write(str(face[i]))
if i < len(face) - 1:
fp.write(' ')
fp.write('\n')
# add empty line to be sure
fp.write('\n') | Writes the given vertices and faces to OFF. :param vertices: vertices as tuples of (x, y, z) coordinates :type vertices: [(float)] :param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...) :type faces: [(int)] |
12,486 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `read_off` function. Write a Python function `def read_off(file)` to solve the following problem:
Reads vertices and faces from an off file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)]
Here is the function:
def read_off(file):
"""
Reads vertices and faces from an off file.
:param file: path to file to read
:type file: str
:return: vertices and faces as lists of tuples
:rtype: [(float)], [(int)]
"""
assert os.path.exists(file), 'file %s not found' % file
with open(file, 'r') as fp:
lines = fp.readlines()
lines = [line.strip() for line in lines]
# Fix for ModelNet bug were 'OFF' and the number of vertices and faces are
# all in the first line.
if len(lines[0]) > 3:
assert lines[0][:3] == 'OFF' or lines[0][:3] == 'off', 'invalid OFF file %s' % file
parts = lines[0][3:].split(' ')
assert len(parts) == 3
num_vertices = int(parts[0])
assert num_vertices > 0
num_faces = int(parts[1])
assert num_faces > 0
start_index = 1
# This is the regular case!
else:
assert lines[0] == 'OFF' or lines[0] == 'off', 'invalid OFF file %s' % file
parts = lines[1].split(' ')
assert len(parts) == 3
num_vertices = int(parts[0])
assert num_vertices > 0
num_faces = int(parts[1])
assert num_faces > 0
start_index = 2
vertices = []
for i in range(num_vertices):
vertex = lines[start_index + i].split(' ')
vertex = [float(point.strip()) for point in vertex if point != '']
assert len(vertex) == 3
vertices.append(vertex)
faces = []
for i in range(num_faces):
face = lines[start_index + num_vertices + i].split(' ')
face = [index.strip() for index in face if index != '']
# check to be sure
for index in face:
assert index != '', 'found empty vertex index: %s (%s)' % (lines[start_index + num_vertices + i], file)
face = [int(index) for index in face]
assert face[0] == len(face) - 1, 'face should have %d vertices but as %d (%s)' % (face[0], len(face) - 1, file)
assert face[0] == 3, 'only triangular meshes supported (%s)' % file
for index in face:
assert index >= 0 and index < num_vertices, 'vertex %d (of %d vertices) does not exist (%s)' % (index, num_vertices, file)
assert len(face) > 1
faces.append(face)
return vertices, faces
assert False, 'could not open %s' % file | Reads vertices and faces from an off file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)] |
12,487 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `write_obj` function. Write a Python function `def write_obj(file, vertices, faces)` to solve the following problem:
Writes the given vertices and faces to OBJ. :param vertices: vertices as tuples of (x, y, z) coordinates :type vertices: [(float)] :param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...) :type faces: [(int)]
Here is the function:
def write_obj(file, vertices, faces):
"""
Writes the given vertices and faces to OBJ.
:param vertices: vertices as tuples of (x, y, z) coordinates
:type vertices: [(float)]
:param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...)
:type faces: [(int)]
"""
num_vertices = len(vertices)
num_faces = len(faces)
assert num_vertices > 0
assert num_faces > 0
with open(file, 'w') as fp:
for vertex in vertices:
assert len(vertex) == 3, 'invalid vertex with %d dimensions found (%s)' % (len(vertex), file)
fp.write('v' + ' ' + str(vertex[0]) + ' ' + str(vertex[1]) + ' ' + str(vertex[2]) + '\n')
for face in faces:
assert len(face) == 3, 'only triangular faces supported (%s)' % file
fp.write('f ')
for i in range(len(face)):
assert face[i] >= 0 and face[i] < num_vertices, 'invalid vertex index %d (of %d vertices) (%s)' % (face[i], num_vertices, file)
# face indices are 1-based
fp.write(str(face[i] + 1))
if i < len(face) - 1:
fp.write(' ')
fp.write('\n')
# add empty line to be sure
fp.write('\n') | Writes the given vertices and faces to OBJ. :param vertices: vertices as tuples of (x, y, z) coordinates :type vertices: [(float)] :param faces: faces as tuples of (num_vertices, vertex_id_1, vertex_id_2, ...) :type faces: [(int)] |
12,488 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `read_obj` function. Write a Python function `def read_obj(file)` to solve the following problem:
Reads vertices and faces from an obj file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)]
Here is the function:
def read_obj(file):
"""
Reads vertices and faces from an obj file.
:param file: path to file to read
:type file: str
:return: vertices and faces as lists of tuples
:rtype: [(float)], [(int)]
"""
assert os.path.exists(file), 'file %s not found' % file
with open(file, 'r') as fp:
lines = fp.readlines()
lines = [line.strip() for line in lines if line.strip()]
vertices = []
faces = []
for line in lines:
parts = line.split(' ')
parts = [part.strip() for part in parts if part]
if parts[0] == 'v':
assert len(parts) == 4, \
'vertex should be of the form v x y z, but found %d parts instead (%s)' % (len(parts), file)
assert parts[1] != '', 'vertex x coordinate is empty (%s)' % file
assert parts[2] != '', 'vertex y coordinate is empty (%s)' % file
assert parts[3] != '', 'vertex z coordinate is empty (%s)' % file
vertices.append([float(parts[1]), float(parts[2]), float(parts[3])])
elif parts[0] == 'f':
assert len(parts) == 4, \
'face should be of the form f v1/vt1/vn1 v2/vt2/vn2 v2/vt2/vn2, but found %d parts (%s) instead (%s)' % (len(parts), line, file)
components = parts[1].split('/')
assert len(components) >= 1 and len(components) <= 3, \
'face component should have the forms v, v/vt or v/vt/vn, but found %d components instead (%s)' % (len(components), file)
assert components[0].strip() != '', \
'face component is empty (%s)' % file
v1 = int(components[0])
components = parts[2].split('/')
assert len(components) >= 1 and len(components) <= 3, \
'face component should have the forms v, v/vt or v/vt/vn, but found %d components instead (%s)' % (len(components), file)
assert components[0].strip() != '', \
'face component is empty (%s)' % file
v2 = int(components[0])
components = parts[3].split('/')
assert len(components) >= 1 and len(components) <= 3, \
'face component should have the forms v, v/vt or v/vt/vn, but found %d components instead (%s)' % (len(components), file)
assert components[0].strip() != '', \
'face component is empty (%s)' % file
v3 = int(components[0])
#assert v1 != v2 and v2 != v3 and v3 != v2, 'degenerate face detected: %d %d %d (%s)' % (v1, v2, v3, file)
if v1 == v2 or v2 == v3 or v1 == v3:
print('[Info] skipping degenerate face in %s' % file)
else:
faces.append([v1 - 1, v2 - 1, v3 - 1]) # indices are 1-based!
else:
assert False, 'expected either vertex or face but got line: %s (%s)' % (line, file)
return vertices, faces
assert False, 'could not open %s' % file | Reads vertices and faces from an obj file. :param file: path to file to read :type file: str :return: vertices and faces as lists of tuples :rtype: [(float)], [(int)] |
12,489 | import os
import time
import h5py
import math
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `makedir` function. Write a Python function `def makedir(dir)` to solve the following problem:
Creates directory if it does not exist. :param dir: directory path :type dir: str
Here is the function:
def makedir(dir):
"""
Creates directory if it does not exist.
:param dir: directory path
:type dir: str
"""
if not os.path.exists(dir):
os.makedirs(dir) | Creates directory if it does not exist. :param dir: directory path :type dir: str |
12,490 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `export_obj` function. Write a Python function `def export_obj(vertices, triangles, filename)` to solve the following problem:
Exports a mesh in the (.obj) format.
Here is the function:
def export_obj(vertices, triangles, filename):
"""
Exports a mesh in the (.obj) format.
"""
with open(filename, 'w') as fh:
for v in vertices:
fh.write("v {} {} {}\n".format(*v))
for f in triangles:
fh.write("f {} {} {}\n".format(*(f + 1))) | Exports a mesh in the (.obj) format. |
12,491 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `export_off` function. Write a Python function `def export_off(vertices, triangles, filename)` to solve the following problem:
Exports a mesh in the (.off) format.
Here is the function:
def export_off(vertices, triangles, filename):
"""
Exports a mesh in the (.off) format.
"""
with open(filename, 'w') as fh:
fh.write('OFF\n')
fh.write('{} {} 0\n'.format(len(vertices), len(triangles)))
for v in vertices:
fh.write("{} {} {}\n".format(*v))
for f in triangles:
fh.write("3 {} {} {}\n".format(*f)) | Exports a mesh in the (.off) format. |
12,492 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `export_mesh` function. Write a Python function `def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh")` to solve the following problem:
Exports a mesh in the COLLADA (.dae) format. Needs PyCollada (https://github.com/pycollada/pycollada).
Here is the function:
def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh"):
"""
Exports a mesh in the COLLADA (.dae) format.
Needs PyCollada (https://github.com/pycollada/pycollada).
"""
import collada
mesh = collada.Collada()
vert_src = collada.source.FloatSource("verts-array", vertices, ('X','Y','Z'))
geom = collada.geometry.Geometry(mesh, "geometry0", mesh_name, [vert_src])
input_list = collada.source.InputList()
input_list.addInput(0, 'VERTEX', "#verts-array")
triset = geom.createTriangleSet(np.copy(triangles), input_list, "")
geom.primitives.append(triset)
mesh.geometries.append(geom)
geomnode = collada.scene.GeometryNode(geom, [])
node = collada.scene.Node(mesh_name, children=[geomnode])
myscene = collada.scene.Scene("mcubes_scene", [node])
mesh.scenes.append(myscene)
mesh.scene = myscene
mesh.write(filename) | Exports a mesh in the COLLADA (.dae) format. Needs PyCollada (https://github.com/pycollada/pycollada). |
12,493 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.r2n2 import models, training, generation
from im2mesh import data
encoder_dict = {
'simple_conv': conv.ConvEncoder,
'resnet18': conv.Resnet18,
'resnet34': conv.Resnet34,
'resnet50': conv.Resnet50,
'resnet101': conv.Resnet101,
'r2n2_simple': r2n2.SimpleConv,
'r2n2_resnet': r2n2.Resnet,
'pointnet_simple': pointnet.SimplePointnet,
'pointnet_resnet': pointnet.ResnetPointnet,
'psgn_cond': psgn_cond.PCGN_Cond,
'voxel_simple': voxels.VoxelEncoder,
'pixel2mesh_cond': pix2mesh_cond.Pix2mesh_Cond,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, **kwargs)` to solve the following problem:
Return the model. Args: cfg (dict): loaded yaml config device (device): pytorch device
Here is the function:
def get_model(cfg, device=None, **kwargs):
''' Return the model.
Args:
cfg (dict): loaded yaml config
device (device): pytorch device
'''
decoder = cfg['model']['decoder']
encoder = cfg['model']['encoder']
dim = cfg['data']['dim']
# z_dim = cfg['model']['z_dim']
c_dim = cfg['model']['c_dim']
# encoder_kwargs = cfg['model']['encoder_kwargs']
decoder_kwargs = cfg['model']['decoder_kwargs']
encoder_kwargs = cfg['model']['encoder_kwargs']
decoder = models.decoder_dict[decoder](
dim=dim, c_dim=c_dim,
**decoder_kwargs
)
encoder = encoder_dict[encoder](
c_dim=c_dim,
**encoder_kwargs
)
model = models.R2N2(decoder, encoder)
model = model.to(device)
return model | Return the model. Args: cfg (dict): loaded yaml config device (device): pytorch device |
12,494 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.r2n2 import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, optimizer, cfg, device, **kwargs)` to solve the following problem:
Returns the trainer object. Args: model (nn.Module): R2N2 model optimizer (optimizer): pytorch optimizer cfg (dict): loaded yaml config device (device): pytorch device
Here is the function:
def get_trainer(model, optimizer, cfg, device, **kwargs):
''' Returns the trainer object.
Args:
model (nn.Module): R2N2 model
optimizer (optimizer): pytorch optimizer
cfg (dict): loaded yaml config
device (device): pytorch device
'''
threshold = cfg['test']['threshold']
out_dir = cfg['training']['out_dir']
vis_dir = os.path.join(out_dir, 'vis')
input_type = cfg['data']['input_type']
trainer = training.Trainer(
model, optimizer, device=device,
input_type=input_type, vis_dir=vis_dir,
threshold=threshold
)
return trainer | Returns the trainer object. Args: model (nn.Module): R2N2 model optimizer (optimizer): pytorch optimizer cfg (dict): loaded yaml config device (device): pytorch device |
12,495 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.r2n2 import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_generator` function. Write a Python function `def get_generator(model, cfg, device, **kwargs)` to solve the following problem:
Returns the generator object. Args: model (nn.Module): R2N2 model cfg (dict): loaded yaml config device (device): pytorch device
Here is the function:
def get_generator(model, cfg, device, **kwargs):
''' Returns the generator object.
Args:
model (nn.Module): R2N2 model
cfg (dict): loaded yaml config
device (device): pytorch device
'''
generator = generation.VoxelGenerator3D(
model, device=device
)
return generator | Returns the generator object. Args: model (nn.Module): R2N2 model cfg (dict): loaded yaml config device (device): pytorch device |
12,496 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.r2n2 import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_data_fields` function. Write a Python function `def get_data_fields(split, cfg, **kwargs)` to solve the following problem:
Returns the data fields. Args: split (str): the split which should be used cfg (dict): loaded yaml config
Here is the function:
def get_data_fields(split, cfg, **kwargs):
''' Returns the data fields.
Args:
split (str): the split which should be used
cfg (dict): loaded yaml config
'''
with_transforms = cfg['data']['with_transforms']
fields = {}
if split == 'train':
fields['voxels'] = data.VoxelsField(
cfg['data']['voxels_file']
)
elif split in ('val', 'test'):
fields['points_iou'] = data.PointsField(
cfg['data']['points_iou_file'],
with_transforms=with_transforms,
unpackbits=cfg['data']['points_unpackbits'],
)
return fields | Returns the data fields. Args: split (str): the split which should be used cfg (dict): loaded yaml config |
12,497 | import os
import logging
from torch.utils import data
import numpy as np
import yaml
The provided code snippet includes necessary dependencies for implementing the `collate_remove_none` function. Write a Python function `def collate_remove_none(batch)` to solve the following problem:
Collater that puts each data field into a tensor with outer dimension batch size. Args: batch: batch
Here is the function:
def collate_remove_none(batch):
''' Collater that puts each data field into a tensor with outer dimension
batch size.
Args:
batch: batch
'''
batch = list(filter(lambda x: x is not None, batch))
return data.dataloader.default_collate(batch) | Collater that puts each data field into a tensor with outer dimension batch size. Args: batch: batch |
12,498 | import os
import logging
from torch.utils import data
import numpy as np
import yaml
The provided code snippet includes necessary dependencies for implementing the `worker_init_fn` function. Write a Python function `def worker_init_fn(worker_id)` to solve the following problem:
Worker init function to ensure true randomness.
Here is the function:
def worker_init_fn(worker_id):
''' Worker init function to ensure true randomness.
'''
random_data = os.urandom(4)
base_seed = int.from_bytes(random_data, byteorder="big")
np.random.seed(base_seed + worker_id) | Worker init function to ensure true randomness. |
12,499 | import os
import urllib
import torch
from torch.utils import model_zoo
def is_url(url):
scheme = urllib.parse.urlparse(url).scheme
return scheme in ('http', 'https') | null |
12,500 | import yaml
from torchvision import transforms
from im2mesh import data
from im2mesh import onet, r2n2, psgn, pix2mesh, dmc
from im2mesh import preprocess
def update_recursive(dict1, dict2):
''' Update two config dictionaries recursively.
Args:
dict1 (dict): first dictionary to be updated
dict2 (dict): second dictionary which entries should be used
'''
for k, v in dict2.items():
if k not in dict1:
dict1[k] = dict()
if isinstance(v, dict):
update_recursive(dict1[k], v)
else:
dict1[k] = v
The provided code snippet includes necessary dependencies for implementing the `load_config` function. Write a Python function `def load_config(path, default_path=None)` to solve the following problem:
Loads config file. Args: path (str): path to config file default_path (bool): whether to use default path
Here is the function:
def load_config(path, default_path=None):
''' Loads config file.
Args:
path (str): path to config file
default_path (bool): whether to use default path
'''
# Load configuration from file itself
with open(path, 'r') as f:
cfg_special = yaml.load(f)
# Check if we should inherit from a config
inherit_from = cfg_special.get('inherit_from')
# If yes, load this config first as default
# If no, use the default_path
if inherit_from is not None:
cfg = load_config(inherit_from, default_path)
elif default_path is not None:
with open(default_path, 'r') as f:
cfg = yaml.load(f)
else:
cfg = dict()
# Include main configuration
update_recursive(cfg, cfg_special)
return cfg | Loads config file. Args: path (str): path to config file default_path (bool): whether to use default path |
12,501 | import yaml
from torchvision import transforms
from im2mesh import data
from im2mesh import onet, r2n2, psgn, pix2mesh, dmc
from im2mesh import preprocess
method_dict = {
'onet': onet,
'r2n2': r2n2,
'psgn': psgn,
'pix2mesh': pix2mesh,
'dmc': dmc,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, dataset=None)` to solve the following problem:
Returns the model instance. Args: cfg (dict): config dictionary device (device): pytorch device dataset (dataset): dataset
Here is the function:
def get_model(cfg, device=None, dataset=None):
''' Returns the model instance.
Args:
cfg (dict): config dictionary
device (device): pytorch device
dataset (dataset): dataset
'''
method = cfg['method']
model = method_dict[method].config.get_model(
cfg, device=device, dataset=dataset)
return model | Returns the model instance. Args: cfg (dict): config dictionary device (device): pytorch device dataset (dataset): dataset |
12,502 | import yaml
from torchvision import transforms
from im2mesh import data
from im2mesh import onet, r2n2, psgn, pix2mesh, dmc
from im2mesh import preprocess
method_dict = {
'onet': onet,
'r2n2': r2n2,
'psgn': psgn,
'pix2mesh': pix2mesh,
'dmc': dmc,
}
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, optimizer, cfg, device)` to solve the following problem:
Returns a trainer instance. Args: model (nn.Module): the model which is used optimizer (optimizer): pytorch optimizer cfg (dict): config dictionary device (device): pytorch device
Here is the function:
def get_trainer(model, optimizer, cfg, device):
''' Returns a trainer instance.
Args:
model (nn.Module): the model which is used
optimizer (optimizer): pytorch optimizer
cfg (dict): config dictionary
device (device): pytorch device
'''
method = cfg['method']
trainer = method_dict[method].config.get_trainer(
model, optimizer, cfg, device)
return trainer | Returns a trainer instance. Args: model (nn.Module): the model which is used optimizer (optimizer): pytorch optimizer cfg (dict): config dictionary device (device): pytorch device |
12,503 | import yaml
from torchvision import transforms
from im2mesh import data
from im2mesh import onet, r2n2, psgn, pix2mesh, dmc
from im2mesh import preprocess
method_dict = {
'onet': onet,
'r2n2': r2n2,
'psgn': psgn,
'pix2mesh': pix2mesh,
'dmc': dmc,
}
The provided code snippet includes necessary dependencies for implementing the `get_generator` function. Write a Python function `def get_generator(model, cfg, device)` to solve the following problem:
Returns a generator instance. Args: model (nn.Module): the model which is used cfg (dict): config dictionary device (device): pytorch device
Here is the function:
def get_generator(model, cfg, device):
''' Returns a generator instance.
Args:
model (nn.Module): the model which is used
cfg (dict): config dictionary
device (device): pytorch device
'''
method = cfg['method']
generator = method_dict[method].config.get_generator(model, cfg, device)
return generator | Returns a generator instance. Args: model (nn.Module): the model which is used cfg (dict): config dictionary device (device): pytorch device |
12,504 | import yaml
from torchvision import transforms
from im2mesh import data
from im2mesh import onet, r2n2, psgn, pix2mesh, dmc
from im2mesh import preprocess
method_dict = {
'onet': onet,
'r2n2': r2n2,
'psgn': psgn,
'pix2mesh': pix2mesh,
'dmc': dmc,
}
def get_inputs_field(mode, cfg):
''' Returns the inputs fields.
Args:
mode (str): the mode which is used
cfg (dict): config dictionary
'''
input_type = cfg['data']['input_type']
with_transforms = cfg['data']['with_transforms']
if input_type is None:
inputs_field = None
elif input_type == 'img':
if mode == 'train' and cfg['data']['img_augment']:
resize_op = transforms.RandomResizedCrop(
cfg['data']['img_size'], (0.75, 1.), (1., 1.))
else:
resize_op = transforms.Resize((cfg['data']['img_size']))
transform = transforms.Compose([
resize_op, transforms.ToTensor(),
])
with_camera = cfg['data']['img_with_camera']
if mode == 'train':
random_view = True
else:
random_view = False
inputs_field = data.ImagesField(
cfg['data']['img_folder'], transform,
with_camera=with_camera, random_view=random_view
)
elif input_type == 'pointcloud':
transform = transforms.Compose([
data.SubsamplePointcloud(cfg['data']['pointcloud_n']),
data.PointcloudNoise(cfg['data']['pointcloud_noise'])
])
with_transforms = cfg['data']['with_transforms']
inputs_field = data.PointCloudField(
cfg['data']['pointcloud_file'], transform,
with_transforms=with_transforms
)
elif input_type == 'voxels':
inputs_field = data.VoxelsField(
cfg['data']['voxels_file']
)
elif input_type == 'idx':
inputs_field = data.IndexField()
else:
raise ValueError(
'Invalid input type (%s)' % input_type)
return inputs_field
The provided code snippet includes necessary dependencies for implementing the `get_dataset` function. Write a Python function `def get_dataset(mode, cfg, return_idx=False, return_category=False)` to solve the following problem:
Returns the dataset. Args: model (nn.Module): the model which is used cfg (dict): config dictionary return_idx (bool): whether to include an ID field
Here is the function:
def get_dataset(mode, cfg, return_idx=False, return_category=False):
''' Returns the dataset.
Args:
model (nn.Module): the model which is used
cfg (dict): config dictionary
return_idx (bool): whether to include an ID field
'''
method = cfg['method']
dataset_type = cfg['data']['dataset']
dataset_folder = cfg['data']['path']
categories = cfg['data']['classes']
# Get split
splits = {
'train': cfg['data']['train_split'],
'val': cfg['data']['val_split'],
'test': cfg['data']['test_split'],
}
split = splits[mode]
# Create dataset
if dataset_type == 'Shapes3D':
# Dataset fields
# Method specific fields (usually correspond to output)
fields = method_dict[method].config.get_data_fields(mode, cfg)
# Input fields
inputs_field = get_inputs_field(mode, cfg)
if inputs_field is not None:
fields['inputs'] = inputs_field
if return_idx:
fields['idx'] = data.IndexField()
if return_category:
fields['category'] = data.CategoryField()
dataset = data.Shapes3dDataset(
dataset_folder, fields,
split=split,
categories=categories,
)
elif dataset_type == 'kitti':
dataset = data.KittiDataset(
dataset_folder, img_size=cfg['data']['img_size'],
return_idx=return_idx
)
elif dataset_type == 'online_products':
dataset = data.OnlineProductDataset(
dataset_folder, img_size=cfg['data']['img_size'],
classes=cfg['data']['classes'],
max_number_imgs=cfg['generation']['max_number_imgs'],
return_idx=return_idx, return_category=return_category
)
elif dataset_type == 'images':
dataset = data.ImageDataset(
dataset_folder, img_size=cfg['data']['img_size'],
return_idx=return_idx,
)
else:
raise ValueError('Invalid dataset "%s"' % cfg['data']['dataset'])
return dataset | Returns the dataset. Args: model (nn.Module): the model which is used cfg (dict): config dictionary return_idx (bool): whether to include an ID field |
12,505 | import os
from im2mesh.dmc import models, training, generation
from im2mesh import data
def get_model(cfg, device=None, **kwargs):
encoder = cfg['model']['encoder']
decoder = cfg['model']['decoder']
c_dim = cfg['model']['c_dim']
encoder_kwargs = cfg['model']['encoder_kwargs']
decoder_kwargs = cfg['model']['decoder_kwargs']
encoder = models.encoder_dict[encoder](
**encoder_kwargs
)
decoder = models.decoder_dict[decoder](
**decoder_kwargs
)
model = models.DMC(decoder, encoder)
model = model.to(device)
return model | null |
12,506 | import os
from im2mesh.dmc import models, training, generation
from im2mesh import data
def get_trainer(model, optimizer, cfg, device, **kwargs):
input_type = cfg['data']['input_type']
out_dir = cfg['training']['out_dir']
vis_dir = os.path.join(out_dir, 'vis')
num_voxels = cfg['model']['num_voxels']
weight_prior = cfg['model']['dmc_weight_prior']
trainer = training.Trainer(
model, optimizer, device=device, input_type=input_type,
vis_dir=vis_dir, num_voxels=num_voxels,
weight_prior=weight_prior,
)
return trainer | null |
12,507 | import os
from im2mesh.dmc import models, training, generation
from im2mesh import data
def get_generator(model, cfg, device, **kwargs):
num_voxels = cfg['model']['num_voxels']
generator = generation.Generator3D(
model, device=device, num_voxels=num_voxels
)
return generator | null |
12,508 | import os
from im2mesh.dmc import models, training, generation
from im2mesh import data
def get_data_fields(split, cfg, **kwargs):
with_transforms = cfg['data']['with_transforms']
# TODO: put this into config
pointcloud_n = 3000
pointcloud_transform = data.SubsamplePointcloud(pointcloud_n)
fields = {}
fields['pointcloud'] = data.PointCloudField(
cfg['data']['pointcloud_file'], pointcloud_transform,
with_transforms=with_transforms
)
return fields | null |
12,509 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_accept_topology` function. Write a Python function `def get_accept_topology(num_tri=3)` to solve the following problem:
Get the list of the singly connected topologies up to a specified number of triangles
Here is the function:
def get_accept_topology(num_tri=3):
"""Get the list of the singly connected topologies up to a specified
number of triangles
"""
# get accpet topology list for up to __3__ triangles
# only the first half of topologies is given in this list as the rest
# half is dual to the first half, i.e. if $x$ is in the list then
# $256-x$ is in the list as well
if num_tri == 3:
accept_topology = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 19, 25, 31, 32, 34, 35, 38, 47, 48, 49, 50, 51, 55, 59, 63, 64, 68, 70, 76, 79, 96, 98, 100, 102, 103, 110, 111, 112, 115, 118, 119, 127, 0]
# get accpet topology list for up to __4__ triangles
# return all topologies as the dual condition is not satisfied anymore
# when the topogolies with 4 triangles are considered
elif num_tri == 4:
accept_topology = [0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 19, 23, 25, 27, 29, 31, 32, 34, 35, 38, 39, 43, 46, 47, 48, 49, 50, 51, 54, 55, 57, 59, 63, 64, 68, 70, 71, 76, 77, 78, 79, 95, 96, 98, 99, 100, 102, 103, 108, 110, 111, 112, 113, 114, 115, 116, 118, 119, 123, 126, 127, 128, 136, 137, 139, 140, 141, 142, 143, 144, 145, 147, 152, 153, 155, 156, 157, 159, 175, 176, 177, 178, 179, 183, 184, 185, 187, 189, 191, 192, 196, 198, 200, 201, 204, 205, 206, 207, 208, 209, 212, 216, 217, 219, 220, 221, 222, 223, 224, 226, 228, 230, 231, 232, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]
return accept_topology | Get the list of the singly connected topologies up to a specified number of triangles |
12,510 | import numpy as np
def check_connected(triangles, v1, v2):
# number of all triangles
T = len(triangles)
compatible_mat = np.zeros((T, T))
match = {}
for ind,x in enumerate(v1):
match[x] = v2[ind]
for i in range(T):
for j in range(T):
t1 = triangles[i]
t2 = triangles[j]
inter1 = list(set(t1).intersection(v1))
inter2 = list(set(t2).intersection(v2))
# only connected if there are two intersection points on both side
# and these intersection points are matched
if len(inter1)==2 and len(inter2)==2:
inter1_m = [match[k] for k in inter1]
if set(inter1_m) == set(inter2):
compatible_mat[i, j]=1
#print "============ ", t1, "<---->" , t2
return compatible_mat
def get_connected_inner_cell(triangles, classes):
T = len(triangles)
connected_inner = np.zeros((T, T))
table = get_triangle_table(symmetry=0)
offset = -1
for topology in table:
tri_ind1 = offset
for tri1 in topology:
tri_ind1 += 1
# if there is more than one triangle
if len(topology)>1:
# traverse all the triangles in the same topology
tri_ind2 = offset
for tri2 in topology:
tri_ind2 += 1
# two intsersection points means connected
if len(set(tri1).intersection(set(tri2))) == 2:
connected_inner[tri_ind1, tri_ind2] = 1
offset += len(topology)
return connected_inner
def get_unique_triangles(table=None, symmetry=1):
if table is None:
table = get_triangle_table(symmetry)
triangles = []
classes = []
for ind, topology in enumerate(table):
for triangle in topology:
triangles.append(triangle)
classes.append(ind)
triangles_unique = []
triangles_class = []
cnt=0
for ind, new_tri in enumerate(triangles):
cnt+=1
if len(triangles_unique):
### repeat checking is disabled
#check repeat
repeat=0
#for pre_tri in triangles_unique:
# if len(set(pre_tri).intersection(set(new_tri)))==3:
# repeat=1
# # print 'repeat detected ', new_tri
# break
### repeat checking is disabled
if repeat==0:
triangles_unique.append(new_tri)
triangles_class.append(classes[ind])
else:
triangles_unique.append(new_tri)
triangles_class.append(classes[ind])
return triangles_unique, triangles_class
The provided code snippet includes necessary dependencies for implementing the `get_connected_pairs` function. Write a Python function `def get_connected_pairs()` to solve the following problem:
return connected pairs in x, y, z directions
Here is the function:
def get_connected_pairs():
"""return connected pairs in x, y, z directions"""
triangles, classes = get_unique_triangles(symmetry=0)
#print triangles
# x direction, from left to right
leftv = [5, 9, 1, 10]
rightv = [7, 8, 3, 11]
connected_x = check_connected(triangles, leftv, rightv)
# y direction, from front to back
frontv = [4, 9, 0, 8]
backv = [6, 10, 2, 11]
connected_y = check_connected(triangles, frontv, backv)
# z direction, from bottom to top
bottomv = [4, 5, 6, 7]
topv = [0, 1, 2, 3]
connected_z = check_connected(triangles, bottomv, topv)
connected_inner = get_connected_inner_cell(triangles, classes)
return connected_x, connected_y, connected_z, connected_inner, classes | return connected pairs in x, y, z directions |
12,511 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_occupancy_table` function. Write a Python function `def get_occupancy_table()` to solve the following problem:
Return binary occupancy status of 8 vertices for all 256 topology types
Here is the function:
def get_occupancy_table():
"""Return binary occupancy status of 8 vertices for all 256 topology types"""
occTable = np.zeros((256, 8))
for x in range(256):
for v in range(8):
occTable[x, v] = int(x)&(pow(2,v))!=0
return occTable | Return binary occupancy status of 8 vertices for all 256 topology types |
12,512 | import numpy as np
import torch
from torch.autograd import Variable
import time
one = Variable(torch.ones(1).type(torch.FloatTensor), requires_grad=True)
eps = 1e-8
def pointTriangleDistance(TRI, P):
# function [dist,PP0] = pointTriangleDistance(TRI,P)
# calculate distance between a point and a triangle in 3D
# SYNTAX
# dist = pointTriangleDistance(TRI,P)
# [dist,PP0] = pointTriangleDistance(TRI,P)
#
# DESCRIPTION
# Calculate the distance of a given point P from a triangle TRI.
# Point P is a row vector of the form 1x3. The triangle is a matrix
# formed by three rows of points TRI = [P1;P2;P3] each of size 1x3.
# dist = pointTriangleDistance(TRI,P) returns the distance of the point P
# to the triangle TRI.
# [dist,PP0] = pointTriangleDistance(TRI,P) additionally returns the
# closest point PP0 to P on the triangle TRI.
#
# Author: Gwolyn Fischer
# Release: 1.0
# Release date: 09/02/02
# Release: 1.1 Fixed Bug because of normalization
# Release: 1.2 Fixed Bug because of typo in region 5 20101013
# Release: 1.3 Fixed Bug because of typo in region 2 20101014
# Possible extention could be a version tailored not to return the distance
# and additionally the closest point, but instead return only the closest
# point. Could lead to a small speed gain.
# Example:
# %% The Problem
# P0 = [0.5 -0.3 0.5]
#
# P1 = [0 -1 0]
# P2 = [1 0 0]
# P3 = [0 0 0]
#
# vertices = [P1; P2; P3]
# faces = [1 2 3]
#
# %% The Engine
# [dist,PP0] = pointTriangleDistance([P1;P2;P3],P0)
#
# %% Visualization
# [x,y,z] = sphere(20)
# x = dist*x+P0(1)
# y = dist*y+P0(2)
# z = dist*z+P0(3)
#
# figure
# hold all
# patch('Vertices',vertices,'Faces',faces,'FaceColor','r','FaceAlpha',0.8)
# plot3(P0(1),P0(2),P0(3),'b*')
# plot3(PP0(1),PP0(2),PP0(3),'*g')
# surf(x,y,z,'FaceColor','b','FaceAlpha',0.3)
# view(3)
# The algorithm is based on
# "David Eberly, 'Distance Between Point and Triangle in 3D',
# Geometric Tools, LLC, (1999)"
# http:\\www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf
#
# ^t
# \ |
# \reg2|
# \ |
# \ |
# \ |
# \|
# *P2
# |\
# | \
# reg3 | \ reg1
# | \
# |reg0\
# | \
# | \ P1
# -------*-------*------->s
# |P0 \
# reg4 | reg5 \ reg6
# rewrite triangle in normal form
#
reg = -1
assert(np.isnan(np.sum(TRI.data.numpy()))==0)
assert(np.isnan(np.sum(P.data.numpy()))==0)
B = TRI[:, 0]
E0 = TRI[:, 1] - B
# E0 = E0/sqrt(sum(E0.^2)); %normalize vector
E1 = TRI[:, 2] - B
# E1 = E1/sqrt(sum(E1.^2)); %normalize vector
D = B - P
a = torch.dot(E0, E0)
b = torch.dot(E0, E1)
c = torch.dot(E1, E1)
d = torch.dot(E0, D)
e = torch.dot(E1, D)
f = torch.dot(D, D)
#print "{0} {1} {2} ".format(B,E1,E0)
det = a * c - b * b
s = b * e - c * d
t = b * d - a * e
# Terible tree of conditionals to determine in which region of the diagram
# shown above the projection of the point into the triangle-plane lies.
if (s.data[0] + t.data[0]) <= det.data[0]:
if s.data[0] < 0.0:
if t.data[0] < 0.0:
# region4
reg = 4
if d.data[0] < 0:
t = 0.0
if -d.data[0] >= a.data[0]:
s = 1.0
sqrdistance = a + 2.0 * d + f
else:
s = -d / (a + eps)
sqrdistance = d * s + f
else:
s.data[0] = 0.0
if e.data[0] >= 0.0:
t = 0.0
sqrdistance = f
else:
if -e.data[0] >= c.data[0]:
t = 1.0
sqrdistance = c + 2.0 * e + f
else:
t = -e / (c + eps)
sqrdistance = e * t + f
# of region 4
else:
reg = 3
# region 3
s.data[0] = 0
if e.data[0] >= 0:
t = 0
sqrdistance = f
else:
if -e.data[0] >= c.data[0]:
t = 1
sqrdistance = c + 2.0 * e + f
else:
t = -e / (c + eps)
sqrdistance = e * t + f
# of region 3
else:
if t.data[0] < 0:
reg = 5
# region 5
t = 0
if d.data[0] >= 0:
s = 0
sqrdistance = f
else:
if -d.data[0] >= a.data[0]:
s = 1.0
sqrdistance = a + 2.0 * d + f; # GF 20101013 fixed typo d*s ->2*d
else:
s = -d / (a + eps)
sqrdistance = d * s + f
else:
reg = 0
# region 0
invDet = 1.0 / (det + eps)
s = s * invDet
t = t * invDet
if s.data[0] == 0:
sqrdistance = d
else:
sqrdistance = s * (a * s + b * t + 2.0 * d) + t * (b * s + c * t + 2.0 * e) + f
else:
if s.data[0] < 0.0:
reg = 2
# region 2
tmp0 = b + d
tmp1 = c + e
if tmp1.data[0] > tmp0.data[0]: # minimum on edge s+t=1
numer = tmp1 - tmp0
denom = a - 2.0 * b + c
if numer.data[0] >= denom.data[0]:
s = 1.0
t = 0.0
sqrdistance = a + 2.0 * d + f; # GF 20101014 fixed typo 2*b -> 2*d
else:
s = numer / (denom + eps)
t = 1 - s
sqrdistance = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f
else: # minimum on edge s=0
s = 0.0
if tmp1.data[0] <= 0.0:
t = 1
sqrdistance = c + 2.0 * e + f
else:
if e.data[0] >= 0.0:
t = 0.0
sqrdistance = f
else:
t = -e / (c + eps)
sqrdistance = e * t + f
# of region 2
else:
if t.data[0] < 0.0:
reg = 6
# region6
tmp0 = b + e
tmp1 = a + d
if tmp1.data[0] > tmp0.data[0]:
numer = tmp1 - tmp0
denom = a - 2.0 * b + c
if numer.data[0] >= denom.data[0]:
t = 1.0
s = 0
sqrdistance = c + 2.0 * e + f
else:
t = numer / (denom + eps)
s = 1 - t
sqrdistance = s * (a * s + b * t + 2.0 * d) + t * (b * s + c * t + 2.0 * e) + f
else:
t = 0.0
if tmp1.data[0] <= 0.0:
s = 1
sqrdistance = a + 2.0 * d + f
else:
if d.data[0] >= 0.0:
s = 0.0
sqrdistance = f
else:
s = -d / (a + eps)
sqrdistance = d * s + f
else:
reg = 1
# region 1
numer = c + e - b - d
if numer.data[0] <= 0:
s = 0.0
t = 1.0
sqrdistance = c + 2.0 * e + f
else:
denom = a - 2.0 * b + c
if numer.data[0] >= denom.data[0]:
s = 1.0
t = 0.0
sqrdistance = a + 2.0 * d + f
else:
s = numer / (denom + eps)
t = 1 - s
sqrdistance = s * (a * s + b * t + 2.0 * d) + t * (b * s + c * t + 2.0 * e) + f
# account for numerical round-off error
#dist = torch.sqrt(torch.max(sqrdistance, 0*one))
# directly return sqr distance
dist = torch.max(sqrdistance, 0*one)
#PP0 = B + s.expand_as(E0) * E0 + t.expand_as(E1) * E1
assert(np.isnan(dist.data[0])==0)
return dist, reg | null |
12,513 | import numpy as np
import torch
from torch.autograd import Variable
from im2mesh.dmc.utils.pointTriangleDistance import pointTriangleDistance, pointTriangleDistanceFast
from im2mesh.dmc.ops.table import get_triangle_table, get_unique_triangles, vertices_on_location
topologys = get_triangle_table()
def dis_to_mesh(pts, pts_index, vertices, faces, x_, y_, z_):
""" Return the distance from a point set to a single topology type
Input:
pts, (Nx3) a set of points
pts_index, (Nx1) indicating if a point is in the cell or not
vertices, (3x12) the 12 vertices on each edge of the cell
faces, (fx3) the
x_, the offset of the cell in x direction
y_, the offset of the cell in y direction
z_, the offset of the cell in z direction
Output:
distances
"""
if pts.is_cuda:
dtype = torch.cuda.FloatTensor
dtype_long = torch.cuda.LongTensor
else:
dtype = torch.FloatTensor
dtype_long = torch.LongTensor
one = Variable(torch.ones(1).type(dtype), requires_grad=True)
if len(pts_index) == 0 and len(faces) == 0:
return 0.0*one
if len(pts_index) == 0 and len(faces) != 0:
return 1.0*one
if len(pts_index) != 0 and len(faces) == 0:
return 1e+3 * one
pts_index = Variable(dtype_long(pts_index))
# for each triangles in each topology, face is a vector of 3
dis_all_faces = []
for face in faces:
triangle = torch.cat((torch.cat(vertices[face[0]]).unsqueeze(1),
torch.cat(vertices[face[1]]).unsqueeze(1),
torch.cat(vertices[face[2]]).unsqueeze(1)), 1)
# use the fast and approximated point to triangle distance
dis_all_faces.append(pointTriangleDistanceFast(triangle, pts.index_select(0, pts_index)
- Variable(dtype([x_, y_, z_])).unsqueeze(0).expand(pts_index.size()[0], 3)))
# only count the nearest distance to the triangles
dis_all_faces, _ = torch.min(torch.cat(dis_all_faces, dim=1), dim=1)
return torch.mean(dis_all_faces).view(1)
The provided code snippet includes necessary dependencies for implementing the `dis_to_meshs` function. Write a Python function `def dis_to_meshs(pts, pts_index, vectices, x_, y_, z_ )` to solve the following problem:
Return the distances from a point set to all acceptable topology types in a single cell Input: pts, (Nx3) a set of points pts_index, (Nx1) indicating if a point is in the cell or not vertices, (3x12) the 12 vertices on each edge of the cell x_, the offset of the cell in x direction y_, the offset of the cell in y direction z_, the offset of the cell in z direction Output: distances
Here is the function:
def dis_to_meshs(pts, pts_index, vectices, x_, y_, z_ ):
""" Return the distances from a point set to all acceptable topology types
in a single cell
Input:
pts, (Nx3) a set of points
pts_index, (Nx1) indicating if a point is in the cell or not
vertices, (3x12) the 12 vertices on each edge of the cell
x_, the offset of the cell in x direction
y_, the offset of the cell in y direction
z_, the offset of the cell in z direction
Output:
distances
"""
distances = [dis_to_mesh(pts[0], pts_index, vectices, faces, x_, y_, z_) for faces in topologys]
distances = torch.cat(distances)
# adaptively assign the cost for the empty case
if len(pts_index)!=0:
distances[-1].item = torch.max(distances[0:-1]).item() * 10.0
return distances | Return the distances from a point set to all acceptable topology types in a single cell Input: pts, (Nx3) a set of points pts_index, (Nx1) indicating if a point is in the cell or not vertices, (3x12) the 12 vertices on each edge of the cell x_, the offset of the cell in x direction y_, the offset of the cell in y direction z_, the offset of the cell in z direction Output: distances |
12,514 | import numpy as np
import torch
from torch.autograd import Variable
from im2mesh.dmc.utils.pointTriangleDistance import pointTriangleDistance, pointTriangleDistanceFast
from im2mesh.dmc.ops.table import get_triangle_table, get_unique_triangles, vertices_on_location
The provided code snippet includes necessary dependencies for implementing the `pts_in_cell` function. Write a Python function `def pts_in_cell(pts, cell)` to solve the following problem:
get the point indices incide of a given cell (pyTorch) Input: pts, a set of points in pytorch format cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2} Output: inds, a list of indices for points inside the cell
Here is the function:
def pts_in_cell(pts, cell):
""" get the point indices incide of a given cell (pyTorch)
Input:
pts, a set of points in pytorch format
cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2}
Output:
inds, a list of indices for points inside the cell
"""
N = pts.size()[1]
cell = torch.FloatTensor(cell)
if pts.is_cuda:
cell = cell.cuda()
inds = [i for i in range(N) if pts[0,i,0].item()>cell[0] and pts[0,i,0].item() < cell[3]
and pts[0,i,1].item()>cell[1] and pts[0,i,1].item() < cell[4]
and pts[0,i,2].item()>cell[2] and pts[0,i,2].item() < cell[5]]
return inds | get the point indices incide of a given cell (pyTorch) Input: pts, a set of points in pytorch format cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2} Output: inds, a list of indices for points inside the cell |
12,515 | import numpy as np
import torch
from torch.autograd import Variable
from im2mesh.dmc.utils.pointTriangleDistance import pointTriangleDistance, pointTriangleDistanceFast
from im2mesh.dmc.ops.table import get_triangle_table, get_unique_triangles, vertices_on_location
The provided code snippet includes necessary dependencies for implementing the `pts_in_cell_numpy` function. Write a Python function `def pts_in_cell_numpy(pts, cell)` to solve the following problem:
get the point indices incide of a given cell (numpy) Input: pts, a set of points in numpy format cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2} Output: inds, a list of indices for points inside the cell
Here is the function:
def pts_in_cell_numpy(pts, cell):
""" get the point indices incide of a given cell (numpy)
Input:
pts, a set of points in numpy format
cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2}
Output:
inds, a list of indices for points inside the cell
"""
N = pts.shape[0]
inds = [i for i in range(N) if pts[i,0]>cell[0] and pts[i,0] < cell[3]
and pts[i,1]>cell[1] and pts[i,1] < cell[4]
and pts[i,2]>cell[2] and pts[i,2] < cell[5]]
return inds | get the point indices incide of a given cell (numpy) Input: pts, a set of points in numpy format cell, a list of 6 numbers {x1, y1, z1, x2, y2, z2} Output: inds, a list of indices for points inside the cell |
12,516 | import numpy as np
import torch
from torch.autograd import Variable
from im2mesh.dmc.utils.pointTriangleDistance import pointTriangleDistance, pointTriangleDistanceFast
from im2mesh.dmc.ops.table import get_triangle_table, get_unique_triangles, vertices_on_location
def offset_to_vertices(offset, x, y, z):
""" get 12 intersect points on each edge of a single cell """
if offset.is_cuda:
dtype = torch.cuda.FloatTensor
else:
dtype = torch.FloatTensor
one = Variable(torch.ones(1).type(dtype), requires_grad=True)
p = [ [(0.5-offset[0, x+1, y+1, z ])*one, 1.0*one, 0.0*one], #0
[1.0*one, (0.5-offset[1, x+1, y+1, z ])*one, 0.0*one], #1
[(0.5-offset[0, x+1, y , z ])*one, 0.0*one, 0.0*one], #2
[0.0*one, (0.5-offset[1, x , y+1, z ])*one, 0.0*one], #3
[(0.5-offset[0, x+1, y+1, z+1])*one, 1.0*one, 1.0*one], #4
[1.0*one, (0.5-offset[1, x+1, y+1,z+1])*one, 1.0*one], #5
[(0.5-offset[0, x+1, y , z+1])*one, 0.0*one, 1.0*one], #6
[0.0*one, (0.5-offset[1, x , y+1,z+1])*one, 1.0*one], #7
[0.0*one, 1.0*one, (0.5-offset[2, x ,y+1,z+1])*one], #8
[1.0*one, 1.0*one, (0.5-offset[2, x+1,y+1,z+1])*one], #9
[1.0*one, 0.0*one, (0.5-offset[2, x+1,y ,z+1])*one], #10
[0.0*one, 0.0*one, (0.5-offset[2, x ,y ,z+1])*one]] #11
return p
def vertices_on_location():
"""Return vertices on different faces
# x direction, from left to right
leftv = [5, 9, 1, 10]
rightv = [7, 8, 3, 11]
# y direction, from front to back
frontv = [4, 9, 0, 8]
backv = [6, 10, 2, 11]
# z direction, from bottom to top
bottomv = [4, 5, 6, 7]
topv = [0, 1, 2, 3]
"""
return [[5, 9, 1, 10],
[7, 8, 3, 11],
[4, 9, 0, 8],
[6, 10, 2, 11],
[4, 5, 6, 7],
[0, 1, 2, 3]]
def get_unique_triangles(table=None, symmetry=1):
if table is None:
table = get_triangle_table(symmetry)
triangles = []
classes = []
for ind, topology in enumerate(table):
for triangle in topology:
triangles.append(triangle)
classes.append(ind)
triangles_unique = []
triangles_class = []
cnt=0
for ind, new_tri in enumerate(triangles):
cnt+=1
if len(triangles_unique):
### repeat checking is disabled
#check repeat
repeat=0
#for pre_tri in triangles_unique:
# if len(set(pre_tri).intersection(set(new_tri)))==3:
# repeat=1
# # print 'repeat detected ', new_tri
# break
### repeat checking is disabled
if repeat==0:
triangles_unique.append(new_tri)
triangles_class.append(classes[ind])
else:
triangles_unique.append(new_tri)
triangles_class.append(classes[ind])
return triangles_unique, triangles_class
The provided code snippet includes necessary dependencies for implementing the `offset_to_normal` function. Write a Python function `def offset_to_normal(offset, x, y, z, location)` to solve the following problem:
get normal vector of all triangles
Here is the function:
def offset_to_normal(offset, x, y, z, location):
"""get normal vector of all triangles"""
p = offset_to_vertices(offset, x, y, z)
# get unique triangles from all topologies
triangles, classes = get_unique_triangles(symmetry=0)
# get normal vector of each triangle
# assign a dummy normal vector to the unconnected ones
# the vertices we care on the specific face
vertices = []
if location<6:
vertices = vertices_on_location()[location]
normal = []
if offset.is_cuda:
dtype = torch.cuda.FloatTensor
else:
dtype = torch.FloatTensor
for tri in triangles:
# if the triangle doesn't has a line on the face we care about
# simply assign a dummy normal vector
intersection = [xx for xx in vertices if xx in tri]
#print tri, intersection
if location < 6 and len(intersection)!=2:
normal.append(Variable(torch.ones(3, 1).type(dtype)))
else:
### when inside/outside is considered
a=tri[0]
b=tri[1]
c=tri[2]
normal.append(torch.cross(torch.cat(p[b])-torch.cat(p[a]), torch.cat(p[c])-torch.cat(p[a])).view(3, 1))
return torch.cat(normal).view(-1,3) | get normal vector of all triangles |
12,517 | import numpy as np
import torch
from torch.autograd import Variable
from im2mesh.dmc.utils.pointTriangleDistance import pointTriangleDistance, pointTriangleDistanceFast
from im2mesh.dmc.ops.table import get_triangle_table, get_unique_triangles, vertices_on_location
The provided code snippet includes necessary dependencies for implementing the `gaussian_kernel` function. Write a Python function `def gaussian_kernel(l, sig=1.)` to solve the following problem:
get the gaussian kernel https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy
Here is the function:
def gaussian_kernel(l, sig=1.):
""" get the gaussian kernel
https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy
"""
ax = np.arange(-l//2 + 1., l//2 + 1.)
xx, yy, zz = np.meshgrid(ax, ax, ax)
kernel = np.exp(-(xx**2 + yy**2 + zz**2) / (2. * sig**2))
return kernel | get the gaussian kernel https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy |
12,518 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
import os
import numpy as np
from utils.util import write_to_off, unique_rows
from _ext import eval_util
def write_to_off(vertices, faces, filename):
"""write the given vertices and faces to off"""
f = open(filename, 'w')
f.write('OFF\n')
n_vertice = vertices.shape[0]
n_face = faces.shape[0]
f.write('%d %d 0\n' % (n_vertice, n_face))
for nv in range(n_vertice):
## !!! exchange the coordinates to match the orignal simplified mesh !!!
## !!! need to check where the coordinate is exchanged !!!
f.write('%f %f %f\n' % (vertices[nv,1], vertices[nv,2], vertices[nv,0]))
for nf in range(n_face):
f.write('3 %d %d %d\n' % (faces[nf,0], faces[nf,1], faces[nf,2]))
def unique_rows(a):
""" Return the matrix with unique rows """
rowtype = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
b = np.ascontiguousarray(a).view(rowtype)
_, idx, inverse = np.unique(b, return_index=True, return_inverse=True)
return a[idx], inverse
The provided code snippet includes necessary dependencies for implementing the `save_mesh_fig` function. Write a Python function `def save_mesh_fig(pts_rnd_, offset, topology, x_grids, y_grids, z_grids, ind, args, phase)` to solve the following problem:
save the estimated mesh with maximum likelihood as image
Here is the function:
def save_mesh_fig(pts_rnd_, offset, topology, x_grids, y_grids, z_grids, ind, args, phase):
""" save the estimated mesh with maximum likelihood as image """
# get the topology type with maximum probability in each cell
num_cells = len(x_grids)-1
_, topology_max = torch.max(topology, dim=1)
topology_max = topology_max.view(num_cells, num_cells, num_cells)
# pre-allocate the memory, not safe
vertices = torch.FloatTensor(num_cells**3 * 12, 3)
faces = torch.FloatTensor(num_cells**3 * 12, 3)
num_vertices = torch.LongTensor(1)
num_faces = torch.LongTensor(1)
# get the mesh from the estimated offest and topology
eval_util.pred_to_mesh(offset.data.cpu(), topology_max.data.cpu(),
vertices, faces, num_vertices, num_faces)
if num_vertices[0] == 0:
return
# cut the vertices and faces matrix according to the numbers
vertices = vertices[0:num_vertices[0], :].numpy()
faces = faces[0:num_faces[0], :].numpy()
# convert the vertices and face to numpy, and remove the duplicated vertices
if len(faces):
vertices = np.asarray(vertices)
vertices_unique, indices = unique_rows(vertices)
faces = np.asarray(faces).flatten()
faces_unique = faces[indices].reshape((-1, 3))
else:
vertices_unique = []
faces_unique = []
# if save_off then skip the png figure saving for efficiency
if phase == 'val' and args.save_off == 1:
# exchange the axes to match the off ground truth
if len(vertices_unique):
vertices_unique = vertices_unique[:, [2, 0, 1]]
write_to_off(vertices_unique, faces_unique,
os.path.join(args.output_dir, 'mesh', '%04d.off'%ind))
else:
xv_cls, yv_cls, zv_cls = np.meshgrid(x_grids[:-1], y_grids[:-1], z_grids[:-1], indexing='ij')
xv_cls = xv_cls.flatten()
yv_cls = yv_cls.flatten()
zv_cls = zv_cls.flatten()
fig = plt.figure(0)
fig.clear()
ax = fig.add_subplot(111, projection='3d')
# plot the scattered points
ax.scatter(pts_rnd_[:, 0], pts_rnd_[:, 1], pts_rnd_[:, 2], '.',
color='#727272', zorder=1)
# plot the mesh
color = [0.8, 0.5, 0.5]
ax.plot_trisurf(vertices_unique[:, 0],
vertices_unique[:, 1],
vertices_unique[:, 2],
triangles=faces_unique,
color=color,
edgecolor='none',
alpha=1.0)
ax.set_xlim(x_grids.min(), x_grids.max())
ax.set_ylim(y_grids.min(), y_grids.max())
ax.set_zlim(z_grids.min(), z_grids.max())
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
if phase == 'train':
fig_name = 'train_noise%.02f_epoch%d.png' % (args.noise, ind)
else:
fig_name = 'val_%s_noise%.02f_ind%d.png' % (
os.path.splitext(os.path.basename(args.model))[0],
args.noise,
ind)
plt.savefig(os.path.join(args.output_dir, fig_name)) | save the estimated mesh with maximum likelihood as image |
12,519 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
import os
import numpy as np
from utils.util import write_to_off, unique_rows
from _ext import eval_util
The provided code snippet includes necessary dependencies for implementing the `save_occupancy_fig` function. Write a Python function `def save_occupancy_fig(pts_rnd_, occupancy, x_grids, y_grids, z_grids, ind, args, phase)` to solve the following problem:
save the estimated occupancy as image
Here is the function:
def save_occupancy_fig(pts_rnd_, occupancy, x_grids, y_grids, z_grids, ind, args, phase):
""" save the estimated occupancy as image """
# skip the occupancy figure saving for efficiency
if phase == 'val' and args.save_off == 1:
return
xv_cls, yv_cls, zv_cls = np.meshgrid(
range(len(x_grids)),
range(len(y_grids)),
range(len(z_grids)),
indexing='ij')
xv_cls = xv_cls.flatten()
yv_cls = yv_cls.flatten()
zv_cls = zv_cls.flatten()
fig = plt.figure(0)
fig.clear()
ax = fig.add_subplot(111, projection='3d')
# plot the scattered points
ax.scatter(pts_rnd_[:, 0], pts_rnd_[:, 1], pts_rnd_[:, 2], '.',
color='#727272', zorder=1)
# assign the occupancy w.r.t. the probability
rgba_x = np.zeros((len(xv_cls), 4))
rgba_x[:, 0] = 1.0
rgba_x[:, 3] = occupancy.flatten()
# plot the occupancy
ax.scatter(xv_cls, yv_cls, zv_cls, '.', color=rgba_x, zorder=1)
ax.set_xlim(x_grids.min(), x_grids.max())
ax.set_ylim(y_grids.min(), y_grids.max())
ax.set_zlim(z_grids.min(), z_grids.max())
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
if phase == 'train':
fig = 'train_occ_noise%.02f_epoch_%d.png' % (args.noise, ind)
else:
fig = 'val_occ_%s_noise%.02f_ind_%d.png' % (
os.path.splitext(os.path.basename(args.model))[0],
args.noise,
ind)
plt.savefig(os.path.join(args.output_dir, fig)) | save the estimated occupancy as image |
12,520 | import argparse
import os
from ConfigParser import SafeConfigParser
from im2mesh.dmc.ops.table import get_triangle_table
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def get_triangle_table(symmetry=1):
"""Get desired table out of 256 topologies
Input:
symmetry: 1 neglect the inside/outside (default)
used for computing the point-to-triangle distance
0 consider inside/outside
used for curvature loss
"""
triangle_table = get_full_table()
table = []
ind = []
num_tri = []
for i in range(len(triangle_table)//(symmetry+1)):
edges = np.asarray(triangle_table[i])
edges = edges[np.where(edges>-1)]
# always valid if there is only one triangle
if len(edges) == 3:
table.append([triangle_table[i][0:3]])
ind.append(i)
num_tri.append(1)
# if there are two triangles, valid if there are four intersections
if len(edges) == 6 and len(np.unique(edges))==4:
table.append([triangle_table[i][0:3], triangle_table[i][3:6]])
ind.append(i)
num_tri.append(2)
# if there are three triangles, valid if there are five intersections
if len(edges) == 9 and len(np.unique(edges))==5:
table.append([triangle_table[i][0:3], triangle_table[i][3:6], triangle_table[i][6:9]])
ind.append(i)
num_tri.append(3)
# if there are four triangles, might be valid if there are six intersections
#if len(edges) == 12 and len(np.unique(edges))==6:
# table.append([triangle_table[i][0:3], triangle_table[i][3:6], triangle_table[i][6:9], triangle_table[i][9:12]] )
# ind.append(i)
# num_tri.append(4)
if symmetry == 1:
# append the empty case to the end of the list
table.append([])
ind.append(0)
num_tri.append(0)
elif symmetry == 0:
# insert free and occupied cases into middle to keep consistency with the symmetry case
# insert the free case
loc = len(table)//2
table.insert(loc, [])
ind.insert(loc, 0)
num_tri.insert(loc, 0)
# insert the occpied case
loc = loc+1
table.insert(loc, [])
ind.insert(loc, 255)
num_tri.insert(loc, 0)
return table
def parse_args():
parser = argparse.ArgumentParser()
# arguments for the model
parser.add_argument('--encoder_type',
help='Specify the type of the encoder, e.g. point, image',
default='point', choices=['point', 'voxel'], type=str)
parser.add_argument('--model',
help='Snapshotted model, for resuming training or validation',
default='', type=str)
parser.add_argument('--num_voxels',
help='Number of voxels on each dimension',
default=8, type=int)
# arguments for the training/test data
parser.add_argument('--data_type',
help='Specify the type of the input points, e.g. ellipsoid, cube, mix',
default='ellipsoid', choices=['ellipsoid', 'cube', 'mix3d', 'shapenet'], type=str)
parser.add_argument('--num_sample',
help='Number of sampled points on each mesh',
default=3000, type=int)
parser.add_argument('--bias_data',
help='Boolean variable to decide if use data sampled with angle bias',
default=False, type=str2bool)
parser.add_argument('--bias_level',
help='Float variable to decide the level of the angle bias, 1 means no data in a specific region',
default=0.0, type=float)
parser.add_argument('--noise',
help='Scale of the noise added to the input data',
default=0.01, type=float)
parser.add_argument('--perturb',
help='Scale of the noise added to the input data',
default=0, type=int)
parser.add_argument('--noise_gt',
help='If true then train the network with noisy gt',
default=0, type=int)
# arguments for directories and cached file names
parser.add_argument('--data_dir',
help='Input directory',
default='./data_blob', type=str)
parser.add_argument('--output_dir',
help='Output directory',
default=None, type=str)
parser.add_argument('--cached_train',
help='Location of training data, full path is needed',
default=None, type=str)
parser.add_argument('--cached_val',
help='Location of validation data, full path is needed',
default=None, type=str)
# arguments for training process
parser.add_argument('--batchsize',
help='Batch size for training',
default=8, type=int)
parser.add_argument('--epoch',
help='Number of epochs',
default=510, type=int)
parser.add_argument('--snapshot',
help='Snapshotting intervals',
default=20, type=int)
parser.add_argument('--verbose',
help='If print the training details or not',
default=True, type=str2bool)
parser.add_argument('--verbose_interval',
help='Interval of printing the training information',
default=10, type=int)
# arguments for saving results
parser.add_argument('--save_model',
help='If save the model or not',
default=True, type=str2bool)
parser.add_argument('--save_off',
help='If save the off mesh during the validation phase or not',
default=0, type=int)
# parameters for grid searching
parser.add_argument('--weight_distance',
default=5.0, type=float)
parser.add_argument('--weight_prior_pos',
default=0.2, type=float)
parser.add_argument('--weight_prior',
default=10.0, type=float)
parser.add_argument('--weight_smoothness',
default=3.0, type=float)
parser.add_argument('--weight_curvature',
default=3.0, type=float)
parser.add_argument('--weight_decay',
default=1e-3, type=float)
parser.add_argument('--learning_rate',
default=1e-4, type=float)
args = parser.parse_args()
# note the voxel and the cells are dual representation
# the corners of the cells are the middle point of the
# voxels
args.num_cells = args.num_voxels - 1
resolution = '%dx%dx%d' % (args.num_voxels, args.num_voxels, args.num_voxels)
if args.cached_train is None:
args.cached_train = os.path.join(
args.data_dir, 'points_%s_%s_train.npy' % (
args.data_type, resolution))
if args.cached_val is None:
args.cached_val = os.path.join(
args.data_dir, 'points_%s_%s_val.npy' % (
args.data_type, resolution))
default_dir = './output'
if args.output_dir is None:
args.output_dir = os.path.join(default_dir, '%s_%s_%s_pts%d_noisygt%d'
% (args.encoder_type, args.data_type, args.num_cells,
args.num_sample, args.noise_gt))
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
if args.save_off and not os.path.isdir(os.path.join(args.output_dir, 'mesh')):
os.makedirs(os.path.join(args.output_dir, 'mesh'))
## only support voxel input for shapenet
if args.encoder_type == 'voxel':
assert args.data_type == 'shapenet', 'Invalid combination of encoder_type and data_type!'
# get the number of accepted topologies
args.num_topology = len(get_triangle_table())
# fix the length of the cell edge as 1.0
args.len_cell = 1.0
# use skip connection in the u-net
args.skip_connection = True
args.num_train = 200
args.num_val = 100
return args | null |
12,521 | import torch
import numpy as np
from im2mesh.dmc.ops.cpp_modules import pred2mesh
The provided code snippet includes necessary dependencies for implementing the `unique_rows` function. Write a Python function `def unique_rows(a)` to solve the following problem:
Return the matrix with unique rows
Here is the function:
def unique_rows(a):
""" Return the matrix with unique rows """
rowtype = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
b = np.ascontiguousarray(a).view(rowtype)
_, idx, inverse = np.unique(b, return_index=True, return_inverse=True)
return a[idx], inverse | Return the matrix with unique rows |
12,522 | import torch
import numpy as np
from im2mesh.dmc.ops.cpp_modules import pred2mesh
The provided code snippet includes necessary dependencies for implementing the `pred_to_mesh_max` function. Write a Python function `def pred_to_mesh_max(offset, topology)` to solve the following problem:
Converts the predicted offset variable and topology to a mesh by choosing the most likely topology Input ---------- arg1 : tensor offset variables [3 x W+1 x H+1 x D+1] arg2 : tensor topology probabilities [W*H*D x T] Returns ------- trimesh format mesh
Here is the function:
def pred_to_mesh_max(offset, topology):
"""
Converts the predicted offset variable and topology to a mesh by choosing the most likely topology
Input
----------
arg1 : tensor
offset variables [3 x W+1 x H+1 x D+1]
arg2 : tensor
topology probabilities [W*H*D x T]
Returns
-------
trimesh format
mesh
"""
# get the topology type with maximum probability in each cell
num_cells = offset.size(1) - 1
_, topology_max = torch.max(topology, dim=1)
topology_max = topology_max.view(num_cells, num_cells, num_cells)
# pre-allocate the memory, not safe
vertices = torch.FloatTensor(num_cells**3 * 12, 3)
faces = torch.FloatTensor(num_cells**3 * 12, 3)
num_vertices = torch.LongTensor(1)
num_faces = torch.LongTensor(1)
topology_max = topology_max.int()
# get the mesh from the estimated offest and topology
pred2mesh.pred2mesh(offset.cpu(), topology_max.cpu(),
vertices, faces, num_vertices, num_faces)
# cut the vertices and faces matrix according to the numbers
vertices = vertices[0:num_vertices[0], :].numpy()
faces = faces[0:num_faces[0], :].numpy()
# convert the vertices and face to numpy, and remove the duplicated vertices
vertices_unique = np.asarray(vertices)
faces_unique = np.asarray(faces)
# if len(faces):
# vertices = np.asarray(vertices)
# vertices_unique, indices = unique_rows(vertices)
# faces = np.asarray(faces).flatten()
# faces_unique = faces[indices].reshape((-1, 3))
# else:
# vertices_unique = []
# faces_unique = []
# if len(vertices_unique):
# vertices_unique = vertices_unique[:, [2, 0, 1]]
return vertices_unique, faces_unique | Converts the predicted offset variable and topology to a mesh by choosing the most likely topology Input ---------- arg1 : tensor offset variables [3 x W+1 x H+1 x D+1] arg2 : tensor topology probabilities [W*H*D x T] Returns ------- trimesh format mesh |
12,523 | import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict
from im2mesh.onet import models, training, generation
from im2mesh import data
from im2mesh import config
def get_prior_z(cfg, device, **kwargs):
''' Returns prior distribution for latent code z.
Args:
cfg (dict): imported yaml config
device (device): pytorch device
'''
z_dim = cfg['model']['z_dim']
p0_z = dist.Normal(
torch.zeros(z_dim, device=device),
torch.ones(z_dim, device=device)
)
return p0_z
encoder_dict = {
'simple_conv': conv.ConvEncoder,
'resnet18': conv.Resnet18,
'resnet34': conv.Resnet34,
'resnet50': conv.Resnet50,
'resnet101': conv.Resnet101,
'r2n2_simple': r2n2.SimpleConv,
'r2n2_resnet': r2n2.Resnet,
'pointnet_simple': pointnet.SimplePointnet,
'pointnet_resnet': pointnet.ResnetPointnet,
'psgn_cond': psgn_cond.PCGN_Cond,
'voxel_simple': voxels.VoxelEncoder,
'pixel2mesh_cond': pix2mesh_cond.Pix2mesh_Cond,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, dataset=None, **kwargs)` to solve the following problem:
Return the Occupancy Network model. Args: cfg (dict): imported yaml config device (device): pytorch device dataset (dataset): dataset
Here is the function:
def get_model(cfg, device=None, dataset=None, **kwargs):
''' Return the Occupancy Network model.
Args:
cfg (dict): imported yaml config
device (device): pytorch device
dataset (dataset): dataset
'''
decoder = cfg['model']['decoder']
encoder = cfg['model']['encoder']
encoder_latent = cfg['model']['encoder_latent']
dim = cfg['data']['dim']
z_dim = cfg['model']['z_dim']
c_dim = cfg['model']['c_dim']
decoder_kwargs = cfg['model']['decoder_kwargs']
encoder_kwargs = cfg['model']['encoder_kwargs']
encoder_latent_kwargs = cfg['model']['encoder_latent_kwargs']
decoder = models.decoder_dict[decoder](
dim=dim, z_dim=z_dim, c_dim=c_dim,
**decoder_kwargs
)
if z_dim != 0:
encoder_latent = models.encoder_latent_dict[encoder_latent](
dim=dim, z_dim=z_dim, c_dim=c_dim,
**encoder_latent_kwargs
)
else:
encoder_latent = None
if encoder == 'idx':
encoder = nn.Embedding(len(dataset), c_dim)
elif encoder is not None:
encoder = encoder_dict[encoder](
c_dim=c_dim,
**encoder_kwargs
)
else:
encoder = None
p0_z = get_prior_z(cfg, device)
model = models.OccupancyNetwork(
decoder, encoder, encoder_latent, p0_z, device=device
)
return model | Return the Occupancy Network model. Args: cfg (dict): imported yaml config device (device): pytorch device dataset (dataset): dataset |
12,524 | import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict
from im2mesh.onet import models, training, generation
from im2mesh import data
from im2mesh import config
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, optimizer, cfg, device, **kwargs)` to solve the following problem:
Returns the trainer object. Args: model (nn.Module): the Occupancy Network model optimizer (optimizer): pytorch optimizer object cfg (dict): imported yaml config device (device): pytorch device
Here is the function:
def get_trainer(model, optimizer, cfg, device, **kwargs):
''' Returns the trainer object.
Args:
model (nn.Module): the Occupancy Network model
optimizer (optimizer): pytorch optimizer object
cfg (dict): imported yaml config
device (device): pytorch device
'''
threshold = cfg['test']['threshold']
out_dir = cfg['training']['out_dir']
vis_dir = os.path.join(out_dir, 'vis')
input_type = cfg['data']['input_type']
trainer = training.Trainer(
model, optimizer,
device=device, input_type=input_type,
vis_dir=vis_dir, threshold=threshold,
eval_sample=cfg['training']['eval_sample'],
)
return trainer | Returns the trainer object. Args: model (nn.Module): the Occupancy Network model optimizer (optimizer): pytorch optimizer object cfg (dict): imported yaml config device (device): pytorch device |
12,525 | import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict
from im2mesh.onet import models, training, generation
from im2mesh import data
from im2mesh import config
The provided code snippet includes necessary dependencies for implementing the `get_generator` function. Write a Python function `def get_generator(model, cfg, device, **kwargs)` to solve the following problem:
Returns the generator object. Args: model (nn.Module): Occupancy Network model cfg (dict): imported yaml config device (device): pytorch device
Here is the function:
def get_generator(model, cfg, device, **kwargs):
''' Returns the generator object.
Args:
model (nn.Module): Occupancy Network model
cfg (dict): imported yaml config
device (device): pytorch device
'''
preprocessor = config.get_preprocessor(cfg, device=device)
generator = generation.Generator3D(
model,
device=device,
threshold=cfg['test']['threshold'],
resolution0=cfg['generation']['resolution_0'],
upsampling_steps=cfg['generation']['upsampling_steps'],
sample=cfg['generation']['use_sampling'],
refinement_step=cfg['generation']['refinement_step'],
simplify_nfaces=cfg['generation']['simplify_nfaces'],
preprocessor=preprocessor,
)
return generator | Returns the generator object. Args: model (nn.Module): Occupancy Network model cfg (dict): imported yaml config device (device): pytorch device |
12,526 | import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict
from im2mesh.onet import models, training, generation
from im2mesh import data
from im2mesh import config
The provided code snippet includes necessary dependencies for implementing the `get_data_fields` function. Write a Python function `def get_data_fields(mode, cfg)` to solve the following problem:
Returns the data fields. Args: mode (str): the mode which is used cfg (dict): imported yaml config
Here is the function:
def get_data_fields(mode, cfg):
''' Returns the data fields.
Args:
mode (str): the mode which is used
cfg (dict): imported yaml config
'''
points_transform = data.SubsamplePoints(cfg['data']['points_subsample'])
with_transforms = cfg['model']['use_camera']
fields = {}
fields['points'] = data.PointsField(
cfg['data']['points_file'], points_transform,
with_transforms=with_transforms,
unpackbits=cfg['data']['points_unpackbits'],
)
if mode in ('val', 'test'):
points_iou_file = cfg['data']['points_iou_file']
voxels_file = cfg['data']['voxels_file']
if points_iou_file is not None:
fields['points_iou'] = data.PointsField(
points_iou_file,
with_transforms=with_transforms,
unpackbits=cfg['data']['points_unpackbits'],
)
if voxels_file is not None:
fields['voxels'] = data.VoxelsField(voxels_file)
return fields | Returns the data fields. Args: mode (str): the mode which is used cfg (dict): imported yaml config |
12,527 | import torch
import torch.nn as nn
import torch.nn.functional as F
def maxpool(x, dim=-1, keepdim=False):
out, _ = x.max(dim=dim, keepdim=keepdim)
return out | null |
12,528 | import torch
import torch.nn as nn
from im2mesh.layers import ResnetBlockFC
def maxpool(x, dim=-1, keepdim=False):
out, _ = x.max(dim=dim, keepdim=keepdim)
return out | null |
12,529 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.pix2mesh import models, training, generation
from im2mesh import data
import pickle
import numpy as np
encoder_dict = {
'simple_conv': conv.ConvEncoder,
'resnet18': conv.Resnet18,
'resnet34': conv.Resnet34,
'resnet50': conv.Resnet50,
'resnet101': conv.Resnet101,
'r2n2_simple': r2n2.SimpleConv,
'r2n2_resnet': r2n2.Resnet,
'pointnet_simple': pointnet.SimplePointnet,
'pointnet_resnet': pointnet.ResnetPointnet,
'psgn_cond': psgn_cond.PCGN_Cond,
'voxel_simple': voxels.VoxelEncoder,
'pixel2mesh_cond': pix2mesh_cond.Pix2mesh_Cond,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, **kwargs)` to solve the following problem:
Returns the Pixel2Mesh model. Args: cfg (yaml file): config file device (PyTorch device): PyTorch device
Here is the function:
def get_model(cfg, device=None, **kwargs):
''' Returns the Pixel2Mesh model.
Args:
cfg (yaml file): config file
device (PyTorch device): PyTorch device
'''
decoder = cfg['model']['decoder']
encoder = cfg['model']['encoder']
feat_dim = cfg['model']['feat_dim']
hidden_dim = cfg['model']['hidden_dim']
decoder_kwargs = cfg['model']['decoder_kwargs']
encoder_kwargs = cfg['model']['encoder_kwargs']
# Encoding necessary due to python2 pickle to python3 pickle convert
ellipsoid = pickle.load(
open(cfg['data']['ellipsoid'], 'rb'), encoding='latin1')
decoder = models.decoder_dict[decoder](
ellipsoid, device=device, hidden_dim=hidden_dim, feat_dim=feat_dim,
**decoder_kwargs
)
encoder = encoder_dict[encoder](
return_feature_maps=True,
**encoder_kwargs
)
model = models.Pix2Mesh(decoder, encoder)
model = model.to(device)
return model | Returns the Pixel2Mesh model. Args: cfg (yaml file): config file device (PyTorch device): PyTorch device |
12,530 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.pix2mesh import models, training, generation
from im2mesh import data
import pickle
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, optimizer, cfg, device)` to solve the following problem:
Return the trainer object for the Pixel2Mesh model. Args: model (PyTorch model): Pixel2Mesh model optimizer( PyTorch optimizer): The optimizer that should be used cfg (yaml file): config file device (PyTorch device): The PyTorch device that should be used
Here is the function:
def get_trainer(model, optimizer, cfg, device):
''' Return the trainer object for the Pixel2Mesh model.
Args:
model (PyTorch model): Pixel2Mesh model
optimizer( PyTorch optimizer): The optimizer that should be used
cfg (yaml file): config file
device (PyTorch device): The PyTorch device that should be used
'''
out_dir = cfg['training']['out_dir']
vis_dir = os.path.join(out_dir, 'vis')
adjust_losses = cfg['model']['adjust_losses']
# Encoding necessary due to python2 pickle to python3 pickle convert
ellipsoid = pickle.load(
open(cfg['data']['ellipsoid'], 'rb'), encoding='latin1')
trainer = training.Trainer(
model, optimizer, ellipsoid, vis_dir, device=device, adjust_losses=adjust_losses)
return trainer | Return the trainer object for the Pixel2Mesh model. Args: model (PyTorch model): Pixel2Mesh model optimizer( PyTorch optimizer): The optimizer that should be used cfg (yaml file): config file device (PyTorch device): The PyTorch device that should be used |
12,531 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.pix2mesh import models, training, generation
from im2mesh import data
import pickle
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_generator` function. Write a Python function `def get_generator(model, cfg, device)` to solve the following problem:
Returns a generator object for the Pixel2Mesh model. Args: model (PyTorch model): Pixel2Mesh model cfg (yaml file): config file device (PyTorch device): The PyTorch device that should be used
Here is the function:
def get_generator(model, cfg, device):
''' Returns a generator object for the Pixel2Mesh model.
Args:
model (PyTorch model): Pixel2Mesh model
cfg (yaml file): config file
device (PyTorch device): The PyTorch device that should be used
'''
base_mesh = np.loadtxt(cfg['data']['base_mesh'], dtype='|S32')
generator = generation.Generator3D(
model, base_mesh, device=device)
return generator | Returns a generator object for the Pixel2Mesh model. Args: model (PyTorch model): Pixel2Mesh model cfg (yaml file): config file device (PyTorch device): The PyTorch device that should be used |
12,532 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.pix2mesh import models, training, generation
from im2mesh import data
import pickle
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_data_fields` function. Write a Python function `def get_data_fields(mode, cfg)` to solve the following problem:
Returns the respective data fields. Args: mode (string): which split should be performed (train/test) cfg (yaml file): config file
Here is the function:
def get_data_fields(mode, cfg):
''' Returns the respective data fields.
Args:
mode (string): which split should be performed (train/test)
cfg (yaml file): config file
'''
with_transforms = cfg['data']['with_transforms']
pointcloud_transform = data.SubsamplePointcloud(
cfg['data']['pointcloud_target_n'])
fields = {}
fields['pointcloud'] = data.PointCloudField(
cfg['data']['pointcloud_file'], pointcloud_transform,
with_transforms=with_transforms)
return fields | Returns the respective data fields. Args: mode (string): which split should be performed (train/test) cfg (yaml file): config file |
12,533 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.psgn import models, training, generation
from im2mesh import data
encoder_dict = {
'simple_conv': conv.ConvEncoder,
'resnet18': conv.Resnet18,
'resnet34': conv.Resnet34,
'resnet50': conv.Resnet50,
'resnet101': conv.Resnet101,
'r2n2_simple': r2n2.SimpleConv,
'r2n2_resnet': r2n2.Resnet,
'pointnet_simple': pointnet.SimplePointnet,
'pointnet_resnet': pointnet.ResnetPointnet,
'psgn_cond': psgn_cond.PCGN_Cond,
'voxel_simple': voxels.VoxelEncoder,
'pixel2mesh_cond': pix2mesh_cond.Pix2mesh_Cond,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, **kwargs)` to solve the following problem:
r''' Returns the model instance. Args: cfg (yaml object): the config file device (PyTorch device): the PyTorch device
Here is the function:
def get_model(cfg, device=None, **kwargs):
r''' Returns the model instance.
Args:
cfg (yaml object): the config file
device (PyTorch device): the PyTorch device
'''
decoder = cfg['model']['decoder']
encoder = cfg['model']['encoder']
dim = cfg['data']['dim']
c_dim = cfg['model']['c_dim']
decoder_kwargs = cfg['model']['decoder_kwargs']
encoder_kwargs = cfg['model']['encoder_kwargs']
decoder = models.decoder_dict[decoder](
dim=dim, c_dim=c_dim,
**decoder_kwargs
)
encoder = encoder_dict[encoder](
c_dim=c_dim,
**encoder_kwargs
)
model = models.PCGN(decoder, encoder)
model = model.to(device)
return model | r''' Returns the model instance. Args: cfg (yaml object): the config file device (PyTorch device): the PyTorch device |
12,534 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.psgn import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, optimizer, cfg, device, **kwargs)` to solve the following problem:
r''' Returns the trainer instance. Args: model (nn.Module): PSGN model optimizer (PyTorch optimizer): The optimizer that should be used cfg (yaml object): the config file device (PyTorch device): the PyTorch device
Here is the function:
def get_trainer(model, optimizer, cfg, device, **kwargs):
r''' Returns the trainer instance.
Args:
model (nn.Module): PSGN model
optimizer (PyTorch optimizer): The optimizer that should be used
cfg (yaml object): the config file
device (PyTorch device): the PyTorch device
'''
input_type = cfg['data']['input_type']
out_dir = cfg['training']['out_dir']
vis_dir = os.path.join(out_dir, 'vis')
trainer = training.Trainer(
model, optimizer, device=device, input_type=input_type,
vis_dir=vis_dir
)
return trainer | r''' Returns the trainer instance. Args: model (nn.Module): PSGN model optimizer (PyTorch optimizer): The optimizer that should be used cfg (yaml object): the config file device (PyTorch device): the PyTorch device |
12,535 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.psgn import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_generator` function. Write a Python function `def get_generator(model, cfg, device, **kwargs)` to solve the following problem:
r''' Returns the generator instance. Args: cfg (yaml object): the config file device (PyTorch device): the PyTorch device
Here is the function:
def get_generator(model, cfg, device, **kwargs):
r''' Returns the generator instance.
Args:
cfg (yaml object): the config file
device (PyTorch device): the PyTorch device
'''
generator = generation.Generator3D(model, device=device)
return generator | r''' Returns the generator instance. Args: cfg (yaml object): the config file device (PyTorch device): the PyTorch device |
12,536 | import os
from im2mesh.encoder import encoder_dict
from im2mesh.psgn import models, training, generation
from im2mesh import data
The provided code snippet includes necessary dependencies for implementing the `get_data_fields` function. Write a Python function `def get_data_fields(mode, cfg, **kwargs)` to solve the following problem:
r''' Returns the data fields. Args: mode (string): The split that is used (train/val/test) cfg (yaml object): the config file
Here is the function:
def get_data_fields(mode, cfg, **kwargs):
r''' Returns the data fields.
Args:
mode (string): The split that is used (train/val/test)
cfg (yaml object): the config file
'''
with_transforms = cfg['data']['with_transforms']
pointcloud_transform = data.SubsamplePointcloud(
cfg['data']['pointcloud_target_n'])
fields = {}
fields['pointcloud'] = data.PointCloudField(
cfg['data']['pointcloud_file'], pointcloud_transform,
with_transforms=with_transforms
)
if mode in ('val', 'test'):
pointcloud_chamfer_file = cfg['data']['pointcloud_chamfer_file']
if pointcloud_chamfer_file is not None:
fields['pointcloud_chamfer'] = data.PointCloudField(
pointcloud_chamfer_file
)
return fields | r''' Returns the data fields. Args: mode (string): The split that is used (train/val/test) cfg (yaml object): the config file |
12,537 | import torch
from im2mesh.utils.io import export_pointcloud
import tempfile
import subprocess
import os
import trimesh
FILTER_SCRIPT_RECONSTRUCTION = '''
<!DOCTYPE FilterScript>
<FilterScript>
<filter name="Surface Reconstruction: Ball Pivoting">
<Param value="0" type="RichAbsPerc" max="1.4129" name="BallRadius" description="Pivoting Ball radius (0 autoguess)" min="0" tooltip="The radius of the ball pivoting (rolling) over the set of points. Gaps that are larger than the ball radius will not be filled; similarly the small pits that are smaller than the ball radius will be filled."/>
<Param value="20" type="RichFloat" name="Clustering" description="Clustering radius (% of ball radius)" tooltip="To avoid the creation of too small triangles, if a vertex is found too close to a previous one, it is clustered/merged with it."/>
<Param value="90" type="RichFloat" name="CreaseThr" description="Angle Threshold (degrees)" tooltip="If we encounter a crease angle that is too large we should stop the ball rolling"/>
<Param value="false" type="RichBool" name="DeleteFaces" description="Delete intial set of faces" tooltip="if true all the initial faces of the mesh are deleted and the whole surface is rebuilt from scratch, other wise the current faces are used as a starting point. Useful if you run multiple times the algorithm with an incrasing ball radius."/>
</filter>
</FilterScript>
'''
def export_pointcloud(vertices, out_file, as_text=True):
assert(vertices.shape[1] == 3)
vertices = vertices.astype(np.float32)
vertices = np.ascontiguousarray(vertices)
vector_dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]
vertices = vertices.view(dtype=vector_dtype).flatten()
plyel = PlyElement.describe(vertices, 'vertex')
plydata = PlyData([plyel], text=as_text)
plydata.write(out_file)
The provided code snippet includes necessary dependencies for implementing the `meshlab_poisson` function. Write a Python function `def meshlab_poisson(pointcloud)` to solve the following problem:
r''' Runs the meshlab ball pivoting algorithm. Args: pointcloud (numpy tensor): input point cloud
Here is the function:
def meshlab_poisson(pointcloud):
r''' Runs the meshlab ball pivoting algorithm.
Args:
pointcloud (numpy tensor): input point cloud
'''
with tempfile.TemporaryDirectory() as tmpdir:
script_path = os.path.join(tmpdir, 'script.mlx')
input_path = os.path.join(tmpdir, 'input.ply')
output_path = os.path.join(tmpdir, 'out.off')
# Write script
with open(script_path, 'w') as f:
f.write(FILTER_SCRIPT_RECONSTRUCTION)
# Write pointcloud
export_pointcloud(pointcloud, input_path, as_text=False)
# Export
env = os.environ
subprocess.Popen('meshlabserver -i ' + input_path + ' -o '
+ output_path + ' -s ' + script_path,
env=env, cwd=os.getcwd(), shell=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
).wait()
mesh = trimesh.load(output_path, process=False)
return mesh | r''' Runs the meshlab ball pivoting algorithm. Args: pointcloud (numpy tensor): input point cloud |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.