From 466138324a9b607bb69d375d2150dcf9ea776b89 Mon Sep 17 00:00:00 2001 From: donghufeng Date: Mon, 2 Dec 2024 17:34:30 +0800 Subject: [PATCH] fix precommit --- .../search/quantum_evolution_search.py | 21 ++- .../quantum_rl/search/quantum_train_search.py | 2 +- .../quantum_rl/validation/quantum_train.py | 27 ++-- examples/quantum_rl/visualization/plot_gif.py | 22 ++- quafu/algorithms/ansatz.py | 2 - quafu/algorithms/estimator.py | 84 +++++----- quafu/algorithms/gradients/gradiant.py | 45 ++---- quafu/algorithms/gradients/param_shift.py | 3 +- quafu/algorithms/gradients/vjp.py | 6 +- quafu/algorithms/templates/amplitude.py | 4 +- quafu/algorithms/templates/basic_entangle.py | 8 +- quafu/backends/backends.py | 3 +- quafu/benchmark/adder.py | 14 +- quafu/benchmark/deutsch_jozsa.py | 2 - quafu/circuits/__init__.py | 2 + quafu/circuits/classical_register.py | 8 +- quafu/circuits/quantum_circuit.py | 153 ++++++------------ quafu/circuits/quantum_register.py | 6 +- quafu/dagcircuits/circuit_dag.py | 31 +--- quafu/dagcircuits/dag_circuit.py | 13 +- quafu/elements/unitary/decomposer.py | 13 +- quafu/exceptions/utils.py | 6 +- quafu/qfasm/qfasm_lexer.py | 2 +- quafu/qfasm/qfasm_parser.py | 135 ++++------------ quafu/results/results.py | 2 +- quafu/users/userapi.py | 2 +- setup.cfg | 7 +- 27 files changed, 221 insertions(+), 402 deletions(-) diff --git a/examples/quantum_rl/search/quantum_evolution_search.py b/examples/quantum_rl/search/quantum_evolution_search.py index b569f0d9..66bffe75 100644 --- a/examples/quantum_rl/search/quantum_evolution_search.py +++ b/examples/quantum_rl/search/quantum_evolution_search.py @@ -5,16 +5,16 @@ import sys sys.path.insert(0, " ") -import time -from functools import reduce +import time # noqa: E402 +from functools import reduce # noqa: E402 -import cirq -import numpy as np -from misc.utils import create_exp_dir -from pymoo.optimize import minimize -from pymop.problem import Problem -from search import nsganet as engine -from search import quantum_encoding, quantum_train_search +import cirq # noqa: E402 +import numpy as np # noqa: E402 +from misc.utils import create_exp_dir # noqa: E402 +from pymoo.optimize import minimize # noqa: E402 +from pymop.problem import Problem # noqa: E402 +from search import nsganet as engine # noqa: E402 +from search import quantum_encoding, quantum_train_search # noqa: E402 parser = argparse.ArgumentParser("Multi-objetive Genetic Algorithm for quantum NAS") parser.add_argument("--save", type=str, default="quantumGA", help="experiment name") @@ -176,7 +176,7 @@ def main(qubits, n_actions, observables): # configure the nsga-net method method = engine.nsganet(pop_size=args.pop_size, n_offsprings=args.n_offspring, eliminate_duplicates=True) - return minimize( + return minimize( problem, method, callback=do_every_generations, @@ -184,7 +184,6 @@ def main(qubits, n_actions, observables): ) - if __name__ == "__main__": n_qubits = 4 # Dimension of the state vectors in CartPole n_actions = 2 # Number of actions in CartPole diff --git a/examples/quantum_rl/search/quantum_train_search.py b/examples/quantum_rl/search/quantum_train_search.py index 6ab02839..65bbff3f 100644 --- a/examples/quantum_rl/search/quantum_train_search.py +++ b/examples/quantum_rl/search/quantum_train_search.py @@ -5,7 +5,7 @@ import numpy as np import tensorflow as tf from misc.utils import compute_returns, create_exp_dir, gather_episodes -from models.quantum_models import generate_model_policy as Network +from models.quantum_models import generate_model_policy as Network # noqa: N812 from search import quantum_encoding diff --git a/examples/quantum_rl/validation/quantum_train.py b/examples/quantum_rl/validation/quantum_train.py index b266f36a..c58ba1de 100644 --- a/examples/quantum_rl/validation/quantum_train.py +++ b/examples/quantum_rl/validation/quantum_train.py @@ -5,16 +5,14 @@ import sys sys.path.insert(0, " ") -import time -from functools import reduce +import time # noqa: E402 +from functools import reduce # noqa: E402 -import cirq -import gym -import models.quantum_genotypes as genotypes -import numpy as np -import tensorflow as tf -from misc.utils import compute_returns, create_exp_dir, gather_episodes -from models.quantum_models import generate_model_policy as Network +import cirq # noqa: E402 +import numpy as np # noqa: E402 +import tensorflow as tf # noqa: E402 +from misc.utils import compute_returns, create_exp_dir, gather_episodes # noqa: E402 +from models.quantum_models import generate_model_policy as Network # noqa: E402,N812 parser = argparse.ArgumentParser("Quantum RL Training") parser.add_argument("--save", type=str, default="qEXP-quafu18_6", help="experiment name") @@ -82,16 +80,10 @@ def main(qubits, genotype, observables): # Assign the model parameters to each optimizer w_in, w_var, w_out = 1, 0, 2 - # best_reward = 0 for epoch in range(n_epochs): logging.info("epoch %d", epoch) - reward_his = train(model, optimizer_in, optimizer_var, optimizer_out, w_in, w_var, w_out) - # valid_reward = infer(model) - - # if np.mean(valid_reward) >= best_reward: - # model.save_weights(os.path.join(args.save, 'weights_id97_quafu.h5')) - # best_reward = np.mean(valid_reward) + train(model, optimizer_in, optimizer_var, optimizer_out, w_in, w_var, w_out) # Training @@ -170,9 +162,10 @@ def reinforce_update(states, actions, returns, logits2, model): break return episode_reward_history + if __name__ == "__main__": qubits = cirq.GridQubit.rect(1, args.n_qubits) - genotype = eval("genotypes.%s" % args.arch) + genotype = eval("genotypes.%s" % args.arch) # noqa:SCS101 ops = [cirq.Z(q) for q in qubits] observables = [reduce((lambda x, y: x * y), ops)] # Z_0*Z_1*Z_2*Z_3 diff --git a/examples/quantum_rl/visualization/plot_gif.py b/examples/quantum_rl/visualization/plot_gif.py index ff3c0264..9320f648 100644 --- a/examples/quantum_rl/visualization/plot_gif.py +++ b/examples/quantum_rl/visualization/plot_gif.py @@ -3,18 +3,16 @@ import sys sys.path.insert(0, " ") -from functools import reduce +from functools import reduce # noqa: E402 -import cirq -import gym -import models.quantum_genotypes as genotypes -import numpy as np -import tensorflow as tf -from misc.utils import get_obs_policy, get_quafu_exp -from models.quantum_models import generate_circuit -from models.quantum_models import generate_model_policy as Network -from models.quantum_models import get_model_circuit_params -from PIL import Image +import cirq # noqa: E402 +import gym # noqa: E402 +import numpy as np # noqa: E402 +from misc.utils import get_obs_policy, get_quafu_exp # noqa: E402 +from models.quantum_models import generate_circuit # noqa: E402 +from models.quantum_models import generate_model_policy as Network # noqa:N812,E402 +from models.quantum_models import get_model_circuit_params # noqa: E402 +from PIL import Image # noqa: E402 parser = argparse.ArgumentParser("Plot gif of pre-trained quantum models on quafu cloud platform") parser.add_argument("--env_name", type=str, default="CartPole-v1", help="environment name") @@ -40,7 +38,7 @@ if __name__ == "__main__": qubits = cirq.GridQubit.rect(1, args.n_qubits) - genotype = eval("genotypes.%s" % args.arch) + genotype = eval("genotypes.%s" % args.arch) # noqa:SCS101 ops = [cirq.Z(q) for q in qubits] observables = [reduce((lambda x, y: x * y), ops)] # Z_0*Z_1*Z_2*Z_3 model = Network(qubits, genotype, args.n_actions, args.beta, observables, args.env_name) diff --git a/quafu/algorithms/ansatz.py b/quafu/algorithms/ansatz.py index d214288c..fdaabbe5 100644 --- a/quafu/algorithms/ansatz.py +++ b/quafu/algorithms/ansatz.py @@ -46,8 +46,6 @@ class QAOAAnsatz(Ansatz): def __init__(self, hamiltonian: Hamiltonian, num_qubits: int, num_layers: int = 1): """Instantiate a QAOAAnsatz""" - # self._pauli_list = hamiltonian.pauli_list - # self._coeffs = hamiltonian.coeffs self._h = hamiltonian self._num_layers = num_layers self._evol = ProductFormula() diff --git a/quafu/algorithms/estimator.py b/quafu/algorithms/estimator.py index 9ec9df82..cc10a4f8 100644 --- a/quafu/algorithms/estimator.py +++ b/quafu/algorithms/estimator.py @@ -95,45 +95,44 @@ def _run_real_machine(self, observables: Hamiltonian, cache_key: Optional[str] = res = self._measure_obs(self._circ) return res, [] + for obs in obslist: + for p in obs[1]: + if p not in measures: + raise CircuitError("Qubit %d in observer %s is not measured." % (p, obs[0])) + + measure_basis, targlist = merge_measure(obslist) + print("Job start, need measured in ", measure_basis) + + exec_res = [] + if cache_key is not None and cache_key in self._exp_cache: + # try to retrieve exe results from cache + exec_res = self._exp_cache[cache_key] else: - for obs in obslist: - for p in obs[1]: - if p not in measures: - raise CircuitError("Qubit %d in observer %s is not measured." % (p, obs[0])) - - measure_basis, targlist = merge_measure(obslist) - print("Job start, need measured in ", measure_basis) - - exec_res = [] - if cache_key is not None and cache_key in self._exp_cache: - # try to retrieve exe results from cache - exec_res = self._exp_cache[cache_key] - else: - # send tasks to cloud platform - lst_task_id = [] - for measure_base in measure_basis: - res = self._measure_obs(self._circ, measure_base=measure_base) - self._circ.gates = copy.deepcopy(inputs) - lst_task_id.append(res.taskid) - - for tid in lst_task_id: - # retrieve task results - while True: - res = self._task.retrieve(tid) - if res.task_status == "Completed": - exec_res.append(res) - break - time.sleep(0.2) - - if cache_key is not None: - # put into cache - self._exp_cache[cache_key] = exec_res - - measure_results = [] - for obi in range(len(obslist)): - obs = obslist[obi] - rpos = [measures.index(p) for p in obs[1]] - measure_results.append(exec_res[targlist[obi]].calculate_obs(rpos)) + # send tasks to cloud platform + lst_task_id = [] + for measure_base in measure_basis: + res = self._measure_obs(self._circ, measure_base=measure_base) + self._circ.gates = copy.deepcopy(inputs) + lst_task_id.append(res.taskid) + + for tid in lst_task_id: + # retrieve task results + while True: + res = self._task.retrieve(tid) + if res.task_status == "Completed": + exec_res.append(res) + break + time.sleep(0.2) + + if cache_key is not None: + # put into cache + self._exp_cache[cache_key] = exec_res + + measure_results = [] + for obi in range(len(obslist)): + obs = obslist[obi] + rpos = [measures.index(p) for p in obs[1]] + measure_results.append(exec_res[targlist[obi]].calculate_obs(rpos)) return sum(measure_results) @@ -188,14 +187,9 @@ def run( Returns: Expectation value """ - res = None if params is not None: self._circ._update_params(params) if self._backend == "sim": - res = self._run_simulation(observables) - else: - # currently cache only work for real machine (cloud systems) - res = self._run_real_machine(observables, cache_key=cache_key) - - return res + return self._run_simulation(observables) + return self._run_real_machine(observables, cache_key=cache_key) diff --git a/quafu/algorithms/gradients/gradiant.py b/quafu/algorithms/gradients/gradiant.py index 6ba573a9..e3af29cc 100644 --- a/quafu/algorithms/gradients/gradiant.py +++ b/quafu/algorithms/gradients/gradiant.py @@ -43,9 +43,7 @@ def grad_para_shift(qc: QuantumCircuit, hamiltonian, backend=SVSimulator()): for i, op in enumerate(qc.gates): if len(op.paras) > 0: - if isinstance(op.paras[0], Parameter) or isinstance( - op.paras[0], ParameterExpression - ): + if isinstance(op.paras[0], Parameter) or isinstance(op.paras[0], ParameterExpression): if op.name not in ["RX", "RY", "RZ"]: raise CircuitError( "It seems the circuit can not apply parameter-shift rule to calculate gradient." @@ -90,7 +88,7 @@ def grad_gate(op): circ << QuantumGate("projCtrl", op.ctrls, [], proj_mat) return circ.wrap() - elif op._targ_name == "RY": + if op._targ_name == "RY": circ = QuantumCircuit(max(op.pos) + 1) deriv_mat = -0.5j * YMatrix @ op._get_targ_matrix() circ << QuantumGate("dRY", op.targs, [], deriv_mat) @@ -100,7 +98,7 @@ def grad_gate(op): circ << QuantumGate("projCtrl", op.ctrls, [], proj_mat) return circ.wrap() - elif op._targ_name == "RZ": + if op._targ_name == "RZ": circ = QuantumCircuit(max(op.pos) + 1) deriv_mat = -0.5j * ZMatrix @ op._get_targ_matrix() circ << QuantumGate("dRZ", op.targs, [], deriv_mat) @@ -109,21 +107,18 @@ def grad_gate(op): proj_mat[cdim - 1, cdim - 1] = 1.0 circ << QuantumGate("projCtrl", op.ctrls, [], proj_mat) return circ.wrap() - else: - raise NotImplementedError - - else: - if op.name == "RX": - deriv_mat = -0.5j * XMatrix @ op.matrix - return QuantumGate("dRX", op.pos, [], deriv_mat) - elif op.name == "RY": - deriv_mat = -0.5j * YMatrix @ op.matrix - return QuantumGate("dRY", op.pos, [], deriv_mat) - elif op.name == "RZ": - deriv_mat = -0.5j * ZMatrix @ op.matrix - return QuantumGate("dRZ", op.pos, [], deriv_mat) - else: - raise NotImplementedError + raise NotImplementedError + + if op.name == "RX": + deriv_mat = -0.5j * XMatrix @ op.matrix + return QuantumGate("dRX", op.pos, [], deriv_mat) + if op.name == "RY": + deriv_mat = -0.5j * YMatrix @ op.matrix + return QuantumGate("dRY", op.pos, [], deriv_mat) + if op.name == "RZ": + deriv_mat = -0.5j * ZMatrix @ op.matrix + return QuantumGate("dRZ", op.pos, [], deriv_mat) + raise NotImplementedError def grad_adjoint(qc, hamiltonian, psi_in=np.array([], dtype=complex)): @@ -139,20 +134,14 @@ def grad_adjoint(qc, hamiltonian, psi_in=np.array([], dtype=complex)): end = len(qc.gates) gate_grads = [[] for _ in range(end)] for i, op in enumerate(qc.gates): - if len(op.paras) > 0 and ( - isinstance(op.paras[0], Parameter) - or isinstance(op.paras[0], ParameterExpression) - ): + if len(op.paras) > 0 and (isinstance(op.paras[0], Parameter) or isinstance(op.paras[0], ParameterExpression)): begin = i break for i in range(begin, end)[::-1]: op = qc.gates[i] phi = backend._apply_op(op.dagger(), phi) - if len(op.paras) > 0 and ( - isinstance(op.paras[0], Parameter) - or isinstance(op.paras[0], ParameterExpression) - ): + if len(op.paras) > 0 and (isinstance(op.paras[0], Parameter) or isinstance(op.paras[0], ParameterExpression)): mu = np.copy(phi) mu = backend._apply_op(grad_gate(op), mu) gate_grads[i].append(np.real(2.0 * np.inner(lam.conj(), mu))) diff --git a/quafu/algorithms/gradients/param_shift.py b/quafu/algorithms/gradients/param_shift.py index 00d6463c..e44e2848 100644 --- a/quafu/algorithms/gradients/param_shift.py +++ b/quafu/algorithms/gradients/param_shift.py @@ -68,8 +68,7 @@ def grad(self, obs: Hamiltonian, params: List[float], cache_key: Optional[str] = res[i] = self._est.run(obs, shifted_params, cache_key=final_cache_key) num_shift_params = len(res) - grads = (res[: num_shift_params // 2] - res[num_shift_params // 2 :]) / 2 - return grads + return (res[: num_shift_params // 2] - res[num_shift_params // 2 :]) / 2 def new_grad(self, obs: Hamiltonian, params: List[float]): """Calculate the gradients of given the circuit based on the parameter shift rule diff --git a/quafu/algorithms/gradients/vjp.py b/quafu/algorithms/gradients/vjp.py index e8b2d0ee..b60744da 100644 --- a/quafu/algorithms/gradients/vjp.py +++ b/quafu/algorithms/gradients/vjp.py @@ -116,9 +116,9 @@ def compute_vjp(jac: np.ndarray, dy: np.ndarray): .. math:: \begin{bmatrix} - \frac{\partial y_1}{\partial x_1} & \cdots & \frac{\partial y_1}{x_n} \\ - \vdots & \ddots & \vdots \\ - \frac{\partial y_m}{\partial x_1} & \cdots & \frac{\partial y_m}{x_n} + \frac{\partial y_1}{\partial x_1} & \cdots & \frac{\partial y_1}{x_n} \\ + \vdots & \ddots & \vdots \\ + \frac{\partial y_m}{\partial x_1} & \cdots & \frac{\partial y_m}{x_n} \end{bmatrix} `dy` is actually the vjp of dependent node diff --git a/quafu/algorithms/templates/amplitude.py b/quafu/algorithms/templates/amplitude.py index a02cbd2a..b0639c60 100644 --- a/quafu/algorithms/templates/amplitude.py +++ b/quafu/algorithms/templates/amplitude.py @@ -17,8 +17,6 @@ import quafu.elements.element_gates as qeg from quafu.elements import QuantumGate -# from .basic_entangle import BasicEntangleLayers - class AmplitudeEmbedding: def __init__(self, state, num_qubits, pad_with=None, normalize=False): @@ -62,7 +60,7 @@ def __radd__(self, other): def _preprocess(self, state, num_qubits, pad_with, normalize): batched = np.ndim(state) > 1 - ##TODO(qtzhuang): If state are batched, additional processing is required + # TODO(qtzhuang): If state are batched, additional processing is required if batched: raise ValueError("Currently not support batched state.") state_batch = state if batched else [state] diff --git a/quafu/algorithms/templates/basic_entangle.py b/quafu/algorithms/templates/basic_entangle.py index c6876773..a5424f9f 100644 --- a/quafu/algorithms/templates/basic_entangle.py +++ b/quafu/algorithms/templates/basic_entangle.py @@ -12,7 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Layers consisting of one-parameter single-qubit rotations on each qubit, followed by a closed chain or ring of CNOT gates.""" +""" +Layers consisting of one-parameter single-qubit rotations on each qubit, +followed by a closed chain or ring of CNOT gates. +""" + import numpy as np import quafu.elements.element_gates as qeg from quafu.elements import QuantumGate @@ -35,7 +39,7 @@ def __init__(self, weights=None, num_qubits=None, repeat=None, rotation="X"): if weights is not None: weights = np.asarray(weights) shape = np.shape(weights) - #TODO(): If weights are batched, i.e. dim>3, additional processing is required + # TODO(): If weights are batched, i.e. dim>3, additional processing is required if weights.ndim > 2: raise ValueError("Weights tensor must be 2-dimensional ") diff --git a/quafu/backends/backends.py b/quafu/backends/backends.py index 7bae7054..fecf3f23 100644 --- a/quafu/backends/backends.py +++ b/quafu/backends/backends.py @@ -46,7 +46,7 @@ def get_chip_info(self, user: User = None): qubits_list.append(qubit[1]) qubits_list = list(set(qubits_list)) qubits_list = sorted(qubits_list, key=lambda x: int(re.findall(r"\d+", x)[0])) - int_to_qubit = {k: v for k, v in enumerate(qubits_list)} + int_to_qubit = dict(enumerate(qubits_list)) qubit_to_int = {v: k for k, v in enumerate(qubits_list)} directed_weighted_edges = [] @@ -94,7 +94,6 @@ def get_chip_info(self, user: User = None): nx.draw_networkx_edges(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) fig.set_figwidth(14) diff --git a/quafu/benchmark/adder.py b/quafu/benchmark/adder.py index 088bfdae..1b49a4b9 100644 --- a/quafu/benchmark/adder.py +++ b/quafu/benchmark/adder.py @@ -60,14 +60,13 @@ def qreg(_i, name): """ if name == "cin": return _i - elif name == "a": + if name == "a": return _i + 1 - elif name == "b": + if name == "b": return _i + 5 - elif name == "cout": + if name == "cout": return _i + 9 - else: - raise ValueError("Unknown qreg name: {}".format(name)) + raise ValueError("Unknown qreg name: {}".format(name)) def creg(_i, name): @@ -76,8 +75,7 @@ def creg(_i, name): """ if name == "ans": return _i - else: - raise ValueError("Unknown creg name: {}".format(name)) + raise ValueError("Unknown creg name: {}".format(name)) """ @@ -118,8 +116,6 @@ def creg(_i, name): 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" diff --git a/quafu/benchmark/deutsch_jozsa.py b/quafu/benchmark/deutsch_jozsa.py index d062d43b..83dd8198 100644 --- a/quafu/benchmark/deutsch_jozsa.py +++ b/quafu/benchmark/deutsch_jozsa.py @@ -14,10 +14,8 @@ import random -import matplotlib.pyplot as plt import numpy as np from quafu.circuits.quantum_circuit import QuantumCircuit -from quafu.visualisation.circuitPlot import CircuitPlotManager def get_const_oracle(qc: QuantumCircuit): diff --git a/quafu/circuits/__init__.py b/quafu/circuits/__init__.py index 27b4a86c..e0cac103 100644 --- a/quafu/circuits/__init__.py +++ b/quafu/circuits/__init__.py @@ -17,3 +17,5 @@ from .classical_register import ClassicalRegister from .quantum_circuit import QuantumCircuit from .quantum_register import QuantumRegister + +__all__ = ["QuantumCircuit", "QuantumRegister", "ClassicalRegister"] diff --git a/quafu/circuits/classical_register.py b/quafu/circuits/classical_register.py index d5741d88..6b9cf0a7 100644 --- a/quafu/circuits/classical_register.py +++ b/quafu/circuits/classical_register.py @@ -22,15 +22,14 @@ class ClassicalRegister: def __init__(self, num: int = 0, name: str = None): self.name = name self.num = num - self.cbits = {i: 0 for i in range(num)} + self.cbits = dict.fromkeys(range(num), 0) self.pos_start = 0 def __getitem__(self, item): """Get mapped global pos""" if item < self.num: return self.pos_start + item - else: - raise IndexError("Index out of range:", item) + raise IndexError("Index out of range:", item) def __iter__(self): self._i = 0 @@ -41,8 +40,7 @@ def __next__(self): x = self._i self._i += 1 return self.__getitem__(x) - else: - raise StopIteration + raise StopIteration def __len__(self): return self.num diff --git a/quafu/circuits/quantum_circuit.py b/quafu/circuits/quantum_circuit.py index 2442ac9c..c8e3a329 100644 --- a/quafu/circuits/quantum_circuit.py +++ b/quafu/circuits/quantum_circuit.py @@ -28,15 +28,12 @@ CircuitWrapper, ControlledCircuitWrapper, ControlledGate, - ControlledOracle, Delay, KrausChannel, - OracleGate, QuantumGate, QuantumPulse, XYResonance, ) -from ..elements.quantum_gate import CircuitWrapper, ControlledCircuitWrapper from ..exceptions import CircuitError from .classical_register import ClassicalRegister from .quantum_register import QuantumRegister @@ -123,9 +120,7 @@ def gates(self, gates: list): self._gates = gates def __lshift__(self, operation: Instruction): - max_pos = ( - max(operation.pos) if isinstance(operation.pos, Iterable) else operation.pos - ) + max_pos = max(operation.pos) if isinstance(operation.pos, Iterable) else operation.pos if max_pos >= self.num: raise CircuitError("Operation act on qubit that not allocated") self.add_ins(operation) @@ -199,12 +194,8 @@ def add_noise(self, channel: str, channel_args, qubits=[], gates=[]): if add_q and add_g: for q in op.pos: if q in qubits: - newinstructions.append( - Instruction.ins_classes[channel](q, *channel_args) - ) - newgates.append( - Instruction.ins_classes[channel](q, *channel_args) - ) + newinstructions.append(Instruction.ins_classes[channel](q, *channel_args)) + newgates.append(Instruction.ins_classes[channel](q, *channel_args)) self.instructions = newinstructions self._gates = newgates return self @@ -221,9 +212,7 @@ def noised(self): def get_parameter_grads(self): if self._has_wrap: - print( - "warning: The circuit has wrapped gates, it will unwarp automaticllay" - ) + print("warning: The circuit has wrapped gates, it will unwarp automaticllay") self.unwrap() self._parameter_grads = {} for i, op in enumerate(self.gates): @@ -238,13 +227,9 @@ def get_parameter_grads(self): para_grads = para.grad() for var in para._variables: if var not in self._parameter_grads.keys(): - self._parameter_grads[var] = [ - [(i, j), para_grads[para._variables[var]]] - ] + self._parameter_grads[var] = [[(i, j), para_grads[para._variables[var]]]] else: - self._parameter_grads[var].append( - [(i, j), para_grads[para._variables[var]]] - ) + self._parameter_grads[var].append([(i, j), para_grads[para._variables[var]]]) self._variables = list(self._parameter_grads.keys()) return self._parameter_grads @@ -276,9 +261,7 @@ def _update_params(self, values, order=[]): need pass the order to match untranspiled circuit's variable. """ if len(values) != len(self.variables): - raise CircuitError( - "The size of input values must be the same to the parameters" - ) + raise CircuitError("The size of input values must be the same to the parameters") for i in range(len(values)): val = values[order[i]] if order else values[i] self._variables[i].value = val @@ -293,9 +276,7 @@ def update_params(self, paras_list: List[Any]): CircuitError """ if len(paras_list) != len(self.parameterized_gates): - raise CircuitError( - "`params_list` must have the same size with parameterized gates" - ) + raise CircuitError("`params_list` must have the same size with parameterized gates") # TODO(): Support updating part of params of a single gate for gate, paras in zip(self.parameterized_gates, paras_list): @@ -306,9 +287,7 @@ def angles2parameters(self): for g in self.gates: if all(isinstance(x, float) for x in g.paras): for i in range(len(g.paras)): - g.paras[i] = Parameter( - f"{self._def_para_name}_{self._para_id}", value=g.paras[i] - ) + g.paras[i] = Parameter(f"{self._def_para_name}_{self._para_id}", value=g.paras[i]) self._para_id += 1 self.get_parameter_grads() @@ -359,7 +338,7 @@ def get_used_qubits(instructions): used_q.append(pos) elif isinstance(ins, Barrier): continue - elif isinstance(ins.pos, int): + if isinstance(ins.pos, int): if ins.pos not in used_q: used_q.append(ins.pos) elif isinstance(ins.pos, list): @@ -447,9 +426,7 @@ def draw_circuit(self, width: int = 4, return_str: bool = False): tq2 = reduce_map[max(gate.targs)] printlist[tq1 * 2, l] = "#" printlist[tq2 * 2, l] = "#" - if tq1 + tq2 in [ - reduce_map[ctrl] * 2 for ctrl in gate.ctrls - ]: + if tq1 + tq2 in [reduce_map[ctrl] * 2 for ctrl in gate.ctrls]: printlist[tq1 + tq2, l] = "*" + gate.symbol else: printlist[tq1 + tq2, l] = gate.symbol @@ -470,30 +447,21 @@ def draw_circuit(self, width: int = 4, return_str: bool = False): for j in range(2 * num - 1): if j % 2 == 0: linestr = ("q[%d]" % (reduce_map_inv[j // 2])).ljust(6) + "".join( - [ - printlist[j, l].center(int(printlist[-1, l]), "-") - for l in range(depth) - ] + [printlist[j, l].center(int(printlist[-1, l]), "-") for l in range(depth)] ) if reduce_map_inv[j // 2] in self.measures.keys(): linestr += " M->c[%d]" % self.measures[reduce_map_inv[j // 2]] circuitstr.append(linestr) else: circuitstr.append( - "".ljust(6) - + "".join( - [ - printlist[j, l].center(int(printlist[-1, l]), " ") - for l in range(depth) - ] - ) + "".ljust(6) + "".join([printlist[j, l].center(int(printlist[-1, l]), " ") for l in range(depth)]) ) circuitstr = "\n".join(circuitstr) if return_str: return circuitstr - else: - print(circuitstr) + print(circuitstr) + return # noqa:R502 def plot_circuit(self, *args, **kwargs): from quafu.visualisation.circuitPlot import CircuitPlotManager @@ -519,9 +487,7 @@ def to_openqasm(self, with_para=False) -> str: openqasm text. """ - valid_gates = list( - QuantumGate.gate_classes.keys() - ) # TODO:include instruction futher + valid_gates = list(QuantumGate.gate_classes.keys()) # TODO:include instruction futher valid_gates.extend(["barrier", "delay", "reset"]) qasm = 'OPENQASM 2.0;\ninclude "qelib1.inc";\n' @@ -554,8 +520,7 @@ def wrap_to_gate(self, name: str): # TODO: check validity of instructions gate_structure = [deepcopy(ins) for ins in self.instructions] - customized = customize_gate(name, gate_structure, self.num) - return customized + return customize_gate(name, gate_structure, self.num) def _reallocate(self, num, qbits: List[int]): """Remap the qubits and gates to new positions.""" @@ -577,9 +542,7 @@ def _reallocate(self, num, qbits: List[int]): for i in range(len(op.targs)): op.targs[i] = qbits_map[op.targs[i]] - def add_controls( - self, ctrlnum, ctrls: List[int] = [], targs: List[int] = [], inplace=False - ) -> "QuantumCircuit": + def add_controls(self, ctrlnum, ctrls: List[int] = [], targs: List[int] = [], inplace=False) -> "QuantumCircuit": num = 0 instrs = [] if len(ctrls + targs) == 0: @@ -589,27 +552,25 @@ def add_controls( else: if len(ctrls) == 0 or len(targs) == 0: raise ValueError("Must provide both ctrls and targs") + assert len(targs) == self.num + assert len(ctrls) == ctrlnum + num = max(ctrls + targs) + 1 + if inplace: + self._reallocate(num, targs) else: - assert len(targs) == self.num - assert len(ctrls) == ctrlnum - num = max(ctrls + targs) + 1 - if inplace: - self._reallocate(num, targs) - else: - temp = copy.deepcopy(self) - temp._reallocate(num, targs) - instrs = temp.instructions + temp = copy.deepcopy(self) + temp._reallocate(num, targs) + instrs = temp.instructions if inplace: for op in self.instructions: if isinstance(op, QuantumGate): op = op.ctrl_by(ctrls) return self - else: - qc = QuantumCircuit(num) - for op in instrs: - if isinstance(op, QuantumGate): - qc << op.ctrl_by(ctrls) + qc = QuantumCircuit(num) + for op in instrs: + if isinstance(op, QuantumGate): + qc << op.ctrl_by(ctrls) return qc def join( @@ -659,13 +620,12 @@ def power(self, n, inplace=False): for _ in range(n - 1): self.instructions += self.instructions return self - else: - nq = QuantumCircuit(self.num) - for _ in range(n): - for op in self.instructions: - nq << op - nq.measures = self.measures - return nq + nq = QuantumCircuit(self.num) + for _ in range(n): + for op in self.instructions: + nq << op + nq.measures = self.measures + return nq def dagger(self, inplace=False): if inplace: @@ -674,15 +634,14 @@ def dagger(self, inplace=False): if isinstance(op, QuantumGate): op = op.dagger() return self - else: - nq = QuantumCircuit(self.num) - for op in self.instructions[::-1]: - if isinstance(op, QuantumGate): - nq << op.dagger() - else: - nq << op - nq.measures = self.measures - return nq + nq = QuantumCircuit(self.num) + for op in self.instructions[::-1]: + if isinstance(op, QuantumGate): + nq << op.dagger() + else: + nq << op + nq.measures = self.measures + return nq def wrap(self, qbits=[]): # TODO:use OracleGate @@ -697,15 +656,11 @@ def unwrap(self): circ = op.circuit.unwrap() for op_ in circ.instructions: instructions.append(op_) - if isinstance( - op_, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel) - ): + if isinstance(op_, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel)): gates.append(op_) else: instructions.append(op) - if isinstance( - op, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel) - ): + if isinstance(op, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel)): gates.append(op) self.instructions = instructions @@ -1156,7 +1111,9 @@ def reset(self, qlist: List[int] = None) -> "QuantumCircuit": Add reset for qubits in qlist. Args: - qlist (list[int]): A list contain the qubit need add reset. When qlist contain at least two qubit, the barrier will be added from minimum qubit to maximum qubit. For example: barrier([0, 2]) create barrier for qubits 0, 1, 2. To create discrete barrier, using barrier([0]), barrier([2]). + qlist (list[int]): A list contain the qubit need add reset. When qlist contain at least two qubit, + the barrier will be added from minimum qubit to maximum qubit. For example: barrier([0, 2]) + create barrier for qubits 0, 1, 2. To create discrete barrier, using barrier([0]), barrier([2]). Note: reset only support for simulator `qfvm_circ`. """ @@ -1189,9 +1146,7 @@ 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)) @@ -1244,13 +1199,9 @@ def cif(self, cbits: List[int], condition: int): instructions = [] for i in range(len(self.instructions) - 1, -1, -1): - if ( - isinstance(self.instructions[i], Cif) - and self.instructions[i].instructions is None - ): + if isinstance(self.instructions[i], Cif) and self.instructions[i].instructions is None: instructions.reverse() self.instructions[i].set_ins(instructions) self.instructions = self.instructions[0 : i + 1] return - else: - instructions.append(self.instructions[i]) + instructions.append(self.instructions[i]) diff --git a/quafu/circuits/quantum_register.py b/quafu/circuits/quantum_register.py index 25a392e9..2ffe2780 100644 --- a/quafu/circuits/quantum_register.py +++ b/quafu/circuits/quantum_register.py @@ -45,10 +45,10 @@ def used(self): def add_depth(self, num: int = 1): self._depth += num - def move_pos(self, new_pos): - old_pos = 0 + self.pos + def move_pos(self, new_pos) -> int: + old_pos = self.pos self.pos = new_pos - return old_pos + return old_pos # noqa:R504 class QuantumRegister: diff --git a/quafu/dagcircuits/circuit_dag.py b/quafu/dagcircuits/circuit_dag.py index 53d4573e..fd5a0db2 100755 --- a/quafu/dagcircuits/circuit_dag.py +++ b/quafu/dagcircuits/circuit_dag.py @@ -97,14 +97,10 @@ def gate_to_node(input_gate, specific_label): gate.duration = getattr(gate, "duration", None) or None gate.unit = getattr(gate, "unit", None) or None - if gate.paras and not isinstance( - gate.paras, list - ): # if paras is True and not a list, make it a list + if gate.paras and not isinstance(gate.paras, list): # if paras is True and not a list, make it a list gate.paras = [gate.paras] - return InstructionNode( - gate.name, gate.pos, gate.paras, gate.duration, gate.unit, label=specific_label - ) + return InstructionNode(gate.name, gate.pos, gate.paras, gate.duration, gate.unit, label=specific_label) # Building a DAG Graph using DAGCircuit from a QuantumCircuit @@ -165,9 +161,7 @@ def circuit_to_dag(circuit: QuantumCircuit, measure_flag=True): if measure_flag: # Add measure_gate node measure_pos = copy.deepcopy(circuit.measures) # circuit.measures is a dict - measure_gate = InstructionNode( - "measure", measure_pos, None, None, None, label="m" - ) + measure_gate = InstructionNode("measure", measure_pos, None, None, None, label="m") g.add_node(measure_gate, color="blue") # Add edges from qubit_last_use[qubit] to measure_gate for qubit in measure_gate.pos: @@ -388,11 +382,10 @@ def draw_dag(dep_g, output_format="png"): if output_format == "png": G.draw("dag.png") return Image(filename="dag.png") - elif output_format == "svg": + if output_format == "svg": G.draw("dag.svg") return SVG(filename="dag.svg") - else: - raise ValueError("Unsupported output format: choose either 'png' or 'svg'") + raise ValueError("Unsupported output format: choose either 'png' or 'svg'") def nodelist_to_dag(op_nodes: List[Any]) -> DAGCircuit: @@ -447,10 +440,7 @@ def nodelist_qubit_mapping_dict(nodes_list): mapping_pos = list(range(len(nodes_list_qubits_used))) # mapping, get a dict - return dict( - zip(sorted(list(nodes_list_qubits_used)), mapping_pos) - ) - + return dict(zip(sorted(nodes_list_qubits_used), mapping_pos)) def nodelist_qubit_mapping_dict_reverse(nodes_list): @@ -463,10 +453,7 @@ def nodelist_qubit_mapping_dict_reverse(nodes_list): """ nodes_qubit_mapping_dict = nodelist_qubit_mapping_dict(nodes_list) # reverse mapping, get a dict - return { - value: key for key, value in nodes_qubit_mapping_dict.items() - } - + return {value: key for key, value in nodes_qubit_mapping_dict.items()} # a function to map nodes_list @@ -489,9 +476,7 @@ def nodes_list_mapping(nodes_list, nodes_qubit_mapping_dict): node_new.pos = {} # the values of the dict are void, so we need to copy the values from the original dict for qubit in node.pos: - node_new.pos[nodes_qubit_mapping_dict[qubit]] = copy.deepcopy( - node.pos[qubit] - ) + node_new.pos[nodes_qubit_mapping_dict[qubit]] = copy.deepcopy(node.pos[qubit]) nodes_list_mapping.append(node_new) return nodes_list_mapping diff --git a/quafu/dagcircuits/dag_circuit.py b/quafu/dagcircuits/dag_circuit.py index fc0b9400..78f20c9c 100755 --- a/quafu/dagcircuits/dag_circuit.py +++ b/quafu/dagcircuits/dag_circuit.py @@ -88,7 +88,7 @@ def update_qubits_used(self): """ if -1 not in self.nodes: raise ValueError("-1 should be in DAGCircuit, please add it first") - self.qubits_used = set(int(edge[2]["label"][1:]) for edge in self.out_edges(-1, data=True)) + self.qubits_used = {int(edge[2]["label"][1:]) for edge in self.out_edges(-1, data=True)} return self.qubits_used def update_cbits_used(self): @@ -224,7 +224,6 @@ def node_qubits_inedges(self, node: InstructionNode): qubits_labels = [int(edge[2]["label"][1:]) for edge in self.in_edges(node, data=True)] return dict(zip(qubits_labels, inedges)) - def node_qubits_outedges(self, node: InstructionNode): """ node_qubits_outedges is a dict of {qubits -> outedges }of node @@ -237,7 +236,7 @@ def node_qubits_outedges(self, node: InstructionNode): raise ValueError("node should be in DAGCircuit") if node in [float("inf")]: raise ValueError('float("inf") has no successors') - outedges = [edge for edge in self.out_edges(node, data=True, keys=True)] # we can get u,v,k,d + outedges = list(self.out_edges(node, data=True, keys=True)) # we can get u,v,k,d qubits_labels = [int(edge[2]["label"][1:]) for edge in self.out_edges(node, data=True)] return dict(zip(qubits_labels, outedges)) @@ -322,11 +321,9 @@ def merge_dag(self, other_dag): self.add_nodes_from(other_dag.nodes(data=True)) self.add_edges_from(other_dag.edges(data=True)) - # remove the edges between -1 and float('inf') - # self.remove_edges_from([edge for edge in self.edges(keys=True) if edge[0] == -1 and edge[1] == float('inf')]) - # update qubits self.update_qubits_used() + return # noqa:502 def add_instruction_node( self, @@ -429,7 +426,7 @@ def substitute_node_with_dag(self, gate: InstructionNode, input_dag): raise ValueError("input_dag should be a DAGCircuit") if input_dag is None: self.remove_instruction_node(gate) - return + return # noqa:502 if self is None: return input_dag @@ -481,7 +478,7 @@ def substitute_node_with_dag(self, gate: InstructionNode, input_dag): # Add nodes and edges from input_dag to self self.add_nodes_from(input_dag.nodes(data=True)) self.add_edges_from(input_dag.edges(data=True)) - return + return # noqa:502 def is_dag(self) -> bool: """ diff --git a/quafu/elements/unitary/decomposer.py b/quafu/elements/unitary/decomposer.py index 67ecdd4d..6ea107f5 100644 --- a/quafu/elements/unitary/decomposer.py +++ b/quafu/elements/unitary/decomposer.py @@ -32,9 +32,7 @@ def __init__(self, array: ndarray, qubits, verbose: bool = False): self.qubits = qubits self.verbose = verbose - self.Mk_table = genMk_table( - self.qubit_num - ) # initialize the general M^k lookup table + self.Mk_table = genMk_table(self.qubit_num) # initialize the general M^k lookup table self.gate_list = [] def __call__(self, *args, **kwargs): @@ -65,16 +63,11 @@ def _decompose_matrix(self, _matrix, qubits): if mu.is_zero(U01) and mu.is_zero(U10): if mu.is_approx(U00, U11): if self.verbose: - print( - "Optimization: Unitaries are equal, " - "skip one step in the recursion for unitaries of size" - ) + print("Optimization: Unitaries are equal, " "skip one step in the recursion for unitaries of size") self._decompose_matrix(U00, qubits[1:]) else: if self.verbose: - print( - "Optimization: q2 is zero, only demultiplexing will be performed." - ) + print("Optimization: q2 is zero, only demultiplexing will be performed.") V, D, W = demultiplexing(U00, U11) self._decompose_matrix(W, qubits[1:]) self.multi_controlled_z(D, qubits[1:], qubits[0]) diff --git a/quafu/exceptions/utils.py b/quafu/exceptions/utils.py index cb244e0e..530206cd 100644 --- a/quafu/exceptions/utils.py +++ b/quafu/exceptions/utils.py @@ -20,11 +20,7 @@ def validate_server_resp(res): """Check results returned by backend service""" status_code = res["status"] if "status" in res else res["code"] - err_msg = ( - res["message"] - if "message" in res - else res["msg"] if "msg" in res else "No error message" - ) + err_msg = res["message"] if "message" in res else res["msg"] if "msg" in res else "No error message" if status_code in [201, 205, 400]: raise UserError(err_msg) diff --git a/quafu/qfasm/qfasm_lexer.py b/quafu/qfasm/qfasm_lexer.py index 008e3a7d..324ef577 100644 --- a/quafu/qfasm/qfasm_lexer.py +++ b/quafu/qfasm/qfasm_lexer.py @@ -205,7 +205,7 @@ def test_data(self, data): print(tok) def test_file(self): - print_file = open("lex.txt", "w+") + print_file = open("lex.txt", "w+") # noqa:SCS109 while True: tok = self.lexer.token() if not tok: diff --git a/quafu/qfasm/qfasm_parser.py b/quafu/qfasm/qfasm_parser.py index ac65638a..027e9254 100644 --- a/quafu/qfasm/qfasm_parser.py +++ b/quafu/qfasm/qfasm_parser.py @@ -35,7 +35,7 @@ GateInstruction, BinaryExpr, IfInstruction, - gate_classes + gate_classes, ) unaryop = { @@ -212,9 +212,7 @@ def handle_gateins(self, gateins: GateInstruction): gate_list.append(gate_classes["ry"](*[*oneargs, gateins.cargs[0]])) gate_list.append(gate_classes["rz"](*[*oneargs, gateins.cargs[1]])) elif gateins.name in self.mulctrl: - gate_list.append( - gate_classes[gateins.name](oneargs[:-1], oneargs[-1]) - ) + gate_list.append(gate_classes[gateins.name](oneargs[:-1], oneargs[-1])) else: # add carg to args if there is if gateins.cargs is not None and len(gateins.cargs) > 0: @@ -290,11 +288,7 @@ def handle_gateins(self, gateins: GateInstruction): def compute_exp(self, carg, cargdict: dict = {}): # recurse - if ( - isinstance(carg, int) - or isinstance(carg, float) - or isinstance(carg, ParameterExpression) - ): + if isinstance(carg, int) or isinstance(carg, float) or isinstance(carg, ParameterExpression): return carg # if it's id, should get real number from gateins if isinstance(carg, Id): @@ -449,9 +443,7 @@ def check_param(self, carg): if isinstance(carg, int) or isinstance(carg, float): return if isinstance(carg, Id) and carg.name not in self.params: - raise ParserError( - f"The parameter {carg.name} is undefined at line {carg.lineno} file {carg.filename}" - ) + raise ParserError(f"The parameter {carg.name} is undefined at line {carg.lineno} file {carg.filename}") if isinstance(carg, UnaryExpr): self.check_param(carg.children[0]) elif isinstance(carg, BinaryExpr): @@ -489,9 +481,7 @@ def check_gate_qargs(self, gateins: GateInstruction): if gatename != "barrier": # check gatename declared if gatename not in self.global_symtab: - raise ParserError( - f"The gate {gatename} is undefined at line {gateins.lineno} file {gateins.filename}" - ) + raise ParserError(f"The gate {gatename} is undefined at line {gateins.lineno} file {gateins.filename}") gatenode = self.global_symtab[gatename] if gatenode.type != "GATE": raise ParserError( @@ -514,9 +504,7 @@ def check_gate_qargs(self, gateins: GateInstruction): ) symnode = self.symtab[qarg.name] if symnode.type != "QARG": - raise ParserError( - f"{qarg.name} is not declared as a qubit at line {qarg.lineno} file {qarg.filename}" - ) + raise ParserError(f"{qarg.name} is not declared as a qubit at line {qarg.lineno} file {qarg.filename}") if len(qargs) != len(set(qargsname)): raise ParserError( f"A qubit used as different argument when call gate {gateins.name} " @@ -624,9 +612,7 @@ def p_statement_qop(self, p): | qif error """ if p[2] != ";": - raise ParserError( - f"Expecting ';' behind statement at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ';' behind statement at line {p[1].lineno} file {p[1].filename}") p[0] = p[1] def p_statement_empty(self, p): @@ -646,27 +632,21 @@ def p_statement_qif(self, p): """ # check primary is a creg and check range if len(p) == 7: - raise ParserError( - f"Illegal IF statement, Expecting ')' at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Illegal IF statement, Expecting ')' at line {p[1].lineno} file {p[1].filename}") if len(p) == 6: raise ParserError( "Illegal IF statement, Expecting INT: the Rvalue can " f"only be INT at line {p[1].lineno} file {p[1].filename}" ) if len(p) == 5: - raise ParserError( - f"Illegal IF statement, Expecting '==' at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Illegal IF statement, Expecting '==' at line {p[1].lineno} file {p[1].filename}") if len(p) == 4: raise ParserError( f"Illegal IF statement, Expecting Cbit: the Lvalue can only be cbit " f"at line {p[1].lineno} file {p[1].filename}" ) if len(p) == 3: - raise ParserError( - f"Illegal IF statement, Expecting '(' at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Illegal IF statement, Expecting '(' at line {p[1].lineno} file {p[1].filename}") cbit = p[3] if cbit.name not in self.global_symtab: @@ -677,31 +657,24 @@ def p_statement_qif(self, p): symnode = self.global_symtab[cbit.name] if symnode.type != "CREG": raise ParserError( - f"{cbit.name} is not declared as classical bit register at " - f"line {cbit.lineno} file {cbit.filename}" + f"{cbit.name} is not declared as classical bit register at " f"line {cbit.lineno} file {cbit.filename}" ) # check range if IndexedId if isinstance(cbit, IndexedId): if cbit.num >= symnode.num: - raise ParserError( - f"{cbit.name} out of range at line {cbit.lineno} file {cbit.filename}" - ) + raise ParserError(f"{cbit.name} out of range at line {cbit.lineno} file {cbit.filename}") # optimization: If the value that creg can represent is smaller than Rvalue, just throw it if p[5] > 2: p[0] = None else: - p[0] = IfInstruction( - node=p[1], cbits=p[3], value=p[5], instruction=p[7] - ) + p[0] = IfInstruction(node=p[1], cbits=p[3], value=p[5], instruction=p[7]) elif isinstance(cbit, Id): # optimization: If the value that creg can represent is smaller than Rvalue, just throw it num = symnode.num if pow(2, num) - 1 < p[5]: p[0] = None else: - p[0] = IfInstruction( - node=p[1], cbits=p[3], value=p[5], instruction=p[7] - ) + p[0] = IfInstruction(node=p[1], cbits=p[3], value=p[5], instruction=p[7]) self.executable_on_backend = False def p_unitaryop(self, p): @@ -731,9 +704,7 @@ def p_unitaryop_error(self, p): | id '(' expression_list error """ if len(p) == 4 or (len(p) == 5 and p[4] != ")"): - raise ParserError( - f"Expecting ')' after '(' at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ')' after '(' at line {p[1].lineno} file {p[1].filename}") raise ParserError( f"Expecting qubit list, received {p[len(p)-1].value} at line {p[1].lineno} file {p[1].filename}" ) @@ -759,9 +730,7 @@ def p_measure_error(self, p): f"Expecting qubit or qubit register after '->' at line {p[1].lineno} file {p[1].filename}" ) if len(p) == 4: - raise ParserError( - f"Expecting '->' for MEASURE at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting '->' for MEASURE at line {p[1].lineno} file {p[1].filename}") if len(p) == 3: raise ParserError( f"Expecting qubit or qubit register after 'measure' at line {p[1].lineno} file {p[1].filename}" @@ -780,9 +749,7 @@ def p_barrier_error(self, p): """ qop : BARRIER error """ - raise ParserError( - f"Expecting Qubit:BARRIER only opperate qubits at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting Qubit:BARRIER only opperate qubits at line {p[1].lineno} file {p[1].filename}") # reset def p_reset(self, p): @@ -797,9 +764,7 @@ def p_reset_error(self, p): """ qop : RESET error """ - raise ParserError( - f"Expecting Qubit: RESET only opperate qubit at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting Qubit: RESET only opperate qubit at line {p[1].lineno} file {p[1].filename}") # gate_qarg_list def p_gate_qarg_list_begin(self, p): @@ -931,9 +896,7 @@ def p_gate_body_emptybody(self, p): | '{' gate_scope error """ if p[3] != "}": - raise ParserError( - "Expecting '}' at the end of gate definition; received " + p[3].value - ) + raise ParserError("Expecting '}' at the end of gate definition; received " + p[3].value) p[0] = [] def p_gate_body(self, p): @@ -942,9 +905,7 @@ def p_gate_body(self, p): | '{' gop_list gate_scope error """ if p[4] != "}": - raise ParserError( - "Expecting '}' at the end of gate definition; received " + p[4].value - ) + raise ParserError("Expecting '}' at the end of gate definition; received " + p[4].value) p[0] = p[2] def p_gop_list_begin(self, p): @@ -972,17 +933,11 @@ def p_gop_nocargs(self, p): | id '(' error """ if len(p) == 4 and p[2] == "(": - raise ParserError( - f"Expecting ')' for gate {p[1].name} at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ')' for gate {p[1].name} at line {p[1].lineno} file {p[1].filename}") if len(p) == 4 and p[3] != ";": - raise ParserError( - f"Expecting ';' after gate {p[1].name} at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ';' after gate {p[1].name} at line {p[1].lineno} file {p[1].filename}") if len(p) == 6 and p[5] != ";": - raise ParserError( - f"Expecting ';' after gate {p[1].name} at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ';' after gate {p[1].name} at line {p[1].lineno} file {p[1].filename}") if len(p) == 5: raise ParserError( f"Expecting ID: Invalid qubit list for gate {p[1].name} at line {p[1].lineno} file {p[1].filename}" @@ -1000,17 +955,11 @@ def p_gop_cargs(self, p): | id '(' expression_list error """ if len(p) == 7 and p[6] != ";": - raise ParserError( - f"Expecting ';' after gate {p[1].name} at line {p[1].lineno}" - ) + raise ParserError(f"Expecting ';' after gate {p[1].name} at line {p[1].lineno}") if len(p) == 6: - raise ParserError( - f"Expecting qubit id after gate {p[1].name} at line {p[1].lineno}" - ) + raise ParserError(f"Expecting qubit id after gate {p[1].name} at line {p[1].lineno}") if len(p) == 5: - raise ParserError( - f"Expecting ')' after gate {p[1].name} at line {p[1].lineno}" - ) + raise ParserError(f"Expecting ')' after gate {p[1].name} at line {p[1].lineno}") p[0] = GateInstruction(node=p[1], qargs=p[5], cargs=p[3]) # check qubit self.check_gate_qargs(p[0]) @@ -1029,9 +978,7 @@ def p_gop_barrier(self, p): f"definition, at line {p[1].lineno} file {p[1].filename}" ) if len(p) == 4 and p[3] != ";": - raise ParserError( - f"Expecting ';' after barrier at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting ';' after barrier at line {p[1].lineno} file {p[1].filename}") p[0] = GateInstruction(node=p[1], qargs=p[2], cargs=[]) self.check_gate_qargs(p[0]) @@ -1049,9 +996,7 @@ def p_statement_bitdecl(self, p): if len(p) == 2: raise ParserError("Expecting valid statement") if p[2] != ";": - raise ParserError( - f"Expecting ';' in qreg or creg declaration at line {p.lineno(2)}" - ) + raise ParserError(f"Expecting ';' in qreg or creg declaration at line {p.lineno(2)}") p[0] = p[1] def p_statement_defparam(self, p): @@ -1061,9 +1006,7 @@ def p_statement_defparam(self, p): | id EQUAL error """ if not isinstance(p[3], int) and not isinstance(p[3], float): - raise ParserError( - f"Expecting 'INT' or 'FLOAT behind '=' at line {p[1].lineno} file {p[1].filename}" - ) + raise ParserError(f"Expecting 'INT' or 'FLOAT behind '=' at line {p[1].lineno} file {p[1].filename}") param_name = p[1].name if param_name in self.params: raise ParserError( @@ -1082,9 +1025,7 @@ def p_qdecl(self, p): f"Expecting ID[int] after QREG at line {p[1].lineno} file {p[1].filename}, received {p[2].value}" ) if p[2].num <= 0: - raise ParserError( - f"QREG size must be positive at line {p[2].lineno} file {p[2].filename}" - ) + raise ParserError(f"QREG size must be positive at line {p[2].lineno} file {p[2].filename}") newsymtabnode = SymtabNode("QREG", p[2], True, True) self.update_sym_tab(newsymtabnode) p[0] = None @@ -1099,9 +1040,7 @@ def p_cdecl(self, p): f"Expecting ID[int] after CREG at line {p[1].lineno} file {p[1].filename}, received {p[2].value}" ) if p[2].num <= 0: - raise ParserError( - f"CREG size must be positive at line {p[2].lineno} file {p[2].filename}" - ) + raise ParserError(f"CREG size must be positive at line {p[2].lineno} file {p[2].filename}") newsymtabnode = SymtabNode("CREG", p[2], True, False) self.update_sym_tab(newsymtabnode) p[0] = None @@ -1125,9 +1064,7 @@ def p_indexed_id(self, p): | id '[' error """ if len(p) == 4 or (len(p) == 5 and p[4] != "]"): - raise ParserError( - f"Expecting INT after [, received{str(p[len(p)-1].value)}" - ) + raise ParserError(f"Expecting INT after [, received{str(p[len(p)-1].value)}") if len(p) == 5 and p[4] == "]": p[0] = IndexedId(p[1], p[3]) @@ -1204,9 +1141,7 @@ def p_expr_binary(self, p): | expression '^' expression """ if p[2] == "/" and p[3] == 0: - raise ParserError( - f"Divided by 0 at line {self.lexer.lexer.lineno} file {self.lexer.lexer.filename}" - ) + raise ParserError(f"Divided by 0 at line {self.lexer.lexer.lineno} file {self.lexer.lexer.filename}") if isinstance(p[1], Node) or isinstance(p[3], Node): p[0] = BinaryExpr(p[2], p[1], p[3]) else: @@ -1290,9 +1225,7 @@ def p_error(self, p): # EOF case if p is None or self.lexer.lexer.token() is None: raise ParserError("Error at end of file") - print( - f"Error near line {self.lexer.lexer.lineno}, Column {self.cal_column(self.lexer.data, p)}" - ) + print(f"Error near line {self.lexer.lexer.lineno}, Column {self.cal_column(self.lexer.data, p)}") def cal_column(self, data: str, p): """Compute the column.""" diff --git a/quafu/results/results.py b/quafu/results/results.py index e0b03a9c..95d67c65 100644 --- a/quafu/results/results.py +++ b/quafu/results/results.py @@ -58,7 +58,7 @@ def __init__(self, input_dict): self.measures = self.transpiled_circuit.measures self.task_status = status_map[input_dict["status"]] - self.res = eval(input_dict["res"]) + self.res = eval(input_dict["res"]) # noqa:SCS101 self.counts = OrderedDict(sorted(self.res.items(), key=lambda s: s[0])) self.logicalq_res = {} diff --git a/quafu/users/userapi.py b/quafu/users/userapi.py index ef2564a5..d885a0b5 100644 --- a/quafu/users/userapi.py +++ b/quafu/users/userapi.py @@ -106,7 +106,7 @@ def save_apitoken(self, apitoken=None): if not os.path.exists(file_dir): os.mkdir(file_dir) - with open(file_path, "w") as f: + with open(file_path, "w") as f: # noqa:SCS109 json.dump(data, f) def _load_account(self): diff --git a/setup.cfg b/setup.cfg index 803f6ba9..a0a08d07 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,5 @@ [flake8] -# ignore doc related rule, should remove in the future: D100, D103, D415, D104, D101, D102, D200, D205, D403, D107, D105, D411, D405, D301, D202, D208, D209, D417, D300, D419, SCS108, D210, W191, E101 -ignore = E203, E741, E731, N803, N806, N802, W503, D212, D100, D103, D415, D104, D101, D102, D200, D205, D403, D107, D105, D411, D405, D301, D202, D208, D209, D417, D300, D419, SCS108, D210, W191, E101 +# ignore doc related rule, should remove in the future: D100, D103, D415, D104, D101, D102, D200, D205, D403, D107, D105, D411, D405, D301, D202, D208, D209, D417, D300, D419, SCS108, D210, W191, E101, C092, D206, D207 +ignore = E203, E741, E731, N803, N806, N802, W503, D212, D100, D103, D415, D104, D101, D102, D200, D205, D403, D107, D105, D411, D405, D301, D202, D208, D209, D417, D300, D419, SCS108, D210, W191, E101, C092, D206, D207 max-line-length = 120 -exclude = - doc +exclude = doc/run.py, doc/source/conf.py