devstone_comparative.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. from __future__ import annotations
  2. import argparse
  3. import csv
  4. import re
  5. import subprocess
  6. import sys
  7. import time
  8. DEFAULT_PARAMS = ((300, 10, 0, 0), (10, 300, 0, 0), (300, 300, 0, 0))
  9. DEFAULT_MODEL_TYPES = ("LI", "HI", "HO", "HOmod")
  10. DEFAULT_MAX_TIME = 1e10
  11. DEFAULT_NUM_REPS = 30
  12. PRELAUNCH_TASKS = {
  13. "adevs": [
  14. "cmake -S devstone/adevs/ -B devstone/adevs/build/ -D CMAKE_BUILD_TYPE=Release",
  15. "cmake --build devstone/adevs/build/ --target devstone",
  16. ],
  17. "cadmium": {
  18. "v1": [
  19. "cmake -S devstone/cadmium/ -B devstone/cadmium/build/ -D CMAKE_BUILD_TYPE=Release",
  20. "cmake --build devstone/cadmium/build/ --target devstone",
  21. ],
  22. "v2": {
  23. "sequential": [
  24. "cmake -S simulators/cadmium_v2/ -B simulators/cadmium_v2/build/ -D CMAKE_BUILD_TYPE=Release",
  25. "cmake --build simulators/cadmium_v2/build/ --target main_devstone",
  26. ],
  27. "parallel": [
  28. "cmake -S simulators/cadmium_v2/ -B simulators/cadmium_v2/build/ -D CMAKE_BUILD_TYPE=Release",
  29. "cmake --build simulators/cadmium_v2/build/ --target parallel_main_devstone",
  30. ],
  31. },
  32. },
  33. "xdevs": {
  34. "c": ["cd simulators/xdevs.c/ && make"],
  35. "cpp": ["cd simulators/xdevs.cpp/ && make"],
  36. "java": {
  37. "sequential": ["cd simulators/xdevs.java/ && mvn clean && mvn compile && mvn package"],
  38. "parallel": ["cd simulators/xdevs.java/ && mvn clean && mvn compile && mvn package"],
  39. },
  40. "rs": {
  41. "old": ["cargo build --manifest-path simulators/xdevs.rs/Cargo.toml --release"],
  42. "new": {
  43. "sequential": ["cargo build --manifest-path simulators/xdevs.rs-new/Cargo.toml --release --example devstone"],
  44. "parallel": ["cargo build --manifest-path simulators/xdevs.rs-new/Cargo.toml --release --features par_all_no_couplings --example devstone"],
  45. "fullparallel": ["cargo build --manifest-path simulators/xdevs.rs-new/Cargo.toml --release --features par_all --example devstone"],
  46. }
  47. },
  48. },
  49. }
  50. COMMANDS = {
  51. "adevs": "devstone/adevs/bin/devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  52. "cadmium": {
  53. "v1": "devstone/cadmium/build/cadmium-dynamic-devstone --kind={model_type} --width={width} --depth={depth} --int-cycles={int_cycles} --ext-cycles={ext_cycles}",
  54. "v2": {
  55. "sequential": "simulators/cadmium_v2/bin/main_devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  56. "parallel": "simulators/cadmium_v2/bin/parallel_main_devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  57. },
  58. },
  59. "pypdevs": {
  60. "standard": {
  61. "python": "python3 devstone/pythonpdevs/main.py -m {model_type} -w {width} -d {depth} -i {int_cycles} -e {ext_cycles}",
  62. "pypy": "pypy3 devstone/pythonpdevs/main.py -m {model_type} -w {width} -d {depth} -i {int_cycles} -e {ext_cycles}",
  63. },
  64. "minimal": {
  65. "python": "python3 devstone/pythonpdevs-minimal/main.py -m {model_type} -d {depth} -w {width} -i {int_cycles} -e {ext_cycles}",
  66. "pypy": "pypy3 devstone/pythonpdevs-minimal/main.py -m {model_type} -d {depth} -w {width} -i {int_cycles} -e {ext_cycles}",
  67. },
  68. },
  69. "xdevs": {
  70. "c": "simulators/xdevs.c/examples/devstone/devstone -w {width} -d {depth} -b {model_type} -m 1",
  71. "cpp": "simulators/xdevs.cpp/src/xdevs/examples/DevStone/DevStone -w {width} -d {depth} -b {model_type} -m 1",
  72. # "go": , # TODO add this
  73. "java": {
  74. "sequential": "java -cp simulators/xdevs.java/target/xdevs-2.0.3-jar-with-dependencies.jar xdevs.lib.performance.DevStoneSimulation --model={model_type} --width={width} --depth={depth} --delay-distribution=Constant-{int_cycles} --coordinator=Coordinator",
  75. "parallel": "java -cp simulators/xdevs.java/target/xdevs-2.0.3-jar-with-dependencies.jar xdevs.lib.performance.DevStoneSimulation --model={model_type} --width={width} --depth={depth} --delay-distribution=Constant-{int_cycles} --coordinator=CoordinatorParallel",
  76. },
  77. "py": "python3 simulators/xdevs.py/xdevs/examples/devstone/devstone.py {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  78. "rs": {
  79. "old": "simulators/xdevs.rs/target/release/xdevs {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  80. "new": {
  81. "sequential": "simulators/xdevs.rs-new/target/release/examples/devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  82. "parallel": "simulators/xdevs.rs-new/target/release/examples/devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  83. "fullparallel": "simulators/xdevs.rs-new/target/release/examples/devstone {model_type} {width} {depth} {int_cycles} {ext_cycles}",
  84. }
  85. },
  86. },
  87. }
  88. DEFAULT_RE = r"model creation time(?:[ \(s\)]*): ?([0-9.e-]+)([ nuµms]*).*(?:engine|simulator) (?:set ?up|creation) time(?:[ \(s\)]*): ?([0-9.e-]+)([ nuµms]*).*simulation time(?:[ \(s\)]*): ?([0-9.e-]+)([ nuµms]*)"
  89. CUSTOM_RE = {}
  90. def serialize_simengines(res: list[str], prefix: str, flavors: str | dict):
  91. if isinstance(flavors, str):
  92. res.append(prefix)
  93. else:
  94. for key, val in flavors.items():
  95. new_prefix = f'{prefix}-{key}' if prefix else key
  96. serialize_simengines(res, new_prefix, val)
  97. def parse_args():
  98. parser = argparse.ArgumentParser(description='Script to compare DEVStone implementations with different engines')
  99. parser.add_argument('-m', '--model-types', help='DEVStone model type (LI, HI, HO, HOmod)')
  100. parser.add_argument('-w', '--width', type=int, help='Width of each coupled model.')
  101. parser.add_argument('-d', '--depth', type=int, help='Number of recursive levels of the model.')
  102. parser.add_argument('-i', '--int-cycles', type=int, help='Dhrystone cycles executed in internal transitions')
  103. parser.add_argument('-e', '--ext-cycles', type=int, help='Dhrystone cycles executed in external transitions')
  104. parser.add_argument('-n', '--num-rep', type=int, help='Number of repetitions per each engine and configuration')
  105. parser.add_argument('-a', '--include_engines', help='Add specific engines to perform the comparative')
  106. parser.add_argument('-r', '--exclude_engines', help='Exclude specific engines from the comparative')
  107. parser.add_argument('-o', '--out-file', help='Output file path')
  108. parser.add_argument('-p', '--params', help='Specify params in a condensed form: w1-d1-ic1-ec1, w2-d2-ic2-ec2...')
  109. args = parser.parse_args()
  110. if args.model_types:
  111. args.model_types = [x.strip() for x in args.model_types.split(",")]
  112. else:
  113. args.model_types = list(DEFAULT_MODEL_TYPES)
  114. if args.params:
  115. params = [x.strip().split("-") for x in args.params.split(",")]
  116. # args.params = [x.strip().split("-") for x in args.params.split(",")]
  117. elif args.depth and args.width:
  118. int_cycles = args.int_cycles or 0
  119. ext_cycles = args.ext_cycles or 0
  120. params = [(args.width, args.depth, int_cycles, ext_cycles)]
  121. # args.params = ((args.depth, args.width, int_cycles, ext_cycles),)
  122. else:
  123. params = list(DEFAULT_PARAMS)
  124. args.params = []
  125. for param in params:
  126. if len(param) == 5:
  127. args.params.append(param)
  128. elif len(param) == 4:
  129. for model in args.model_types:
  130. args.params.append((model, *param))
  131. else:
  132. raise ValueError(f'invalid number of params ({param})')
  133. engines = args.include_engines.split(',') if args.include_engines else list(COMMANDS.keys())
  134. args.include_engines = []
  135. for eng in engines:
  136. commands = COMMANDS
  137. for s in eng.split('-'):
  138. commands = commands.get(s, dict())
  139. subengines = []
  140. serialize_simengines(subengines, '', commands)
  141. if not subengines:
  142. raise RuntimeError(f'unknown simulation engine {eng}')
  143. subengines = [f'{eng}-{x}' if x else f'{eng}' for x in subengines]
  144. args.include_engines.extend(subengines)
  145. if args.exclude_engines:
  146. args.include_engines = [x for x in args.include_engines if x not in args.exclude_engines.split(",")]
  147. args.prelaunch = {}
  148. args.commands = {}
  149. args.regex = {}
  150. for eng in args.include_engines:
  151. prelaunch = PRELAUNCH_TASKS
  152. cmd = COMMANDS
  153. regex = CUSTOM_RE
  154. for s in eng.split('-'):
  155. if isinstance(prelaunch, dict):
  156. prelaunch = prelaunch.get(s, dict())
  157. cmd = cmd.get(s, dict())
  158. if not isinstance(regex, str):
  159. regex = regex.get(s, DEFAULT_RE)
  160. if isinstance(prelaunch, dict):
  161. prelaunch = None
  162. if not cmd:
  163. raise RuntimeError(f'unknown simulation engine {eng}')
  164. if isinstance(cmd, dict):
  165. # TODO instead of this, serialize all the flavors of the engine
  166. raise RuntimeError(f'There are more than one flavor for the engine {eng}')
  167. else:
  168. args.prelaunch[eng] = prelaunch
  169. args.commands[eng] = cmd
  170. args.regex[eng] = regex
  171. if not args.num_rep:
  172. args.num_rep = DEFAULT_NUM_REPS
  173. if not args.out_file:
  174. args.out_file = "devstone_%de_%dp_%d.csv" % (len(args.include_engines), len(args.params), int(time.time()))
  175. return args
  176. def execute_prelaunch(cmd):
  177. try:
  178. result = subprocess.run(cmd.split(), stdout=subprocess.PIPE)
  179. except Exception as e:
  180. print(f"Error executing prelaunch command. ({str(e)})")
  181. return
  182. print(result.stdout)
  183. def execute_cmd(cmd, regex, csv_writer):
  184. # Execute simulation
  185. try:
  186. result = subprocess.run(cmd.split(), stdout=subprocess.PIPE)
  187. except Exception as e:
  188. print(f"{engine}: Error executing simulation. ({str(e)})")
  189. return
  190. # Read data from output
  191. res_out = result.stdout.decode('UTF-8').strip()
  192. if not res_out:
  193. res_out = str(result.stderr).strip()
  194. res_out.replace("\n", " ")
  195. found = re.search(regex, res_out, flags=re.IGNORECASE | re.DOTALL)
  196. if not found:
  197. print(f"{engine}: Simulation execution times could not be extracted.")
  198. print(result.stdout)
  199. return
  200. groups = found.groups()
  201. if len(groups) == 3:
  202. model_time, engine_time, sim_time = tuple(map(float, found.groups()))
  203. elif len(groups) == 6:
  204. times = list(map(float, (groups[0], groups[2], groups[4])))
  205. units = (groups[1], groups[3], groups[5])
  206. for i in range(3):
  207. if units[i]:
  208. unit = units[i].strip()
  209. if unit.startswith('s'):
  210. pass
  211. elif unit.startswith('ms'):
  212. times[i] *= 1e-3
  213. elif unit.startswith('us') or unit.startswith('µs'):
  214. times[i] *= 1e-6
  215. elif unit.startswith('ns'):
  216. times[i] *= 1e-9
  217. else:
  218. raise Exception(f"unknown time units: {unit}")
  219. times = tuple(times)
  220. model_time, engine_time, sim_time = times
  221. total_time = sum((model_time, engine_time, sim_time))
  222. # Write results into output file
  223. row = (engine, i_exec, model_type, width, depth, int_cycles, ext_cycles, model_time, engine_time, sim_time, total_time)
  224. csv_writer.writerow(row)
  225. if __name__ == "__main__":
  226. sys.setrecursionlimit(10000)
  227. args = parse_args()
  228. if not args.include_engines:
  229. raise RuntimeError("No engines were selected.")
  230. with open(args.out_file, "w") as csv_file:
  231. csv_writer = csv.writer(csv_file, delimiter=';')
  232. csv_writer.writerow(("engine", "iter", "model", "width", "depth", "int_delay", "ext_delay", "model_time", "runner_time", "sim_time", "total_time"))
  233. for engine, engine_cmd in args.commands.items():
  234. engine_prelaunch = args.prelaunch[engine]
  235. if engine_prelaunch is not None:
  236. print(f'({engine}) executing prelaunch tasks...')
  237. for prelaunch_cmd in engine_prelaunch:
  238. execute_prelaunch(prelaunch_cmd)
  239. engine_regex = args.regex[engine]
  240. for params in args.params:
  241. model_type, width, depth, int_cycles, ext_cycles = params
  242. engine_cmd_f = engine_cmd.format(model_type=model_type, width=width, depth=depth,
  243. int_cycles=int_cycles, ext_cycles=ext_cycles)
  244. if not engine_cmd_f:
  245. continue
  246. for i_exec in range(args.num_rep):
  247. print(f'({i_exec}) {engine_cmd_f}')
  248. execute_cmd(engine_cmd_f, engine_regex, csv_writer)
  249. csv_file.flush()