Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate complementary polynomial for QSP using flip convolution. #930

Merged
merged 66 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 58 commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
edcfd45
small cleanup
anurudhp Apr 1, 2024
f5446a9
move to `qsp/`
anurudhp Apr 1, 2024
1f80d6f
move `RandomGate` to `for_testing/`
anurudhp Apr 1, 2024
405e118
add gqsp bloq examples
anurudhp Apr 2, 2024
81249ad
docstring + examples use `TestGWRAtom`
anurudhp Apr 2, 2024
1670969
generate notebook
anurudhp Apr 2, 2024
59dd8d1
update docstring
anurudhp Apr 2, 2024
ad285fe
fix examples
anurudhp Apr 2, 2024
8eee92d
fix test
anurudhp Apr 2, 2024
54e5b3d
fix GWRAtom unitary, add test
anurudhp Apr 3, 2024
4b595c6
pass `verify` through to `qsp_complementary_polynomial`
anurudhp Apr 3, 2024
51c4915
[GQSP] hamiltonian simulation
anurudhp Apr 2, 2024
8657793
call graph + docstring
anurudhp Apr 3, 2024
7768ad2
move poly. approximations to separate file
anurudhp Apr 3, 2024
54d4929
add simple hubbard example, fix decompose
anurudhp Apr 3, 2024
d220e13
fix degree calc
anurudhp Apr 3, 2024
bccc820
address comments
anurudhp Apr 3, 2024
9401dfe
move all degree calc to polyapprox
anurudhp Apr 3, 2024
c2f51b5
move `polynomial_approximations` to `qualtran.linalg`
anurudhp Apr 3, 2024
ad2de9b
`polynomial_approximations.py` -> `jacobi_anger_approximations`
anurudhp Apr 3, 2024
76bb086
fix type, clean test
anurudhp Apr 3, 2024
78421f7
more poly tests
anurudhp Apr 3, 2024
4e38b0f
fix imports
anurudhp Apr 3, 2024
b779766
fix simulation: QSP polynomials must have |P(z)| <= 1.
anurudhp Apr 4, 2024
5c12a2e
add notebook
anurudhp Apr 4, 2024
d7015c6
docstring + TODOs
anurudhp Apr 4, 2024
46a43f1
nearly optimal scaling
anurudhp Apr 4, 2024
3c746b3
simplify tests
anurudhp Apr 4, 2024
6c54801
Set up to explore error in the Hamiltonian
Epsilon1024 Apr 11, 2024
3e26f57
Working version of the Paper's code in scratch
Epsilon1024 May 1, 2024
2853220
Added tests
Epsilon1024 May 2, 2024
ce8dc5f
Move normalization outside of complementary Q calculation.
Epsilon1024 May 3, 2024
e9ea8ec
Upstream sync
Epsilon1024 May 3, 2024
367ec00
Merge branch 'hamiltonian' into main_sync
Epsilon1024 May 3, 2024
63a36a7
Added qsp test
Epsilon1024 May 8, 2024
f8f5ea9
Merge branch 'quantumlib:main' into main_sync
Epsilon1024 May 8, 2024
6256110
Cleanup fast qsp
Epsilon1024 May 8, 2024
0897823
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 8, 2024
5c0a96b
Merge branch 'hamiltonian' into main_sync
Epsilon1024 May 8, 2024
eceffc0
Fixed formatting
Epsilon1024 May 8, 2024
fee4e47
Merge branch 'main_sync' of https://github.com/Epsilon1024/Qualtran i…
Epsilon1024 May 8, 2024
1987bf8
Added tests to fast_qsp
Epsilon1024 May 18, 2024
0668670
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ha…
Epsilon1024 May 20, 2024
6e78bf2
Merge branch 'main_sync' into hamiltonian
Epsilon1024 May 20, 2024
0dca227
Add "num_tests" parameter to slow tests
Epsilon1024 May 20, 2024
295a133
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 20, 2024
c6bfe00
Merge branch 'hamiltonian' into main_sync
Epsilon1024 May 20, 2024
889dd6b
Fixed type checking issue caught by linter.
Epsilon1024 May 20, 2024
af45940
Linter doesn't recognize "np.astype" method. Changed a line to redefine
Epsilon1024 May 20, 2024
adac21c
Fix type checking.
Epsilon1024 May 20, 2024
03bf501
Scaled down slow tests
Epsilon1024 May 20, 2024
bddb56a
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 20, 2024
631e556
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 23, 2024
0bb0be9
Added qsp uniary test
Epsilon1024 May 23, 2024
c5c8994
Merge branch 'main' into main_sync
Epsilon1024 May 23, 2024
4f3f81c
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 23, 2024
1a39a1c
Fix testing parameters.
Epsilon1024 May 23, 2024
e399e26
Merge branch 'main_sync' of https://github.com/Epsilon1024/Qualtran i…
Epsilon1024 May 23, 2024
b751148
Minor docstring fixes
Epsilon1024 May 29, 2024
67a5d65
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 29, 2024
ad53bea
Temporarily remove parameters of failing test. Added TODO to code.
Epsilon1024 May 29, 2024
4d2d430
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 30, 2024
c04137a
Update random seed
Epsilon1024 May 31, 2024
86f360a
Merge branch 'main' of https://github.com/quantumlib/Qualtran into ma…
Epsilon1024 May 31, 2024
b41cef3
Fix type checking
Epsilon1024 May 31, 2024
99ca7bf
Update fast_qsp.py
tanujkhattar May 31, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions qualtran/bloqs/qsp/fast_qsp.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add type hints and docstrings to all functions

Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Sequence, Union

import numpy as np
from numpy._typing import NDArray
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
from scipy.optimize import minimize


class FastQSP:
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
"""
A helper class to obtain Q polynomial given P.
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved

This will
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
P: Co-efficients of a complex QSP polynomial.
only_reals: If "true", then only real polynomial values will be returned.
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
"""

def __init__(self, poly: NDArray[np.number], only_reals: bool = False):
self.only_reals = only_reals
if self.only_reals:
self.conv_p_negative = self.conv_by_flip_conj(poly) * -1
else:
assert poly.dtype == np.complex128
self.conv_p_negative = self.complex_conv_by_flip_conj(poly.real, poly.imag) * -1
self.conv_p_negative[poly.shape[0] - 1] = 1 - np.linalg.norm(poly) ** 2

def loss_function(self, x):

Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
if self.only_reals:
conv_result = self.conv_by_flip_conj(x)
else:
real_part = x[: len(x) // 2]
imag_part = x[len(x) // 2 :]
conv_result = self.complex_conv_by_flip_conj(real_part, imag_part)

# Compute loss using squared distance function
loss = np.linalg.norm(self.conv_p_negative - conv_result) ** 2
return loss

@staticmethod
def array_to_complex(x):
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
real_part = x[: len(x) // 2]
imag_part = x[len(x) // 2 :]
return real_part + 1.0j * imag_part

def conv_by_flip_conj(self, poly):
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
return np.convolve(poly, np.flip(poly, axis=[0]), mode="full")
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved

def complex_conv_by_flip_conj(self, real_part: NDArray, imag_part: NDArray):
"""
Performs the flip convolution.

This method is used in sveral parts of the complementary polynomial
calculation. Due to a limitation of the scipy optimizer, the
input array must be split into its real and imaginary components first.
"""
real_flip = np.flip(real_part, axis=[0])
imag_flip = np.flip(-1 * imag_part, axis=[0])

conv_real_part = np.convolve(real_part, real_flip, mode="full")
conv_imag_part = np.convolve(imag_part, imag_flip, mode="full")

conv_real_imag = np.convolve(real_part, imag_flip, mode="full")
conv_imag_real = np.convolve(imag_part, real_flip, mode="full")

# Compute real and imaginary part of the convolution
real_conv = conv_real_part - conv_imag_part
imag_conv = conv_real_imag + conv_imag_real

# Combine to form the complex result
return real_conv + 1j * imag_conv
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved


def fast_complementary_polynomial(
P: Union[NDArray[np.number], Sequence[complex]],
only_reals: bool = False,
tolerance: float = 1e-10,
):
"""
Computes the Q polynomial given P
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docstring nit, see comment on FastQSP docstring above


Computes polynomial $Q$ of degree at-most that of $P$, satisfying

$$ \abs{P(e^{i\theta})}^2 + \abs{Q(e^{i\theta})}^2 = 1 $$

using the flip convolution method described in Eq(60). This
a replacement for the complementary_polynomial in the
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
generalized_qsp module.

Note that by default, this method will take a complex input and
return a complex output. If only real-valued results are desired,
this must be explicitly set by setting "only_reals" to True.
Since there are many possible complimentary polynomials given an
input P, setting "only_reals" will run a slightly different method
than the default to insure the complementary polynomial is real.
This method, however, is significantly less accurate than
the default method. If a real valued complementary polynomial
is desired, it is recommended to use the complementary_polynomial
method from the generalized_qsp module instead.

Args:
P: Co-efficients of a complex polynomial.
only_reals: If true, performs the calculation to only use and return real
valued coefficients. Note that if this is set to "true", and P is
complex, an error will be thrown.
tolerance: The allowable tolerance for finding the minimum of the
qsp loss function. In general, this number should be at least 1/10 of
the desired tolerance used by the code that calls this method.

References:
[Generalized Quantum Signal Processing](https://arxiv.org/abs/2308.01501)
Motlagh and Wiebe. (2023). Equation 60.
"""
np.random.seed(42)
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
if only_reals:
poly = np.array(P, dtype=np.float64)
q_initial = np.random.randn(poly.shape[0])
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
else:
poly = np.array(P, dtype=np.complex128)
q_initial = np.random.randn(poly.shape[0] * 2)
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
q_initial_normalized = q_initial / np.linalg.norm(q_initial)

qsp = FastQSP(poly, only_reals=only_reals)

minimizer = minimize(qsp.loss_function, q_initial_normalized, jac="3-point", tol=tolerance)
if only_reals:
return minimizer.x

return qsp.array_to_complex(minimizer.x)
127 changes: 127 additions & 0 deletions qualtran/bloqs/qsp/fast_qsp_test.py
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numpy as np
import pytest

from qualtran.bloqs.for_testing.matrix_gate import MatrixGate

from .fast_qsp import fast_complementary_polynomial
from .generalized_qsp_test import (
check_polynomial_pair_on_random_points_on_unit_circle,
random_qsp_polynomial,
verify_generalized_qsp,
)


@pytest.mark.parametrize("degree, precision", [(4, 1e-5), (5, 1e-5)])
def test_complementary_polynomial_quick(degree: int, precision: float):
random_state = np.random.RandomState(42)
for _ in range(2):
P = random_qsp_polynomial(degree, random_state=random_state)
Q = fast_complementary_polynomial(P)
check_polynomial_pair_on_random_points_on_unit_circle(
P, Q, random_state=random_state, rtol=precision
)


@pytest.mark.parametrize("degree, precision", [(3, 1e-4), (4, 1e-4)])
def test_real_polynomial_has_real_complementary_polynomial_quick(degree: int, precision: float):
random_state = np.random.RandomState(42)

for _ in range(10):
P = random_qsp_polynomial(degree, random_state=random_state, only_real_coeffs=True)
Q = fast_complementary_polynomial(P, only_reals=True)
Q = np.around(Q, decimals=8)
assert np.isreal(Q).all()
check_polynomial_pair_on_random_points_on_unit_circle(
P, Q, random_state=random_state, rtol=precision
)


@pytest.mark.slow
@pytest.mark.parametrize(
"degree, num_tests, precision", [(5, 20, 2e-5), (10, 20, 2e-5), (20, 5, 2e-5), (30, 3, 2e-5)]
)
def test_complementary_polynomial(degree: int, num_tests: int, precision: float):
random_state = np.random.RandomState(42)

results = []
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
for _ in range(num_tests):
P = random_qsp_polynomial(degree, random_state=random_state)
Q = fast_complementary_polynomial(P)
results.append(np.array(Q))
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
check_polynomial_pair_on_random_points_on_unit_circle(
P, Q, random_state=random_state, rtol=precision
)


@pytest.mark.slow
@pytest.mark.parametrize("degree, num_tests", [(2, 10), (3, 10), (4, 10), (5, 10), (10, 10)])
def test_fast_real_qsp_with_symbolic_signal_matrix(degree: int, num_tests: int):
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
random_state = np.random.RandomState(102)

for _ in range(num_tests):
P = random_qsp_polynomial(degree, random_state=random_state)
U = MatrixGate.random(2, random_state=random_state)
Q = fast_complementary_polynomial(P)
verify_generalized_qsp(U, P, Q=Q)


@pytest.mark.slow
@pytest.mark.parametrize(
"degree, num_tests, precision",
[(2, 10, 2e-2), (3, 10, 2e-2), (4, 10, 2e-2), (5, 10, 2e-2), (10, 10, 2e-2), (20, 10, 2e-2)],
)
def test_real_polynomial_has_real_complementary_polynomial(
degree: int, num_tests: int, precision: float
):
random_state = np.random.RandomState(42)
for _ in range(num_tests):
P = random_qsp_polynomial(degree, random_state=random_state, only_real_coeffs=True)
Q = fast_complementary_polynomial(P, only_reals=True)
Q = np.around(Q, decimals=8)
assert np.isreal(Q).all()
check_polynomial_pair_on_random_points_on_unit_circle(
P, Q, random_state=random_state, rtol=precision
)


@pytest.mark.slow
@pytest.mark.parametrize(
"bitsize, degree, negative_power, tolerance",
[
(1, 2, 0, 1e-5),
(1, 2, 1, 1e-5),
(1, 2, 2, 1e-5),
(2, 2, 0, 1e-5),
(2, 2, 1, 1e-5),
(2, 2, 2, 1e-5),
(1, 5, 2, 1e-4),
(1, 5, 0, 1e-4),
(3, 5, 0, 1e-4),
(3, 5, 2, 1e-4),
(2, 20, 1, 1e-1),
],
)
Epsilon1024 marked this conversation as resolved.
Show resolved Hide resolved
def test_generalized_qsp_with_complex_poly_on_random_unitaries(
bitsize: int, degree: int, negative_power: int, tolerance: float
):
random_state = np.random.RandomState(42)

for _ in range(10):
U = MatrixGate.random(bitsize, random_state=random_state)
P = random_qsp_polynomial(degree, random_state=random_state)
Q = fast_complementary_polynomial(P)
verify_generalized_qsp(U, P, negative_power=negative_power, Q=Q, tolerance=tolerance)
5 changes: 3 additions & 2 deletions qualtran/bloqs/qsp/generalized_qsp_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ def verify_generalized_qsp(
Q: Optional[Sequence[complex]] = None,
*,
negative_power: int = 0,
tolerance: float = 1e-5,
):
input_unitary = cirq.unitary(U)
N = input_unitary.shape[0]
Expand All @@ -154,14 +155,14 @@ def verify_generalized_qsp(
P, input_unitary, negative_power=negative_power
)
actual_top_left = result_unitary[:N, :N]
assert_matrices_almost_equal(expected_top_left, actual_top_left)
assert_matrices_almost_equal(expected_top_left, actual_top_left, atol=tolerance)

assert not isinstance(gqsp_U.Q, Shaped)
expected_bottom_left = evaluate_polynomial_of_matrix(
gqsp_U.Q, input_unitary, negative_power=negative_power
)
actual_bottom_left = result_unitary[N:, :N]
assert_matrices_almost_equal(expected_bottom_left, actual_bottom_left)
assert_matrices_almost_equal(expected_bottom_left, actual_bottom_left, atol=tolerance)


@pytest.mark.slow
Expand Down
Loading