diff --git a/examples/layer_control.ipynb b/examples/layer_control.ipynb new file mode 100644 index 00000000..6d79d090 --- /dev/null +++ b/examples/layer_control.ipynb @@ -0,0 +1,240 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "a033bf32-69c9-48bc-a275-8ce1a3901365", + "metadata": {}, + "source": [ + "## Layer Control\n", + "\n", + "This notebook demonstrates the use of the lonbord map's `layer_control`, to control layer visibility and layer properties." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb983a26-ab11-4070-91bd-c78371ca6d68", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "\n", + "import geopandas as gpd\n", + "from palettable.colorbrewer.sequential import Blues_8\n", + "\n", + "from lonboard import Map, PathLayer, PolygonLayer\n", + "from lonboard.colormap import apply_continuous_cmap" + ] + }, + { + "cell_type": "markdown", + "id": "3dcbf11b-6c10-46bc-a6de-1d1d37f4e8b6", + "metadata": {}, + "source": [ + "### Get data\n", + "\n", + "Download data from the web and save as geoparquet so we can show some data on our Lonboard map and create a layer control." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56896a28-4d72-426e-9ea0-2e3854e389f8", + "metadata": {}, + "outputs": [], + "source": [ + "file_urls = [\n", + " (\n", + " \"ne_10m_roads_north_america.parquet\",\n", + " \"https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads_north_america.zip\",\n", + " ),\n", + " (\n", + " \"geoBoundariesCGAZ_ADM1.parquet\",\n", + " \"https://github.com/wmgeolab/geoBoundaries/raw/main/releaseData/CGAZ/geoBoundariesCGAZ_ADM1.geojson\",\n", + " ),\n", + " (\n", + " \"rivers_asia_37331.parquet\",\n", + " \"https://storage.googleapis.com/fao-maps-catalog-data/geonetwork/aquamaps/rivers_asia_37331.zip\",\n", + " ),\n", + "]\n", + "for filename, url in file_urls:\n", + " if Path(filename).exists() is False:\n", + " print(f\"Reading {filename} from web and saving as geoparquet.\")\n", + " gdf = gpd.read_file(url, engine=\"pyogrio\")\n", + " gdf.to_parquet(filename)\n", + " del gdf\n", + " else:\n", + " print(f\"{filename} already downloaded.\")" + ] + }, + { + "cell_type": "markdown", + "id": "00e57959-6b12-4dc7-8621-6f725d928b96", + "metadata": {}, + "source": [ + "### Read geoparquet files into geopandas dataframes" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "230e851e-8bb9-4697-9143-688537c746a0", + "metadata": {}, + "outputs": [], + "source": [ + "boundary_df = gpd.read_parquet(\"geoBoundariesCGAZ_ADM1.parquet\")\n", + "boundary_df = boundary_df.loc[\n", + " (boundary_df[\"shapeGroup\"] == \"USA\")\n", + " & (~boundary_df[\"shapeName\"].isin([\"Alaska\", \"Hawaii\"]))\n", + "] # parse data down to lower 48 of USA\n", + "\n", + "road_df = gpd.read_parquet(\"ne_10m_roads_north_america.parquet\")\n", + "road_df = road_df.loc[\n", + " road_df[\"class\"] == \"Interstate\"\n", + "] # parse data down to just interstates\n", + "\n", + "river_df = gpd.read_parquet(\"rivers_asia_37331.parquet\")\n", + "river_df = river_df.loc[river_df[\"MAJ_NAME\"] == \"Amur\"] # parse data down to just Amur" + ] + }, + { + "cell_type": "markdown", + "id": "f98bf950-2f66-47eb-8e3a-8123aa2083d5", + "metadata": {}, + "source": [ + "### Create layers\n", + "\n", + "* Create a `PolygonLayer` from the boundary dataframe that is brown with a darker brown outline, that's 1 pixel wide.\n", + "\n", + "* Create a `PathLayer` from the road dataframe with a title and minimum width.\n", + "\n", + "* Create a `PathLayer` from the river dataframe that uses the 'Strahler' column for setting the color and width of the lines, as well as some defaults on the width to make the more prominent rivers darker and wider on the map." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3366f15-245f-4a8f-b87d-dcb7fd993392", + "metadata": {}, + "outputs": [], + "source": [ + "boundary_layer = PolygonLayer.from_geopandas(\n", + " boundary_df,\n", + " title=\"Boundaries\",\n", + " get_fill_color=[137, 81, 41],\n", + " get_line_color=[102, 60, 31],\n", + " get_line_width=1,\n", + " line_width_units=\"pixels\",\n", + " stroked=True,\n", + ")\n", + "\n", + "road_layer = PathLayer.from_geopandas(road_df, width_min_pixels=0.8)\n", + "\n", + "river_layer = PathLayer.from_geopandas(\n", + " river_df,\n", + " title=\"Rivers\",\n", + " get_color=apply_continuous_cmap(river_df[\"Strahler\"] / 7, Blues_8),\n", + " get_width=river_df[\"Strahler\"],\n", + " width_scale=3000,\n", + " width_min_pixels=0.5,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "9cdd3071-2dd6-4b77-b42d-7def62e3087d", + "metadata": {}, + "source": [ + "### Create the Lonboard `Map` and `layer_control`\n", + "\n", + "Create a lonboard map, and then create a `layer_control` with the `include_settings` parameter to True then display them both.\n", + "\n", + "With `include_settings=True` we will get a layer control that includes the setttings cog, which when expanded will allow us to change some of the layer properties. Note that we did not give this layer a title, so when we make the layer control, the default title will show in the layer control.\n", + "\n", + "If the user unchecks the checkbox next to the layer's name the layer's visibility will be set to False.\n", + "\n", + "!!! note\n", + "\n", + " We're only adding the boundary and road layer at this point, not the river layer. We'll add that later, and when we do we can see the layer control automatically react to the new layer being added to the map, and it will show up in our layer control." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae4529e4-b656-47eb-8928-a51f02d038fb", + "metadata": {}, + "outputs": [], + "source": [ + "lonboard_map = Map([boundary_layer, road_layer])\n", + "lc = lonboard_map.layer_control(include_settings=True)\n", + "\n", + "display(lonboard_map)\n", + "display(lc)" + ] + }, + { + "cell_type": "markdown", + "id": "9c291004-4d2d-4f7f-9dcb-f3f1d098114f", + "metadata": {}, + "source": [ + "### Change the title of the road layer\n", + "\n", + "By default the title of the layer is the layer's type. When we change the title of the layer, it will automatically be changed in the layer control." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2039d785-3edb-44b8-bbb7-ab61397bdae4", + "metadata": {}, + "outputs": [], + "source": [ + "road_layer.title = \"Roads\"" + ] + }, + { + "cell_type": "markdown", + "id": "d475c61b-e0fd-4227-a3c1-aa2cabeec7d0", + "metadata": {}, + "source": [ + "### Add the River layer\n", + "\n", + "When we add the river layer to the map, the layer control will automatically detect the new layer, and also add it to the layer control.\n", + "\n", + "When we expand the cog for the river layer we will see that the `Color` and the `Width` properties of the layer display `Custom` instead of a color picker/float widget. \n", + "\"Custom\" is displayed in the layer control currently because the layer uses the values from the rows of data to render the lines. This may change in future releases of Lonboard." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13a4bb69-6871-4e40-946f-27edccac9f05", + "metadata": {}, + "outputs": [], + "source": [ + "lonboard_map.add_layer(river_layer, reset_zoom=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "lonboard_toc", + "language": "python", + "name": "lonboard_toc" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lonboard/_layer.py b/lonboard/_layer.py index a7167fe5..577d3c20 100644 --- a/lonboard/_layer.py +++ b/lonboard/_layer.py @@ -92,6 +92,11 @@ def __init__( extensions: Sequence[BaseExtension] = (), **kwargs: Any, ) -> None: + if self.title is None: + if hasattr(self, "_layer_type"): + self.title = self._layer_type.title() + " Layer" + else: + self.title = "Layer" # We allow layer extensions to dynamically inject properties onto the layer # widgets where the layer is defined. We wish to allow extensions and their # properties to be passed in the layer constructor. _However_, if @@ -281,6 +286,12 @@ def _add_extension_traits(self, extensions: Sequence[BaseExtension]) -> None: for an example. """ + title = t.CUnicode(default_value=None, allow_none=True).tag(sync=True) + """ + The title of the layer. The title of the layer is visible in the layer control + produced by map.layer_control(). + """ + def default_geoarrow_viewport( table: Table, diff --git a/lonboard/_map.py b/lonboard/_map.py index 9979e476..bfb3240e 100644 --- a/lonboard/_map.py +++ b/lonboard/_map.py @@ -9,11 +9,16 @@ import traitlets as t from ipywidgets import CallbackDispatcher from ipywidgets.embed import dependency_state, embed_minimal_html +from ipywidgets.widgets.widget_box import VBox from lonboard._base import BaseAnyWidget from lonboard._layer import BaseLayer from lonboard._viewport import compute_view from lonboard.basemap import CartoBasemap +from lonboard.controls import ( + _make_layer_control_item, + _make_layer_control_item_with_settings, +) from lonboard.traits import ( DEFAULT_INITIAL_VIEW_STATE, BasemapUrl, @@ -626,3 +631,37 @@ def as_html(self) -> HTML: @traitlets.default("view_state") def _default_initial_view_state(self) -> dict[str, Any]: return compute_view(self.layers) # type: ignore + + def layer_control(self, *, include_settings: bool = False) -> VBox: + """Make layer control box for the layers in the Map. + + Args: + include_settings: If `False` The controler will only contain a checkbox for each layer, which controls layer visibility in the Lonboard map. If `True` The controller will also have a settings button, which when clicked will expose properties for the layer which can be changed. If a layer's property is None when the layer is added to the control, a widget for controling that property will not be created. + + !!! note + + For layer properties that are set as an array of values to control the display of each feature separately (example, using a color map to vary the color of the features based on the data) the layer control will display "Custom" instead of allowing the user to change the property. This may change in a future version of Lonboard. + + !!! note + + The layer control uses the [ipywidgets color picker](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#color-picker) to set colors. This widget does not respect alpha values, so if you are using an RGBA value to set the color and the alpha of the layer, and then you use the color picker, it will set the alpha value 255. + + Returns: + ipywidgets VBox of the layer control. + + """ + if include_settings is False: + item_creation_function = _make_layer_control_item + else: + item_creation_function = _make_layer_control_item_with_settings + + control_items = [item_creation_function(layer) for layer in self.layers] + contol = VBox(control_items) + + ## Observe the map's layers trait, so additions/removals of layers will result in the control recreating itself to reflect the map's current state + def handle_layer_change(_: traitlets.utils.bunch.Bunch) -> None: + control_items = [item_creation_function(layer) for layer in self.layers] + contol.children = control_items + + self.observe(handle_layer_change, "layers", "change") + return contol diff --git a/lonboard/controls.py b/lonboard/controls.py index 0a855559..e3f92f9a 100644 --- a/lonboard/controls.py +++ b/lonboard/controls.py @@ -1,13 +1,26 @@ -from collections.abc import Sequence +from __future__ import annotations + from functools import partial -from typing import Any +from typing import TYPE_CHECKING, Any +import ipywidgets import traitlets from ipywidgets import FloatRangeSlider from ipywidgets.widgets.trait_types import TypedTuple # Import from source to allow mkdocstrings to link to base class -from ipywidgets.widgets.widget_box import VBox +from ipywidgets.widgets.widget_box import HBox, VBox + +from lonboard._vendor.matplotlib.colors import _to_rgba_no_colorcycle +from lonboard.traits import ( + ColorAccessor, + FloatAccessor, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + + from lonboard._layer import BaseLayer class MultiRangeSlider(VBox): @@ -88,3 +101,287 @@ def callback(change: dict, *, i: int) -> None: initial_values.append(child.value) super().__init__(children, value=initial_values, **kwargs) + + +def _rgb2hex(r: int, g: int, b: int) -> str: + """Convert an RGB color code values to hex.""" + return f"#{r:02x}{g:02x}{b:02x}" + + +def _hex2rgb(hex_color: str) -> list[int]: + """Convert a hex color code to RGB.""" + return [int(val * 255) for val in _to_rgba_no_colorcycle(hex_color)] + + +def _link_rgb_and_hex_traits( + rgb_object: Any, + rgb_trait_name: str, + hex_object: Any, + hex_trait_name: str, +) -> None: + """Make links between two objects/traits that hold RBG and hex color codes.""" + + def handle_rgb_color_change(change: traitlets.utils.bunch.Bunch) -> None: + new_color_rgb = change.get("new")[0:3] + new_color_hex = _rgb2hex(*new_color_rgb) + hex_object.set_trait(hex_trait_name, new_color_hex) + + rgb_object.observe(handle_rgb_color_change, rgb_trait_name, "change") + + def handle_hex_color_change(change: traitlets.utils.bunch.Bunch) -> None: + new_color_hex = change.get("new") + new_color_rgb = _hex2rgb(new_color_hex) + rgb_object.set_trait(rgb_trait_name, new_color_rgb) + + hex_object.observe(handle_hex_color_change, hex_trait_name, "change") + + +def _make_visibility_w(layer: BaseLayer) -> ipywidgets.HBox: + """Make a widget to control layer visibility.""" + visibility_w = ipywidgets.Checkbox( + value=True, + description="", + disabled=False, + indent=False, + ) + visibility_w.layout = ipywidgets.Layout(width="16px") + layer_name = ipywidgets.Text("Boundaries") + layer_name.layout = ipywidgets.Layout(width="160px") + + ipywidgets.dlink((layer, "title"), (layer_name, "value")) + ipywidgets.link((layer, "visible"), (visibility_w, "value")) + return ipywidgets.HBox([visibility_w, layer_name]) + + +def _make_layer_control_item(layer: BaseLayer) -> VBox: + """Return a VBox to be used by a layer control based on the input layer. + + The VBox will only contain a toggle for the layer's visibility. + """ + visibility_w = _make_visibility_w(layer) + + # with_layer_controls is False return the visibility widget within a VBox + # within a HBox to maintain consistency with the layer control item that would be returned + # if with_layer_controls were True + return VBox([HBox([visibility_w])]) + + +def _make_layer_control_item_with_settings(layer: BaseLayer) -> VBox: + """Return a VBox to be used by a layer control based on the input layer. + + The VBox will contain a toggle for the layer's + visibility and a button that when clicked will display widgets linked to the layers + traits so they can be modified. + """ + visibility_w = _make_visibility_w(layer) + + # with_layer_controls is True, make a button that will display the layer props, + # and widgets for the layer properties. Instead of making the trait controlling + # widgets in a random order, make lists so we can make the color widgets at the + # top, followed by the boolean widgets and the number widgets so the layer props + # display has some sort of order + color_widgets, bool_widgets, number_widgets = _make_layer_trait_widgets(layer) + + layer_props_title = ipywidgets.HTML(value=f"{layer.title} Properties") + props_box_layout = ipywidgets.Layout( + border="solid 3px #EEEEEE", + width="240px", + display="none", + ) + props_widgets = [layer_props_title, *color_widgets, *bool_widgets, *number_widgets] + layer_props_box = VBox(props_widgets, layout=props_box_layout) + + props_button = ipywidgets.Button(description="", icon="gear") + props_button.layout.width = "36px" + + def on_props_button_click(_: ipywidgets.widgets.widget_button.Button) -> None: + if layer_props_box.layout.display != "none": + layer_props_box.layout.display = "none" + else: + layer_props_box.layout.display = "flex" + + props_button.on_click(on_props_button_click) + return VBox([HBox([visibility_w, props_button]), layer_props_box]) + + +def _trait_name_to_description(trait_name: str) -> str: + """Make a human readable name from the trait.""" + return trait_name.replace("get_", "").replace("_", " ").title() + + +## style and layout to keep property wigets consistent +prop_style = {"description_width": "initial"} +prop_layout = ipywidgets.Layout(width="224px") + + +def _make_color_picker_widget( + layer: BaseLayer, + trait_name: str, +) -> ipywidgets.widget: + trait_description = _trait_name_to_description(trait_name) + color_trait_value = getattr(layer, trait_name) + if isinstance(color_trait_value, (list, tuple)) and len(color_trait_value) in [ + 3, + 4, + ]: + # list or tuples of 3/4 are RGB(a) values + hex_color = _rgb2hex(*color_trait_value[0:3]) + elif color_trait_value is None: + hex_color = "#000000" + else: + return ipywidgets.Label(value=f"{trait_description}: Custom") + color_picker_w = ipywidgets.ColorPicker( + description=trait_description, + layout=prop_layout, + value=hex_color, + ) + _link_rgb_and_hex_traits(layer, trait_name, color_picker_w, "value") + return color_picker_w + + +def _make_bool_widget( + layer: BaseLayer, + trait_name: str, +) -> ipywidgets.widget: + trait_description = _trait_name_to_description(trait_name) + bool_w = ipywidgets.Checkbox( + value=True, + description=trait_description, + disabled=False, + style=prop_style, + layout=prop_layout, + ) + ipywidgets.link((layer, trait_name), (bool_w, "value")) + return bool_w + + +def _make_float_widget( + layer: BaseLayer, + trait_name: str, + trait: traitlets.TraitType, +) -> ipywidgets.widget: + trait_description = _trait_name_to_description(trait_name) + if isinstance(getattr(layer, trait_name), float) is False: + # not a single value do not make a control widget + return ipywidgets.Label(value=f"{trait_description}: Custom") + min_val = None + if hasattr(trait, "min"): + min_val = trait.min + + max_val = None + if hasattr(trait, "max"): + max_val = trait.max + if max_val == float("inf"): + max_val = 999999999999 + + if max_val is not None and max_val is not None: + ## min/max are not None, make a bounded float + float_w = ipywidgets.BoundedFloatText( + value=True, + description=trait_description, + disabled=False, + indent=True, + min=min_val, + max=max_val, + style=prop_style, + layout=prop_layout, + ) + else: + ## min/max are None, use normal float, not bounded. + float_w = ipywidgets.FloatText( + value=True, + description=trait_description, + disabled=False, + indent=True, + layout=prop_layout, + ) + ipywidgets.link((layer, trait_name), (float_w, "value")) + return float_w + + +def _make_int_widget( + layer: BaseLayer, + trait_name: str, + trait: traitlets.TraitType, +) -> ipywidgets.widget: + trait_description = _trait_name_to_description(trait_name) + if isinstance(getattr(layer, trait_name), int) is False: + # not a single value, do not make a control widget + return ipywidgets.Label(value=f"{trait_description}: Custom") + min_val = None + if hasattr(trait, "min"): + min_val = trait.min + + max_val = None + if hasattr(trait, "max"): + max_val = trait.max + if max_val == float("inf"): + max_val = 999999999999 + + if max_val is not None and max_val is not None: + ## min/max are not None, make a bounded int + int_w = ipywidgets.BoundedIntText( + value=True, + description=trait_description, + disabled=False, + indent=True, + min=min_val, + max=max_val, + style=prop_style, + layout=prop_layout, + ) + else: + ## min/max are None, use normal int, not bounded. + int_w = ipywidgets.IntText( + value=True, + description=trait_description, + disabled=False, + indent=True, + style=prop_style, + layout=prop_layout, + ) + ipywidgets.link((layer, trait_name), (int_w, "value")) + return int_w + + +def _make_layer_trait_widgets(layer: BaseLayer) -> tuple[list, list, list]: + color_widgets = [] + bool_widgets = [] + number_widgets = [] + + for trait_name, trait in layer.traits().items(): + ## Guard against making widgets for protected traits + if trait_name.startswith("_"): + continue + # Guard against making widgets for things we've determined we should not + # make widgets to change + if trait_name in ["visible", "selected_index", "title"]: + continue + + try: + val = getattr(layer, trait_name) + except traitlets.TraitError: + # if accessing the trait causes an error do not make a widget + continue + + if isinstance(trait, ColorAccessor): + color_picker_w = _make_color_picker_widget(layer, trait_name) + color_widgets.append(color_picker_w) + else: + if val is None: + # do not create a widget for non color traits that are None + # becase we dont have a way to set them back to None + continue + + if isinstance(trait, traitlets.traitlets.Bool): + bool_w = _make_bool_widget(layer, trait_name) + bool_widgets.append(bool_w) + + elif isinstance(trait, (FloatAccessor, traitlets.traitlets.Float)): + float_w = _make_float_widget(layer, trait_name, trait) + number_widgets.append(float_w) + + elif isinstance(trait, (traitlets.traitlets.Int)): + int_w = _make_int_widget(layer, trait_name, trait) + number_widgets.append(int_w) + return (color_widgets, bool_widgets, number_widgets) diff --git a/lonboard/types/layer.py b/lonboard/types/layer.py index 8b73db8d..b79ada77 100644 --- a/lonboard/types/layer.py +++ b/lonboard/types/layer.py @@ -77,6 +77,7 @@ class BaseLayerKwargs(TypedDict, total=False): visible: bool opacity: IntFloat auto_highlight: bool + title: str class BitmapLayerKwargs(BaseLayerKwargs, total=False):