display.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # MODULE: grass.jupyter.display
  2. #
  3. # AUTHOR(S): Caitlin Haedrich <caitlin DOT haedrich AT gmail>
  4. #
  5. # PURPOSE: This module contains functions for non-interactive display
  6. # in Jupyter Notebooks
  7. #
  8. # COPYRIGHT: (C) 2021 Caitlin Haedrich, 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. import os
  14. import shutil
  15. import tempfile
  16. import grass.script as gs
  17. from .region import RegionManagerFor2D
  18. class GrassRenderer:
  19. """GrassRenderer creates and displays GRASS maps in
  20. Jupyter Notebooks.
  21. Elements are added to the display by calling GRASS display modules.
  22. Basic usage::
  23. >>> m = GrassRenderer()
  24. >>> m.run("d.rast", map="elevation")
  25. >>> m.run("d.legend", raster="elevation")
  26. >>> m.show()
  27. GRASS display modules can also be called by using the name of module
  28. as a class method and replacing "." with "_" in the name.
  29. Shortcut usage::
  30. >>> m = GrassRenderer()
  31. >>> m.d_rast(map="elevation")
  32. >>> m.d_legend(raster="elevation")
  33. >>> m.show()
  34. """
  35. def __init__(
  36. self,
  37. height=400,
  38. width=600,
  39. filename=None,
  40. env=None,
  41. font="sans",
  42. text_size=12,
  43. renderer="cairo",
  44. use_region=False,
  45. saved_region=None,
  46. ):
  47. """Creates an instance of the GrassRenderer class.
  48. :param int height: height of map in pixels
  49. :param int width: width of map in pixels
  50. :param str filename: filename or path to save a PNG of map
  51. :param str env: environment
  52. :param str font: font to use in rendering; either the name of a font from
  53. $GISBASE/etc/fontcap (or alternative fontcap file specified
  54. by GRASS_FONT_CAP), or alternatively the full path to a FreeType
  55. font file
  56. :param int text_size: default text size, overwritten by most display modules
  57. :param renderer: GRASS renderer driver (options: cairo, png, ps, html)
  58. :param use_region: if True, use either current or provided saved region,
  59. else derive region from rendered layers
  60. :param saved_region: if name of saved_region is provided,
  61. this region is then used for rendering
  62. """
  63. # Copy Environment
  64. if env:
  65. self._env = env.copy()
  66. else:
  67. self._env = os.environ.copy()
  68. # Environment Settings
  69. self._env["GRASS_RENDER_WIDTH"] = str(width)
  70. self._env["GRASS_RENDER_HEIGHT"] = str(height)
  71. self._env["GRASS_FONT"] = font
  72. self._env["GRASS_RENDER_TEXT_SIZE"] = str(text_size)
  73. self._env["GRASS_RENDER_IMMEDIATE"] = renderer
  74. self._env["GRASS_RENDER_FILE_READ"] = "TRUE"
  75. self._env["GRASS_RENDER_TRANSPARENT"] = "TRUE"
  76. # Create PNG file for map
  77. # If not user-supplied, we will write it to a map.png in a
  78. # temporary directory that we can delete later. We need
  79. # this temporary directory for the legend anyways so we'll
  80. # make it now
  81. self._tmpdir = tempfile.TemporaryDirectory()
  82. if filename:
  83. self._filename = filename
  84. else:
  85. self._filename = os.path.join(self._tmpdir.name, "map.png")
  86. # Set environment var for file
  87. self._env["GRASS_RENDER_FILE"] = self._filename
  88. # Create Temporary Legend File
  89. self._legend_file = os.path.join(self._tmpdir.name, "legend.txt")
  90. self._env["GRASS_LEGEND_FILE"] = str(self._legend_file)
  91. # rendering region setting
  92. self._region_manager = RegionManagerFor2D(use_region, saved_region, self._env)
  93. @property
  94. def filename(self):
  95. """Filename or full path to the file with the resulting image.
  96. The value can be set during initialization. When the filename was not provided
  97. during initialization, a path to temporary file is returned. In that case, the
  98. file is guaranteed to exist as long as the object exists.
  99. """
  100. return self._filename
  101. @property
  102. def region_manager(self):
  103. """Region manager object"""
  104. return self._region_manager
  105. def run(self, module, **kwargs):
  106. """Run modules from the GRASS display family (modules starting with "d.").
  107. This function passes arguments directly to grass.script.run_command()
  108. so the syntax is the same.
  109. :param str module: name of GRASS module
  110. :param `**kwargs`: named arguments passed to run_command()"""
  111. # Check module is from display library then run
  112. if module[0] == "d":
  113. self._region_manager.set_region_from_command(module, **kwargs)
  114. gs.run_command(module, env=self._env, **kwargs)
  115. else:
  116. raise ValueError("Module must begin with letter 'd'.")
  117. def __getattr__(self, name):
  118. """Parse attribute to GRASS display module. Attribute should be in
  119. the form 'd_module_name'. For example, 'd.rast' is called with 'd_rast'.
  120. """
  121. # Check to make sure format is correct
  122. if not name.startswith("d_"):
  123. raise AttributeError(_("Module must begin with 'd_'"))
  124. # Reformat string
  125. grass_module = name.replace("_", ".")
  126. # Assert module exists
  127. if not shutil.which(grass_module):
  128. raise AttributeError(_("Cannot find GRASS module {}").format(grass_module))
  129. def wrapper(**kwargs):
  130. # Run module
  131. self.run(grass_module, **kwargs)
  132. return wrapper
  133. def show(self):
  134. """Displays a PNG image of map"""
  135. from IPython.display import Image
  136. return Image(self._filename)