Skip to content

Commit 44a86a8

Browse files
authored
Mypy issues part 3 (#898)
* Mypy issues part 3 More miscellaenous mypy fixes.
1 parent ec6bb8b commit 44a86a8

32 files changed

Lines changed: 179 additions & 120 deletions

dev_tools/qualtran_dev_tools/jupyter_autogen.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ class NotebookSpecV2:
7272

7373
@directory.default
7474
def _default_directory(self) -> str:
75-
return str(Path(self.module.__file__).parent)
75+
path = self.module.__file__
76+
assert path is not None
77+
return str(Path(path).parent)
7678

7779
@property
7880
def path_stem(self):
@@ -156,7 +158,7 @@ class _PyCell(_Cell):
156158
cell_id: str
157159

158160

159-
def get_bloq_doc_cells(bloqdoc: BloqDocSpec, cid_prefix: str) -> List[_MarkdownCell]:
161+
def get_bloq_doc_cells(bloqdoc: BloqDocSpec, cid_prefix: str) -> List[_Cell]:
160162
"""Cells introducing the `bloq_cls`"""
161163

162164
md_doc: str = '\n'.join(get_markdown_docstring_lines(bloqdoc.bloq_cls))
@@ -230,7 +232,7 @@ def get_call_graph_cells(bloqdoc: BloqDocSpec, cid_prefix: str) -> List[_Cell]:
230232

231233

232234
def get_cells(bloqdoc: BloqDocSpec) -> List[_Cell]:
233-
cells = []
235+
cells: List[_Cell] = []
234236
cid_prefix = f'{bloqdoc.bloq_cls.__name__}'
235237
cells += get_bloq_doc_cells(bloqdoc, cid_prefix)
236238
cells += get_example_instances_cells(bloqdoc, cid_prefix)

qualtran/_infra/bloq_example.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def bloq_example(_func: Callable[[], _BloqType], **kwargs: Any) -> BloqExample[_
8484

8585
@typing.overload
8686
def bloq_example(
87-
_func: None, *, generalizer: _GeneralizerType = lambda x: x
87+
_func: None = None, *, generalizer: _GeneralizerType = lambda x: x
8888
) -> Callable[[Callable[[], _BloqType]], BloqExample[_BloqType]]:
8989
...
9090

qualtran/bloqs/chemistry/df/double_factorization.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
QBit,
4747
Register,
4848
Signature,
49+
Soquet,
4950
SoquetT,
5051
)
5152
from qualtran.bloqs.basic_gates import CSwap, Hadamard, Toffoli
@@ -156,17 +157,17 @@ def short_name(self) -> str:
156157
def build_composite_bloq(
157158
self,
158159
bb: 'BloqBuilder',
159-
succ_l: SoquetT,
160+
succ_l: Soquet,
160161
l_ne_zero: SoquetT,
161-
succ_p: SoquetT,
162+
succ_p: Soquet,
162163
p: SoquetT,
163164
rot_aa: SoquetT,
164165
spin: SoquetT,
165166
xi: SoquetT,
166167
offset: SoquetT,
167168
rot: SoquetT,
168169
rotations: SoquetT,
169-
sys: SoquetT,
170+
sys: NDArray[Soquet], # type: ignore[type-var]
170171
) -> Dict[str, 'SoquetT']:
171172
# 1st half
172173
in_prep = InnerPrepareDoubleFactorization(
@@ -374,7 +375,7 @@ def signature(self) -> Signature:
374375
def build_composite_bloq(
375376
self,
376377
bb: 'BloqBuilder',
377-
ctrl: SoquetT,
378+
ctrl: NDArray[Soquet], # type: ignore[type-var]
378379
l: SoquetT,
379380
p: SoquetT,
380381
spin: SoquetT,

qualtran/bloqs/chemistry/pbc/first_quantization/projectile/select_and_prepare.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import numpy as np
1919
from attrs import evolve, field, frozen
20+
from numpy.typing import NDArray
2021

2122
from qualtran import (
2223
Bloq,
@@ -107,7 +108,7 @@ def short_name(self) -> str:
107108
def build_call_graph(self, ssa: 'SympySymbolAllocator') -> Set['BloqCountT']:
108109
if self.is_adjoint:
109110
# inverting inequality tests at zero Toffoli.
110-
return {}
111+
return set()
111112
else:
112113
return {(Toffoli(), 6 * self.num_bits_t + 2)}
113114

@@ -147,6 +148,7 @@ def wire_symbol(self, soq: 'Soquet') -> 'WireSymbol':
147148
(c_idx,) = soq.idx
148149
filled = bool(self.cvs[c_idx])
149150
return Circle(filled)
151+
raise ValueError(f'Unknown name: {soq.reg.name}')
150152

151153
def build_composite_bloq(
152154
self, bb: BloqBuilder, ctrl: SoquetT, sel: SoquetT, targets: SoquetT, junk: SoquetT
@@ -294,9 +296,9 @@ def build_composite_bloq(
294296
r: SoquetT,
295297
s: SoquetT,
296298
mu: SoquetT,
297-
nu_x: SoquetT,
298-
nu_y: SoquetT,
299-
nu_z: SoquetT,
299+
nu_x: Soquet,
300+
nu_y: Soquet,
301+
nu_z: Soquet,
300302
m: SoquetT,
301303
succ_nu: SoquetT,
302304
l: SoquetT,
@@ -462,7 +464,7 @@ def short_name(self) -> str:
462464
def build_composite_bloq(
463465
self,
464466
bb: BloqBuilder,
465-
ham_ctrl: SoquetT,
467+
ham_ctrl: NDArray[Soquet], # type: ignore[type-var]
466468
i_ne_j: SoquetT,
467469
plus_t: SoquetT,
468470
i: SoquetT,
@@ -478,7 +480,7 @@ def build_composite_bloq(
478480
m: SoquetT,
479481
l: SoquetT,
480482
sys: SoquetT,
481-
proj: SoquetT,
483+
proj: NDArray[Soquet], # type: ignore[type-var]
482484
) -> Dict[str, 'SoquetT']:
483485
# ancilla for swaps from electronic and projectile system registers.
484486
# we assume these are left in a clean state after SELECT operations
@@ -543,8 +545,10 @@ def build_composite_bloq(
543545
j, sys, q = bb.add(
544546
MultiplexedCSwap3D(self.num_bits_p, self.eta), sel=j, targets=sys, junk=q
545547
)
546-
_ = [bb.free(pi) for pi in p]
547-
_ = [bb.free(qi) for qi in q]
548+
for pi in p:
549+
bb.free(pi)
550+
for qi in q:
551+
bb.free(qi)
548552
ham_ctrl[:] = flag_t, flag_t_mean, flag_uv, flag_proj
549553
bb.free(rl)
550554
return {

qualtran/bloqs/chemistry/pbc/first_quantization/select_and_prepare.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import numpy as np
1919
from attrs import frozen
20+
from numpy.typing import NDArray
2021

2122
from qualtran import (
2223
Bloq,
@@ -28,6 +29,7 @@
2829
QBit,
2930
Register,
3031
Signature,
32+
Soquet,
3133
SoquetT,
3234
)
3335
from qualtran.bloqs.basic_gates import Toffoli
@@ -131,7 +133,7 @@ def signature(self) -> Signature:
131133
@staticmethod
132134
def _reshape_reg(
133135
bb: BloqBuilder, in_reg: SoquetT, out_shape: Tuple[int, ...], bitsize: int
134-
) -> SoquetT:
136+
) -> NDArray[Soquet]: # type: ignore[type-var]
135137
"""Reshape registers allocated as a big register.
136138
137139
Example:
@@ -162,6 +164,7 @@ def wire_symbol(self, soq: 'Soquet') -> 'WireSymbol':
162164
return TextBox('×(x)')
163165
elif soq.reg.name == 'junk':
164166
return TextBox('×(y)')
167+
raise ValueError(f'Unknown name: {soq.reg.name}')
165168

166169
def short_name(self) -> str:
167170
return 'MultiSwap'
@@ -279,9 +282,9 @@ def build_composite_bloq(
279282
r: SoquetT,
280283
s: SoquetT,
281284
mu: SoquetT,
282-
nu_x: SoquetT,
283-
nu_y: SoquetT,
284-
nu_z: SoquetT,
285+
nu_x: Soquet,
286+
nu_y: Soquet,
287+
nu_z: Soquet,
285288
m: SoquetT,
286289
succ_nu: SoquetT,
287290
l: SoquetT,
@@ -445,9 +448,9 @@ def build_composite_bloq(
445448
r: SoquetT,
446449
s: SoquetT,
447450
mu: SoquetT,
448-
nu_x: SoquetT,
449-
nu_y: SoquetT,
450-
nu_z: SoquetT,
451+
nu_x: Soquet,
452+
nu_y: Soquet,
453+
nu_z: Soquet,
451454
m: SoquetT,
452455
l: SoquetT,
453456
sys: SoquetT,
@@ -490,8 +493,10 @@ def build_composite_bloq(
490493
j, sys, q = bb.add(
491494
MultiplexedCSwap3D(self.num_bits_p, self.eta), sel=j, targets=sys, junk=q
492495
)
493-
_ = [bb.free(pi) for pi in p]
494-
_ = [bb.free(qi) for qi in q]
496+
for pi in p:
497+
bb.free(pi)
498+
for qi in q:
499+
bb.free(qi)
495500
bb.free(rl)
496501
return {
497502
'tuv': tuv,

qualtran/bloqs/chemistry/sf/single_factorization.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
import numpy as np
2929
from attrs import evolve, frozen
30+
from numpy.typing import NDArray
3031

3132
from qualtran import (
3233
Bloq,
@@ -37,6 +38,7 @@
3738
QBit,
3839
Register,
3940
Signature,
41+
Soquet,
4042
SoquetT,
4143
)
4244
from qualtran._infra.data_types import BoundedQUInt
@@ -329,10 +331,10 @@ def build_composite_bloq(
329331
self,
330332
bb: 'BloqBuilder',
331333
*,
332-
ctrl: SoquetT,
334+
ctrl: NDArray[Soquet], # type: ignore[type-var]
333335
l: SoquetT,
334-
pq: SoquetT,
335-
rot_aa: SoquetT,
336+
pq: NDArray[Soquet], # type: ignore[type-var]
337+
rot_aa: NDArray[Soquet], # type: ignore[type-var]
336338
swap_pq: SoquetT,
337339
spin: SoquetT,
338340
sys: SoquetT,

qualtran/bloqs/chemistry/sparse/prepare.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
QAny,
3030
QBit,
3131
Register,
32+
Soquet,
3233
SoquetT,
3334
)
3435
from qualtran.bloqs.arithmetic.comparison import LessThanEqual
@@ -43,6 +44,7 @@
4344
from qualtran.linalg.lcu_util import preprocess_lcu_coefficients_for_reversible_sampling
4445

4546
if TYPE_CHECKING:
47+
from qualtran import Bloq
4648
from qualtran.resource_counting import BloqCountT, SympySymbolAllocator
4749

4850

@@ -102,12 +104,12 @@ def _add(p_indx: int, q_indx: int, r_indx: int, s_indx: int):
102104
_add(q, q, q, p)
103105
for p in range(num_spat):
104106
_add(p, p, p, p)
105-
eris_eight = np.array(eris_eight)
107+
eris_eight_np = np.array(eris_eight)
106108
pqrs_indx_np = np.array(pqrs_indx)
107-
keep_indx = np.where(np.abs(eris_eight) > drop_element_thresh)
108-
eris_eight = eris_eight[keep_indx]
109+
keep_indx = np.where(np.abs(eris_eight_np) > drop_element_thresh)
110+
eris_eight_np = eris_eight_np[keep_indx]
109111
pqrs_indx_np = pqrs_indx_np[keep_indx[0]]
110-
return np.concatenate((tpq_indx, pqrs_indx_np)), np.concatenate((tpq_sparse, eris_eight))
112+
return np.concatenate((tpq_indx, pqrs_indx_np)), np.concatenate((tpq_sparse, eris_eight_np))
111113

112114

113115
@frozen
@@ -319,8 +321,8 @@ def build_composite_bloq(
319321
swap_rs: 'SoquetT',
320322
swap_pqrs: 'SoquetT',
321323
flag_1b: 'SoquetT',
322-
alt_pqrs: 'SoquetT',
323-
theta: 'SoquetT',
324+
alt_pqrs: NDArray[Soquet], # type: ignore[type-var]
325+
theta: NDArray[Soquet], # type: ignore[type-var]
324326
keep: 'SoquetT',
325327
less_than: 'SoquetT',
326328
alt_flag_1b: 'SoquetT',

qualtran/bloqs/factoring/mod_add.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,8 @@ def build_composite_bloq(
243243
sign = bb.add(XGate(), q=sign)
244244

245245
# Free the ancilla qubits.
246-
junk_bit = bb.free(junk_bit)
247-
sign = bb.free(sign)
246+
bb.free(junk_bit)
247+
bb.free(sign)
248248

249249
# Return the output registers.
250250
return {'x': x, 'y': y}

qualtran/bloqs/factoring/mod_mul.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ def build_composite_bloq(
7878
self, bb: 'BloqBuilder', ctrl: 'SoquetT', x: 'SoquetT'
7979
) -> Dict[str, 'SoquetT']:
8080
k = self.k
81-
neg_k_inv = -pow(k, -1, mod=self.mod)
81+
if isinstance(self.mod, sympy.Expr) or isinstance(k, sympy.Expr):
82+
neg_k_inv = sympy.Mod(sympy.Pow(k, -1), self.mod)
83+
else:
84+
neg_k_inv = -pow(k, -1, mod=self.mod)
8285

8386
# We store the result of the CtrlScaleModAdd into this new register
8487
# and then clear the original `x` register by multiplying in the inverse.
@@ -148,7 +151,7 @@ def signature(self) -> 'Signature':
148151
def on_classical_vals(self, x: 'ClassicalValT') -> Dict[str, 'ClassicalValT']:
149152
return {'x': (2 * x) % self.p}
150153

151-
def build_composite_bloq(self, bb: 'BloqBuilder', x: SoquetT) -> Dict[str, 'SoquetT']:
154+
def build_composite_bloq(self, bb: 'BloqBuilder', x: Soquet) -> Dict[str, 'SoquetT']:
152155

153156
# Allocate ancilla bits for sign and double.
154157
lower_bit = bb.allocate(n=1)

qualtran/bloqs/hamiltonian_simulation/hamiltonian_simulation_by_gqsp.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
from functools import cached_property
15-
from typing import Dict, Tuple, TYPE_CHECKING, Union
15+
from typing import cast, Dict, Tuple, TYPE_CHECKING, Union
1616

1717
import numpy as np
1818
from attrs import field, frozen
@@ -111,9 +111,10 @@ def approx_cos(self) -> Union[NDArray[np.complex_], Shaped]:
111111
if self.is_symbolic():
112112
return Shaped((2 * self.degree + 1,))
113113

114-
poly = approx_exp_cos_by_jacobi_anger(-self.t * self.alpha, degree=self.degree)
114+
poly = approx_exp_cos_by_jacobi_anger(-self.t * self.alpha, degree=cast(int, self.degree))
115+
115116
# TODO(#860) current scaling method does not compute true maximum, so we scale down a bit more by (1 - 2\eps)
116-
poly = scale_down_to_qsp_polynomial(poly) * (1 - 2 * self.precision)
117+
poly = scale_down_to_qsp_polynomial(list(poly)) * (1 - 2 * self.precision)
117118
return poly
118119

119120
@cached_property
@@ -168,7 +169,7 @@ def build_composite_bloq(self, bb: 'BloqBuilder', **soqs: 'SoquetT') -> Dict[str
168169
bb.free(soq)
169170
else:
170171
for soq_element in soq:
171-
bb.free(soq)
172+
bb.free(cast(Soquet, soq))
172173

173174
return soqs
174175

0 commit comments

Comments
 (0)