display.py 5.0 KB

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