Skip to content

Commit

Permalink
fix: code style
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhaoyilunnn committed Aug 17, 2023
1 parent 24998ec commit add2af6
Show file tree
Hide file tree
Showing 46 changed files with 1,309 additions and 892 deletions.
10 changes: 9 additions & 1 deletion src/quafu/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@
from .users.userapi import User
from .simulators.simulator import simulate

__all__ = ["QuantumCircuit", "ExecResult", "Task", "User", "SimuResult", "simulate", "get_version"]
__all__ = [
"QuantumCircuit",
"ExecResult",
"Task",
"User",
"SimuResult",
"simulate",
"get_version",
]


def get_version():
Expand Down
2 changes: 1 addition & 1 deletion src/quafu/algorithms/ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __init__(self, pauli: str, num_layers: int = 1):

def _build(self, pauli):
"""Construct circuit"""
gate_list = self._evol.evol(pauli, 0.)
gate_list = self._evol.evol(pauli, 0.0)
for g in gate_list:
self.add_gate(g)

Expand Down
53 changes: 34 additions & 19 deletions src/quafu/backends/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@

class Backend(object):
def __init__(self, backend_info: dict):
self.name = backend_info['system_name']
self._valid_gates = backend_info['valid_gates']
self.qubit_num = backend_info['qubits']
self.system_id = backend_info['system_id']
self.status = backend_info['status']
self.name = backend_info["system_name"]
self._valid_gates = backend_info["valid_gates"]
self.qubit_num = backend_info["qubits"]
self.system_id = backend_info["system_id"]
self.status = backend_info["status"]
self.qv = backend_info["QV"]
# self.task_in_queue = backend_info["task_in_queue"]

Expand All @@ -37,13 +37,12 @@ def get_chip_info(self, user: User = None):
api_token = user.api_token
data = {"system_name": self.name.lower()}
headers = {"api_token": api_token}
chip_info = requests.post(url=User.chip_api, data=data,
headers=headers)
chip_info = requests.post(url=User.chip_api, data=data, headers=headers)
chip_info = json.loads(chip_info.text)
json_topo_struct = chip_info["topological_structure"]
qubits_list = []
for gate in json_topo_struct.keys():
qubit = gate.split('_')
qubit = gate.split("_")
qubits_list.append(qubit[0])
qubits_list.append(qubit[1])
qubits_list = list(set(qubits_list))
Expand All @@ -56,14 +55,14 @@ def get_chip_info(self, user: User = None):
edges_dict = {}
clist = []
for gate, name_fidelity in json_topo_struct.items():
gate_qubit = gate.split('_')
gate_qubit = gate.split("_")
qubit1 = qubit_to_int[gate_qubit[0]]
qubit2 = qubit_to_int[gate_qubit[1]]
gate_name = list(name_fidelity.keys())[0]
fidelity = name_fidelity[gate_name]['fidelity']
fidelity = name_fidelity[gate_name]["fidelity"]
directed_weighted_edges.append([qubit1, qubit2, fidelity])
clist.append([qubit1, qubit2])
gate_reverse = gate.split('_')[1] + '_' + gate.split('_')[0]
gate_reverse = gate.split("_")[1] + "_" + gate.split("_")[0]
if gate not in edges_dict and gate_reverse not in edges_dict:
edges_dict[gate] = fidelity
else:
Expand All @@ -72,7 +71,7 @@ def get_chip_info(self, user: User = None):
edges_dict[gate] = fidelity

for gate, fidelity in edges_dict.items():
gate_qubit = gate.split('_')
gate_qubit = gate.split("_")
qubit1, qubit2 = qubit_to_int[gate_qubit[0]], qubit_to_int[gate_qubit[1]]
weighted_edges.append([qubit1, qubit2, np.round(fidelity, 3)])

Expand All @@ -85,26 +84,42 @@ def get_chip_info(self, user: User = None):

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] >= 0.9]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] < 0.9]
elarge_labels = {(u, v): "%.3f" % d["weight"] for (u, v, d) in G.edges(data=True) if d["weight"] >= 0.9}
esmall_labels = {(u, v): "%.3f" % d["weight"] for (u, v, d) in G.edges(data=True) if d["weight"] < 0.9}
elarge_labels = {
(u, v): "%.3f" % d["weight"]
for (u, v, d) in G.edges(data=True)
if d["weight"] >= 0.9
}
esmall_labels = {
(u, v): "%.3f" % d["weight"]
for (u, v, d) in G.edges(data=True)
if d["weight"] < 0.9
}

pos = nx.spring_layout(G, seed=1)
fig, ax = plt.subplots()
nx.draw_networkx_nodes(G, pos, node_size=400, ax=ax)

nx.draw_networkx_edges(G, pos, edgelist=elarge, width=2, ax=ax)
nx.draw_networkx_edges(
G, pos, edgelist=esmall, width=2, alpha=0.5, style="dashed"
, ax=ax)
G, pos, edgelist=esmall, width=2, alpha=0.5, style="dashed", ax=ax
)

nx.draw_networkx_labels(G, pos, font_size=14, font_family="sans-serif", ax=ax)
# edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, elarge_labels, font_size=12, font_color="green", ax=ax)
nx.draw_networkx_edge_labels(G, pos, esmall_labels, font_size=12, font_color="red", ax=ax)
nx.draw_networkx_edge_labels(
G, pos, elarge_labels, font_size=12, font_color="green", ax=ax
)
nx.draw_networkx_edge_labels(
G, pos, esmall_labels, font_size=12, font_color="red", ax=ax
)
fig.set_figwidth(14)
fig.set_figheight(14)
fig.tight_layout()
return {"mapping": int_to_qubit, "topology_diagram": fig, "full_info": chip_info}
return {
"mapping": int_to_qubit,
"topology_diagram": fig,
"full_info": chip_info,
}

def get_valid_gates(self):
return self._valid_gates
55 changes: 28 additions & 27 deletions src/quafu/benchmark/adder.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,36 +46,36 @@ def qreg(_i, name):
qreg b[4];
qreg cout[1];
"""
if name == 'cin':
if name == "cin":
return _i
elif name == 'a':
elif name == "a":
return _i + 1
elif name == 'b':
elif name == "b":
return _i + 5
elif name == 'cout':
elif name == "cout":
return _i + 9
else:
raise ValueError('Unknown qreg name: {}'.format(name))
raise ValueError("Unknown qreg name: {}".format(name))


def creg(_i, name):
"""
creg ans[5];
"""
if name == 'ans':
if name == "ans":
return _i
else:
raise ValueError('Unknown creg name: {}'.format(name))
raise ValueError("Unknown creg name: {}".format(name))


"""
// set input states
x a[0]; // a = 0001
x b; // b = 1111
"""
qc.x(qreg(0, 'a'))
qc.x(qreg(0, "a"))
for i in range(4):
qc.x(qreg(i, 'b'))
qc.x(qreg(i, "b"))

"""
// add a to b, storing result in b
Expand All @@ -89,14 +89,14 @@ def creg(_i, name):
unmaj a[0],b[1],a[1];
unmaj cin[0],b[0],a[0];
"""
majority(qreg(0, 'cin'), qreg(0, 'b'), qreg(0, 'a'))
majority(qreg(0, 'a'), qreg(1, 'b'), qreg(1, 'a'))
majority(qreg(0, "cin"), qreg(0, "b"), qreg(0, "a"))
majority(qreg(0, "a"), qreg(1, "b"), qreg(1, "a"))
for i in range(1, 4):
majority(qreg(i-1, 'a'), qreg(i, 'b'), qreg(i, 'a'))
qc.cnot(qreg(3, 'a'), qreg(0, 'cout'))
unmaj(qreg(2, 'a'), qreg(3, 'b'), qreg(3, 'a'))
unmaj(qreg(1, 'a'), qreg(2, 'b'), qreg(2, 'a'))
unmaj(qreg(0, 'a'), qreg(1, 'b'), qreg(1, 'a'))
majority(qreg(i - 1, "a"), qreg(i, "b"), qreg(i, "a"))
qc.cnot(qreg(3, "a"), qreg(0, "cout"))
unmaj(qreg(2, "a"), qreg(3, "b"), qreg(3, "a"))
unmaj(qreg(1, "a"), qreg(2, "b"), qreg(2, "a"))
unmaj(qreg(0, "a"), qreg(1, "b"), qreg(1, "a"))

"""
measure b[0] -> ans[0];
Expand All @@ -105,22 +105,23 @@ def creg(_i, name):
measure b[3] -> ans[3];
measure cout[0] -> ans[4];
"""
measure_pos = [qreg(i, 'b') for i in range(4)] + [qreg(0, 'cout')]
measure_cbits = [creg(i, 'ans') for i in range(5)]
measure_pos = [qreg(i, "b") for i in range(4)] + [qreg(0, "cout")]
measure_cbits = [creg(i, "ans") for i in range(5)]
qc.measure(measure_pos, cbits=measure_cbits)
# qc.draw_circuit()
# print(qc.to_openqasm())

init_labels = dict.fromkeys(range(n))
init_labels[0] = 'cin'
init_labels[0] = "cin"
for i in range(4):
init_labels[i+1] = f'a_{i}'
init_labels[i + 1] = f"a_{i}"
for i in range(5):
init_labels[i+5] = f'b_{i}'

end_labels = {i+5: f'ans_{i}' for i in range(5)}
qc.plot_circuit(title='Quantum ripple-carry adder',
init_labels=init_labels,
end_labels=end_labels,
)
init_labels[i + 5] = f"b_{i}"

end_labels = {i + 5: f"ans_{i}" for i in range(5)}
qc.plot_circuit(
title="Quantum ripple-carry adder",
init_labels=init_labels,
end_labels=end_labels,
)
plt.show()
20 changes: 10 additions & 10 deletions src/quafu/benchmark/deutsch_jozsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ def get_const_oracle(qc: QuantumCircuit):
output = np.random.randint(2)
if output == 1:
qc.x(n)
qc.name = 'Constant Oracle'
qc.name = "Constant Oracle"
return qc


def get_balanced_oracle(qc: QuantumCircuit):
n = qc.num - 1
b_str = ''.join([random.choice('01') for _ in range(n)])
b_str = "".join([random.choice("01") for _ in range(n)])

# Place X-qu_gate
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
if b_str[qubit] == "1":
qc.x(qubit)

# Use barrier as divider
Expand All @@ -35,10 +35,10 @@ def get_balanced_oracle(qc: QuantumCircuit):

# Place X-qu_gate
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
if b_str[qubit] == "1":
qc.x(qubit)

qc.name = 'Balanced Oracle'
qc.name = "Balanced Oracle"
return qc


Expand All @@ -52,12 +52,12 @@ def deutsch_jozsa(n: int, case: str):

# Add oracle
#################################################
if case == 'balanced':
if case == "balanced":
get_balanced_oracle(circuit)
elif case == 'constant':
elif case == "constant":
get_const_oracle(circuit)
else:
raise ValueError('undefined case: ' + case)
raise ValueError("undefined case: " + case)
#################################################

# Repeat H-qu_gate
Expand All @@ -71,5 +71,5 @@ def deutsch_jozsa(n: int, case: str):
return circuit


dj_qc = deutsch_jozsa(n=4, case='constant')
dj_qc.plot_circuit(title='Deutsch-Josza Circuit', show=True)
dj_qc = deutsch_jozsa(n=4, case="constant")
dj_qc.plot_circuit(title="Deutsch-Josza Circuit", show=True)
2 changes: 1 addition & 1 deletion src/quafu/benchmark/unitary_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

nqubit = 5
qubits = list(range(nqubit))
U0 = unitary_group.rvs(2 ** nqubit)
U0 = unitary_group.rvs(2**nqubit)

# Using QSD to decompose the unitary
qc = QuantumCircuit(nqubit)
Expand Down
10 changes: 6 additions & 4 deletions src/quafu/benchmark/variational/brickwall_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ def brickwall_layout_circuit(params, pbc=False):
def plot():
para = random.random((n_layers, qubit_num, 2))
qc = brickwall_layout_circuit(para)
qc.plot_circuit(title='Brickwall Layout for \nVariational Circuit',
show=True,
save=False,
)
qc.plot_circuit(
title="Brickwall Layout for \nVariational Circuit",
show=True,
save=False,
)


plot()
9 changes: 5 additions & 4 deletions src/quafu/benchmark/variational/ladder_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ def ladder_layout_circuit(params, pbc=False):
def plot():
para = random.random((n_layers, bit_num))
qc = ladder_layout_circuit(para)
qc.plot_circuit(title='Ladder Layout for \nVariational Circuit',
show=True,
save=False,
)
qc.plot_circuit(
title="Ladder Layout for \nVariational Circuit",
show=True,
save=False,
)
2 changes: 1 addition & 1 deletion src/quafu/benchmark/variational_n4.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,4 @@

qc.from_openqasm(qasm)
qc.draw_circuit()
qc.plot_circuit(show=True, title='Variational n4')
qc.plot_circuit(show=True, title="Variational n4")
15 changes: 12 additions & 3 deletions src/quafu/circuits/para_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@


class QAOACircuit(QuantumCircuit):
def __init__(self, logical_qubits, physical_qubits, nodes, edges, params, p, gate="CNOT"):
def __init__(
self, logical_qubits, physical_qubits, nodes, edges, params, p, gate="CNOT"
):
num = logical_qubits
self.logical_qubits = logical_qubits
self.physical_qubits = physical_qubits
Expand All @@ -19,8 +21,15 @@ def compile_to_IOP(self):
QASM from qcover directly
"""
qaoa_compiler = QcoverCompiler()
self.qasm = qaoa_compiler.graph_to_qasm(self.logical_qubits, self.physical_qubits, self.nodes, self.edges,
self.paras, self.p, gate=self.gate)
self.qasm = qaoa_compiler.graph_to_qasm(
self.logical_qubits,
self.physical_qubits,
self.nodes,
self.edges,
self.paras,
self.p,
gate=self.gate,
)

def upate_paras(self, paras):
self.paras = paras
Expand Down
4 changes: 3 additions & 1 deletion src/quafu/circuits/quantum_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,9 @@ def measure(self, pos: List[int] = None, cbits: List[int] = None) -> None:
if not len(set(cbits)) == len(cbits):
raise ValueError("Classical bits not uniquely assigned.")
if not len(cbits) == n_num:
raise ValueError("Number of measured bits should equal to the number of classical bits")
raise ValueError(
"Number of measured bits should equal to the number of classical bits"
)
else:
cbits = list(range(e_num, e_num + n_num))

Expand Down
Loading

0 comments on commit add2af6

Please sign in to comment.