testPyPDEVS.py 9.7 KB

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