display.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. from pathlib import Path
  15. from IPython.display import Image
  16. import grass.script as gs
  17. class GrassRenderer:
  18. """The grassRenderer class creates and displays GRASS maps in
  19. Jupyter Notebooks."""
  20. def __init__(
  21. self, env=None, width=600, height=400, filename="map.png", text_size=12
  22. ):
  23. """Initiates an instance of the GrassRenderer class."""
  24. if env:
  25. self._env = env.copy()
  26. else:
  27. self._env = os.environ.copy()
  28. self._env["GRASS_RENDER_WIDTH"] = str(width)
  29. self._env["GRASS_RENDER_HEIGHT"] = str(height)
  30. self._env["GRASS_TEXT_SIZE"] = str(text_size)
  31. self._env["GRASS_RENDER_IMMEDIATE"] = "cairo"
  32. self._env["GRASS_RENDER_FILE"] = str(filename)
  33. self._env["GRASS_RENDER_FILE_READ"] = "TRUE"
  34. self._legend_file = Path(filename).with_suffix(".grass_vector_legend")
  35. self._env["GRASS_LEGEND_FILE"] = str(self._legend_file)
  36. self._filename = filename
  37. self.run("d.erase")
  38. def run(self, module, **kwargs):
  39. """Run modules from "d." GRASS library"""
  40. # Check module is from display library then run
  41. if module[0] == "d":
  42. gs.run_command(module, env=self._env, **kwargs)
  43. else:
  44. raise ValueError("Module must begin with letter 'd'.")
  45. def show(self):
  46. """Displays a PNG image of the map (non-interactive)"""
  47. return Image(self._filename)