Debian Codegraph @

tests/flattening/flatten.py

raw
1 #!/usr/bin/env python3
2
3 from pathlib import Path
4 from subprocess import run
5 from typing import List, Tuple
6 import argparse
7 import asyncio
8 import csv
9 import json
10 import os
11 import shlex
12 import time
13
14
15 async def flatten(
16 instance: List[Path],
17 minizinc: str,
18 prefix_args: List[str],
19 suffix_args: List[str],
20 ):
21 cmd = []
22 cmd.extend(prefix_args)
23 cmd.extend(
24 [
25 minizinc,
26 "--solver",
27 "org.minizinc.mzn-fzn",
28 "-c",
29 "-s",
30 "-v",
31 ]
32 )
33 cmd.extend(suffix_args)
34 cmd.extend(instance)
35 p = await asyncio.create_subprocess_exec(
36 *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
37 )
38 stdout, stderr = await p.communicate()
39 return p.returncode, stdout.decode(), stderr.decode()
40
41
42 async def process(
43 semaphore: asyncio.Semaphore,
44 count: Tuple[int, int],
45 instance: List[Path],
46 minizinc: str,
47 prefix_args: List[str],
48 suffix_args: List[str],
49 root: Path,
50 stats,
51 ):
52 files = [p.relative_to(root).as_posix() for p in instance]
53 name = " with ".join(files)
54 i, n = count
55 async with semaphore:
56 print(f"Flattening {name} [{i}/{n}]...")
57 exit_code, stdout, stderr = await flatten(
58 instance, minizinc, prefix_args, suffix_args
59 )
60 while len(files) < 2:
61 files.append("")
62 for line in stdout.splitlines():
63 l = line.strip()
64 if l.startswith("%%%mzn-stat: "):
65 [key, val] = l[13:].split("=")
66 try:
67 val = json.loads(val)
68 except json.JSONDecodeError:
69 pass
70 stats.writerow(files + [key, val])
71
72 if exit_code == 0:
73 print(f"Flattening {name} succeeded.")
74 return True
75 else:
76 print(f"Flattening {name} failed.")
77 print(stderr)
78 return False
79
80
81 async def main(args):
82 minizinc = args.minizinc
83 instances = []
84 version = run([minizinc, "--version"], capture_output=True, encoding="utf-8").stdout
85 print("Flattening benchmarking tool\n")
86 print(version)
87 root = Path(args.instances)
88 if root.is_dir():
89 for mzn in root.rglob("*.mzn"):
90 dzns = list(mzn.parent.rglob("*.dzn"))
91 if len(dzns) > 0:
92 for dzn in dzns:
93 instances.append([mzn, dzn])
94 else:
95 instances.append([mzn])
96 elif root.is_file():
97 with root.open("r", newline="") as fp:
98 for row in csv.reader(fp):
99 instances.append([Path(root.parent) / f for f in row if len(f) > 0])
100 root = root.parent
101 else:
102 raise ValueError(f"Failed to collect instances from '{root}'")
103 n = len(instances)
104 max_workers = n
105 if args.parallel == 0:
106 max_workers = os.cpu_count()
107 elif args.parallel > 0:
108 max_workers = args.parallel
109 semaphore = asyncio.Semaphore(max_workers)
110 print(f"{n} instances collected.")
111 print(f"Flattening with {max_workers} workers.\n")
112 prefix_args = shlex.split(args.prefix_args)
113 suffix_args = shlex.split(args.args)
114 with open(args.output, "w", newline="") as csvfile:
115 stats = csv.writer(csvfile)
116 stats.writerow(["model", "data_file", "statistic", "value"])
117 stats.writerow(["", "", "_minizincVersion", version])
118 stats.writerow(["", "", "_minizincCommand", minizinc])
119 stats.writerow(["", "", "_minizincPrefixArgs", prefix_args])
120 stats.writerow(["", "", "_minizincSuffixArgs", suffix_args])
121 results = await asyncio.gather(
122 *[
123 process(
124 semaphore,
125 (i, n),
126 instance,
127 minizinc,
128 prefix_args,
129 suffix_args,
130 root,
131 stats,
132 )
133 for i, instance in enumerate(instances)
134 ]
135 )
136 fails = results.count(False)
137 stats.writerow(["", "", "_flatFailures", fails])
138 print(f"{fails}/{n} instances failed to flatten.")
139
140 try:
141 # Print summary if dependencies are available
142 import pandas as pd
143 from tabulate import tabulate
144
145 df = pd.read_csv(args.output)
146 df.value = pd.to_numeric(df.value, errors="coerce")
147 df_s = (
148 df.groupby(by=["statistic"])
149 .sum(numeric_only=True)
150 .reset_index(level=0)
151 .sort_values(by="statistic")
152 )
153 print(tabulate(df_s, headers=["statistic", "total"], tablefmt="pretty"))
154 except ImportError:
155 pass
156
157
158 if __name__ == "__main__":
159 parser = argparse.ArgumentParser(description="Run flattening benchmark.")
160 parser.add_argument(
161 "instances",
162 type=str,
163 help="instances directory",
164 )
165 parser.add_argument(
166 "output",
167 type=str,
168 help="output CSV file",
169 )
170 parser.add_argument(
171 "--minizinc",
172 default="minizinc",
173 type=str,
174 help="Path to the minizinc binary to use",
175 )
176 parser.add_argument(
177 "--prefix-args",
178 default="",
179 type=str,
180 help="Command line options to add to beginning of minizinc call",
181 )
182 parser.add_argument(
183 "--args",
184 default="",
185 type=str,
186 help="Command line options to add to end of minizinc call",
187 )
188 parser.add_argument(
189 "--parallel",
190 default=0,
191 type=int,
192 help="Parallel instances to flatten",
193 )
194
195 start = time.time()
196 asyncio.run(main(parser.parse_args()))
197 print(f"Done in {time.time() - start}s.")