render3d.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # MODULE: grass.jupyter.display
  2. #
  3. # AUTHOR(S): Vaclav Petras <wenzeslaus gmail com>
  4. #
  5. # PURPOSE: This module contains functions for non-interactive display
  6. # in Jupyter Notebooks
  7. #
  8. # COPYRIGHT: (C) 2021 Vaclav Petras, and by the GRASS Development Team
  9. #
  10. # This program is free software under the GNU General Public
  11. # License (>=v2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. """Render 3D visualizations"""
  14. import os
  15. import tempfile
  16. import grass.script as gs
  17. from .display import GrassRenderer
  18. from .region import RegionManagerFor3D
  19. class Grass3dRenderer:
  20. """Creates and displays 3D visualization using GRASS GIS 3D rendering engine NVIZ.
  21. The 3D image is created using the *render* function which uses the *m.nviz.image*
  22. module in the background. Additional images can be
  23. placed on the image using the *overlay* attribute which is the 2D renderer, i.e.,
  24. has interface of the *GrassRenderer* class.
  25. Basic usage::
  26. >>> img = Grass3dRenderer()
  27. >>> img.render(elevation_map="elevation", color_map="elevation", perspective=20)
  28. >>> img.overlay.d_legend(raster="elevation", at=(60, 97, 87, 92))
  29. >>> img.show()
  30. For the OpenGL rendering with *m.nviz.image* to work, a display (screen) is needed.
  31. This is not guaranteed on headless systems such as continuous integration (CI) or
  32. Binder service(s). This class uses Xvfb and PyVirtualDisplay to support rendering
  33. in these environments.
  34. """
  35. def __init__(
  36. self,
  37. width: int = 600,
  38. height: int = 400,
  39. filename: str = None,
  40. mode: str = "fine",
  41. resolution_fine: int = 1,
  42. screen_backend: str = "auto",
  43. font: str = "sans",
  44. text_size: float = 12,
  45. renderer2d: str = "cairo",
  46. use_region: bool = False,
  47. saved_region: str = None,
  48. ):
  49. """Checks screen_backend and creates a temporary directory for rendering.
  50. :param width: width of image in pixels
  51. :param height: height of image in pixels
  52. :param filename: filename or path to save the resulting PNG image
  53. :param mode: 3D rendering mode (options: fine, coarse, both)
  54. :param resolution_fine: resolution multiplier for the fine mode
  55. :param screen_backend: backend for running the 3D rendering
  56. :param font: font to use in 2D rendering
  57. :param text_size: default text size in 2D rendering, usually overwritten
  58. :param renderer2d: GRASS 2D renderer driver (options: cairo, png)
  59. :param use_region: if True, use either current or provided saved region,
  60. else derive region from rendered layers
  61. :param saved_region: if name of saved_region is provided,
  62. this region is then used for rendering
  63. When *resolution_fine* is 1, rasters are used in the resolution according
  64. to the computational region as usual in GRASS GIS.
  65. Setting *resolution_fine* to values higher than one, causes rasters to
  66. be resampled to a coarser resolution (2 for twice as coarse than computational
  67. region resolution). This allows for fast rendering of large rasters without
  68. changing the computational region.
  69. By default (``screen_backend="auto"``), when
  70. pyvirtualdisplay Python package is present, the class assumes that it is
  71. running in a headless environment, so pyvirtualdisplay is used. When the
  72. package is not present, *m.nviz.image* is executed directly. When
  73. *screen_backend* is set to ``"pyvirtualdisplay"`` and the package cannot be
  74. imported, ValueError is raised. When *screen_backend* is set to ``"simple"``,
  75. *m.nviz.image* is executed directly. For other values of *screen_backend*,
  76. ValueError is raised.
  77. """
  78. self._width = width
  79. self._height = height
  80. self._mode = mode
  81. self._resolution_fine = resolution_fine
  82. # Temporary dir and files
  83. self._tmpdir = tempfile.TemporaryDirectory()
  84. if filename:
  85. self._filename = filename
  86. else:
  87. self._filename = os.path.join(self._tmpdir.name, "map.png")
  88. # Screen backend
  89. try:
  90. # This tests availability of the module and needs to work even
  91. # when the package is not installed.
  92. # pylint: disable=import-outside-toplevel,unused-import
  93. import pyvirtualdisplay # noqa: F401
  94. pyvirtualdisplay_available = True
  95. except ImportError:
  96. pyvirtualdisplay_available = False
  97. if screen_backend == "auto" and pyvirtualdisplay_available:
  98. self._screen_backend = "pyvirtualdisplay"
  99. elif screen_backend == "auto":
  100. self._screen_backend = "simple"
  101. elif screen_backend == "pyvirtualdisplay" and not pyvirtualdisplay_available:
  102. raise ValueError(
  103. _(
  104. "Screen backend '{}' cannot be used "
  105. "because pyvirtualdisplay cannot be imported"
  106. ).format(screen_backend)
  107. )
  108. elif screen_backend in ["simple", "pyvirtualdisplay"]:
  109. self._screen_backend = screen_backend
  110. else:
  111. raise ValueError(
  112. _(
  113. "Screen backend '{}' does not exist. "
  114. "See documentation for the list of supported backends."
  115. ).format(screen_backend)
  116. )
  117. self.overlay = GrassRenderer(
  118. height=height,
  119. width=width,
  120. filename=self._filename,
  121. font=font,
  122. text_size=text_size,
  123. renderer=renderer2d,
  124. use_region=use_region,
  125. saved_region=saved_region,
  126. )
  127. # rendering region setting
  128. self._region_manager = RegionManagerFor3D(use_region, saved_region)
  129. @property
  130. def filename(self):
  131. """Filename or full path to the file with the resulting image.
  132. The value can be set during initialization. When the filename was not provided
  133. during initialization, a path to temporary file is returned. In that case, the
  134. file is guaranteed to exist as long as the object exists.
  135. """
  136. return self._filename
  137. @property
  138. def region_manager(self):
  139. """Region manager object"""
  140. return self._region_manager
  141. def render(self, **kwargs):
  142. """Run rendering using *m.nviz.image*.
  143. Keyword arguments are passed as parameters to the *m.nviz.image* module.
  144. Parameters set in constructor such as *mode* are used here unless another value
  145. is provided. Parameters related to size, file, and format are handled
  146. internally and will be ignored when passed here.
  147. Calling this function again, overwrites the previously rendered image,
  148. so typically, it is called only once.
  149. """
  150. module = "m.nviz.image"
  151. name = os.path.join(self._tmpdir.name, "nviz")
  152. ext = "tif"
  153. full_name = f"{name}.{ext}"
  154. kwargs["output"] = name
  155. kwargs["format"] = ext
  156. kwargs["size"] = (self._width, self._height)
  157. if "mode" not in kwargs:
  158. kwargs["mode"] = self._mode
  159. if "resolution_fine" not in kwargs:
  160. kwargs["resolution_fine"] = self._resolution_fine
  161. if self._screen_backend == "pyvirtualdisplay":
  162. import inspect # pylint: disable=import-outside-toplevel
  163. # This is imported only when needed and when the package is available,
  164. # but generally, it may not be available.
  165. # pylint: disable=import-outside-toplevel,import-error
  166. from pyvirtualdisplay import Display
  167. additional_kwargs = {}
  168. has_env_copy = False
  169. if "manage_global_env" in inspect.signature(Display).parameters:
  170. additional_kwargs["manage_global_env"] = False
  171. has_env_copy = True
  172. with Display(
  173. size=(self._width, self._height), **additional_kwargs
  174. ) as display:
  175. if has_env_copy:
  176. env = display.env()
  177. else:
  178. env = os.environ.copy()
  179. self._region_manager.set_region_from_command(env=env, **kwargs)
  180. self.overlay.region_manager.set_region_from_env(env)
  181. gs.run_command(module, env=env, **kwargs)
  182. else:
  183. env = os.environ.copy()
  184. self._region_manager.set_region_from_command(env=env, **kwargs)
  185. self.overlay.region_manager.set_region_from_env(env)
  186. gs.run_command(module, env=env, **kwargs)
  187. # Lazy import to avoid an import-time dependency on PIL.
  188. from PIL import Image # pylint: disable=import-outside-toplevel
  189. img = Image.open(full_name)
  190. img.save(self._filename)
  191. def show(self):
  192. """Displays a PNG image of map"""
  193. # Lazy import to avoid an import-time dependency on IPython.
  194. from IPython.display import Image # pylint: disable=import-outside-toplevel
  195. return Image(self._filename)