Skip to content

Adapt velocity layer for an easier use with a ColormapControl #1035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions examples/Velocity_with_colormap.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You will need to install the following packages:\n",
"- `ipyleaflet`\n",
"- `requests`\n",
"- `xarray`\n",
"- `netcdf4`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set up for JupyterLite\n",
"try:\n",
" import piplite\n",
" await piplite.install('ipyleaflet')\n",
"except ImportError:\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import ipyleaflet\n",
"from ipyleaflet.velocity import Velocity\n",
"import xarray as xr\n",
"from branca.colormap import linear"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"center = [44.33956524809713, -130.60546875000003]\n",
"zoom = 3\n",
"m = ipyleaflet.Map(\n",
" center=center,\n",
" zoom=zoom,\n",
" interpolation=\"nearest\",\n",
" basemap=ipyleaflet.basemaps.CartoDB.DarkMatter,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.path.exists(\"wind-global.nc\"):\n",
" url = \"https://github.com/benbovy/xvelmap/raw/master/notebooks/wind-global.nc\"\n",
" import requests\n",
"\n",
" r = requests.get(url)\n",
" wind_data = r.content\n",
" with open(\"wind-global.nc\", \"wb\") as f:\n",
" f.write(wind_data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds = xr.open_dataset(\"wind-global.nc\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display_options = {\n",
" \"velocityType\": \"Global Wind\",\n",
" \"displayPosition\": \"bottomleft\",\n",
" \"displayEmptyString\": \"No wind data\",\n",
"}\n",
"wind = Velocity(\n",
" data=ds,\n",
" zonal_speed=\"u_wind\",\n",
" meridional_speed=\"v_wind\",\n",
" latitude_dimension=\"lat\",\n",
" longitude_dimension=\"lon\",\n",
" velocity_scale=0.01,\n",
" max_velocity=20,\n",
" colormap = linear.viridis,\n",
" display_options=display_options\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"colormap_control = ipyleaflet.ColormapControl(\n",
" colormap=wind.colormap,\n",
" value_min=wind.min_velocity,\n",
" value_max=wind.max_velocity,\n",
" position='topright',\n",
" transparent_bg=False,\n",
")\n",
"m.add(wind)\n",
"m"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"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.9.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
4 changes: 0 additions & 4 deletions ipyleaflet/leaflet.py
Original file line number Diff line number Diff line change
Expand Up @@ -2049,16 +2049,13 @@ class ColormapControl(WidgetControl):

Attributes
----------
caption : str, default 'caption'
The caption of the colormap.
colormap: branca.colormap.ColorMap instance, default linear.OrRd_06
The colormap used for the effect.
value_min : float, default 0.0
The minimal value taken by the data to be represented by the colormap.
value_max : float, default 1.0
The maximal value taken by the data to be represented by the colormap.
"""
caption = Unicode('caption')
colormap = Instance(ColorMap, default_value=linear.OrRd_06)
value_min = CFloat(0.0)
value_max = CFloat(1.0)
Expand All @@ -2068,7 +2065,6 @@ def _default_widget(self):
widget = Output(layout={'height': '40px', 'width': '520px', 'margin': '0px -19px 0px 0px'})
with widget:
colormap = self.colormap.scale(self.value_min, self.value_max)
colormap.caption = self.caption
display(colormap)

return widget
Expand Down
86 changes: 49 additions & 37 deletions ipyleaflet/velocity.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
#

from traittypes import Dataset
from traitlets import Unicode, Bool, Dict, Float, List

from .leaflet import Layer
from traitlets import Unicode, Bool, Dict, Float, List, Any, default
from .leaflet import Layer, ColormapControl
from .xarray_ds import ds_x_to_json
from branca.colormap import linear


class Velocity(Layer):
Expand Down Expand Up @@ -38,49 +38,61 @@ class Velocity(Layer):
Used to align color scale.
velocity_scale: float, 0.005
To be modified for particle animations.
color_scale: array, default []
Array of hex/rgb colors for user-specified color scale.
branca.colormap.LinearColorMap instance, default linear.OrRd_06
The colormap used for displaying the Velocity data
_color_scale: array, default []
Array of hex/rgb colors for user-specified color scale, it is private and defined from the colormap.

"""

_view_name = Unicode('LeafletVelocityView').tag(sync=True)
_model_name = Unicode('LeafletVelocityModel').tag(sync=True)
_view_name = Unicode("LeafletVelocityView").tag(sync=True)
_model_name = Unicode("LeafletVelocityModel").tag(sync=True)

zonal_speed = Unicode('', help='Name of the zonal speed in the dataset')
meridional_speed = Unicode('', help='Name of the meridional speed in the dataset')
latitude_dimension = Unicode('latitude', help='Name of the latitude dimension in the dataset')
longitude_dimension = Unicode('longitude', help='Name of the longitude dimension in the dataset')
zonal_speed = Unicode("", help="Name of the zonal speed in the dataset")
meridional_speed = Unicode("", help="Name of the meridional speed in the dataset")
latitude_dimension = Unicode(
"latitude", help="Name of the latitude dimension in the dataset"
)
longitude_dimension = Unicode(
"longitude", help="Name of the longitude dimension in the dataset"
)
units = Unicode(None, allow_none=True)

data = Dataset().tag(dtype=None, sync=True, to_json=ds_x_to_json)

# Options
display_values = Bool(True).tag(sync=True, o=True)
display_options = Dict({
'velocityType': 'Global Wind',
'position': 'bottomleft',
'emptyString': 'No velocity data',
'angleConvention': 'bearingCW',
'displayPosition': 'bottomleft',
'displayEmptyString': 'No velocity data',
'speedUnit': 'kt'
}).tag(sync=True)
display_options = Dict(
{
"velocityType": "Global Wind",
"position": "bottomleft",
"emptyString": "No velocity data",
"angleConvention": "bearingCW",
"displayPosition": "bottomleft",
"displayEmptyString": "No velocity data",
"speedUnit": "kt",
}
).tag(sync=True)
min_velocity = Float(0).tag(sync=True, o=True)
max_velocity = Float(10).tag(sync=True, o=True)
velocity_scale = Float(0.005).tag(sync=True, o=True)
color_scale = List([
"rgb(36,104, 180)",
"rgb(60,157, 194)",
"rgb(128,205,193)",
"rgb(151,218,168)",
"rgb(198,231,181)",
"rgb(238,247,217)",
"rgb(255,238,159)",
"rgb(252,217,125)",
"rgb(255,182,100)",
"rgb(252,150,75)",
"rgb(250,112,52)",
"rgb(245,64,32)",
"rgb(237,45,28)",
"rgb(220,24,32)",
"rgb(180,0,35)"
]).tag(sync=True, o=True)
colormap = Any(linear.OrRd_06)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to be able to change this trait dynamically

velocity_layer.colormap = linear.Accent_04

(same comment for caption)

color_scale = List([]).tag(sync=True, o=True)

@default("color_scale")
def _default_color_scale(self):
return [
f"rgba{tuple(int(x * 255) for x in color)}"
for color in self.colormap.colors
]

@default("subitems")
def _default_subitems(self):
colormap_control = ColormapControl(
colormap=self.colormap,
value_min=self.min_velocity,
value_max=self.max_velocity,
position="topright",
transparent_bg=False,
)
return (colormap_control,)