testPyPDEVS.py 9.1 KB

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