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")
Note
Contrary to typical command line / GUI module usage, grass.jupyter enables output overwrite by default to align with behaviour of other Python packages and to allow repeated executions of the same cells and of the whole notebook. The default command line behaviour can be restored by setting GRASS_OVERWRITE environmental variable to “0” after gj.init() call: os.environ[“GRASS_OVERWRITE”] = “0”.
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:
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.
-
class
grass.jupyter.
InteractiveMap
(width=400, height=400, tiles='CartoDB positron', API_key=None, use_region=False, saved_region=None, map_backend=None)[source]¶ Bases:
object
This class creates interactive GRASS maps with folium or ipyleaflet.
Basic Usage:
>>> m = InteractiveMap() >>> m.add_vector("streams") >>> m.add_raster("elevation") >>> m.show()
Creates a blank folium/ipyleaflet map centered on g.region.
If map_backend is not specified, InteractiveMap tries to import ipyleaflet first, then folium if it fails. The backend can be specified explicitely with valid values “folium” and “ipyleaflet” .
In case of folium backend, 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 In case of ipyleaflet, only the tileset name and not the URL is currently supported.
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
map_backend (str) – “ipyleaflet” or “folium” or None
-
add_layer_control
(**kwargs)[source]¶ Add layer control to display.
A Layer Control is added by default. Call this function to customize layer control object. Accepts keyword arguments to be passed to leaflet layer control object
-
add_raster
(name, title=None, **kwargs)[source]¶ Imports raster into temporary WGS84 location, exports as png and overlays on a 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 image overlay
-
add_vector
(name, title=None, **kwargs)[source]¶ Imports vector into temporary WGS84 location, re-formats to a GeoJSON and adds to 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 GeoJSON overlay
-
setup_computational_region_interface
()[source]¶ Sets up the interface for users to draw and modify the computational region on the map.
This includes creating a toggle button to activate the region editing mode, and instantiating an InteractiveRegionController to handle the region selection and modification functionality.
-
setup_drawing_interface
()[source]¶ Sets up the drawing interface for users to interactively draw and manage geometries on the map.
This includes creating a toggle button to activate the drawing mode, and instantiating an InteractiveDrawController to handle the drawing functionality.
-
class
grass.jupyter.
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
-
class
grass.jupyter.
Map3D
(width: int = 600, height: int = 400, filename: str | None = 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 = 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.
-
class
grass.jupyter.
Raster
(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
grass.jupyter.interactivemap.Layer
Overlays rasters on a folium or ipyleaflet map.
Basic Usage: >>> m = folium.Map() >>> gj.Raster(“elevation”, opacity=0.5).add_to(m) >>> m
>>> m = ipyleaflet.Map() >>> gj.Raster("elevation", opacity=0.5).add_to(m) >>> m
Reproject GRASS raster, export to PNG, and compute bounding box.
-
class
grass.jupyter.
SeriesMap
(width=None, height=None, env=None, use_region=False, saved_region=None)[source]¶ Bases:
grass.jupyter.baseseriesmap.BaseSeriesMap
Creates visualizations from a series of rasters or vectors in Jupyter Notebooks.
Basic usage:
>>> series = gj.SeriesMap(height = 500) >>> series.add_rasters(["elevation_shade", "geology", "soils"]) >>> series.add_vectors(["streams", "streets", "viewpoints"]) >>> series.d_barscale() >>> series.show() # Create Slider >>> series.save("image.gif")
This class of grass.jupyter is experimental and under development. The API can change at anytime.
Creates an instance of the SeriesMap 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_names
(names)[source]¶ Add list of names associated with layers. Default will be names of first series added.
-
add_rasters
(rasters, **kwargs)[source]¶ - Parameters
rasters (list) – list of raster layers to add to SeriesMap
-
class
grass.jupyter.
TimeSeriesMap
(width=None, height=None, env=None, use_region=False, saved_region=None)[source]¶ Bases:
grass.jupyter.baseseriesmap.BaseSeriesMap
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
(baseseries, fill_gaps=False)[source]¶ - Parameters
baseseries (str) – name of space-time dataset
fill_gaps (bool) – fill empty time steps with data from previous step
-
class
grass.jupyter.
Vector
(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
grass.jupyter.interactivemap.Layer
Adds vectors to a folium or ipyleaflet map.
Basic Usage: >>> m = folium.Map() >>> gj.Vector(“roadsmajor”).add_to(m) >>> m
>>> m = ipyleaflet.Map() >>> gj.Vector("roadsmajor").add_to(m) >>> m
Reproject GRASS vector and export to GeoJSON.
-
grass.jupyter.
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
Submodules¶
grass.jupyter.baseseriesmap module¶
Base class for SeriesMap and TimeSeriesMap
-
class
grass.jupyter.baseseriesmap.
BaseSeriesMap
(width=None, height=None, env=None)[source]¶ Bases:
object
Base class for SeriesMap and TimeSeriesMap
Creates an instance of the visualizations class.
- Parameters
width (int) – width of map in pixels
height (int) – height of map in pixels
env (str) – environment
-
save
(filename, duration=500, label=True, font=None, 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 label on each frame param str font: font file param int text_size: size of label 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.interactivemap module¶
Interactive visualizations map with folium or ipyleaflet
-
class
grass.jupyter.interactivemap.
InteractiveDrawController
(map_object, ipyleaflet, ipywidgets, toggle_button, vectors, **kwargs)[source]¶ Bases:
object
A controller for interactive drawing on a map.
- Attributes:
map: The map object. _ipyleaflet: The ipyleaflet module. draw_control: The draw control. drawn_geometries: The list of drawn geometries. self.vector_layers: List of vector layers geo_json_layers: The dictionary of GeoJSON layers. save_button_control: The save button control. toggle_button: The toggle button activating/deactivating drawing.
Initializes the InteractiveDrawController.
- Parameters
map_object – The map object.
ipyleaflet – The ipyleaflet module.
ipywidgets – The ipywidgets module.
toggle_button – The toggle button activating/deactivating drawing.
vectors – List of vector layers.
-
class
grass.jupyter.interactivemap.
InteractiveMap
(width=400, height=400, tiles='CartoDB positron', API_key=None, use_region=False, saved_region=None, map_backend=None)[source]¶ Bases:
object
This class creates interactive GRASS maps with folium or ipyleaflet.
Basic Usage:
>>> m = InteractiveMap() >>> m.add_vector("streams") >>> m.add_raster("elevation") >>> m.show()
Creates a blank folium/ipyleaflet map centered on g.region.
If map_backend is not specified, InteractiveMap tries to import ipyleaflet first, then folium if it fails. The backend can be specified explicitely with valid values “folium” and “ipyleaflet” .
In case of folium backend, 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 In case of ipyleaflet, only the tileset name and not the URL is currently supported.
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
map_backend (str) – “ipyleaflet” or “folium” or None
-
add_layer_control
(**kwargs)[source]¶ Add layer control to display.
A Layer Control is added by default. Call this function to customize layer control object. Accepts keyword arguments to be passed to leaflet layer control object
-
add_raster
(name, title=None, **kwargs)[source]¶ Imports raster into temporary WGS84 location, exports as png and overlays on a 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 image overlay
-
add_vector
(name, title=None, **kwargs)[source]¶ Imports vector into temporary WGS84 location, re-formats to a GeoJSON and adds to 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 GeoJSON overlay
-
setup_computational_region_interface
()[source]¶ Sets up the interface for users to draw and modify the computational region on the map.
This includes creating a toggle button to activate the region editing mode, and instantiating an InteractiveRegionController to handle the region selection and modification functionality.
-
setup_drawing_interface
()[source]¶ Sets up the drawing interface for users to interactively draw and manage geometries on the map.
This includes creating a toggle button to activate the drawing mode, and instantiating an InteractiveDrawController to handle the drawing functionality.
-
class
grass.jupyter.interactivemap.
InteractiveQueryController
(map_object, ipyleaflet, ipywidgets, rasters, vectors, width, **kwargs)[source]¶ Bases:
object
A controller for interactive querying on a map.
- Attributes:
map: The ipyleaflet.Map object. _ipyleaflet: The ipyleaflet module. _ipywidgets: The ipywidgets module. raster_name: The name of the raster layer. vector_name: The name of the vector layer. width: The width of the map as an int. query_control: The query control.
Initializes the InteractiveQueryController.
- Parameters
map – The map object.
ipyleaflet – The ipyleaflet module.
ipywidgets – The ipywidgets module.
-
handle_interaction
(**kwargs)[source]¶ Handles the map interaction event.
- Parameters
kwargs – The event arguments.
-
query_raster
(coordinates)[source]¶ Queries the raster layer.
- Parameters
coordinates – The coordinates.
- Returns
The raster output.
-
class
grass.jupyter.interactivemap.
InteractiveRegionController
(map_object, ipyleaflet, ipywidgets, **kwargs)[source]¶ Bases:
object
A controller for interactive region selection on a map.
- Attributes:
map: The map object. region_rectangle: The rectangle representing the selected region. _ipyleaflet: The ipyleaflet module. _ipywidgets: The ipywidgets module. save_button: The button to save the selected region. bottom_output_widget: The output widget to display the selected region. changed_region (dict): The dictionary to store the changed region.
Initializes the InteractiveRegionController.
- Parameters
map_object – The map object.
ipyleaflet – The ipyleaflet module.
ipywidgets – The ipywidgets module.
-
class
grass.jupyter.interactivemap.
Layer
(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
object
Base class for overlaing raster or vector layer on a folium or ipyleaflet map.
Reproject GRASS raster, export to PNG, and compute bounding box.
param str name: layer name param str title: title of layer 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/ipyleaflet layer instance
-
class
grass.jupyter.interactivemap.
Raster
(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
grass.jupyter.interactivemap.Layer
Overlays rasters on a folium or ipyleaflet map.
Basic Usage: >>> m = folium.Map() >>> gj.Raster(“elevation”, opacity=0.5).add_to(m) >>> m
>>> m = ipyleaflet.Map() >>> gj.Raster("elevation", opacity=0.5).add_to(m) >>> m
Reproject GRASS raster, export to PNG, and compute bounding box.
-
class
grass.jupyter.interactivemap.
Vector
(name, title=None, use_region=False, saved_region=None, renderer=None, **kwargs)[source]¶ Bases:
grass.jupyter.interactivemap.Layer
Adds vectors to a folium or ipyleaflet map.
Basic Usage: >>> m = folium.Map() >>> gj.Vector(“roadsmajor”).add_to(m) >>> m
>>> m = ipyleaflet.Map() >>> gj.Vector("roadsmajor").add_to(m) >>> m
Reproject GRASS vector and export to 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
grass.jupyter.map3d module¶
Render 3D visualizations
-
class
grass.jupyter.map3d.
Map3D
(width: int = 600, height: int = 400, filename: str | None = 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 = 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.
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.
-
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_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.
RegionManagerForSeries
(use_region, saved_region, width, height, env)[source]¶ Bases:
object
Region manager for SeriesMap
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
-
set_region_from_rasters
(rasters)[source]¶ Sets computational region for rendering from a series of rasters.
This function sets the region from a series of rasters. If the extent or resolution has already been set by calling this function previously or by the set_region_from vectors() function, this function will not modify it.
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.
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
grass.jupyter.seriesmap module¶
Create and display visualizations for a series of rasters.
-
class
grass.jupyter.seriesmap.
SeriesMap
(width=None, height=None, env=None, use_region=False, saved_region=None)[source]¶ Bases:
grass.jupyter.baseseriesmap.BaseSeriesMap
Creates visualizations from a series of rasters or vectors in Jupyter Notebooks.
Basic usage:
>>> series = gj.SeriesMap(height = 500) >>> series.add_rasters(["elevation_shade", "geology", "soils"]) >>> series.add_vectors(["streams", "streets", "viewpoints"]) >>> series.d_barscale() >>> series.show() # Create Slider >>> series.save("image.gif")
This class of grass.jupyter is experimental and under development. The API can change at anytime.
Creates an instance of the SeriesMap 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_names
(names)[source]¶ Add list of names associated with layers. Default will be names of first series added.
-
add_rasters
(rasters, **kwargs)[source]¶ - Parameters
rasters (list) – list of raster layers to add to SeriesMap
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:
grass.jupyter.baseseriesmap.BaseSeriesMap
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
(baseseries, fill_gaps=False)[source]¶ - Parameters
baseseries (str) – name of space-time dataset
fill_gaps (bool) – fill empty time steps with data from previous step
-
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.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_number_of_cores
(requested, env=None)[source]¶ Get the number of cores to use for multiprocessing.
- Parameters
requested (int) – Desired number of cores.
env (dict) – Optional process environment.
- Return int
Number of cores to use, constrained by system availability.
-
grass.jupyter.utils.
get_region
(env=None)[source]¶ Returns current computational region as dictionary.
Additionally, it adds long key names.
-
grass.jupyter.utils.
get_region_bounds_latlon
()[source]¶ Gets the current computational region bounds in latlon.
- Return list of tuples
represent the southwest and northeast corners of the region in (latitude, longitude) format.
-
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.
query_raster
(coord, raster_list)[source]¶ Queries raster data at specified coordinates.
- Parameters
coord – Coordinates given as a tuple (latitude, longitude).
raster_list (list) – List of raster names to query.
- Returns
str: HTML formatted string containing the results of the raster queries.
-
grass.jupyter.utils.
query_vector
(coord, vector_list, distance)[source]¶ Queries vector data at specified coordinates.
- Parameters
coord – Coordinates given as a tuple (latitude, longitude).
vector_list (list) – List of vector names to query.
distance – Distance within which to query the vector attributes.
- Returns
str: HTML formatted string containing the results of the vector queries.
-
grass.jupyter.utils.
reproject_latlon
(coord)[source]¶ Reproject coordinates
- Parameters
coord – coordinates given as tuple (latitude, longitude)
- Returns
reprojected coordinates (returned as tuple)
-
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.
save_gif
(input_files, output_filename, duration=500, label=True, labels=None, font=None, text_size=12, text_color='gray')[source]¶ Creates a GIF animation
param list input_files: list of paths to source param str output_filename: destination gif filename param int duration: time to display each frame; milliseconds param bool label: include label stamp on each frame param list labels: list of labels for each source image param str font: font file param int text_size: size of label text param str text_color: color to use for the text
-
grass.jupyter.utils.
save_vector
(name, geo_json)[source]¶ Saves the user drawn vector.
- Parameters
geo_json – name of the geojson file to be saved
name – name with which vector should be saved
-
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