-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
291 lines (254 loc) · 7.83 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
from __future__ import annotations
from posix import listdir
from re import S, match
from typing import Any, Sequence
import pickle
import argparse
from bqskit.ir.operation import Operation
from qiskit import circuit
from networkx.classes.graph import Graph
from math import sqrt, ceil
from bqskit import Circuit
from bqskit.ir.lang.qasm2.qasm2 import OPENQASM2Language
#from bqskit.passes.util.converttocnot import ToCNOTPass
from mapping import find_num_qudits
def load_block_circuit(
block_path : str,
options : dict[str, Any]
) -> Circuit:
if options['checkpoint_as_qasm']:
with open(block_path, "r") as f:
return OPENQASM2Language().decode(f.read())
else:
with open(block_path, 'rb') as f:
return pickle.load(f)
def save_block_circuit(
block_path : str,
block_circuit : Circuit,
options : dict[str, Any]
) -> None:
if options['checkpoint_as_qasm']:
qasm = OPENQASM2Language().encode(block_circuit)
with open(block_path, "w") as f:
f.write(qasm)
else:
with open(block_path, 'wb') as f:
pickle.dump(block_circuit, f)
def load_block_topology(
block_path : str,
) -> Graph | Sequence[tuple[int,int]]:
with open(block_path, "rb") as f:
return pickle.load(f)
def save_block_topology(
subtopology: Graph,
block_path : str,
) -> None:
with open(block_path, 'wb') as f:
pickle.dump(subtopology, f)
def save_circuit_structure(
partition_directory: str,
structure_list : Sequence[Sequence[int]],
) -> None:
with open(f"{partition_directory}/structure.pickle", "wb") as f:
pickle.dump(structure_list, f)
def load_circuit_structure(
partition_directory : str,
) -> Sequence[Sequence[int]]:
with open(f"{partition_directory}/structure.pickle", "rb") as f:
return pickle.load(f)
def setup_options(
qasm_file : str,
args : argparse.Namespace
) -> dict[str,Any]:
# Select coupling map
valid_map_types = ["mesh", "linear", "falcon"]
if not args.map_type in valid_map_types:
raise RuntimeError(
f"{args.map_type} is not a valid coupling map type."
)
num_q = find_num_qudits(qasm_file)
if args.map_type == "mesh":
num_p_sqrt = ceil(sqrt(num_q))
num_p = num_p_sqrt ** 2
coupling_map = (
f"{args.map_type}_{num_p}"
)
elif args.map_type == "linear":
coupling_map = (
f"{args.map_type}_{num_q}"
)
num_p = num_q
else: #elif args.map_type == "falcon"
#sizes = [16, 27, 65]
if num_q <= 16:
coupling_map = f"falcon_16"
num_p = 16
elif num_q <= 27:
coupling_map = f"falcon_27"
num_p = 27
elif num_q <= 65:
coupling_map = f"falcon_65"
num_p = 65
elif num_q <= 113:
coupling_map = f"falcon_113"
num_p = 113
elif num_q <= 209:
coupling_map = f"falcon_209"
num_p = 209
elif num_q <= 435:
coupling_map = f"falcon_435"
num_p = 435
else:
raise RuntimeError(
f"{num_q} qubits is too large for the falcon map type."
)
# Select partitioner
valid_partitioners = ["scan", "greedy", "quick", "custom"]
if not args.partitioner in valid_partitioners:
raise RuntimeError(
f"{args.partitioner} is not a valid partitioner type."
)
partitioner = args.partitioner
options = {
"blocksize" : args.blocksize,
"coupling_map" : f"coupling_maps/{coupling_map}",
"topology" : args.map_type,
"num_p" : num_p,
"partitioner" : partitioner,
"checkpoint_as_qasm" : True,
"direct_ops" : 0,
"indirect_ops" : 0,
"external_ops" : 0,
"direct_volume" : 0,
"indirect_volume" : 0,
"external_volume" : 0,
"max_block_length" : 0,
"min_block_length" : 0,
"estimated_cnots" : 0,
"total_volume" : 0,
"router" : args.router,
"original_qasm_file" : qasm_file,
}
target_name = qasm_file.split("qasm/")[-1].split(".qasm")[0]
target_name += "_" + coupling_map
target_name += f"_blocksize_{args.blocksize}"
options["layout_qasm_file"] = "layout_qasm/" + target_name + ".qasm"
target_name += f"_{partitioner}"
options["partition_dir"] = "block_files/" + target_name
options["save_part_name"] = target_name
if args.alltoall:
suffix = "_alltoall"
#elif args.logical_connectivity:
# suffix = "_logicalconnectivity"
else:
suffix = "_kernel"
target_name += suffix
options["target_name"] = target_name
options["synthesized_qasm_file"] = "synthesized_qasm/" + target_name + ".qasm"
options["resynthesized_qasm_file"] = "resynthesized_qasm/" + target_name + ".qasm"
options["relayout_qasm_file"] = "relayout_qasm/" + target_name + ".qasm"
options["relayout_remapping_file"] = "relayout_qasm/" + target_name + ".pickle"
options["mapped_qasm_file"] = "mapped_qasm/" + target_name + f"_{args.router}" + ".qasm"
options["remapped_qasm_file"] = "mapped_qasm/" + f"{target_name}_{args.router}_remapped.qasm"
options["synthesis_dir"] = "synthesis_files/" + target_name
options["opt_dir"] = "optimized_files/" + target_name
options["resynthesis_dir"] = "synthesis_files/" + target_name + "_resynth"
options["nosynth_dir"] = options["synthesis_dir"] + f"_{args.router}_nosynth"
options["subtopology_dir"] = "subtopology_files/" + target_name
options["kernel_dir"] = f"kernels/{coupling_map}_blocksize_{args.blocksize}"
options["unsynthesized_layout"] = f"unsynthesized_layout/{target_name}.qasm"
options["unsynthesized_qubit_remapping"] = f"unsynthesized_layout/{target_name}.pickle"
options["unsynthesized_mapping"] = f"unsynthesized_mapping/{target_name}_{args.router}.qasm"
return options
def get_summary(
options : dict[str, Any],
block_files : Sequence[str],
post_flag : bool = False,
) -> str:
total_ops = sum([options["direct_ops"], options["indirect_ops"],
options["external_ops"]])
string = (
"\nSummary:\n"
f"Number of blocks: {len(block_files)}\n"
f"Mean block size (cnots): {total_ops/len(block_files)}\n\n"
f"Total internal direct operations: {options['direct_ops']}\n"
f"Total internal indirect operations: {options['indirect_ops']}\n"
f"Total external operations: {options['external_ops']}\n"
)
if post_flag:
string += get_mapping_results(options)
string += get_original_count(options)
print(string)
return string
def get_mapping_results(
options : dict[str, Any],
) -> str:
path = options["mapped_qasm_file"]
cnots = 0
swaps = 0
with open(path, "r") as qasmfile:
for line in qasmfile:
if match("cx", line):
cnots += 1
elif match("swap", line):
swaps += 1
with open(path, "r") as f:
circ = OPENQASM2Language().decode(f.read())
# ToCNOTPass().run(circ)
depth = circ.num_cycles
parallelism = circ.parallelism
return (
f"Synthesized CNOTs: {cnots}\nSWAPs from routing: {swaps}\n"
f"Circuit depth: {depth}\nParallelism: {parallelism}\n"
)
def get_remapping_results(
options : dict[str, Any],
) -> str:
path = options["remapped_qasm_file"]
cnots = 0
swaps = 0
with open(path, "r") as qasmfile:
for line in qasmfile:
if match("cx", line):
cnots += 1
elif match("swap", line):
swaps += 1
with open(path, "r") as f:
circ = OPENQASM2Language().decode(f.read())
# ToCNOTPass().run(circ)
depth = circ.num_cycles
parallelism = circ.parallelism
return (
f"Synthesized CNOTs: {cnots}\nSWAPs from routing: {swaps}\n"
f"Circuit depth: {depth}\nParallelism: {parallelism}\n"
)
def get_original_count(
options : dict[str, Any],
) -> str:
path = options["original_qasm_file"]
cnots = 0
with open(path, "r") as qasmfile:
for line in qasmfile:
if match("cx", line):
cnots += 1
with open(path, "r") as f:
circ = OPENQASM2Language().decode(f.read())
# ToCNOTPass().run(circ)
depth = circ.num_cycles
parallelism = circ.parallelism
return (
f"Original CNOTs: {cnots}\nOriginal depth: {depth}\n"
f"Parallelism: {parallelism}\n"
)
def rewrite_block(
block_path : str,
original_qudit_group : Sequence[int],
new_qudit_group : Sequence[int],
options : dict[str, Any],
) -> None:
circuit = load_block_circuit(block_path, options)
for i, qudit in enumerate(sorted(new_qudit_group)):
if qudit in original_qudit_group:
continue
circuit.insert_qudit(i)
save_block_circuit(block_path, circuit, options)