testPyPDEVS.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #!/usr/bin/env python3
  2. import os
  3. import subprocess
  4. import csv
  5. import re
  6. from argparse import ArgumentParser, Action
  7. from pathlib import Path
  8. from itertools import product
  9. from datetime import datetime
  10. from pandas.errors import ParserError
  11. MODEL_TYPES = ("LI", "HI", "HO", "HOmod")
  12. DS_MODEL_TYPES = ("LI2HI", "HI2LI", "LI-HI", "dLI", "dHI")
  13. GEN_METHODS = ("start", "uniform", "end")
  14. INT_CYCLES = 0
  15. EXT_CYCLES = 0
  16. PyPDEVS = "./pythonpdevs/main.py"
  17. MinimalPyPDEVS = "./pythonpdevs-minimal/main.py"
  18. # Regex to capture times from script output
  19. TIME_PATTERN = re.compile(
  20. r"Model creation time: ([\d.eE+-]+).*"
  21. r"Engine setup time: ([\d.eE+-]+).*"
  22. r"Simulation time: ([\d.eE+-]+)",
  23. re.S
  24. )
  25. def create_graph(file):
  26. subprocess.run(f"procpath plot -d {file} -f {file[:-7]}.svg -q rss", shell=True)
  27. def run_devstone(model_type, depth, width, mode, out, memory, *, classic=False, number=1, gen_mode="uniform"):
  28. """Runs the devstone_driver.py script and returns timing results as floats."""
  29. SCRIPT_PATH = PyPDEVS
  30. if mode == "minimal":
  31. SCRIPT_PATH = MinimalPyPDEVS
  32. cmd = [
  33. "uv", "run", SCRIPT_PATH,
  34. "-m", model_type,
  35. "-d", str(depth),
  36. "-w", str(width),
  37. "-i", str(INT_CYCLES),
  38. "-e", str(EXT_CYCLES),
  39. ]
  40. if mode == "dynamic":
  41. cmd.extend(["-D"])
  42. if classic:
  43. cmd.extend(["-C"])
  44. cmd.extend(["-n", str(number)])
  45. cmd.extend(["-g", gen_mode])
  46. if mode == "classic":
  47. cmd.extend(["-C"])
  48. full_cmd = " ".join(cmd)
  49. if memory:
  50. Path("/".join(memory["file"].split("/")[0:-1])).mkdir(parents=True, exist_ok=True)
  51. full_cmd = (
  52. f"{full_cmd} & "
  53. f"PID=$!; "
  54. f"python -m procpath record -i {memory['interval']} -f stat -d {memory['file']} "
  55. f"--stop-without-result \"$..children[?(@.stat.pid == $PID)]\""
  56. )
  57. result = subprocess.run(full_cmd, shell=True, capture_output=True, text=True)
  58. cout = result.stdout.strip()
  59. if out:
  60. print(cout)
  61. if memory:
  62. create_graph(memory["file"])
  63. cerr = result.stderr.strip()
  64. match = TIME_PATTERN.search(cout)
  65. if match:
  66. creation, setup, sim = map(float, match.groups())
  67. return creation, setup, sim
  68. print("Failed to run: ", " ".join(cmd))
  69. print(cout)
  70. print(cerr)
  71. return None, None, None
  72. def defaultArguments(parser):
  73. parser.add_argument("-p", "--path", type=str, default="./Results-PyPDEVS", help="Path to the results directory")
  74. parser.add_argument("-f", '--filename', type=str, default="", help="Name of the output file")
  75. parser.add_argument("-a", "--append", action="store_true", help="Append to the output file instead of overwriting.")
  76. parser.add_argument("-md", "--max-depth", default=8, type=int, help="Max depth for the generated models")
  77. parser.add_argument("-ds", "--depth-stepsize", type=int, help="Determines for which depths a model is generated.")
  78. parser.add_argument("-mw", "--max-width", default=8, type=int, help="Max width for the generated models")
  79. parser.add_argument("-ws", "--width-stepsize", type=int, help="Determines for which depths a model is generated.")
  80. parser.add_argument("-r", "--repetitions", default=1, type=int, help="The number of times a simulation is repeated")
  81. parser.add_argument("-O", "--output", action="store_true", help="Print Simulation Outputs")
  82. parser.add_argument("-M", "--memory", action="store_true", help="Measures the memory usage of a simulation.")
  83. parser.add_argument("-i", "--interval", default=1.0, type=float, help="The interval at which measurements are taken.")
  84. def Minimal(subparsers):
  85. minimal = subparsers.add_parser("minimal", help="Minimal DEVS kernel")
  86. minimal.set_defaults(mode="minimal")
  87. defaultArguments(minimal)
  88. minimal.add_argument(
  89. "-ms", "--model-structure",
  90. nargs="+",
  91. choices=MODEL_TYPES,
  92. default=MODEL_TYPES
  93. )
  94. def Classic(subparsers):
  95. classic = subparsers.add_parser("classic", help="Classic DEVS Simulator")
  96. classic.set_defaults(mode="classic")
  97. defaultArguments(classic)
  98. classic.add_argument(
  99. "-ms", "--model-structure",
  100. nargs="+",
  101. choices=MODEL_TYPES,
  102. default=MODEL_TYPES
  103. )
  104. def Parallel(subparsers):
  105. parallel = subparsers.add_parser("parallel", help="Parallel DEVS")
  106. parallel.set_defaults(mode="parallel")
  107. defaultArguments(parallel)
  108. parallel.add_argument(
  109. "-ms", "--model-structure",
  110. nargs="+",
  111. choices=MODEL_TYPES,
  112. default=MODEL_TYPES
  113. )
  114. def Dynamic(subparsers):
  115. dynamic = subparsers.add_parser("dynamic", help="Dynamic Structure DEVS")
  116. dynamic.set_defaults(mode="dynamic")
  117. defaultArguments(dynamic)
  118. dynamic.add_argument(
  119. "-ms", "--model-structure",
  120. nargs="+",
  121. choices=MODEL_TYPES + DS_MODEL_TYPES,
  122. default=MODEL_TYPES + DS_MODEL_TYPES
  123. )
  124. dynamic.add_argument(
  125. "-C", "--classic",
  126. action="store_true",
  127. default=False,
  128. help="Selects the Classic DEVS Simulator"
  129. )
  130. dynamic.add_argument(
  131. "-n", "--number",
  132. default=1,
  133. type=int,
  134. help="Number of models to be generated in a cycle per coupled model")
  135. dynamic.add_argument(
  136. "-g", "--gen-mode",
  137. choices=GEN_METHODS,
  138. default="uniform"
  139. )
  140. def parse_args():
  141. parser = ArgumentParser()
  142. subparsers = parser.add_subparsers(dest="mode")
  143. Minimal(subparsers)
  144. Parallel(subparsers)
  145. Classic(subparsers)
  146. Dynamic(subparsers)
  147. args = parser.parse_args()
  148. if args.depth_stepsize is None:
  149. args.depth_stepsize = args.max_depth
  150. if args.width_stepsize is None:
  151. args.width_stepsize = args.max_width
  152. return args
  153. def run(writer, csvfile, model_type, d, w, args, mem_cmd, extra):
  154. """Orchestrates the repeated simulation runs."""
  155. for depth in range(d[1], d[0] + 1, d[1]):
  156. for width in range(w[1], w[0] + 1, w[1]):
  157. for run in range(args.repetitions):
  158. creation, setup, sim = run_devstone(
  159. model_type, depth, width,
  160. args.mode, args.output,
  161. mem_cmd,
  162. **extra
  163. )
  164. # Only write to CSV if a writer was provided
  165. if writer and creation is not None:
  166. row = {
  167. "model_type": model_type, "depth": depth, "width": width, "run": run,
  168. "creation_time": creation, "setup_time": setup, "simulation_time": sim,
  169. }
  170. if args.mode == "dynamic":
  171. row["number"] = args.number
  172. row["generator_mode"] = args.gen_mode
  173. writer.writerow(row)
  174. csvfile.flush()
  175. if __name__ == "__main__":
  176. args = parse_args()
  177. print(args)
  178. d = (args.max_depth, args.depth_stepsize)
  179. w = (args.max_width, args.width_stepsize)
  180. if d[0] % d[1] != 0:
  181. raise RuntimeError("Invalid depth stepsize.")
  182. if w[0] % w[1] != 0:
  183. raise RuntimeError("Invalid width stepsize.")
  184. fieldnames = ["model_type", "depth", "width", "run",
  185. "creation_time", "setup_time", "simulation_time"]
  186. mode = args.mode
  187. if mode == "dynamic":
  188. if args.classic:
  189. mode += "-classic"
  190. fieldnames += ["number", "generator_mode"]
  191. extra = {
  192. "classic": False if not hasattr(args, "classic") else args.classic,
  193. "gen_mode": "uniform" if not hasattr(args, "gen_mode") else args.gen_mode,
  194. "number": 1 if not hasattr(args, "number") else args.number,
  195. }
  196. for model_type in args.model_structure:
  197. model_time_file = f"{args.path}/Time/{mode}/{model_type}"
  198. model_memory_file = f"{args.path}/Memory/{mode}/{model_type}"
  199. if args.filename:
  200. suffix = f"_{args.filename}"
  201. model_time_file += suffix
  202. model_memory_file += suffix
  203. model_time_file += ".csv"
  204. model_memory_file += ".sqlite"
  205. mem_cmd = {"interval": args.interval, "file": model_memory_file} if args.memory else {}
  206. if not args.memory:
  207. file_mode = "a" if args.append else "w"
  208. write_header = not args.append or not os.path.exists(model_time_file)
  209. with open(model_time_file, file_mode, newline="") as csvfile:
  210. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  211. if write_header:
  212. writer.writeheader()
  213. run(writer, csvfile, model_type, d, w, args, mem_cmd, extra)
  214. print(f"✅ Saved timing results to {model_time_file}")
  215. else:
  216. if os.path.exists(model_memory_file) and not args.append:
  217. os.remove(model_memory_file)
  218. print("📊 Measuring memory (Timing results will not be saved)...")
  219. run(None, None, model_type, d, w, args, mem_cmd, extra)
  220. print(f"✅ Saved memory database to {model_memory_file}")