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

grass.jupyter: Allow Users to view/update computational region #3838

Merged
merged 19 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
116 changes: 115 additions & 1 deletion python/grass/jupyter/interactivemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@
import base64
import json
from .reprojection_renderer import ReprojectionRenderer
from .utils import (
get_region_bounds_latlon,
reproject_region,
update_region,
get_location_proj_string,
)


def get_backend(interactive_map):
Expand Down Expand Up @@ -302,6 +308,7 @@ def _import_ipyleaflet(error):
# Set LayerControl default
self.layer_control = False
self.layer_control_object = None
self.region_rectangle = None

self._renderer = ReprojectionRenderer(
use_region=use_region, saved_region=saved_region
Expand Down Expand Up @@ -347,13 +354,120 @@ def add_layer_control(self, **kwargs):
else:
self.layer_control_object = self._ipyleaflet.LayersControl(**kwargs)

def draw_computational_region(self):
"""
Allow Users to draw the computational region and modify it.
"""
import ipywidgets as widgets

region_mode_button = widgets.ToggleButton(
icon="square-o",
description="",
value=False,
tooltip="Click to show and edit computational region",
layout=widgets.Layout(width="40px", margin="0px 0px 0px 0px"),
)

save_button = widgets.Button(
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
description="Update region",
tooltip="Click to update region",
disabled=True,
)
bottom_output_widget = widgets.Output(
layout={
"width": "100%",
"max_height": "300px",
"overflow": "auto",
"display": "none",
}
)

changed_region = {}
save_button_control = None

def update_output(region):
with bottom_output_widget:
bottom_output_widget.clear_output()
print(
_(
"Region changed to: n={n}, s={s}, e={e}, w={w} "
"nsres={nsres} ewres={ewres}"
).format(**region)
)

def on_rectangle_change(value):
save_button.disabled = False
bottom_output_widget.layout.display = "none"
latlon_bounds = value["new"][0]
changed_region["north"] = latlon_bounds[2]["lat"]
changed_region["south"] = latlon_bounds[0]["lat"]
changed_region["east"] = latlon_bounds[2]["lng"]
changed_region["west"] = latlon_bounds[0]["lng"]

def toggle_region_mode(change):
nonlocal save_button_control

if change["new"]:
region_bounds = get_region_bounds_latlon()
self.region_rectangle = self._ipyleaflet.Rectangle(
bounds=region_bounds,
color="red",
fill_color="red",
fill_opacity=0.5,
draggable=True,
transform=True,
rotation=False,
name="Computational region",
)
self.region_rectangle.observe(on_rectangle_change, names="locations")
self.map.fit_bounds(region_bounds)
self.map.add(self.region_rectangle)

save_button_control = self._ipyleaflet.WidgetControl(
widget=save_button, position="topright"
)
self.map.add_control(save_button_control)
else:
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
if self.region_rectangle:
self.region_rectangle.transform = False
self.map.remove(self.region_rectangle)
self.region_rectangle = None

save_button.disabled = True

if save_button_control:
self.map.remove(save_button_control)
bottom_output_widget.layout.display = "none"

def save_region(change):
from_proj = "+proj=longlat +datum=WGS84 +no_defs"
to_proj = get_location_proj_string()
reprojected_region = reproject_region(changed_region, from_proj, to_proj)
new = update_region(reprojected_region)
bottom_output_widget.layout.display = "block"
update_output(new)

region_mode_button.observe(toggle_region_mode, names="value")
save_button.on_click(save_region)

region_mode_control = self._ipyleaflet.WidgetControl(
widget=region_mode_button, position="topright"
)
self.map.add_control(region_mode_control)

output_control = self._ipyleaflet.WidgetControl(
widget=bottom_output_widget, position="bottomleft"
)
self.map.add_control(output_control)

def show(self):
"""This function returns a folium figure or ipyleaflet map object
with a GRASS raster and/or vector overlaid on a basemap.

If map has layer control enabled, additional layers cannot be
added after calling show()."""

if self._ipyleaflet:
self.draw_computational_region()
self.map.fit_bounds(self._renderer.get_bbox())
if self._folium:
if self.layer_control:
Expand Down
18 changes: 18 additions & 0 deletions python/grass/jupyter/testsuite/interactivemap_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ def can_import_folium():
return False


def can_import_ipyleaflet():
"""Test ipyleaflet import to see if test can be run."""
try:
import ipyleaflet # noqa

return True
except ImportError:
return False


class TestDisplay(TestCase):
# Setup variables
files = []
Expand Down Expand Up @@ -88,6 +98,14 @@ def test_save_as_html(self):
interactive_map.save(filename)
self.assertFileExists(filename)

@unittest.skipIf(not can_import_ipyleaflet(), "Cannot import ipyleaflet")
def test_draw_computational_region(self):
"""Test the draw_computational_region method."""
# Create InteractiveMap
interactive_map = gj.InteractiveMap()
interactive_map.draw_computational_region()
self.assertTrue(callable(interactive_map.draw_computational_region))


if __name__ == "__main__":
test()
28 changes: 28 additions & 0 deletions python/grass/jupyter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,34 @@ def get_rendering_size(region, width, height, default_width=600, default_height=
return (default_width, round(default_width * region_height / region_width))


def get_region_bounds_latlon():
"""Gets the current computational region bounds in latlon."""
region = gs.parse_command("g.region", flags="gbp")
return [
(float(region["ll_s"]), float(region["ll_w"])),
(float(region["ll_n"]), float(region["ll_e"])),
]


def update_region(region):
"""Updates the computational region bounds.

:return: the new region
"""
current = gs.region()
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
new = gs.parse_command(
"g.region",
flags="ga",
n=region["north"],
s=region["south"],
e=region["east"],
w=region["west"],
nsres=current["nsres"],
ewres=current["ewres"],
)
petrasovaa marked this conversation as resolved.
Show resolved Hide resolved
return new


def save_gif(
input_files,
output_filename,
Expand Down
Loading