grass.jupyter package¶
Display classes and setup functions for running GRASS GIS in Jupyter Notebooks
The grass.jupyter subpackage improves the integration of GRASS GIS and Jupyter Notebooks. The original version was written as part of Google Summer of Code in 2021 and experimental version was included in GRASS GIS 8.0. Since then, much more development happened adding better session handling and rendering of additional data types.
For standard usage, simply import the top level package with a convenient alias, e.g.,:
>>> import grass.jupyter as gj
The objects in submodules and names of submodules may change in the future.
Note
To import the package, you need to tell Python where the GRASS GIS Python package is. Please, refer to example notebooks for an example of the full workflow.
Note
Although most of the functionality is general, the defaults, resource management, and other behavior assumes usage in an interactive notebook, so using the functionality in other contexts (e.g. a script) may result in unexpected behavior. Consult the documentation or mailing list if in doubt. Suggest generalized functionality using issues and pull requests.
New in version 8.2.
Submodules¶
grass.jupyter.interactivemap module¶
Interactive visualizations map with folium
-
class
grass.jupyter.interactivemap.InteractiveMap(width=400, height=400, tiles='CartoDB positron', API_key=None, use_region=False, saved_region=None)[source]¶ Bases:
objectThis class creates interative GRASS maps with folium.
Basic Usage:
>>> m = InteractiveMap() >>> m.add_vector("streams") >>> m.add_raster("elevation") >>> m.add_layer_control() >>> m.show()
-
add_layer_control(**kwargs)[source]¶ Add layer control to display”
Accepts keyword arguments to be passed to folium.LayerControl()
-
add_raster(name, title=None, **kwargs)[source]¶ Imports raster into temporary WGS84 location, exports as png and overlays on folium map.
Color table for the raster can be modified with r.colors before calling this function.
Note
This will only work if the raster is located in the current mapset.
To change the color table of a raster located outside the current mapset, switch to that mapset with g.mapset, modify the color table with r.color then switch back to the initial mapset and run this function.
Parameters: - name (str) – name of raster to add to display; positional-only parameter
- title (str) – raster name for layer control
**kwargskwargs: keyword arguments passed to folium.raster_layers.ImageOverlay()
-
add_vector(name, title=None, **kwargs)[source]¶ Imports vector into temporary WGS84 location, re-formats to a GeoJSON and adds to folium map.
Parameters: - name (str) – name of vector to be added to map; positional-only parameter
- title (str) – vector name for layer control
**kwargskwargs: keyword arguments passed to folium.GeoJson()
-
-
class
grass.jupyter.interactivemap.Raster(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
objectOverlays rasters on folium maps.
Basic Usage: >>> m = folium.Map() >>> gj.Raster(“elevation”, opacity=0.5).add_to(m) >>> m
grass.jupyter.map module¶
2D rendering and display functionality
-
class
grass.jupyter.map.Map(height=None, width=None, filename=None, env=None, font='sans', text_size=12, renderer='cairo', use_region=False, saved_region=None, read_file=False)[source]¶ Bases:
objectMap creates and displays GRASS maps in Jupyter Notebooks.
Elements are added to the display by calling GRASS display modules.
Basic usage:
>>> m = Map() >>> m.run("d.rast", map="elevation") >>> m.run("d.legend", raster="elevation") >>> m.show()
GRASS display modules can also be called by using the name of module as a class method and replacing “.” with “_” in the name.
Shortcut usage:
>>> m = Map() >>> m.d_rast(map="elevation") >>> m.d_legend(raster="elevation") >>> m.show()
-
filename¶ Filename or full path to the file with the resulting image.
The value can be set during initialization. When the filename was not provided during initialization, a path to temporary file is returned. In that case, the file is guaranteed to exist as long as the object exists.
-
region_manager¶ Region manager object
-
grass.jupyter.map3d module¶
Render 3D visualizations
-
class
grass.jupyter.map3d.Map3D(width: int = 600, height: int = 400, filename: str = None, mode: str = 'fine', resolution_fine: int = 1, screen_backend: str = 'auto', font: str = 'sans', text_size: float = 12, renderer2d: str = 'cairo', use_region: bool = False, saved_region: str = None)[source]¶ Bases:
objectCreates and displays 3D visualization using GRASS GIS 3D rendering engine NVIZ.
The 3D image is created using the render function which uses the m.nviz.image module in the background. Additional images can be placed on the image using the overlay attribute which is the 2D renderer, i.e., has interface of the Map class.
Basic usage:
>>> img = Map() >>> img.render(elevation_map="elevation", color_map="elevation", perspective=20) >>> img.overlay.d_legend(raster="elevation", at=(60, 97, 87, 92)) >>> img.show()
For the OpenGL rendering with m.nviz.image to work, a display (screen) is needed. This is not guaranteed on headless systems such as continuous integration (CI) or Binder service(s). This class uses Xvfb and PyVirtualDisplay to support rendering in these environments.
-
filename¶ Filename or full path to the file with the resulting image.
The value can be set during initialization. When the filename was not provided during initialization, a path to temporary file is returned. In that case, the file is guaranteed to exist as long as the object exists.
-
region_manager¶ Region manager object
-
render(**kwargs)[source]¶ Run rendering using m.nviz.image.
Keyword arguments are passed as parameters to the m.nviz.image module. Parameters set in constructor such as mode are used here unless another value is provided. Parameters related to size, file, and format are handled internally and will be ignored when passed here.
Calling this function again, overwrites the previously rendered image, so typically, it is called only once.
-
grass.jupyter.region module¶
Manage computational or display region settings for display (render) classes.
-
class
grass.jupyter.region.RegionManagerFor2D(use_region, saved_region, width, height, env)[source]¶ Bases:
objectRegion manager for 2D displays (gets region from display commands)
-
adjust_rendering_size_from_region()[source]¶ Sets the environmental render width and height variables based on the region dimensions. Only first call of this method sets the variables, subsequent calls do not adjust them.
-
set_region_from_command(module, **kwargs)[source]¶ Sets computational region for rendering.
This functions identifies a raster/vector map from command and tries to set computational region based on that. It takes the extent from the first layer (raster or vector) and resolution and alignment from first raster layer.
If user specified the name of saved region during object’s initialization, the provided region is used. If it’s not specified and use_region=True, current region is used.
-
-
class
grass.jupyter.region.RegionManagerFor3D(use_region, saved_region)[source]¶ Bases:
objectRegion manager for 3D displays (gets region from m.nviz.image command)
-
set_region_from_command(env, **kwargs)[source]¶ Sets computational region for rendering.
This functions identifies a raster map from m.nviz.image command and tries to set computational region based on that.
If user specified the name of saved region during object’s initialization, the provided region is used. If it’s not specified and use_region=True, current region is used.
-
-
class
grass.jupyter.region.RegionManagerForInteractiveMap(use_region, saved_region, src_env, tgt_env)[source]¶ Bases:
objectRegion manager for an interactive map (gets region from raster and vector)
-
bbox¶ Bbox property for accessing maximum bounding box of all rendered layers.
-
set_region_from_raster(raster)[source]¶ Sets computational region for rendering.
This functions sets computational region based on a raster map in the target environment.
If user specified the name of saved region during object’s initialization, the provided region is used. If it’s not specified and use_region=True, current region is used.
Also enlarges bounding box based on the raster.
-
-
class
grass.jupyter.region.RegionManagerForTimeSeries(use_region, saved_region, env)[source]¶ Bases:
objectRegion manager for TimeSeries visualizations.
-
set_region_from_timeseries(timeseries)[source]¶ Sets computational region for rendering.
This function sets the computation region from the extent of a space-time dataset by using its bounding box and resolution.
If user specified the name of saved region during object’s initialization, the provided region is used. If it’s not specified and use_region=True, current region is used.
-
grass.jupyter.reprojection_renderer module¶
Reprojects rasters to Pseudo-Mercator and vectors to WGS84. Exports reprojected rasters and vectors to PNGs and geoJSONs, respectively.
-
class
grass.jupyter.reprojection_renderer.ReprojectionRenderer(use_region=False, saved_region=None, work_dir=None)[source]¶ Bases:
object- This class reprojects rasters and vectors to folium-compatible temporary location
- and projection.
In preparation to displaying with folium, it saves vectors to geoJSON and rasters to PNG images.
grass.jupyter.setup module¶
Initialization GRASS GIS session and its finalization
-
grass.jupyter.setup.init(path, location=None, mapset=None, grass_path=None)[source]¶ Initiates a GRASS session and sets GRASS environment variables.
Calling this function returns an object which represents the session.
>>> import grass.jupyter as gj >>> session = gj.init(...)
The session is ended when session.finish is called or when the object is destroyed when kernel ends or restarts. This function returns a copy of an internally kept reference, so the return value can be safely ignored when not needed.
The returned object can be used to switch to another mapset:
>>> session.switch_mapset("mapset_name")
Subsequent calls to the init function result in switching the mapset if a session is active and result in creation of new session if it is not active. On the other hand, if you see
GISRC - variable not setafter calling a GRASS module, you know you don’t have an active GRASS session.Parameters: - path (str) – path to GRASS mapset or database
- location (str) – name of GRASS location within the database
- mapset (str) – name of mapset within location
grass.jupyter.timeseriesmap module¶
Create and display visualizations for space-time datasets.
-
class
grass.jupyter.timeseriesmap.MethodCallCollector[source]¶ Bases:
objectRecords lists of GRASS modules calls to hand to Map.run().
Used for base layers and overlays in TimeSeriesMap visualizations.
-
class
grass.jupyter.timeseriesmap.TimeSeriesMap(timeseries, element_type='strds', fill_gaps=False, env=None, use_region=False, saved_region=None)[source]¶ Bases:
objectCreates visualizations of time-space raster and vector datasets in Jupyter Notebooks.
Basic usage:
>>> img = TimeSeriesMap("series_name") >>> img.d_legend() # Add legend >>> img.time_slider() # Create TimeSlider >>> img.animate()
This class of grass.jupyter is experimental and under development. The API can change at anytime.
-
animate(duration=500, label=True, font='DejaVuSans.ttf', text_size=12, text_color='gray', filename=None)[source]¶ Creates a GIF animation of rendered layers.
Text color must be in a format accepted by PIL ImageColor module. For supported formats, visit: https://pillow.readthedocs.io/en/stable/reference/ImageColor.html#color-names
param int duration: time to display each frame; milliseconds param bool label: include date/time stamp on each frame param str font: font file param int text_size: size of date/time text param str text_color: color to use for the text. param str filename: name of output GIF file
-
baselayer¶ Add base layer to TimeSeriesMap visualization
-
overlay¶ Add overlay to TimeSeriesMap visualization
-
render()[source]¶ Renders image for each time-step in space-time dataset.
Save PNGs to temporary directory. Must be run before creating a visualization (i.e. time_slider or animate). Can be time-consuming to run with large space-time datasets.
-
set_background_color(color)[source]¶ Set background color of images.
Passed to d.rast and d.erase. Either a standard color name, R:G:B triplet, or Hex. Default is white.
>>> img = TimeSeriesMap("series_name") >>> img.set_background_color("#088B36") # GRASS GIS green >>> img.animate()
-
time_slider(slider_width=None)[source]¶ Create interactive timeline slider.
param str slider_width: width of datetime selection slider
The slider_width parameter sets the width of the slider in the output cell. It should be formatted as a percentage (%) between 0 and 100 of the cell width or in pixels (px). Values should be formatted as strings and include the “%” or “px” suffix. For example, slider_width=”80%” or slider_width=”500px”. slider_width is passed to ipywidgets in ipywidgets.Layout(width=slider_width).
-
-
grass.jupyter.timeseriesmap.collect_layers(timeseries, element_type, fill_gaps)[source]¶ Create lists of layer names and start_times for a space-time raster or vector dataset.
For datasets with variable time steps, makes step regular with “gran” method for t.rast.list or t.vect.list then fills in missing layers with previous time step layer.
Parameters: - timeseries (str) – name of space-time dataset
- element_type (str) – element type, “stvds” or “strds”
- fill_gaps (bool) – fill empty time steps with data from previous step
grass.jupyter.utils module¶
Utility functions warpping existing processes in a suitable way
-
grass.jupyter.utils.estimate_resolution(raster, mapset, location, dbase, env)[source]¶ Estimates resolution of reprojected raster.
Parameters: - raster (str) – name of raster
- mapset (str) – mapset of raster
- location (str) – name of source location
- dbase (str) – path to source database
- env (dict) – target environment
Return float estimate: estimated resolution of raster in destination environment
-
grass.jupyter.utils.get_location_proj_string(env=None)[source]¶ Returns projection of environment in PROJ.4 format
-
grass.jupyter.utils.get_map_name_from_d_command(module, **kwargs)[source]¶ Returns map name from display command.
Assumes only positional parameters. When more maps are present (e.g., d.rgb), it returns only 1. Returns empty string if fails to find it.
-
grass.jupyter.utils.get_region(env=None)[source]¶ Returns current computational region as dictionary.
Additionally, it adds long key names.
-
grass.jupyter.utils.get_rendering_size(region, width, height, default_width=600, default_height=400)[source]¶ Returns the rendering width and height based on the region aspect ratio.
Parameters: - region (dict) – region dictionary
- width (integer) – rendering width (can be None)
- height (integer) – rendering height (can be None)
- default_width (integer) – default rendering width (can be None)
- default_height (integer) – default rendering height (can be None)
Return tuple (width, height): adjusted width and height
When both width and height are provided, values are returned without adjustment. When one value is provided, the other is computed based on the region aspect ratio. When no dimension is given, the default width or height is used and the other dimension computed.
-
grass.jupyter.utils.reproject_region(region, from_proj, to_proj)[source]¶ Reproject boundary of region from one projection to another.
Parameters: - region (dict) – region to reproject as a dictionary with long key names output of get_region
- from_proj (str) – PROJ.4 string of region; output of get_location_proj_string
- in_proj (str) – PROJ.4 string of target location; output of get_location_proj_string
Return dict region: reprojected region as a dictionary with long key names
-
grass.jupyter.utils.set_target_region(src_env, tgt_env)[source]¶ Set target region based on source region
-
grass.jupyter.utils.setup_location(name, path, epsg, src_env)[source]¶ Setup temporary location with different projection but same computational region as source location
Parameters: - name (str) – name of new location
- path (path) – path to new location’s database
- epsg (str) – EPSG code
- src_env (dict) – source environment
Return str rcfile: name of new locations rcfile
Return dict new_env: new environment