forked from munich-quantum-toolkit/bench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
275 lines (229 loc) · 8.58 KB
/
utils.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
"""Utility functions for the MQT Bench module."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from importlib import import_module, metadata, resources
from pathlib import Path
from typing import TYPE_CHECKING
import networkx as nx
import numpy as np
from pytket import __version__ as __tket_version__
from qiskit import QuantumCircuit
from qiskit import __version__ as __qiskit_version__
from qiskit.converters import circuit_to_dag
if TYPE_CHECKING: # pragma: no cover
from types import ModuleType
from qiskit_optimization import QuadraticProgram
@dataclass
class SupermarqFeatures:
"""Data class for the Supermarq features of a quantum circuit."""
program_communication: float
critical_depth: float
entanglement_ratio: float
parallelism: float
liveness: float
def get_supported_benchmarks() -> list[str]:
"""Returns a list of all supported benchmarks."""
return [
"ae",
"dj",
"grover-noancilla",
"grover-v-chain",
"ghz",
"graphstate",
"portfolioqaoa",
"portfoliovqe",
"qaoa",
"qft",
"qftentangled",
"qnn",
"qpeexact",
"qpeinexact",
"qwalk-noancilla",
"qwalk-v-chain",
"random",
"realamprandom",
"su2random",
"twolocalrandom",
"vqe",
"wstate",
"shor",
"pricingcall",
"pricingput",
"groundstate",
"routing",
"tsp",
]
def get_supported_levels() -> list[str | int]:
"""Returns a list of all supported benchmark levels."""
return ["alg", "indep", "nativegates", "mapped", 0, 1, 2, 3]
def get_supported_compilers() -> list[str]:
"""Returns a list of all supported compilers."""
return ["qiskit", "tket"]
def get_default_config_path() -> str:
"""Returns the path to the default configuration file."""
return str(resources.files("mqt.bench") / "config.json")
def get_default_qasm_output_path() -> str:
"""Returns the path where all .qasm files are stored."""
return str(resources.files("mqt.bench") / "viewer" / "static" / "files" / "qasm_output")
def get_default_evaluation_output_path() -> str:
"""Returns the path where all .qasm files are stored."""
return str(resources.files("mqt.bench") / "evaluation")
def get_zip_folder_path() -> str:
"""Returns the path where the zip file is stored."""
return str(resources.files("mqt.bench") / "viewer" / "static" / "files")
def get_examplary_max_cut_qp(n_nodes: int, degree: int = 2) -> QuadraticProgram:
"""Returns a quadratic problem formulation of a max cut problem of a random graph.
Arguments:
n_nodes: number of graph nodes (and also number of qubits)
degree: edges per node
"""
from qiskit_optimization.applications import Maxcut # noqa: PLC0415 lazy import to reduce import cost
graph = nx.random_regular_graph(d=degree, n=n_nodes, seed=111)
maxcut = Maxcut(graph)
return maxcut.to_quadratic_program()
def get_openqasm_gates() -> list[str]:
"""Returns a list of all quantum gates within the openQASM 2.0 standard header."""
# according to https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/qasm/libs/qelib1.inc
return [
"u3",
"u2",
"u1",
"cx",
"id",
"u0",
"u",
"p",
"x",
"y",
"z",
"h",
"s",
"sdg",
"t",
"tdg",
"rx",
"ry",
"rz",
"sx",
"sxdg",
"cz",
"cy",
"swap",
"ch",
"ccx",
"cswap",
"crx",
"cry",
"crz",
"cu1",
"cp",
"cu3",
"csx",
"cu",
"rxx",
"rzz",
"rccx",
"rc3x",
"c3x",
"c3sqrtx",
"c4x",
]
def save_as_qasm(
qc_str: str,
filename: str,
gate_set: list[str] | None = None,
mapped: bool = False,
c_map: list[list[int]] | None = None,
target_directory: str = "",
) -> bool:
"""Saves a quantum circuit as a qasm file.
Arguments:
qc_str: Quantum circuit to be stored as a string
filename: filename
gate_set: set of used gates
mapped: boolean indicating whether the quantum circuit is mapped to a specific hardware layout
c_map: coupling map of used hardware layout
target_directory: directory where the qasm file is stored
"""
if c_map is None:
c_map = []
file = Path(target_directory, filename + ".qasm")
try:
mqtbench_module_version = metadata.version("mqt.bench")
except Exception:
print("'mqt.bench' is most likely not installed. Please run 'pip install . or pip install mqt.bench'.")
return False
with file.open("w") as f:
f.write("// Benchmark was created by MQT Bench on " + str(date.today()) + "\n")
f.write("// For more information about MQT Bench, please visit https://www.cda.cit.tum.de/mqtbench/\n")
f.write("// MQT Bench version: " + mqtbench_module_version + "\n")
if "qiskit" in filename:
f.write("// Qiskit version: " + str(__qiskit_version__) + "\n")
elif "tket" in filename:
f.write("// TKET version: " + str(__tket_version__) + "\n")
if gate_set:
f.write("// Used Gate Set: " + str(gate_set) + "\n")
if mapped:
f.write("// Coupling List: " + str(c_map) + "\n")
f.write("\n")
f.write(qc_str)
f.close()
return True
def calc_supermarq_features(
qc: QuantumCircuit,
) -> SupermarqFeatures:
"""Calculates the Supermarq features for a given quantum circuit. Code adapted from https://github.com/Infleqtion/client-superstaq/blob/91d947f8cc1d99f90dca58df5248d9016e4a5345/supermarq-benchmarks/supermarq/converters.py."""
num_qubits = qc.num_qubits
dag = circuit_to_dag(qc)
dag.remove_all_ops_named("barrier")
# Program communication = circuit's average qubit degree / degree of a complete graph.
graph = nx.Graph()
for op in dag.two_qubit_ops():
q1, q2 = op.qargs
graph.add_edge(qc.find_bit(q1).index, qc.find_bit(q2).index)
degree_sum = sum(graph.degree(n) for n in graph.nodes)
program_communication = degree_sum / (num_qubits * (num_qubits - 1)) if num_qubits > 1 else 0
# Liveness feature = sum of all entries in the liveness matrix / (num_qubits * depth).
activity_matrix = np.zeros((num_qubits, dag.depth()))
for i, layer in enumerate(dag.layers()):
for op in layer["partition"]:
for qubit in op:
activity_matrix[qc.find_bit(qubit).index, i] = 1
liveness = np.sum(activity_matrix) / (num_qubits * dag.depth()) if dag.depth() > 0 else 0
# Parallelism feature = max((((# of gates / depth) -1) /(# of qubits -1)), 0).
parallelism = (
max(((len(dag.gate_nodes()) / dag.depth()) - 1) / (num_qubits - 1), 0)
if num_qubits > 1 and dag.depth() > 0
else 0
)
# Entanglement-ratio = ratio between # of 2-qubit gates and total number of gates in the circuit.
entanglement_ratio = len(dag.two_qubit_ops()) / len(dag.gate_nodes()) if len(dag.gate_nodes()) > 0 else 0
# Critical depth = # of 2-qubit gates along the critical path / total # of 2-qubit gates.
longest_paths = dag.count_ops_longest_path()
n_ed = sum(longest_paths[name] for name in {op.name for op in dag.two_qubit_ops()} if name in longest_paths)
n_e = len(dag.two_qubit_ops())
critical_depth = n_ed / n_e if n_e != 0 else 0
assert 0 <= program_communication <= 1
assert 0 <= critical_depth <= 1
assert 0 <= entanglement_ratio <= 1
assert 0 <= parallelism <= 1
assert 0 <= liveness <= 1
return SupermarqFeatures(
program_communication,
critical_depth,
entanglement_ratio,
parallelism,
liveness,
)
def get_module_for_benchmark(benchmark_name: str) -> ModuleType:
"""Returns the module for a specific benchmark."""
if benchmark_name in ["portfolioqaoa", "portfoliovqe", "pricingcall", "pricingput"]:
return import_module("mqt.bench.benchmarks.qiskit_application_finance." + benchmark_name)
if benchmark_name == "groundstate":
return import_module("mqt.bench.benchmarks.qiskit_application_nature.groundstate")
if benchmark_name == "routing":
return import_module("mqt.bench.benchmarks.qiskit_application_optimization.routing")
if benchmark_name == "tsp":
return import_module("mqt.bench.benchmarks.qiskit_application_optimization.tsp")
return import_module("mqt.bench.benchmarks." + benchmark_name)