display.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. def run(self, module, **kwargs):
  85. """Run modules from the GRASS display family (modules starting with "d.").
  86. This function passes arguments directly to grass.script.run_command()
  87. so the syntax is the same.
  88. :param str module: name of GRASS module
  89. :param `**kwargs`: named arguments passed to run_command()"""
  90. # Check module is from display library then run
  91. if module[0] == "d":
  92. gs.run_command(module, env=self._env, **kwargs)
  93. else:
  94. raise ValueError("Module must begin with letter 'd'.")
  95. def __getattr__(self, name):
  96. """Parse attribute to GRASS display module. Attribute should be in
  97. the form 'd_module_name'. For example, 'd.rast' is called with 'd_rast'.
  98. """
  99. # Check to make sure format is correct
  100. if not name.startswith("d_"):
  101. raise AttributeError(_("Module must begin with 'd_'"))
  102. # Reformat string
  103. grass_module = name.replace("_", ".")
  104. # Assert module exists
  105. if not shutil.which(grass_module):
  106. raise AttributeError(_("Cannot find GRASS module {}").format(grass_module))
  107. def wrapper(**kwargs):
  108. # Run module
  109. self.run(grass_module, **kwargs)
  110. return wrapper
  111. def show(self):
  112. """Displays a PNG image of map"""
  113. from IPython.display import Image
  114. return Image(self._filename)