From 1eee6660e2e3f57b0a216b70408c7ed430161fe3 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 13:38:41 -0700 Subject: [PATCH 01/13] add pyproject.toml --- LICENSE | 2 +- pyproject.toml | 35 +++++++++++++++++++++++++++++++++++ requirements.txt | 1 - 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 pyproject.toml delete mode 100644 requirements.txt diff --git a/LICENSE b/LICENSE index 5bafd43..83446f5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019-2025 Dmytro Fedoriaka +Copyright (c) 2019-2026 Dmytro Fedoriaka Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..3fe6630 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,35 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = ["setuptools>=77.0.3"] + +[project] +# https://packaging.python.org/en/latest/specifications/declaring-project-metadata/ +name = "quantum_decomp" +version = "1.1.3" +description = "Tool for decomposing unitary matrix into quantum gates" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Dmytro Fedoriaka }] + +# https://pypi.org/classifiers/ +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Topic :: Scientific/Engineering", +] + +# https://peps.python.org/pep-0508/ +dependencies = [ + "numpy>=2.0", +] + +[project.urls] +"Homepage" = "https://github.com/fedimser/quantum_decomp" + +[tool.setuptools.packages.find] +include = ["quantum_decomp*"] +namespaces = false + +[tool.black] +line-length = 80 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 2683e31..0000000 --- a/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -numpy>=1.17 \ No newline at end of file From 1cead675b48b0c9034fae3f7ab1821c89daacf5a Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 13:47:15 -0700 Subject: [PATCH 02/13] update CI --- .github/workflows/ci.yml | 27 +++++++++++++-------------- pyproject.toml | 8 ++++++++ setup.py | 21 --------------------- 3 files changed, 21 insertions(+), 35 deletions(-) delete mode 100644 setup.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ecbc333..14e75fb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,19 +8,20 @@ on: jobs: tests-ubuntu: + strategy: + matrix: + python-version: [ '3.11', '3.13', '3.15' ] name: Tests (Ubuntu) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: - python-version: '3.12' + python-version: ${{ matrix.python-version }} + allow-prereleases: true architecture: 'x64' - name: Install requirements - run: | - pip install -r requirements.txt - pip install pytest>=5.3 pycodestyle - pip install cirq qiskit qsharp + run: python -m pip install ".[test]" - name: Check style run: pycodestyle . - name: Run tests @@ -30,15 +31,13 @@ jobs: name: Tests (Windows) runs-on: windows-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: - python-version: '3.12' + python-version: '3.15' architecture: 'x64' + allow-prereleases: true - name: Install requirements - run: | - pip install -r requirements.txt - pip install pytest>=5.3 pycodestyle - pip install cirq qiskit qsharp + run: python -m pip install ".[test]" - name: Run tests run: pytest . diff --git a/pyproject.toml b/pyproject.toml index 3fe6630..fd737d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,14 @@ dependencies = [ "numpy>=2.0", ] +test = [ + "cirq>=1.7.0", + "pycodestyle", + "pytest>=9.1.1", + "qdk>=1.32", + "qiskit>=2.5.2", +] + [project.urls] "Homepage" = "https://github.com/fedimser/quantum_decomp" diff --git a/setup.py b/setup.py deleted file mode 100644 index 148352e..0000000 --- a/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import setuptools - -with open("README.md", "r", encoding='utf-8') as readme_file: - long_description = readme_file.read() - -with open('requirements.txt', 'r', encoding='utf-8') as req_file: - requirements = [r.strip() for r in req_file.readlines()] - -setuptools.setup( - name="quantum_decomp", - version="1.1.2", - author="Dmytro Fedoriaka", - description="Tool for decomposing unitary matrix into quantum gates", - long_description=long_description, - long_description_content_type="text/markdown", - license='MIT', - url="https://github.com/fedimser/quantum_decomp", - packages=setuptools.find_packages(), - python_requires='>=3.7', - install_requires=requirements, -) From 98cf994ac5bd57b656ab5f5af8ba41a13fd74957 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 13:49:39 -0700 Subject: [PATCH 03/13] fix syntax --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fd737d8..9b51d82 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ readme = "README.md" requires-python = ">=3.11" license = "MIT" license-files = ["LICENSE"] -authors = [{ name = "Dmytro Fedoriaka }] +authors = [{ name = "Dmytro Fedoriaka" }] # https://pypi.org/classifiers/ classifiers = [ From dc9f9a167918b38e8b03acf1d889caceb38f0760 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 13:54:08 -0700 Subject: [PATCH 04/13] fix qiskit warning --- quantum_decomp/quantum_decomp_main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/quantum_decomp/quantum_decomp_main.py b/quantum_decomp/quantum_decomp_main.py index d5132cd..beec957 100644 --- a/quantum_decomp/quantum_decomp_main.py +++ b/quantum_decomp/quantum_decomp_main.py @@ -238,7 +238,9 @@ def gate_to_qiskit(gate2): arg_gates = controls + [target] cgate = gate_to_qiskit(gate.gate2) if len(controls): - cgate = cgate.control(num_ctrl_qubits=len(controls)) + cgate = cgate.control( + num_ctrl_qubits=len(controls), annotated=False + ) circuit.append(cgate, arg_gates) elif isinstance(gate, GateSingle): circuit.append(gate_to_qiskit(gate.gate2), [qubits[gate.qubit_id]]) From 880567585511d2a4fa2fc1e0f75364319308fb76 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 13:59:12 -0700 Subject: [PATCH 05/13] fix q# tests --- quantum_decomp/qsharp_integration_test.py | 29 +++++++++-------------- 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/quantum_decomp/qsharp_integration_test.py b/quantum_decomp/qsharp_integration_test.py index 91da4b0..6e2c2bd 100644 --- a/quantum_decomp/qsharp_integration_test.py +++ b/quantum_decomp/qsharp_integration_test.py @@ -4,12 +4,11 @@ """ import io -import tempfile from contextlib import redirect_stdout import cirq import numpy as np -import qsharp +from qdk import qsharp from scipy.stats import unitary_group import quantum_decomp as qd @@ -36,28 +35,22 @@ def dump_qsharp_unitary(op_code, qubits_count): return: np.array - unitary matrix implemented by given operation. """ - with tempfile.TemporaryDirectory() as tmp_dir: - with open(tmp_dir + "/qsharp.json", "w") as f: - f.write('{"files":["Op.qs"]}') - with open(tmp_dir + "/Op.qs", "w") as f: - f.write(op_code) - qsharp.init(project_root=tmp_dir, - target_profile=qsharp.TargetProfile.Base) - f = io.StringIO() - with redirect_stdout(f): - qsharp.eval( - f'Std.Diagnostics.DumpOperation({qubits_count}, Op.Op);') - dump_output = f.getvalue() - - tokens = dump_output.replace('𝑖', 'j').replace('−', '-').split(' ')[1:] + qsharp.eval(op_code) + + f = io.StringIO() + with redirect_stdout(f): + qsharp.eval(f"Std.Diagnostics.DumpOperation({qubits_count}, Op);") + dump_output = f.getvalue() + + tokens = dump_output.replace("𝑖", "j").replace("−", "-").split(" ")[1:] values = np.array([np.complex128(x) for x in tokens], dtype=np.complex128) - assert len(values == (2**qubits_count)**2) + assert len(values == (2**qubits_count) ** 2) ans = values.reshape((2**qubits_count, 2**qubits_count)) return change_matrix_endianness(ans, qubits_count) def check_on_matrix(matrix): - op_code = qd.matrix_to_qsharp(matrix, op_name='Op') + op_code = qd.matrix_to_qsharp(matrix, op_name="Op") qubits_count = int(np.log2(matrix.shape[0])) dump_matrix = dump_qsharp_unitary(op_code, qubits_count) assert cirq.equal_up_to_global_phase(matrix, dump_matrix, atol=2e-4) From a8742004cd6509be1785039c7e7771442577b113 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:01:08 -0700 Subject: [PATCH 06/13] fix pyproject.toml --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 9b51d82..a1453fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ "numpy>=2.0", ] +[project.optional-dependencies] test = [ "cirq>=1.7.0", "pycodestyle", From 5def5454367f801c85ac10fdfe137567fcbf5745 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:02:57 -0700 Subject: [PATCH 07/13] switch to python 3.14 --- .github/workflows/ci.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14e75fb..96dba39 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ jobs: tests-ubuntu: strategy: matrix: - python-version: [ '3.11', '3.13', '3.15' ] + python-version: [ '3.11', '3.14' ] name: Tests (Ubuntu) runs-on: ubuntu-latest steps: @@ -18,7 +18,6 @@ jobs: - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - allow-prereleases: true architecture: 'x64' - name: Install requirements run: python -m pip install ".[test]" @@ -34,9 +33,8 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - python-version: '3.15' + python-version: '3.14' architecture: 'x64' - allow-prereleases: true - name: Install requirements run: python -m pip install ".[test]" - name: Run tests From 9e6d0ce0648c8e9dbc5270050afe905d6cf4ac7b Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:22:27 -0700 Subject: [PATCH 08/13] fix pyright errors --- quantum_decomp/src/decompose_4x4.py | 2 +- quantum_decomp/src/gate.py | 113 +++++++++++++++++----------- quantum_decomp/src/gate2.py | 36 ++++++--- 3 files changed, 93 insertions(+), 58 deletions(-) diff --git a/quantum_decomp/src/decompose_4x4.py b/quantum_decomp/src/decompose_4x4.py index 16a6b97..78a6be2 100644 --- a/quantum_decomp/src/decompose_4x4.py +++ b/quantum_decomp/src/decompose_4x4.py @@ -175,7 +175,7 @@ def decompose_4x4_tp(U): if np.abs(np.linalg.det(B)) > 1e-9: B = B / np.sqrt(det) break - assert is_special_unitary(B) + assert B is not None and is_special_unitary(B) x2, y2 = 0, 0 for x, y in grid: diff --git a/quantum_decomp/src/gate.py b/quantum_decomp/src/gate.py index 4c14002..66783bb 100644 --- a/quantum_decomp/src/gate.py +++ b/quantum_decomp/src/gate.py @@ -1,51 +1,65 @@ +from abc import ABC, abstractmethod + import numpy as np +from numpy.typing import NDArray +from quantum_decomp.src.gate2 import Gate2 from quantum_decomp.src.two_level_unitary import TwoLevelUnitary -class Gate: +class Gate(ABC): """Represents gate acting on register of qubits.""" - pass + + @abstractmethod + def to_matrix(self, qubits_count: int) -> NDArray[np.complex128]: + """Return the matrix representation for the given register size.""" + raise NotImplementedError class GateSingle(Gate): """Represents gate acting on a single qubit in a register.""" - def __init__(self, gate2, qubit_id): + def __init__(self, gate2: Gate2, qubit_id: int) -> None: self.gate2 = gate2 self.qubit_id = qubit_id def to_qsharp_command(self, qubits_count): - if self.gate2.name in ('Rx', 'Ry', 'Rz'): + if self.gate2.name in ("Rx", "Ry", "Rz"): # QSharp uses different sign. - return '%s(%.15f, qs[%d]);' % ( - self.gate2.name, -self.gate2.arg, self.qubit_id) - elif self.gate2.name == 'R1': - return 'R1(%.15f, qs[%d]);' % (self.gate2.arg, self.qubit_id) - elif self.gate2.name == 'X': - return 'X(qs[%d]);' % (self.qubit_id) - - def to_matrix(self, qubits_count): + return "%s(%.15f, qs[%d]);" % ( + self.gate2.name, + -self.gate2.arg, + self.qubit_id, + ) + elif self.gate2.name == "R1": + return "R1(%.15f, qs[%d]);" % (self.gate2.arg, self.qubit_id) + elif self.gate2.name == "X": + return "X(qs[%d]);" % (self.qubit_id) + + def to_matrix(self, qubits_count: int) -> NDArray[np.complex128]: """Tensor product I x I x ... x `gate2.to_matrix()` x I x ... x I.""" matrix = self.gate2.to_matrix() tile_size = 2 ** (self.qubit_id + 1) ts2 = tile_size // 2 # Half tile size. - if (self.qubit_id == 0): + if self.qubit_id == 0: tile = matrix else: tile = np.zeros((tile_size, tile_size), dtype=np.complex128) subtile = np.eye(tile_size // 2) for i in range(2): for j in range(2): - tile[i * ts2:(i + 1) * ts2, - j * ts2:(j + 1) * ts2] = subtile * matrix[i, j] + tile[i * ts2 : (i + 1) * ts2, j * ts2 : (j + 1) * ts2] = ( + subtile * matrix[i, j] + ) - matrix_size = 2 ** qubits_count + matrix_size = 2**qubits_count ret = np.zeros((matrix_size, matrix_size), dtype=np.complex128) for i in range(2 ** (qubits_count - self.qubit_id - 1)): - ret[i * tile_size:(i + 1) * tile_size, - i * tile_size:(i + 1) * tile_size] = tile + ret[ + i * tile_size : (i + 1) * tile_size, + i * tile_size : (i + 1) * tile_size, + ] = tile return ret @@ -57,9 +71,9 @@ def type(self): class GateFC(Gate): - """ Represents fully contolled gate.""" + """Represents fully contolled gate.""" - def __init__(self, gate2, qubit_id): + def __init__(self, gate2: Gate2, qubit_id: int) -> None: self.gate2 = gate2 self.qubit_id = qubit_id @@ -67,51 +81,60 @@ def to_qsharp_command(self, qubits_count): # On one qubit controlled gate is just single-qubit gate. if qubits_count == 1: return GateSingle(self.gate2, self.qubit_id).to_qsharp_command( - qubits_count) + qubits_count + ) control_ids = [i for i in range(qubits_count) if i != self.qubit_id] - controls = '[' + ', '.join(['qs[%d]' % i for i in control_ids]) + ']' - if self.gate2.name in ('Rx', 'Ry', 'Rz'): + controls = "[" + ", ".join(["qs[%d]" % i for i in control_ids]) + "]" + if self.gate2.name in ("Rx", "Ry", "Rz"): # QSharp uses different sign. - return 'Controlled %s(%s, (%.15f, qs[%d]));' % ( - self.gate2.name, controls, -self.gate2.arg, self.qubit_id) - elif self.gate2.name == 'R1': - return 'Controlled R1(%s, (%.15f, qs[%d]));' % ( - controls, self.gate2.arg, self.qubit_id) - elif self.gate2.name == 'X': + return "Controlled %s(%s, (%.15f, qs[%d]));" % ( + self.gate2.name, + controls, + -self.gate2.arg, + self.qubit_id, + ) + elif self.gate2.name == "R1": + return "Controlled R1(%s, (%.15f, qs[%d]));" % ( + controls, + self.gate2.arg, + self.qubit_id, + ) + elif self.gate2.name == "X": if qubits_count == 2: - return 'CNOT(qs[%d], qs[%d]);' % ( - control_ids[0], self.qubit_id) - return 'Controlled X(%s, (qs[%d]));' % (controls, self.qubit_id) - - def to_matrix(self, qubits_count): - matrix_size = 2 ** qubits_count - index2 = (matrix_size - 1) - index1 = index2 - 2 ** self.qubit_id + return "CNOT(qs[%d], qs[%d]);" % (control_ids[0], self.qubit_id) + return "Controlled X(%s, (qs[%d]));" % (controls, self.qubit_id) + + def to_matrix(self, qubits_count: int) -> NDArray[np.complex128]: + matrix_size = 2**qubits_count + index2 = matrix_size - 1 + index1 = index2 - 2**self.qubit_id matrix = TwoLevelUnitary( - self.gate2.to_matrix(), - matrix_size, - index1, - index2) + self.gate2.to_matrix(), matrix_size, index1, index2 + ) return matrix.get_full_matrix() def __repr__(self): return "%s on bit %d, fully controlled" % ( - str(self.gate2), self.qubit_id) + str(self.gate2), + self.qubit_id, + ) def type(self): return self.gate2.name + "-FC" -def gates_to_matrix(gates, qubits_count): +def gates_to_matrix( + gates: list[Gate], qubits_count: int +) -> NDArray[np.complex128]: """Converts gate sequence to matrix implemented by this sequence.""" - result = np.eye(2 ** qubits_count) + result = np.eye(2**qubits_count, dtype=np.complex128) for gate in gates: assert isinstance(gate, Gate) result = gate.to_matrix(qubits_count) @ result return result -def apply_on_qubit(gates, qubit_id): +def apply_on_qubit(gates: list[Gate2], qubit_id: int) -> list[GateSingle]: """Converts Gate2 gates to GateSingle gates acting on the same qubit.""" return [GateSingle(gate, qubit_id) for gate in gates] diff --git a/quantum_decomp/src/gate2.py b/quantum_decomp/src/gate2.py index 4bcb32b..e8c4053 100644 --- a/quantum_decomp/src/gate2.py +++ b/quantum_decomp/src/gate2.py @@ -1,7 +1,11 @@ +from typing import Literal, assert_never + import numpy as np from quantum_decomp.src.utils import PAULI_X +GateName = Literal["Ry", "Rz", "R1", "X"] + class Gate2: """Represents gate acting on one qubit. @@ -12,21 +16,29 @@ class Gate2: R1(a) = diag(1, exp(i*a)) """ - def __init__(self, name, arg=None): - assert name in ['Ry', 'Rz', 'R1', 'X'] + def __init__(self, name: GateName, arg: float = 0.0): self.name = name self.arg = arg - def to_matrix(self): - if self.name == 'Ry': - return np.array([[np.cos(self.arg / 2), np.sin(self.arg / 2)], - [-np.sin(self.arg / 2), np.cos(self.arg / 2)]]) - elif self.name == 'Rz': - return np.diag([np.exp(0.5j * self.arg), np.exp(-0.5j * self.arg)]) - elif self.name == 'R1': - return np.diag([1.0, np.exp(1j * self.arg)]) - elif self.name == 'X': - return PAULI_X + def to_matrix(self) -> np.typing.NDArray[np.complex128]: + match self.name: + case "Ry": + return np.array( + [ + [np.cos(self.arg / 2), np.sin(self.arg / 2)], + [-np.sin(self.arg / 2), np.cos(self.arg / 2)], + ] + ) + case "Rz": + return np.diag( + [np.exp(0.5j * self.arg), np.exp(-0.5j * self.arg)] + ) + case "R1": + return np.diag([1.0, np.exp(1j * self.arg)]) + case "X": + return PAULI_X + case _: + raise ValueError(f"Unknown gate: {self.name}") def is_identity(self): return np.allclose(self.to_matrix(), np.eye(2)) From 6cba34f1fc37f57eb9230773539f644ab8d05e47 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:23:08 -0700 Subject: [PATCH 09/13] format with black --- quantum_decomp/quantum_decomp_main.py | 92 ++++++++------ quantum_decomp/quantum_decomp_test.py | 97 +++++++++------ quantum_decomp/src/decompose_2x2.py | 12 +- quantum_decomp/src/decompose_4x4.py | 148 ++++++++++++++--------- quantum_decomp/src/decompose_4x4_test.py | 45 ++++--- quantum_decomp/src/gate2_test.py | 27 +++-- quantum_decomp/src/gate_test.py | 36 +++--- quantum_decomp/src/linalg.py | 8 +- quantum_decomp/src/test_utils.py | 21 +--- quantum_decomp/src/two_level_unitary.py | 14 ++- quantum_decomp/src/utils.py | 2 +- 11 files changed, 291 insertions(+), 211 deletions(-) diff --git a/quantum_decomp/quantum_decomp_main.py b/quantum_decomp/quantum_decomp_main.py index beec957..4cfd727 100644 --- a/quantum_decomp/quantum_decomp_main.py +++ b/quantum_decomp/quantum_decomp_main.py @@ -7,8 +7,14 @@ from .src.gate import GateFC, GateSingle from .src.gate2 import Gate2 from .src.two_level_unitary import TwoLevelUnitary -from .src.utils import (PAULI_X, IDENTITY_2x2, is_power_of_two, - is_special_unitary, is_unitary, permute_matrix) +from .src.utils import ( + PAULI_X, + IDENTITY_2x2, + is_power_of_two, + is_special_unitary, + is_unitary, + permute_matrix, +) def two_level_decompose(A): @@ -27,17 +33,25 @@ def make_eliminating_matrix(a, b): Makes second element equal to zero. Guarantees np.angle(c)=0. """ - assert (np.abs(a) > 1e-9 and np.abs(b) > 1e-9) + assert np.abs(a) > 1e-9 and np.abs(b) > 1e-9 theta = np.arctan(np.abs(b / a)) lmbda = -np.angle(a) mu = np.pi + np.angle(b) - np.angle(a) - lmbda - result = np.array([[np.cos(theta) * np.exp(1j * lmbda), - np.sin(theta) * np.exp(1j * mu)], - [-np.sin(theta) * np.exp(-1j * mu), - np.cos(theta) * np.exp(-1j * lmbda)]]) + result = np.array( + [ + [ + np.cos(theta) * np.exp(1j * lmbda), + np.sin(theta) * np.exp(1j * mu), + ], + [ + -np.sin(theta) * np.exp(-1j * mu), + np.cos(theta) * np.exp(-1j * lmbda), + ], + ] + ) assert is_special_unitary(result) assert np.allclose(np.angle(result[0, 0] * a + result[1, 0] * b), 0) - assert (np.abs(result[0, 1] * a + result[1, 1] * b) < 1e-9) + assert np.abs(result[0, 1] * a + result[1, 1] * b) < 1e-9 return result assert is_unitary(A) @@ -72,7 +86,7 @@ def make_eliminating_matrix(a, b): # After we are done with row, diagonal element is 1. assert np.allclose(cur_A[i, i], 1.0) - last_matrix = TwoLevelUnitary(cur_A[n - 2:n, n - 2:n], n, n - 2, n - 1) + last_matrix = TwoLevelUnitary(cur_A[n - 2 : n, n - 2 : n], n, n - 2, n - 1) if not last_matrix.is_identity(): result.append(last_matrix) @@ -101,9 +115,9 @@ def two_level_decompose_gray(A): def add_flips(flip_mask, gates): """Adds X gates for all qubits specified by qubit_mask.""" qubit_id = 0 - while (flip_mask > 0): + while flip_mask > 0: if (flip_mask % 2) == 1: - gates.append(GateSingle(Gate2('X'), qubit_id)) + gates.append(GateSingle(Gate2("X"), qubit_id)) flip_mask //= 2 qubit_id += 1 @@ -118,7 +132,7 @@ def matrix_to_gates(A, **kwargs): :param A: 2^N x 2^N unitary matrix. :return: sequence of `Gate`s. """ - if 'optimize' in kwargs and kwargs['optimize'] and A.shape[0] == 4: + if "optimize" in kwargs and kwargs["optimize"] and A.shape[0] == 4: return decompose_4x4_optimal(A) matrices = two_level_decompose_gray(A) @@ -151,15 +165,19 @@ def matrix_to_qsharp(matrix, **kwargs): "ApplyUnitaryMatrix". :return: string - Q# code. """ - op_name = 'ApplyUnitaryMatrix' - if 'op_name' in kwargs: - op_name = kwargs['op_name'] - header = ('operation %s (qs : Qubit[]) : Unit is Adj + Ctl {\n' % op_name) - footer = '}\n' + op_name = "ApplyUnitaryMatrix" + if "op_name" in kwargs: + op_name = kwargs["op_name"] + header = "operation %s (qs : Qubit[]) : Unit is Adj + Ctl {\n" % op_name + footer = "}\n" qubits_count = int(np.log2(matrix.shape[0])) - code = '\n'.join([' ' + gate.to_qsharp_command(qubits_count) - for gate in matrix_to_gates(matrix, **kwargs)]) - return header + code + '\n' + footer + code = "\n".join( + [ + " " + gate.to_qsharp_command(qubits_count) + for gate in matrix_to_gates(matrix, **kwargs) + ] + ) + return header + code + "\n" + footer def matrix_to_cirq_circuit(A, **kwargs): @@ -171,13 +189,13 @@ def matrix_to_cirq_circuit(A, **kwargs): import cirq def gate_to_cirq(gate2): - if gate2.name == 'X': + if gate2.name == "X": return cirq.X - elif gate2.name == 'Ry': + elif gate2.name == "Ry": return cirq.ry(-gate2.arg) - elif gate2.name == 'Rz': + elif gate2.name == "Rz": return cirq.rz(-gate2.arg) - elif gate2.name == 'R1': + elif gate2.name == "R1": return cirq.ZPowGate(exponent=gate2.arg / np.pi) else: raise RuntimeError("Can't implement: %s" % gate2) @@ -189,18 +207,19 @@ def gate_to_cirq(gate2): for gate in gates: if isinstance(gate, GateFC): - controls = [qubits[i] - for i in range(qubits_count) if i != gate.qubit_id] + controls = [ + qubits[i] for i in range(qubits_count) if i != gate.qubit_id + ] target = qubits[gate.qubit_id] arg_gates = controls + [target] cgate = cirq.ControlledGate( - gate_to_cirq(gate.gate2), - num_controls=qubits_count - 1) + gate_to_cirq(gate.gate2), num_controls=qubits_count - 1 + ) circuit.append(cgate.on(*arg_gates)) elif isinstance(gate, GateSingle): circuit.append(gate_to_cirq(gate.gate2).on(qubits[gate.qubit_id])) else: - raise RuntimeError('Unknown gate type.') + raise RuntimeError("Unknown gate type.") return circuit @@ -214,13 +233,13 @@ def matrix_to_qiskit_circuit(A, **kwargs): from qiskit.circuit.library import RYGate, RZGate, U1Gate, XGate def gate_to_qiskit(gate2): - if gate2.name == 'X': + if gate2.name == "X": return XGate() - elif gate2.name == 'Ry': + elif gate2.name == "Ry": return RYGate(-gate2.arg) - elif gate2.name == 'Rz': + elif gate2.name == "Rz": return RZGate(-gate2.arg) - elif gate2.name == 'R1': + elif gate2.name == "R1": return U1Gate(gate2.arg) else: raise RuntimeError("Can't implement: %s" % gate2) @@ -232,8 +251,9 @@ def gate_to_qiskit(gate2): for gate in gates: if isinstance(gate, GateFC): - controls = [qubits[i] - for i in range(qubits_count) if i != gate.qubit_id] + controls = [ + qubits[i] for i in range(qubits_count) if i != gate.qubit_id + ] target = qubits[gate.qubit_id] arg_gates = controls + [target] cgate = gate_to_qiskit(gate.gate2) @@ -245,5 +265,5 @@ def gate_to_qiskit(gate2): elif isinstance(gate, GateSingle): circuit.append(gate_to_qiskit(gate.gate2), [qubits[gate.qubit_id]]) else: - raise RuntimeError('Unknown gate type.') + raise RuntimeError("Unknown gate type.") return circuit diff --git a/quantum_decomp/quantum_decomp_test.py b/quantum_decomp/quantum_decomp_test.py index d711e71..c0cd466 100644 --- a/quantum_decomp/quantum_decomp_test.py +++ b/quantum_decomp/quantum_decomp_test.py @@ -4,10 +4,15 @@ from scipy.stats import ortho_group, unitary_group import quantum_decomp as qd -from quantum_decomp.src.test_utils import (CNOT, QFT_2, SWAP, assert_all_close, - check_decomp, - random_orthogonal_matrix, - random_unitary) +from quantum_decomp.src.test_utils import ( + CNOT, + QFT_2, + SWAP, + assert_all_close, + check_decomp, + random_orthogonal_matrix, + random_unitary, +) from quantum_decomp.src.two_level_unitary import TwoLevelUnitary from quantum_decomp.src.utils import is_power_of_two @@ -53,33 +58,43 @@ def test_decompose_2x2(): def test_decompose_3x3(): w = np.exp((2j / 3) * np.pi) - A = w * np.array([[1, 1, 1], - [1, w, w * w], - [1, w * w, w]]) / np.sqrt(3) + A = w * np.array([[1, 1, 1], [1, w, w * w], [1, w * w, w]]) / np.sqrt(3) _check_two_level_decompose(A) # This test checks that two-level decomposition algorithm ensures that # diagonal element is equal to 1 after we are done with a row. def test_diagonal_elements_handled_correctly(): - _check_matrix_to_gates(np.array([ - [1j, 0, 0, 0], - [0, -1j, 0, 0], - [0, 0, -1j, 0], - [0, 0, 0, 1j], - ])) - _check_matrix_to_gates(np.array([ - [1, 0, 0, 0], - [0, 0, 0, 1j], - [0, 0, 1, 0], - [0, 1j, 0, 0], - ])) - _check_matrix_to_gates(np.array([ - [0, 0, 1j, 0], - [0, 1j, 0, 0], - [1j, 0, 0, 0], - [0, 0, 0, 1], - ])) + _check_matrix_to_gates( + np.array( + [ + [1j, 0, 0, 0], + [0, -1j, 0, 0], + [0, 0, -1j, 0], + [0, 0, 0, 1j], + ] + ) + ) + _check_matrix_to_gates( + np.array( + [ + [1, 0, 0, 0], + [0, 0, 0, 1j], + [0, 0, 1, 0], + [0, 1j, 0, 0], + ] + ) + ) + _check_matrix_to_gates( + np.array( + [ + [0, 0, 1j, 0], + [0, 1j, 0, 0], + [1j, 0, 0, 0], + [0, 0, 0, 1], + ] + ) + ) def test_decompose_random(): @@ -100,10 +115,18 @@ def test_decompose_gray_4x4(): _check_decompose_gray(np.eye(4).T) w = np.exp((2j / 3) * np.pi) - A = w * np.array([[1, 1, 1, 0], - [1, w, w * w, 0], - [1, w * w, w, 0], - [0, 0, 0, np.sqrt(3)]]) / np.sqrt(3) + A = ( + w + * np.array( + [ + [1, 1, 1, 0], + [1, w, w * w, 0], + [1, w * w, w, 0], + [0, 0, 0, np.sqrt(3)], + ] + ) + / np.sqrt(3) + ) _check_decompose_gray(A) @@ -155,12 +178,16 @@ def test_matrix_to_gates_identity(): def test_matrix_to_qsharp_SWAP(): qsharp_code = qd.matrix_to_qsharp(SWAP) - expected = "\n".join([ - "operation ApplyUnitaryMatrix (qs : Qubit[]) : Unit is Adj + Ctl {", - " CNOT(qs[1], qs[0]);", - " CNOT(qs[0], qs[1]);", - " CNOT(qs[1], qs[0]);", - "}", ""]) + expected = "\n".join( + [ + "operation ApplyUnitaryMatrix (qs : Qubit[]) : Unit is Adj + Ctl {", + " CNOT(qs[1], qs[0]);", + " CNOT(qs[0], qs[1]);", + " CNOT(qs[1], qs[0]);", + "}", + "", + ] + ) assert qsharp_code == expected diff --git a/quantum_decomp/src/decompose_2x2.py b/quantum_decomp/src/decompose_2x2.py index fe88eed..874fd42 100644 --- a/quantum_decomp/src/decompose_2x2.py +++ b/quantum_decomp/src/decompose_2x2.py @@ -14,7 +14,7 @@ def su_to_gates(A): u01 = A[0, 1] u00_abs = np.abs(u00) if u00_abs > 1.0: - assert (u00_abs < 1 + 1e-9) + assert u00_abs < 1 + 1e-9 u00_abs = 1.0 theta = np.arccos(u00_abs) lmbda = np.angle(u00) @@ -22,11 +22,11 @@ def su_to_gates(A): result = [] if np.abs(lmbda - mu) > 1e-9: - result.append(Gate2('Rz', lmbda - mu)) + result.append(Gate2("Rz", lmbda - mu)) if np.abs(theta) > 1e-9: - result.append(Gate2('Ry', 2 * theta)) + result.append(Gate2("Ry", 2 * theta)) if np.abs(lmbda + mu) > 1e-9: - result.append(Gate2('Rz', lmbda + mu)) + result.append(Gate2("Rz", lmbda + mu)) return result @@ -40,7 +40,7 @@ def unitary2x2_to_gates(A): if np.abs(phi) < 1e-9: return su_to_gates(A) elif np.allclose(A, PAULI_X): - return [Gate2('X')] + return [Gate2("X")] else: A = np.diag([1.0, np.exp(-1j * phi)]) @ A - return su_to_gates(A) + [Gate2('R1', phi)] + return su_to_gates(A) + [Gate2("R1", phi)] diff --git a/quantum_decomp/src/decompose_4x4.py b/quantum_decomp/src/decompose_4x4.py index 78a6be2..ec31f6c 100644 --- a/quantum_decomp/src/decompose_4x4.py +++ b/quantum_decomp/src/decompose_4x4.py @@ -14,21 +14,28 @@ import numpy as np from quantum_decomp.src.decompose_2x2 import su_to_gates -from quantum_decomp.src.gate import (GateFC, GateSingle, apply_on_qubit, - gates_to_matrix) +from quantum_decomp.src.gate import ( + GateFC, + GateSingle, + apply_on_qubit, + gates_to_matrix, +) from quantum_decomp.src.gate2 import Gate2 from quantum_decomp.src.linalg import orthonormal_eigensystem -from quantum_decomp.src.utils import (cast_to_real, is_real, - is_special_unitary, is_unitary, - skip_identities) +from quantum_decomp.src.utils import ( + cast_to_real, + is_real, + is_special_unitary, + is_unitary, + skip_identities, +) # "Magic basis". Columns are Phi vectors defined in [2]. # Last two columns replaced to make formula A2 true. # Columns of Phi form maximally entangled basis. -Phi = np.sqrt(0.5) * np.array([[1, -1j, 0, 0], - [0, 0, -1j, 1], - [0, 0, -1j, -1], - [1, 1j, 0, 0]]) +Phi = np.sqrt(0.5) * np.array( + [[1, -1j, 0, 0], [0, 0, -1j, 1], [0, 0, -1j, -1], [1, 1j, 0, 0]] +) Phi_dag = Phi.conj().T @@ -66,8 +73,12 @@ def magic_N(a): def trace_B(A): """Partial trace.""" assert A.shape == (4, 4) - return np.array([[A[0, 0] + A[1, 1], A[0, 2] + A[1, 3]], - [A[2, 0] + A[3, 1], A[2, 2] + A[3, 3]]]) + return np.array( + [ + [A[0, 0] + A[1, 1], A[0, 2] + A[1, 3]], + [A[2, 0] + A[3, 1], A[2, 2] + A[3, 3]], + ] + ) def is_maximally_entangled_state(x): @@ -145,12 +156,13 @@ def normalize(x, y): else: a = normalize(c[0], c[2]) b = normalize(c[0], c[1]) - a2_phase = (phase[2] - phase[0]) + a2_phase = phase[2] - phase[0] if np.abs(c[0]) + np.abs(c[2]) < 1e-9: - a2_phase = (phase[3] - phase[1]) + a2_phase = phase[3] - phase[1] a = np.array([a[0], a[1] * np.exp(1j * a2_phase)]) - b = np.array([b[0] * np.exp(1j * phase[0]), - b[1] * np.exp(1j * phase[1])]) + b = np.array( + [b[0] * np.exp(1j * phase[0]), b[1] * np.exp(1j * phase[1])] + ) assert np.allclose(np.kron(a, b), state) return a, b @@ -170,7 +182,7 @@ def decompose_4x4_tp(U): B = None for x, y in grid: - B = U[2 * x:2 * x + 2, 2 * y:2 * y + 2] + B = U[2 * x : 2 * x + 2, 2 * y : 2 * y + 2] det = np.linalg.det(B) if np.abs(np.linalg.det(B)) > 1e-9: B = B / np.sqrt(det) @@ -182,8 +194,12 @@ def decompose_4x4_tp(U): if np.abs(B[x, y]) > 1e-9: x2, y2 = x, y b = B[x2, y2] - A = np.array([[U[x2, y2] / b, U[x2, y2 + 2] / b], - [U[x2 + 2, y2] / b, U[x2 + 2, y2 + 2] / b]]) + A = np.array( + [ + [U[x2, y2] / b, U[x2, y2 + 2] / b], + [U[x2 + 2, y2] / b, U[x2 + 2, y2 + 2] / b], + ] + ) A /= np.sqrt(np.linalg.det(A)) assert is_special_unitary(A) @@ -240,8 +256,11 @@ def restore_phase(a, b, c): if len(deltas) == 2: delta = None for d in deltas: - p2 = -1j * (e_f_ort * np.exp(1j * d) + e_ort_f * - np.exp(-1j * d)) / np.sqrt(2) + p2 = ( + -1j + * (e_f_ort * np.exp(1j * d) + e_ort_f * np.exp(-1j * d)) + / np.sqrt(2) + ) if _allclose(p2, Psi_bar[:, 2]): delta = d assert delta is not None @@ -249,8 +268,9 @@ def restore_phase(a, b, c): # Correcting ambiguity in sign. # Formula A5b has "+/-", and we need to choose correct sign. p3_1 = Psi_bar[:, 3] - p3_2 = (e_f_ort * np.exp(1j * delta) - e_ort_f * - np.exp(-1j * delta)) / np.sqrt(2) + p3_2 = ( + e_f_ort * np.exp(1j * delta) - e_ort_f * np.exp(-1j * delta) + ) / np.sqrt(2) negate_k = 1 for i in range(4): if abs(p3_2[i]) > 1e-9 and np.real(p3_1[i] / p3_2[i]) < -0.5: @@ -261,11 +281,15 @@ def restore_phase(a, b, c): assert is_unitary(np.array([e_f, e_f_ort, e_ort_f, e_ort_f_ort])) assert np.allclose(Psi_bar[:, 0], (e_f + e_ort_f_ort) / np.sqrt(2)) assert np.allclose(Psi_bar[:, 1], -1j * (e_f - e_ort_f_ort) / np.sqrt(2)) - p2 = -1j * (e_f_ort * np.exp(1j * delta) + e_ort_f * - np.exp(-1j * delta)) / np.sqrt(2) + p2 = ( + -1j + * (e_f_ort * np.exp(1j * delta) + e_ort_f * np.exp(-1j * delta)) + / np.sqrt(2) + ) assert np.allclose(Psi_bar[:, 2], p2) - p3 = (e_f_ort * np.exp(1j * delta) - e_ort_f * - np.exp(-1j * delta)) / np.sqrt(2) + p3 = ( + e_f_ort * np.exp(1j * delta) - e_ort_f * np.exp(-1j * delta) + ) / np.sqrt(2) assert _allclose(Psi_bar[:, 3], p3) UA = np.array([e.conj(), e_ort.conj() * np.exp(1j * delta)]) @@ -274,10 +298,14 @@ def restore_phase(a, b, c): assert is_unitary(UB) UAUB = np.kron(UA, UB) - UAUB_alt = np.array([e_f.conj(), - e_f_ort.conj() * np.exp(-1j * delta), - e_ort_f.conj() * np.exp(1j * delta), - e_ort_f_ort.conj()]) + UAUB_alt = np.array( + [ + e_f.conj(), + e_f_ort.conj() * np.exp(-1j * delta), + e_ort_f.conj() * np.exp(1j * delta), + e_ort_f_ort.conj(), + ] + ) assert np.allclose(UAUB, UAUB_alt) assert is_unitary(UAUB) @@ -333,20 +361,22 @@ def decompose_to_magic_diagonal(U): assert np.allclose(VAVB @ Psi @ np.diag(np.exp(1j * xi)), Phi) assert np.allclose(U @ Psi @ np.diag(np.exp(-1j * eps)), Psi_tilde) - assert np.allclose(UAUB.conj().T @ Psi_tilde @ np.diag( - np.exp(1j * (eps + xi + lmbda))), Phi) + assert np.allclose( + UAUB.conj().T @ Psi_tilde @ np.diag(np.exp(1j * (eps + xi + lmbda))), + Phi, + ) assert _allclose(U, np.kron(UA, UB) @ Ud @ np.kron(VA, VB)) # Restore coefficients of non-local unitary. - gl_phase = - 0.25 * np.sum(lmbda) + gl_phase = -0.25 * np.sum(lmbda) alpha_x = -0.5 * (lmbda[0] + lmbda[2] + 2 * gl_phase) alpha_y = -0.5 * (lmbda[1] + lmbda[2] + 2 * gl_phase) alpha_z = -0.5 * (lmbda[0] + lmbda[1] + 2 * gl_phase) alpha = np.array([alpha_x, alpha_y, alpha_z]) - assert np.allclose(lmbda[0], - gl_phase - alpha_x + alpha_y - alpha_z) - assert np.allclose(lmbda[1], - gl_phase + alpha_x - alpha_y - alpha_z) - assert np.allclose(lmbda[2], - gl_phase - alpha_x - alpha_y + alpha_z) - assert np.allclose(lmbda[3], - gl_phase + alpha_x + alpha_y + alpha_z) + assert np.allclose(lmbda[0], -gl_phase - alpha_x + alpha_y - alpha_z) + assert np.allclose(lmbda[1], -gl_phase + alpha_x - alpha_y - alpha_z) + assert np.allclose(lmbda[2], -gl_phase - alpha_x - alpha_y + alpha_z) + assert np.allclose(lmbda[3], -gl_phase + alpha_x + alpha_y + alpha_z) assert _allclose(Ud, np.exp(1j * gl_phase) * magic_N(alpha)) assert _allclose(U, np.exp(1j * gl_phase) * UAUB @ magic_N(alpha) @ VAVB) @@ -364,12 +394,12 @@ def decompose_to_magic_diagonal(U): assert _allclose(U, np.exp(1j * gl_phase) * UAUB @ magic_N(alpha) @ VAVB) return { - 'UA': UA, - 'UB': UB, - 'VA': VA, - 'VB': VB, - 'alpha': alpha, - 'global_phase': gl_phase, + "UA": UA, + "UB": UB, + "VA": VA, + "VB": VB, + "alpha": alpha, + "global_phase": gl_phase, } @@ -384,14 +414,14 @@ def decompose_magic_N(a): t3 = 2 * a[1] - 0.5 * np.pi result = [] - result.append(GateSingle(Gate2('Rz', 0.5 * np.pi), 1)) - result.append(GateFC(Gate2('X'), 0)) - result.append(GateSingle(Gate2('Rz', t1), 0)) - result.append(GateSingle(Gate2('Ry', t2), 1)) - result.append(GateFC(Gate2('X'), 1)) - result.append(GateSingle(Gate2('Ry', t3), 1)) - result.append(GateFC(Gate2('X'), 0)) - result.append(GateSingle(Gate2('Rz', -0.5 * np.pi), 0)) + result.append(GateSingle(Gate2("Rz", 0.5 * np.pi), 1)) + result.append(GateFC(Gate2("X"), 0)) + result.append(GateSingle(Gate2("Rz", t1), 0)) + result.append(GateSingle(Gate2("Ry", t2), 1)) + result.append(GateFC(Gate2("X"), 1)) + result.append(GateSingle(Gate2("Ry", t3), 1)) + result.append(GateFC(Gate2("X"), 0)) + result.append(GateSingle(Gate2("Rz", -0.5 * np.pi), 0)) N = magic_N(a) assert np.allclose(N, gates_to_matrix(result, 2) * np.exp(0.25j * np.pi)) @@ -412,17 +442,17 @@ def decompose_4x4_optimal(U): magic_decomp = decompose_to_magic_diagonal(U) result = [] - result += apply_on_qubit(su_to_gates(magic_decomp['VA']), 1) - result += apply_on_qubit(su_to_gates(magic_decomp['VB']), 0) - result += decompose_magic_N(magic_decomp['alpha']) - result += apply_on_qubit(su_to_gates(magic_decomp['UA']), 1) - result += apply_on_qubit(su_to_gates(magic_decomp['UB']), 0) + result += apply_on_qubit(su_to_gates(magic_decomp["VA"]), 1) + result += apply_on_qubit(su_to_gates(magic_decomp["VB"]), 0) + result += decompose_magic_N(magic_decomp["alpha"]) + result += apply_on_qubit(su_to_gates(magic_decomp["UA"]), 1) + result += apply_on_qubit(su_to_gates(magic_decomp["UB"]), 0) # Adding global phase using Rz and R1. - gl_phase = magic_decomp['global_phase'] + 0.25 * np.pi + gl_phase = magic_decomp["global_phase"] + 0.25 * np.pi if np.abs(gl_phase) > 1e-9: - result.append(GateSingle(Gate2('Rz', 2 * gl_phase), 0)) - result.append(GateSingle(Gate2('R1', 2 * gl_phase), 0)) + result.append(GateSingle(Gate2("Rz", 2 * gl_phase), 0)) + result.append(GateSingle(Gate2("R1", 2 * gl_phase), 0)) result = skip_identities(result) diff --git a/quantum_decomp/src/decompose_4x4_test.py b/quantum_decomp/src/decompose_4x4_test.py index 8ec9dc1..23e1938 100644 --- a/quantum_decomp/src/decompose_4x4_test.py +++ b/quantum_decomp/src/decompose_4x4_test.py @@ -1,12 +1,19 @@ import numpy as np from scipy.stats import ortho_group, unitary_group -from quantum_decomp.src.decompose_4x4 import (decompose_4x4_optimal, - decompose_4x4_tp, - decompose_product_state) -from quantum_decomp.src.test_utils import (CNOT, QFT_2, SWAP, assert_all_close, - check_decomp, - random_special_unitary) +from quantum_decomp.src.decompose_4x4 import ( + decompose_4x4_optimal, + decompose_4x4_tp, + decompose_product_state, +) +from quantum_decomp.src.test_utils import ( + CNOT, + QFT_2, + SWAP, + assert_all_close, + check_decomp, + random_special_unitary, +) def test_decompose_4x4_optimal_corner_cases(): @@ -15,16 +22,23 @@ def test_decompose_4x4_optimal_corner_cases(): check_decomp(QFT_2, decompose_4x4_optimal(QFT_2)) w = np.exp((2j / 3) * np.pi) - A = w * np.array([[1, 1, 1, 0], - [1, w, w * w, 0], - [1, w * w, w, 0], - [0, 0, 0, np.sqrt(3)]]) / np.sqrt(3) + A = ( + w + * np.array( + [ + [1, 1, 1, 0], + [1, w, w * w, 0], + [1, w * w, w, 0], + [0, 0, 0, np.sqrt(3)], + ] + ) + / np.sqrt(3) + ) check_decomp(A, decompose_4x4_optimal(A), tol=3e-8) - Phi = np.sqrt(0.5) * np.array([[1, -1j, 0, 0], - [0, 0, -1j, 1], - [0, 0, -1j, -1], - [1, 1j, 0, 0]]) + Phi = np.sqrt(0.5) * np.array( + [[1, -1j, 0, 0], [0, 0, -1j, 1], [0, 0, -1j, -1], [1, 1j, 0, 0]] + ) check_decomp(Phi, decompose_4x4_optimal(Phi)) @@ -70,5 +84,4 @@ def _check(state): assert np.allclose(np.kron(a, b), state) _check([0, -3e-49j, -np.sqrt(0.5), -np.sqrt(0.5)]) - _check([-6.29490599e-09 - 7.85046229e-17j, - 0, 0, -1e-09 + 1.00000000e+00j]) + _check([-6.29490599e-09 - 7.85046229e-17j, 0, 0, -1e-09 + 1.00000000e00j]) diff --git a/quantum_decomp/src/gate2_test.py b/quantum_decomp/src/gate2_test.py index 2cbe5fd..3b20665 100644 --- a/quantum_decomp/src/gate2_test.py +++ b/quantum_decomp/src/gate2_test.py @@ -4,19 +4,20 @@ def test_Gate2_to_matrix(): - assert np.allclose(Gate2('X').to_matrix(), [[0, 1], [1, 0]]) + assert np.allclose(Gate2("X").to_matrix(), [[0, 1], [1, 0]]) - assert np.allclose(Gate2('R1', 0).to_matrix(), np.diag([1, 1])) - assert np.allclose( - Gate2('R1', np.pi / 2).to_matrix(), np.diag([1, 1j])) - assert np.allclose(Gate2('R1', np.pi).to_matrix(), np.diag([1, -1])) - - assert np.allclose(Gate2('Ry', 0).to_matrix(), np.diag([1, 1])) - assert np.allclose(Gate2('Ry', np.pi / 2).to_matrix(), - np.array([[1, 1], [-1, 1]]) / np.sqrt(2)) - assert np.allclose(Gate2('Ry', np.pi).to_matrix(), - np.array([[0, 1], [-1, 0]])) + assert np.allclose(Gate2("R1", 0).to_matrix(), np.diag([1, 1])) + assert np.allclose(Gate2("R1", np.pi / 2).to_matrix(), np.diag([1, 1j])) + assert np.allclose(Gate2("R1", np.pi).to_matrix(), np.diag([1, -1])) - assert np.allclose(Gate2('Rz', 0).to_matrix(), np.diag([1, 1])) + assert np.allclose(Gate2("Ry", 0).to_matrix(), np.diag([1, 1])) assert np.allclose( - Gate2('Rz', np.pi).to_matrix(), np.diag([1j, -1j])) + Gate2("Ry", np.pi / 2).to_matrix(), + np.array([[1, 1], [-1, 1]]) / np.sqrt(2), + ) + assert np.allclose( + Gate2("Ry", np.pi).to_matrix(), np.array([[0, 1], [-1, 0]]) + ) + + assert np.allclose(Gate2("Rz", 0).to_matrix(), np.diag([1, 1])) + assert np.allclose(Gate2("Rz", np.pi).to_matrix(), np.diag([1j, -1j])) diff --git a/quantum_decomp/src/gate_test.py b/quantum_decomp/src/gate_test.py index e5a0167..b03605b 100644 --- a/quantum_decomp/src/gate_test.py +++ b/quantum_decomp/src/gate_test.py @@ -5,28 +5,24 @@ def test_GateSingle_to_matrix(): - assert np.allclose(GateSingle(Gate2('X'), 0).to_matrix(2), - [[0, 1, 0, 0], - [1, 0, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 0]]) + assert np.allclose( + GateSingle(Gate2("X"), 0).to_matrix(2), + [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], + ) - assert np.allclose(GateSingle(Gate2('X'), 1).to_matrix(2), - [[0, 0, 1, 0], - [0, 0, 0, 1], - [1, 0, 0, 0], - [0, 1, 0, 0]]) + assert np.allclose( + GateSingle(Gate2("X"), 1).to_matrix(2), + [[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]], + ) def test_GateFC_to_matrix(): - assert np.allclose(GateFC(Gate2('X'), 0).to_matrix(2), - [[1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 0]]) + assert np.allclose( + GateFC(Gate2("X"), 0).to_matrix(2), + [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], + ) - assert np.allclose(GateFC(Gate2('X'), 1).to_matrix(2), - [[1, 0, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 0], - [0, 1, 0, 0]]) + assert np.allclose( + GateFC(Gate2("X"), 1).to_matrix(2), + [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], + ) diff --git a/quantum_decomp/src/linalg.py b/quantum_decomp/src/linalg.py index 19a29a5..0864003 100644 --- a/quantum_decomp/src/linalg.py +++ b/quantum_decomp/src/linalg.py @@ -36,10 +36,10 @@ def find_real_basis(vecs): break assert v2 != -1 vecs = [ - project_on_orth_subspace( - vecs[i], - vecs[v2]) for i in range( - len(vecs)) if i != v2] + project_on_orth_subspace(vecs[i], vecs[v2]) + for i in range(len(vecs)) + if i != v2 + ] return ans diff --git a/quantum_decomp/src/test_utils.py b/quantum_decomp/src/test_utils.py index a8c7a4f..72b166e 100644 --- a/quantum_decomp/src/test_utils.py +++ b/quantum_decomp/src/test_utils.py @@ -3,18 +3,11 @@ from quantum_decomp.src.gate import gates_to_matrix -SWAP = np.array([[1, 0, 0, 0], - [0, 0, 1, 0], - [0, 1, 0, 0], - [0, 0, 0, 1]]) -CNOT = np.array([[1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 0]]) -QFT_2 = 0.5 * np.array([[1, 1, 1, 1], - [1, 1j, -1, -1j], - [1, -1, 1, -1], - [1, -1j, -1, 1j]]) +SWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) +CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) +QFT_2 = 0.5 * np.array( + [[1, 1, 1, 1], [1, 1j, -1, -1j], [1, -1, 1, -1], [1, -1j, -1, 1j]] +) def random_unitary(n): @@ -33,9 +26,7 @@ def random_orthogonal_matrix(n): def assert_all_close(x, y, tol=1e-9): diff = np.abs(x - y) if np.max(diff) > tol: - raise AssertionError( - 'Not close:\nx=%s\ny=%s\ndiff=%s' % - (x, y, diff)) + raise AssertionError("Not close:\nx=%s\ny=%s\ndiff=%s" % (x, y, diff)) def check_decomp(matrix, gates, tol=1e-9): diff --git a/quantum_decomp/src/two_level_unitary.py b/quantum_decomp/src/two_level_unitary.py index 8d0c9e8..1b1422b 100644 --- a/quantum_decomp/src/two_level_unitary.py +++ b/quantum_decomp/src/two_level_unitary.py @@ -25,7 +25,10 @@ def __init__(self, matrix2x2, matrix_size, index1, index2): def __repr__(self): self.order_indices() return "%s on (%d, %d)" % ( - str(self.matrix_2x2), self.index1, self.index2) + str(self.matrix_2x2), + self.index1, + self.index2, + ) def order_indices(self): if self.index1 > self.index2: @@ -46,13 +49,12 @@ def multiply_right(self, A): A[:, idx] = A[:, idx] @ self.matrix_2x2 def inv(self): - return TwoLevelUnitary(self.matrix_2x2.conj().T, - self.matrix_size, - self.index1, - self.index2) + return TwoLevelUnitary( + self.matrix_2x2.conj().T, self.matrix_size, self.index1, self.index2 + ) def apply_permutation(self, perm): - assert (len(perm) == self.matrix_size) + assert len(perm) == self.matrix_size self.index1 = perm[self.index1] self.index2 = perm[self.index2] diff --git a/quantum_decomp/src/utils.py b/quantum_decomp/src/utils.py index 438a15d..1bb8c4b 100644 --- a/quantum_decomp/src/utils.py +++ b/quantum_decomp/src/utils.py @@ -12,7 +12,7 @@ def is_orthogonal(Q): def is_unitary(A): n = A.shape[0] - if (A.shape != (n, n)): + if A.shape != (n, n): raise ValueError("Matrix is not square.") A = np.array(A) return np.allclose(np.eye(n), A @ A.conj().T) From 37b036689cab9fd7756877aa35ef7ba9b3021f84 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:33:13 -0700 Subject: [PATCH 10/13] add lint CI workflow --- .github/workflows/ci.yml | 15 +++++++++++++-- lint.sh | 13 +++++++++++-- pyproject.toml | 5 ++++- pyrightconfig.json | 4 ++++ 4 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 pyrightconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96dba39..9f92d5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,19 @@ on: branches: [ master ] jobs: + lint: + name: Lint (black+pyright) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.14' + architecture: 'x64' + - name: Install requirements + run: pip install .[lint,test] + - name: Lint + run: ./lint.sh tests-ubuntu: strategy: matrix: @@ -21,8 +34,6 @@ jobs: architecture: 'x64' - name: Install requirements run: python -m pip install ".[test]" - - name: Check style - run: pycodestyle . - name: Run tests run: pytest . diff --git a/lint.sh b/lint.sh index 7dd2aee..60ace5c 100755 --- a/lint.sh +++ b/lint.sh @@ -1,2 +1,11 @@ -autopep8 --in-place --aggressive --aggressive -r quantum_decomp -pycodestyle quantum_decomp \ No newline at end of file +result=0 + +echo "Running black..." +black --check ./quantum_decomp --fast +result+=$? + +echo "Running pyright..." +pyright ./quantum_decomp +result+=$? + +exit $result \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index a1453fb..a5a5d7a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,11 +27,14 @@ dependencies = [ [project.optional-dependencies] test = [ "cirq>=1.7.0", - "pycodestyle", "pytest>=9.1.1", "qdk>=1.32", "qiskit>=2.5.2", ] +lint = [ + "black==25.1.0", + "pyright==1.1.414", +] [project.urls] "Homepage" = "https://github.com/fedimser/quantum_decomp" diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 0000000..4f4c0c6 --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "pythonVersion": "3.14", + "typeCheckingMode": "standard", +} \ No newline at end of file From 519ab4acfd3082155547b86a83febd563a9d1f0d Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:42:19 -0700 Subject: [PATCH 11/13] use qsharp.dump_operation --- quantum_decomp/qsharp_integration_test.py | 27 +++++++++++------------ 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/quantum_decomp/qsharp_integration_test.py b/quantum_decomp/qsharp_integration_test.py index 6e2c2bd..1d49383 100644 --- a/quantum_decomp/qsharp_integration_test.py +++ b/quantum_decomp/qsharp_integration_test.py @@ -8,6 +8,7 @@ import cirq import numpy as np +from numpy.typing import NDArray from qdk import qsharp from scipy.stats import unitary_group @@ -16,17 +17,23 @@ from quantum_decomp.src.utils import permute_matrix -def change_int_endianness(val, n): +def change_int_endianness(val: int, n: int) -> int: return sum(((val >> i) & 1) << (n - 1 - i) for i in range(n)) -def change_matrix_endianness(matrix, n): +def change_matrix_endianness( + matrix: NDArray[np.complex128], + n: int, +) -> NDArray[np.complex128]: assert matrix.shape == (2**n, 2**n) perm = [change_int_endianness(i, n) for i in range(2**n)] return permute_matrix(matrix, perm) -def dump_qsharp_unitary(op_code, qubits_count): +def dump_qsharp_unitary( + op_code: str, + qubits_count: int, +) -> NDArray[np.complex128]: """Returns unitary matrix which is implemented by Q# operation. args: @@ -36,17 +43,9 @@ def dump_qsharp_unitary(op_code, qubits_count): np.array - unitary matrix implemented by given operation. """ qsharp.eval(op_code) - - f = io.StringIO() - with redirect_stdout(f): - qsharp.eval(f"Std.Diagnostics.DumpOperation({qubits_count}, Op);") - dump_output = f.getvalue() - - tokens = dump_output.replace("𝑖", "j").replace("−", "-").split(" ")[1:] - values = np.array([np.complex128(x) for x in tokens], dtype=np.complex128) - assert len(values == (2**qubits_count) ** 2) - ans = values.reshape((2**qubits_count, 2**qubits_count)) - return change_matrix_endianness(ans, qubits_count) + values = np.array(qsharp.dump_operation("Op", qubits_count)) + assert values.shape == (2**qubits_count, 2**qubits_count) + return change_matrix_endianness(values, qubits_count) def check_on_matrix(matrix): From 01cad4fd0f5eff1097dba3cb88f9d3b6203e4744 Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:48:23 -0700 Subject: [PATCH 12/13] remove unused imports --- pyrightconfig.json | 1 + quantum_decomp/__init__.py | 9 +++++++++ quantum_decomp/qsharp_integration_test.py | 3 --- quantum_decomp/src/gate2.py | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/pyrightconfig.json b/pyrightconfig.json index 4f4c0c6..05c1be2 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,4 +1,5 @@ { "pythonVersion": "3.14", "typeCheckingMode": "standard", + "reportUnusedImport": "error", } \ No newline at end of file diff --git a/quantum_decomp/__init__.py b/quantum_decomp/__init__.py index 0b58cba..d3ce581 100644 --- a/quantum_decomp/__init__.py +++ b/quantum_decomp/__init__.py @@ -6,3 +6,12 @@ two_level_decompose, two_level_decompose_gray, ) + +__all__ = [ + "matrix_to_cirq_circuit", + "matrix_to_qiskit_circuit", + "matrix_to_gates", + "matrix_to_qsharp", + "two_level_decompose", + "two_level_decompose_gray", +] diff --git a/quantum_decomp/qsharp_integration_test.py b/quantum_decomp/qsharp_integration_test.py index 1d49383..ca48be6 100644 --- a/quantum_decomp/qsharp_integration_test.py +++ b/quantum_decomp/qsharp_integration_test.py @@ -3,9 +3,6 @@ an operation, which applies specified matrix to a register of qubits. """ -import io -from contextlib import redirect_stdout - import cirq import numpy as np from numpy.typing import NDArray diff --git a/quantum_decomp/src/gate2.py b/quantum_decomp/src/gate2.py index e8c4053..0441cfe 100644 --- a/quantum_decomp/src/gate2.py +++ b/quantum_decomp/src/gate2.py @@ -1,4 +1,4 @@ -from typing import Literal, assert_never +from typing import Literal import numpy as np From d954de0211353ef1bd95a85b69c450b00682ec5a Mon Sep 17 00:00:00 2001 From: Dmytro Fedoriaka Date: Sun, 20 Sep 2026 14:51:16 -0700 Subject: [PATCH 13/13] empty commit