Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 0 additions & 2 deletions qualtran/_infra/bloq.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
if TYPE_CHECKING:
import cirq
import networkx as nx
import pennylane as qml
import quimb.tensor as qtn
import sympy
from numpy.typing import NDArray
Expand All @@ -41,7 +40,6 @@

from qualtran import (
AddControlledT,
Adjoint,
BloqBuilder,
CompositeBloq,
ConnectionT,
Expand Down
1 change: 0 additions & 1 deletion qualtran/_infra/composite_bloq.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,6 @@ def _get_dangling_soquets(signature: Signature, right: bool = True) -> Dict[str,
dang = LeftDangle

all_soqs: Dict[str, SoquetT] = {}
soqs: SoquetT
for reg in regs:
all_soqs[reg.name] = _reg_to_soq(dang, reg)
return all_soqs
Expand Down
10 changes: 5 additions & 5 deletions qualtran/_infra/quantum_graph_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@


def test_dangling():
assert LeftDangle is LeftDangle
assert RightDangle is RightDangle
assert LeftDangle is LeftDangle # noqa: PLR0124
assert RightDangle is RightDangle # noqa: PLR0124
assert LeftDangle is not RightDangle
assert RightDangle is not LeftDangle

assert isinstance(LeftDangle, DanglingT)
assert isinstance(RightDangle, DanglingT)

assert LeftDangle == LeftDangle
assert RightDangle == RightDangle
assert LeftDangle == LeftDangle # noqa: PLR0124
assert RightDangle == RightDangle # noqa: PLR0124
assert LeftDangle != RightDangle

with pytest.raises(ValueError, match='Do not instantiate.*'):
my_new_dangle = DanglingT('hi mom')
_ = DanglingT('hi mom')


def test_dangling_hash():
Expand Down
1 change: 0 additions & 1 deletion qualtran/_infra/registers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ def test_multidim_register():
@pytest.mark.parametrize('n, N, m, M', [(4, 10, 5, 19), (4, 16, 5, 32)])
def test_selection_registers_indexing(n, N, m, M):
dtypes = [BQUInt(n, N), BQUInt(m, M)]
regs = [Register(sym, dtype) for sym, dtype in zip(['x', 'y'], dtypes)]
for x in range(int(dtypes[0].iteration_length)):
for y in range(int(dtypes[1].iteration_length)):
assert np.ravel_multi_index((x, y), (N, M)) == x * M + y
Expand Down
23 changes: 11 additions & 12 deletions qualtran/bloqs/arithmetic/comparison_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,18 +202,17 @@ def _less_than_equal_expected_t_complexity(gate: LessThanEqual):
# When both registers are of the same size the T complexity is
# 8n - 4 same as in the second reference.
return TComplexity(t=8 * n - 4, clifford=46 * n - 21)
# When the registers differ in size and `n` is the size of the smaller one and
# `d` is the difference in size. The T complexity is the sum of the tree
# decomposition as before giving 8n + O(1) and the T complexity of an `And` gate
# over `d` registers giving 4d + O(1) totaling 8n + 4d + O(1).
# From the decomposition we get that the constant is -4 as well as the clifford counts.
elif d == 1:
return TComplexity(t=8 * n, clifford=46 * n - 1 + 2 * is_second_longer)
else:
# When the registers differ in size and `n` is the size of the smaller one and
Comment thread
fdmalone marked this conversation as resolved.
# `d` is the difference in size. The T complexity is the sum of the tree
# decomposition as before giving 8n + O(1) and the T complexity of an `And` gate
# over `d` registers giving 4d + O(1) totaling 8n + 4d + O(1).
# From the decomposition we get that the constant is -4 as well as the clifford counts.
if d == 1:
return TComplexity(t=8 * n, clifford=46 * n - 1 + 2 * is_second_longer)
else:
return TComplexity(
t=8 * n + 4 * d - 4, clifford=46 * n + 17 * d - 18 + 2 * is_second_longer
)
return TComplexity(
t=8 * n + 4 * d - 4, clifford=46 * n + 17 * d - 18 + 2 * is_second_longer
)


@pytest.mark.parametrize("x_bitsize", [*range(1, 5)])
Expand Down Expand Up @@ -302,7 +301,7 @@ def test_greater_than_constant():
q0 = bb.add_register('x', bitsize)
anc = bb.add_register('result', 1)
q0, anc = bb.add(GreaterThanConstant(bitsize, 17), x=q0, target=anc)
cbloq = bb.finalize(x=q0, result=anc)
bb.finalize(x=q0, result=anc)
qlt_testing.assert_wire_symbols_match_expected(
GreaterThanConstant(bitsize, 17), ['In(x)', '⨁(x > 17)']
)
Expand Down
1 change: 0 additions & 1 deletion qualtran/bloqs/arithmetic/controlled_addition.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
from qualtran.symbolics.types import is_symbolic

if TYPE_CHECKING:
import quimb.tensor as qtn

from qualtran.drawing import WireSymbol
from qualtran.resource_counting import BloqCountDictT, SympySymbolAllocator
Expand Down
1 change: 0 additions & 1 deletion qualtran/bloqs/arithmetic/permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
from qualtran.symbolics import bit_length, is_symbolic, Shaped, slen, SymbolicInt

if TYPE_CHECKING:
import sympy

from qualtran import BloqBuilder, SoquetT
from qualtran.resource_counting import BloqCountDictT, BloqCountT, SympySymbolAllocator
Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/basic_gates/rotation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def test_t_like_rotation_gates():
[Rx(0.01), Ry(0.01), Rz(0.01), ZPowGate(0.01), YPowGate(0.01), XPowGate(0.01), CZPowGate(0.01)],
)
def test_rotation_gates_adjoint(bloq):
assert type(bloq) == type(bloq.adjoint())
assert type(bloq) == type(bloq.adjoint()) # noqa: E721
np.testing.assert_allclose(
bloq.tensor_contract() @ bloq.adjoint().tensor_contract(),
np.identity(2 ** bloq.signature.n_qubits()),
Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/block_encoding/linear_combination.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
SoquetT,
)
from qualtran.bloqs.block_encoding import BlockEncoding
from qualtran.bloqs.block_encoding.lcu_block_encoding import BlackBoxPrepare, BlackBoxSelect
from qualtran.bloqs.block_encoding.phase import Phase
from qualtran.bloqs.bookkeeping.auto_partition import AutoPartition, Unused
from qualtran.bloqs.bookkeeping.partition import Partition
from qualtran.bloqs.multiplexers.black_box_select import BlackBoxSelect
from qualtran.bloqs.reflections.prepare_identity import PrepareIdentity
from qualtran.bloqs.state_preparation.black_box_prepare import BlackBoxPrepare
from qualtran.linalg.lcu_util import preprocess_probabilities_for_reversible_sampling
Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/bookkeeping/allocate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_free_nonzero_state_vector_leads_to_unnormalized_state():
bb = BloqBuilder()
qs1 = bb.add(Allocate(QAny(10)))
qs2 = bb.add(OnEach(10, Hadamard()), q=qs1)
no_return = bb.add(Free(QAny(10)), reg=qs2)
_no_return = bb.add(Free(QAny(10)), reg=qs2)
assert np.allclose(bb.finalize().tensor_contract(), np.sqrt(1 / 2**10))


Expand Down
1 change: 0 additions & 1 deletion qualtran/bloqs/bookkeeping/free.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@

if TYPE_CHECKING:
import cirq
import pennylane
import quimb.tensor as qtn
from pennylane.operation import Operation
from pennylane.wires import Wires
Expand Down
1 change: 0 additions & 1 deletion qualtran/bloqs/chemistry/df/select_bloq.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ def signature(self) -> Signature:
def build_call_graph(self, ssa: 'SympySymbolAllocator') -> 'BloqCountDictT':
# Step 4 in the reference.
nlxi = (self.num_eig + self.num_spin_orb // 2 - 1).bit_length()
nxi = (self.num_spin_orb // 2 - 1).bit_length()
cost_a = nlxi - 1 # contiguous register
data_size = self.num_eig + self.num_spin_orb // 2
cost_c = self.num_spin_orb * (self.num_bits_rot - 2) # apply rotations
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@


def test_uniform_super_position_ij():
prep = UniformSuperpostionIJFirstQuantization(eta=10, num_bits_rot_aa=8)
_ = UniformSuperpostionIJFirstQuantization(eta=10, num_bits_rot_aa=8)
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_select_t_costs():
cost = get_cost_value(sel_first_quant, QECGatesCost()).total_t_count()

# Swaps
expected_cost = 4 * (12 * eta * num_bits_p + 6 * num_bits_n) + 4 * (4 * eta - 6) #
expected_cost = 4 * (12 * eta * num_bits_p + 6 * num_bits_n) + 4 * (4 * eta - 6)
# SELT
expected_cost += 4 * (5 * (num_bits_n - 1) + 2 + 1)
# SELUV
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from qualtran.drawing import Text, WireSymbol

if TYPE_CHECKING:
from qualtran.resource_counting import BloqCountDictT, BloqCountT, SympySymbolAllocator
from qualtran.resource_counting import BloqCountDictT, SympySymbolAllocator


@frozen
Expand Down
4 changes: 1 addition & 3 deletions qualtran/bloqs/cryptography/ecc/ec_add_r_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
_ec_window_add_r_small,
ECWindowAddR,
)
from qualtran.bloqs.cryptography.ecc.ec_point import ECPoint
from qualtran.resource_counting.generalizers import ignore_alloc_free, ignore_split_join

from .ec_add_r import ECWindowAddR
from .ec_point import ECPoint


@pytest.mark.parametrize('bloq', [_ec_add_r, _ec_add_r_small, _ec_window_add_r_small])
def test_ec_add_r(bloq_autotester, bloq):
Expand Down
4 changes: 2 additions & 2 deletions qualtran/bloqs/data_loading/qroam_clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
from qualtran.symbolics import ceil, is_symbolic, log2, prod, SymbolicFloat, SymbolicInt

if TYPE_CHECKING:
from qualtran import Bloq, BloqBuilder, SoquetT, QDType
from qualtran import Bloq, BloqBuilder, QDType, SoquetT
from qualtran.resource_counting import BloqCountDictT, CostKey, SympySymbolAllocator
from qualtran.simulation.classical_sim import ClassicalValT
from qualtran.resource_counting import BloqCountDictT, SympySymbolAllocator, CostKey

from qualtran.bloqs.data_loading.select_swap_qrom import _alloc_anc_for_reg, SelectSwapQROM

Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/data_loading/qrom.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def nth_operation_callgraph(self, **kwargs: int) -> Set['BloqCountT']:
selection_idx = tuple(kwargs[reg.name] for reg in self.selection_registers)
ret = 0
for i, d in enumerate(self.data):
target_bitsize, target_shape = self.target_bitsizes[i], self.target_shapes[i]
_target_bitsize, target_shape = self.target_bitsizes[i], self.target_shapes[i]
assert all(isinstance(x, (int, numbers.Integral)) for x in target_shape)
for idx in np.ndindex(cast(Tuple[int, ...], target_shape)):
data_to_load = int(d[selection_idx + idx])
Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/gf_poly_arithmetic/gf2_poly_add_k.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _validate_g_x(self, attribute, value):
if value.degree > self.qgf_poly.degree:
raise ValueError(f"Degree of constant polynomial must be <= {self.qgf_poly.degree}")
if not is_symbolic(self.qgf_poly.degree, self.qgf_poly.qgf):
if not value.field is self.qgf_poly.qgf.gf_type:
if value.field is not self.qgf_poly.qgf.gf_type:
raise ValueError(
f"Constant polynomial must be defined over galois field {self.qgf_poly.qgf.gf_type}"
)
Expand Down
2 changes: 1 addition & 1 deletion qualtran/bloqs/optimization/k_xor_sat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.
from .kikuchi_adjacency_list import KikuchiNonZeroIndex
from .kikuchi_adjacency_matrix import KikuchiMatrixEntry
from .kikuchi_block_encoding import KikuchiHamiltonian, KikuchiMatrixEntry, KikuchiNonZeroIndex
from .kikuchi_block_encoding import KikuchiHamiltonian
from .kikuchi_guiding_state import GuidingState, SimpleGuidingState
from .kxor_instance import Constraint, KXorInstance
from .load_kxor_instance import LoadConstraintScopes, LoadUniqueScopeIndex, PRGAUniqueConstraintRHS
2 changes: 1 addition & 1 deletion qualtran/resource_counting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
format_call_graph_debug_text,
)

from ._costing import GeneralizerT, get_cost_value, get_cost_cache, query_costs, CostKey, CostValT
from ._costing import get_cost_value, get_cost_cache, query_costs, CostKey, CostValT

from ._success_prob import SuccessProb
from ._qubit_counts import QubitCount
Expand Down
3 changes: 2 additions & 1 deletion qualtran/resource_counting/_call_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@

from qualtran import Bloq, CompositeBloq, DecomposeNotImplementedError, DecomposeTypeError

from ._generalization import _make_composite_generalizer, GeneralizerT

BloqCountT = Tuple[Bloq, Union[int, sympy.Expr]]
BloqCountDictT = Mapping[Bloq, Union[int, sympy.Expr]]
MutableBloqCountDictT = MutableMapping[Bloq, Union[int, sympy.Expr]]
from ._generalization import _make_composite_generalizer, GeneralizerT


def big_O(expr) -> sympy.Order:
Expand Down
3 changes: 1 addition & 2 deletions qualtran/resource_counting/classify_bloqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
Common categories relevant for resource esimtation include classifications
like whether the bloq is a Clifford operation, whether it's a rotation, etc.
"""
import collections.abc as abc
from collections import defaultdict
from collections import abc, defaultdict
from typing import cast, Dict, List, Optional, Sequence, TYPE_CHECKING, Union

import numpy as np
Expand Down
19 changes: 9 additions & 10 deletions qualtran/rotation_synthesis/lattice/_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,17 +143,16 @@ def get_grid_operator(self, config: mc.MathConfig) -> GridOperatorAction:
name = "K*"
else:
raise ValueError("Shouldn't be here.")
elif -0.8 <= e1.z <= 0.8 and -0.8 <= e2.z <= 0.8:
g = go.RSqrt2
name = "R"
elif e1.z >= -0.2 and e2.z >= -0.2:
c = min(e1.z, e2.z) # type: ignore[type-var]
n = max(1, config.floor(l_value**c / config.sqrt2))
g = go.BSqrt2**n
name = f"B^{n}"
else:
if -0.8 <= e1.z <= 0.8 and -0.8 <= e2.z <= 0.8:
g = go.RSqrt2
name = "R"
elif e1.z >= -0.2 and e2.z >= -0.2:
c = min(e1.z, e2.z) # type: ignore[type-var]
n = max(1, config.floor(l_value**c / config.sqrt2))
g = go.BSqrt2**n
name = f"B^{n}"
else:
raise ValueError("Shouldn't be here.")
raise ValueError("Shouldn't be here.")
return GridOperatorAction(g, (name,))

def apply(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
def su_unitary_to_zxz_angles(
u: np.ndarray, config: mc.MathConfig
) -> tuple[rst.Real, rst.Real, rst.Real]:
det = u[0, 0] * u[1, 1] - u[0, 1] * u[1, 0]
_det = u[0, 0] * u[1, 1] - u[0, 1] * u[1, 0]
# print(det)
# assert config.isclose(det, 1)

Expand Down
2 changes: 1 addition & 1 deletion qualtran/rotation_synthesis/rings/_zsqrt2.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@


@attrs.frozen(hash=True)
class ZSqrt2:
class ZSqrt2: # noqa: PLW1641 (false positive)
r"""Elements of the ring $\mathbb{Z}[\sqrt{2}]$.

Elements of the ring $\mathbb{Z}[\sqrt{2}]$ are represented by $a+b\sqrt{2}$
Expand Down
4 changes: 4 additions & 0 deletions qualtran/rotation_synthesis/rings/zsqrt2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ def test_value(x: rings.ZSqrt2):
assert float(x) == pytest.approx(x.a + _SQRT_2 * x.b)


def test_hash():
assert hash(rings.ZSqrt2(3, 4)) == hash(rings.ZSqrt2(3, 4))


@pytest.mark.parametrize("p", range(10))
@pytest.mark.parametrize("x", [rings.ZSqrt2(*p) for p in itertools.product(range(-2, 2), repeat=2)])
def test_power(p: int, x: rings.ZSqrt2):
Expand Down
2 changes: 1 addition & 1 deletion qualtran/serialization/bloq.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def _search_for_subbloqs(
_search_for_subbloqs(subbloq, bloq_to_id, pred, max_depth - 1)
else:
_search_for_subbloqs(subbloq, bloq_to_id, pred, 0)
except (DecomposeTypeError, DecomposeNotImplementedError) as e:
except (DecomposeTypeError, DecomposeNotImplementedError):
# No decomposition, nothing to recurse on.
pass

Expand Down
1 change: 0 additions & 1 deletion qualtran/serialization/data_types_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import sympy

from qualtran import BQUInt, QAny, QBit, QDType, QFxp, QInt, QIntOnesComp, QMontgomeryUInt, QUInt
from qualtran._infra.data_types import QMontgomeryUInt
from qualtran.serialization.data_types import data_type_from_proto, data_type_to_proto


Expand Down
2 changes: 1 addition & 1 deletion qualtran/simulation/tensor/_quimb_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def test_cbloq_to_quimb_with_no_ops_on_register():
selection, target = soqs['selection'], soqs['target']
selection = bb.add(Split(QAny(2)), reg=selection)
selection = bb.add(Join(QAny(2)), reg=selection)
cbloq = bb.finalize(selection=selection, target=soqs['target'])
cbloq = bb.finalize(selection=selection, target=target)
np.testing.assert_allclose(cbloq.tensor_contract(), np.eye(2**3))

# Single qubit with no operation acting on it.
Expand Down
4 changes: 2 additions & 2 deletions qualtran/symbolics/math_funcs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def test_smax():
assert smax(1) == 1
assert smax([1]) == 1
assert smax((1, 2)) == 2
assert smax(None) == None
assert smax(None) is None
with pytest.raises(TypeError):
_ = smax(None, None)
with pytest.raises(TypeError):
Expand All @@ -101,7 +101,7 @@ def test_smin():
assert smin(1) == 1
assert smin([1]) == 1
assert smin((1, 2)) == 1
assert smin(None) == None
assert smin(None) is None
with pytest.raises(TypeError):
_ = smin(None, None)
with pytest.raises(TypeError):
Expand Down
2 changes: 0 additions & 2 deletions qualtran/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,6 @@ def assert_bloq_example_make(bloq_ex: BloqExample) -> None:
raise BloqCheckException.fail(f'{bloq} is not an instance of Bloq')
if not isinstance(bloq, bloq_ex.bloq_cls):
raise BloqCheckException.fail(f'{bloq} is not an instance of {bloq_ex.bloq_cls}')
return


def check_bloq_example_make(bloq_ex: BloqExample) -> Tuple[BloqCheckResult, str]:
Expand Down Expand Up @@ -593,7 +592,6 @@ def assert_bloq_example_serializes(bloq_ex: BloqExample) -> None:
raise BloqCheckException.fail(
f'Roundtrip equality failed.\n{bloq=}\n{bloq_roundtrip=}\n'
) from e
return None


def check_bloq_example_serializes(bloq_ex: BloqExample) -> Tuple[BloqCheckResult, str]:
Expand Down
Loading