Skip to content
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

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

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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
155 changes: 155 additions & 0 deletions examples/Velocity_with_colormap.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
{
"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",
" caption='wind velocity (m/s)',\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"colormap_control = ipyleaflet.ColormapControl(\n",
" caption=wind.caption,\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
}
93 changes: 56 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,68 @@ 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)
caption = Unicode("").tag(sync=True, o=True)
Copy link
Member

Choose a reason for hiding this comment

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

We don't need to sync this one traits with the front-end?

Suggested change
color_scale = List([]).tag(sync=True, o=True)
caption = Unicode("").tag(sync=True, o=True)
color_scale = List([]).tag(sync=True, o=True)
caption = Unicode("").tag(o=True)


@default("color_scale")
def _default_color_scale(self):
self.color_scale = []

for color in self.colormap.colors:
rgb_tuple = tuple(int(x * 256) for x in color[:3])
rgb_str = f"rgb{rgb_tuple}"
self.color_scale.append(rgb_str)

return self.color_scale
HaudinFlorence marked this conversation as resolved.
Show resolved Hide resolved

@default("subitems")
def _default_subitems(self):
colormap_control = ColormapControl(
caption=self.caption,
colormap=self.colormap,
value_min=self.min_velocity,
value_max=self.max_velocity,
position="topright",
transparent_bg=False,
)
self.subitems = (colormap_control,)
return self.subitems
HaudinFlorence marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions js/src/layers/Velocity.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export class LeafletVelocityModel extends layer.LeafletLayerModel {
maxVelocity: 10,
velocityScale: 0.005,
colorScale: [],
caption:''
HaudinFlorence marked this conversation as resolved.
Show resolved Hide resolved
};
}
}
Expand Down