devstate.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright 2023 Modelling, Simulation and Design Lab (MSDL)
  2. # at the University of Antwerp (http://msdl.uantwerpen.be/).
  3. #
  4. # Licensed under the GNU Public License v3 (the "License");
  5. # you may not use this file except in compliance with the
  6. # License. You may obtain a copy of the License at
  7. # https://www.gnu.org/licenses/gpl-3.0.en.html
  8. #
  9. # Unless required by applicable law or agreed to in writing,
  10. # software distributed under the License is distributed on an
  11. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. # either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the
  14. # License.
  15. from pytcore.state.pystate import PyState
  16. from uuid import UUID
  17. class DevState(PyState):
  18. """
  19. Version of PyState that allows dumping to .dot files
  20. + node id's are generated sequentially to make writing tests easier
  21. """
  22. def __init__(self):
  23. self.free_id = 0
  24. super().__init__()
  25. def new_id(self) -> UUID:
  26. self.free_id += 1
  27. return UUID(int=self.free_id - 1)
  28. def dump(self, path: str, png_path: str = None):
  29. """Dumps the whole MV graph to a graphviz .dot-file
  30. Args:
  31. path (str): path for .dot-file
  32. png_path (str, optional): path for .png image generated from the .dot-file. Defaults to None.
  33. """
  34. with open(path, "w") as f:
  35. f.write("digraph main {\n")
  36. for n in sorted(self.nodes):
  37. if n in self.values:
  38. x = self.values[n]
  39. if isinstance(x, tuple):
  40. x = f"{x[0]}"
  41. else:
  42. x = repr(x)
  43. f.write("\"a_%s\" [label=\"%s\"];\n" % (
  44. n.int, x.replace('"', '\\"')))
  45. else:
  46. f.write("\"a_%s\" [label=\"\"];\n" % n)
  47. for i, e in sorted(list(self.edges.items())):
  48. f.write("\"a_%s\" [label=\"e_%s\" shape=point];\n" % (i.int, i.int))
  49. f.write("\"a_%s\" -> \"a_%s\" [arrowhead=none];\n" % (e[0].int, i.int))
  50. f.write("\"a_%s\" -> \"a_%s\";\n" % (i.int, e[1].int))
  51. f.write("}")
  52. if png_path is not None:
  53. # generate png from dot-file
  54. bashCommand = f"dot -Tpng {path} -o {png_path}"
  55. import subprocess
  56. process = subprocess.Popen(
  57. bashCommand.split(), stdout=subprocess.PIPE)
  58. output, error = process.communicate()