grass.jupyter package

The grass.jupyter is a convenient GRASS GIS interface for Jupyter notebooks.

Python is a great tool for data science and scientific computing. Jupyter is an environment with computational notebooks which makes it even better tool for analysis and workflow prototyping. Computational notebooks are documents combining code, text, and results such as figures and tables. JupyterLab is an environment where you interact with all these parts. You can install it locally on your machine or use it online from some service provider.

The grass.jupyter subpackage improves the integration of GRASS GIS and Jupyter notebooks compared to the standard Python API. 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.

Usage

To start using it in a notebook, import the top level package with a convenient alias, such as gj, like this:

>>> import grass.jupyter as gj

Note

To import the package, you need to tell Python where the GRASS GIS Python package is unless you manually set this on your system or in the command line. Please, refer to the example notebooks linked below for an example of the full workflow.

Note

On Windows, there is no system Python and GRASS GIS needs to use its own Python. Jupyter needs to be installed into that Python. Please, refer to the wiki for Windows-specific instructions.

To use existing data, we start a GRASS session in an existing mapset:

>>> gj.init("grassdata/nc_basic_spm_grass7/user1")

All classes and functions for interaction in notebooks are now available under gj, for example we can display a map with a selected raster and vector:

>>> streams_map = gj.Map()
>>> streams_map.d_rast(map="elevation")
>>> streams_map.d_vect(map="streams")
>>> streams_map.show()

Other classes and functions are described below and in the example notebooks. Static HTML versions of the example notebooks are available on GitHub and interactive ones with live code are available on Binder:

https://mybinder.org/badge_logo.svg

There are also internal classes and functions which are not guaranteed to have as stable API, although they are available through their specific submodules. For all standard cases, use only classes and function imported with import grass.jupyter as gj. If in doubt, use dir(gj) to see available objects. Both the objects in submodules and names of submodules may change in the future.

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.

Authors

Caitlin Haedrich, NC State University, Center for Geospatial Analytics

Vaclav Petras, NC State University, Center for Geospatial Analytics

Anna Petrasova, NC State University, Center for Geospatial Analytics

Initial development was done by Caitlin Haedrich during Google Summer of Code in 2021 mentored by Vaclav Petras, Stephan Blumentrath, and Helena Mitasova.

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: object

This class creates interactive GRASS maps with folium.

Basic Usage:

>>> m = InteractiveMap()
>>> m.add_vector("streams")
>>> m.add_raster("elevation")
>>> m.add_layer_control()
>>> m.show()

Creates a blank folium map centered on g.region.

tiles parameter is passed directly to folium.Map() which supports several built-in tilesets (including “OpenStreetMap”, “Stamen Toner”, “Stamen Terrain”, “Stamen Watercolor”, “Mapbox Bright”, “Mapbox Control Room”, “CartoDB positron”, “CartoDB dark_matter”) as well as custom tileset URL (i.e. “http://{s}.yourtiles.com/{z}/{x}/{y}.png”). For more information, visit folium documentation: https://python-visualization.github.io/folium/modules.html

Raster and vector data are always reprojected to Pseudo-Mercator. With use_region=True or saved_region=myregion, the region extent is reprojected and the number of rows and columns of that region is kept the same. This region is then used for reprojection. By default, use_region is False, which results in the reprojection of the entire raster in its native resolution. The reprojected resolution is estimated with r.proj. Vector data are always reprojected without any clipping, i.e., region options don’t do anything.

Parameters
  • height (int) – height in pixels of figure (default 400)

  • width (int) – width in pixels of figure (default 400)

  • tiles (str) – map tileset to use

  • API_key (str) – API key for Mapbox or Cloudmade tiles

  • use_region (bool) – use computational region of current mapset

  • saved_region (str) – name of saved computation region

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()

save(filename)[source]

Save map as an html map.

Parameters

filename (str) – name of html file

show()[source]

This function returns a folium figure object with a GRASS raster overlaid on a basemap.

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

class grass.jupyter.interactivemap.Raster(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]

Bases: object

Overlays rasters on folium maps.

Basic Usage: >>> m = folium.Map() >>> gj.Raster(“elevation”, opacity=0.5).add_to(m) >>> m

Reproject GRASS raster, export to PNG, and compute bounding box.

param str name: raster name param str title: title of raster to display in layer control legend param bool use_region: use computational region of current mapset param str saved_region: name of saved computation region param renderer: instance of ReprojectionRenderer **kwargs: keyword arguments passed to folium.raster_layers.ImageOverlay()

add_to(folium_map)[source]

Add raster to folium map with folium.raster_layers.ImageOverlay()

A folium map is an instance of folium.Map.

class grass.jupyter.interactivemap.Vector(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]

Bases: object

Adds vectors to a folium map.

Basic Usage: >>> m = folium.Map() >>> gj.Vector(“roadsmajor”).add_to(m) >>> m

Reproject GRASS vector and export to folium-ready PNG. Also computes bounding box for PNG overlay in folium map.

param str name: vector name param str title: title of vector to display in layer control legend param bool use_region: use computational region of current mapset param str saved_region: name of saved computation region renderer: instance of ReprojectionRenderer **kwargs: keyword arguments passed to folium.GeoJson()

add_to(folium_map)[source]

Add vector to folium map with folium.GeoJson()

grass.jupyter.map module

2D rendering and display functionality

class grass.jupyter.map.Map(width=None, height=None, filename=None, env=None, font='sans', text_size=12, renderer='cairo', use_region=False, saved_region=None, read_file=False)[source]

Bases: object

Map 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()

Creates an instance of the Map class.

Parameters
  • height (int) – height of map in pixels

  • width (int) – width of map in pixels

  • filename (str) – filename or path to save a PNG of map

  • env (str) – environment

  • font (str) – font to use in rendering; either the name of a font from $GISBASE/etc/fontcap (or alternative fontcap file specified by GRASS_FONT_CAP), or alternatively the full path to a FreeType font file

  • text_size (int) – default text size, overwritten by most display modules

  • renderer – GRASS renderer driver (options: cairo, png, ps, html)

  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

  • read_file (bool) – if False (default), erase filename before re-writing to clear contents. If True, read file without clearing contents first.

property 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.

property region_manager

Region manager object

run(module, **kwargs)[source]

Run modules from the GRASS display family (modules starting with “d.”).

This function passes arguments directly to grass.script.run_command() so the syntax is the same.

Parameters
  • module (str) – name of GRASS module

  • **kwargs – named arguments passed to run_command()

save(filename)[source]

Saves a PNG image of map to the specified filename

show()[source]

Displays a PNG image of map

grass.jupyter.map3d module

Render 3D visualizations

class grass.jupyter.map3d.Map3D(width: int = 600, height: int = 400, filename: Optional[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: Optional[str] = None)[source]

Bases: object

Creates 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.

Checks screen_backend and creates a temporary directory for rendering.

Parameters
  • width – width of image in pixels

  • height – height of image in pixels

  • filename – filename or path to save the resulting PNG image

  • mode – 3D rendering mode (options: fine, coarse, both)

  • resolution_fine – resolution multiplier for the fine mode

  • screen_backend – backend for running the 3D rendering

  • font – font to use in 2D rendering

  • text_size – default text size in 2D rendering, usually overwritten

  • renderer2d – GRASS 2D renderer driver (options: cairo, png)

  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

When resolution_fine is 1, rasters are used in the resolution according to the computational region as usual in GRASS GIS. Setting resolution_fine to values higher than one, causes rasters to be resampled to a coarser resolution (2 for twice as coarse than computational region resolution). This allows for fast rendering of large rasters without changing the computational region.

By default (screen_backend="auto"), when pyvirtualdisplay Python package is present, the class assumes that it is running in a headless environment, so pyvirtualdisplay is used. When the package is not present, m.nviz.image is executed directly. When screen_backend is set to "pyvirtualdisplay" and the package cannot be imported, ValueError is raised. When screen_backend is set to "simple", m.nviz.image is executed directly. For other values of screen_backend, ValueError is raised.

property 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.

property 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.

show()[source]

Displays a PNG image of map

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: object

Region manager for 2D displays (gets region from display commands)

Manages region during rendering.

Parameters
  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

  • width – rendering width

  • height – rendering height

  • env – environment for rendering

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.

set_region_from_env(env)[source]

Copies GRASS_REGION from provided environment to local environment to set the computational region

class grass.jupyter.region.RegionManagerFor3D(use_region, saved_region)[source]

Bases: object

Region manager for 3D displays (gets region from m.nviz.image command)

Manages region during rendering.

Parameters
  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

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: object

Region manager for an interactive map (gets region from raster and vector)

Manages region during rendering for interactive map.

Parameters
  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

  • src_env – source environment (original projection)

  • tgt_env – target environment (pseudomercator)

property bbox

Bbox property for accessing maximum bounding box of all rendered layers.

property resolution

Resolution to be used for reprojection.

set_bbox_vector(vector)[source]

Enlarge bounding box based on vector

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: object

Region manager for TimeSeries visualizations.

Manages region during rendering.

Parameters
  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

  • env – environment for rendering

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.

Creates Pseudo-Mercator and WGS84 locations. If no work_dir provided, also creates temporary working directory to contain locations.

param bool use_region: use computational region of current mapset param str saved_region: name of saved computation region to use param work_dir: path to directory where locations, files should be written

get_bbox()[source]

Return bounding box of computation region in WGS84

render_raster(name)[source]

Reprojects raster to Pseudo-Mercator and saves PNG in working directory. Return PNG filename and bounding box of WGS84.

param str name: name of raster

render_vector(name)[source]

Reproject vector to WGS84 and save geoJSON in working directory. Return geoJSON filename.

param str name: name of vector

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 set after 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.TimeSeriesMap(width=None, height=None, env=None, use_region=False, saved_region=None)[source]

Bases: object

Creates visualizations of time-space raster and vector datasets in Jupyter Notebooks.

Basic usage:

>>> img = TimeSeriesMap("series_name")
>>> img.d_legend()  # Add legend
>>> img.show()  # Create TimeSlider
>>> img.save("image.gif")

This class of grass.jupyter is experimental and under development. The API can change at anytime.

Creates an instance of the TimeSeriesMap visualizations class.

Parameters
  • width (int) – width of map in pixels

  • height (int) – height of map in pixels

  • env (str) – environment

  • use_region – if True, use either current or provided saved region, else derive region from rendered layers

  • saved_region – if name of saved_region is provided, this region is then used for rendering

add_raster_series(timeseries, fill_gaps=False)[source]
Parameters
  • timeseries (str) – name of space-time dataset

  • fill_gaps (bool) – fill empty time steps with data from previous step

add_vector_series(timeseries, fill_gaps=False)[source]
Parameters
  • timeseries (str) – name of space-time dataset

  • fill_gaps (bool) – fill empty time steps with data from previous step

d_legend(**kwargs)[source]

Display legend.

Wraps d.legend and uses same keyword arguments.

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. show or save). Can be time-consuming to run with large space-time datasets.

save(filename, duration=500, label=True, font='DejaVuSans.ttf', text_size=12, text_color='gray')[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 str filename: name of output GIF file 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.

show(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.check_timeseries_exists(timeseries, element_type)[source]

Check that timeseries is time space dataset

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.timeseriesmap.fill_none_values(names)[source]

Replace None values in array with previous item

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.

Number of rows and columns is preserved.

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