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.display module¶
2D rendering and display functionality
-
class
grass.jupyter.display.GrassRenderer(height=None, width=None, filename=None, env=None, font='sans', text_size=12, renderer='cairo', use_region=False, saved_region=None)[source]¶ Bases:
objectGrassRenderer creates and displays GRASS maps in Jupyter Notebooks.
Elements are added to the display by calling GRASS display modules.
Basic usage:: >>> m = GrassRenderer() >>> 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 = GrassRenderer() >>> 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.interact_display module¶
Interactive visualizations map with folium
-
class
grass.jupyter.interact_display.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.interact_display.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.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.
-
grass.jupyter.render3d module¶
Render 3D visualizations
-
class
grass.jupyter.render3d.Grass3dRenderer(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 GrassRenderer class.
Basic usage:
>>> img = Grass3dRenderer() >>> 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.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.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