display.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. from IPython.display import Image
  16. import tempfile
  17. import grass.script as gs
  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. 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 int text_size: default text size, overwritten by most display modules
  50. :param renderer: GRASS renderer driver (options: cairo, png, ps, html)
  51. """
  52. # Copy Environment
  53. if env:
  54. self._env = env.copy()
  55. else:
  56. self._env = os.environ.copy()
  57. # Environment Settings
  58. self._env["GRASS_RENDER_WIDTH"] = str(width)
  59. self._env["GRASS_RENDER_HEIGHT"] = str(height)
  60. self._env["GRASS_RENDER_TEXT_SIZE"] = str(text_size)
  61. self._env["GRASS_RENDER_IMMEDIATE"] = renderer
  62. self._env["GRASS_RENDER_FILE_READ"] = "TRUE"
  63. # Create PNG file for map
  64. # If not user-supplied, we will write it to a map.png in a
  65. # temporary directory that we can delete later. We need
  66. # this temporary directory for the legend anyways so we'll
  67. # make it now
  68. self._tmpdir = tempfile.TemporaryDirectory()
  69. if filename:
  70. self._filename = filename
  71. else:
  72. self._filename = os.path.join(self._tmpdir.name, "map.png")
  73. # Set environment var for file
  74. self._env["GRASS_RENDER_FILE"] = self._filename
  75. # Create Temporary Legend File
  76. self._legend_file = os.path.join(self._tmpdir.name, "legend.txt")
  77. self._env["GRASS_LEGEND_FILE"] = str(self._legend_file)
  78. def run(self, module, **kwargs):
  79. """Run modules from "d." GRASS library"""
  80. # Check module is from display library then run
  81. if module[0] == "d":
  82. gs.run_command(module, env=self._env, **kwargs)
  83. else:
  84. raise ValueError("Module must begin with letter 'd'.")
  85. def __getattr__(self, name):
  86. """Parse attribute to GRASS display module. Attribute should be in
  87. the form 'd_module_name'. For example, 'd.rast' is called with 'd_rast'.
  88. """
  89. # Check to make sure format is correct
  90. if not name.startswith("d_"):
  91. raise AttributeError(_("Module must begin with 'd_'"))
  92. # Reformat string
  93. grass_module = name.replace("_", ".")
  94. # Assert module exists
  95. if not shutil.which(grass_module):
  96. raise AttributeError(_("Cannot find GRASS module {}").format(grass_module))
  97. def wrapper(**kwargs):
  98. # Run module
  99. self.run(grass_module, **kwargs)
  100. return wrapper
  101. def show(self):
  102. """Displays a PNG image of the map"""
  103. return Image(self._filename)