Skip to content

Commit

Permalink
Merge pull request #119 from dlyongemallo/remove_some_mypy_type_ignores
Browse files Browse the repository at this point in the history
Remove a number of unnecessary "# type: ignores".
  • Loading branch information
jvdwetering authored Jul 1, 2023
2 parents 5f668ad + 2dbc3df commit 93f9a6b
Show file tree
Hide file tree
Showing 17 changed files with 53 additions and 52 deletions.
4 changes: 2 additions & 2 deletions pyzx/circuit/emojiparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def circuit_to_emoji(c: Circuit, compress_rows:bool=True) -> str:
for s in strings:
s.extend([':W_:']*(r-len(s)))
if not hasattr(gate, "to_emoji"): raise TypeError("Gate {} cannot be converted to emoji".format(str(gate)))
gate.to_emoji(strings) # type: ignore
gate.to_emoji(strings)
if not compress_rows:
r = max([len(s) for s in strings])
for s in strings:
Expand All @@ -42,4 +42,4 @@ def circuit_to_emoji(c: Circuit, compress_rows:bool=True) -> str:
for s in strings:
s.extend([':W_:']*(r-len(s)))

return "\n".join(["".join(s) for s in strings])
return "\n".join(["".join(s) for s in strings])
2 changes: 1 addition & 1 deletion pyzx/circuit/graphparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def graph_to_circuit(g:BaseGraph[VT,ET], split_phases:bool=True) -> Circuit:
if t == VertexType.Z: c.add_gate("ZPhase", q, phase=phase)
else: c.add_gate("XPhase", q, phase=phase)

neigh = [w for w in g.neighbors(v) if rs[w]==r and w<v] # type: ignore # TODO: find a different way to do comparison of vertices
neigh = [w for w in g.neighbors(v) if rs[w]==r and w<v] # TODO: find a different way to do comparison of vertices
for n in neigh:
t2 = ty[n]
q2 = qs[n]
Expand Down
6 changes: 3 additions & 3 deletions pyzx/drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,10 +550,10 @@ def matrix_to_latex(m: np.ndarray) -> str:
best_val = None
denom = None
for v in m.flat:
if abs(v) > epsilon: # type: ignore #TODO: Figure out how numpy typing works
if abs(v) > epsilon:
if best_val is None:
best_val = v
denom = Fraction(cmath.phase(v)/math.pi).limit_denominator(512).denominator # type: ignore #TODO: Figure out how numpy typing works
denom = Fraction(cmath.phase(v)/math.pi).limit_denominator(512).denominator
else:
p = Fraction(cmath.phase(v)/math.pi).limit_denominator(512)
if p.denominator < denom:
Expand All @@ -569,7 +569,7 @@ def matrix_to_latex(m: np.ndarray) -> str:
v = best_val
m = m/v

s = pretty_complex(v) # type: ignore #TODO: Figure out how numpy typing works
s = pretty_complex(v)
if s == "1": s = ""
if s == "-1": s= "-"
out += s + "\n\\begin{pmatrix}\n"
Expand Down
10 changes: 5 additions & 5 deletions pyzx/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,14 @@ def graph_to_json(g: GraphS, scale:FloatInt, verts:Optional[List[int]]=None,edge
verts = list(g.vertices())
if edges is None:
edges = list(g.edges())
nodes = [{'name': int(v), # type: ignore
nodes = [{'name': int(v),
'x': (g.row(v) + 1) * scale,
'y': (g.qubit(v) + 2) * scale,
't': g.type(v),
'phase': phase_to_s(g.phase(v),g.type(v)) }
for v in verts]
links = [{'source': int(g.edge_s(e)), # type: ignore
'target': int(g.edge_t(e)), # type: ignore
links = [{'source': int(g.edge_s(e)),
'target': int(g.edge_t(e)),
't': g.edge_type(e) } for e in edges]
scalar = g.scalar.to_json()
return json.dumps({'nodes': nodes, 'links': links, 'scalar': scalar})
Expand Down Expand Up @@ -377,12 +377,12 @@ def graph_from_json(self, js: Dict[str,Any]) -> None:
t = int(n["t"])
phase = s_to_phase(n["phase"], t) # type: ignore
if v not in marked:
self.graph.add_vertex_indexed(v) # type: ignore
self.graph.add_vertex_indexed(v)
else:
marked.remove(v)
self.graph.set_position(v, q, r)
self.graph.set_phase(v, phase)
self.graph.set_type(v, t) # type: ignore
self.graph.set_type(v, t)
self.graph.remove_vertices(marked)
marked = self.graph.edge_set()
for e in js["links"]:
Expand Down
6 changes: 3 additions & 3 deletions pyzx/editor_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ def pauli_push(g: BaseGraph[VT,ET],
if len(new_verts) == 2:
etab[g.edge(new_verts[0],new_verts[1])] = [0,1]
else:
r = (g.row(v) + sum(g.row(n) for n in new_verts)) / (len(new_verts) + 1) # type: ignore # I don't understand this error
q = (g.qubit(v) + sum(g.qubit(n) for n in new_verts))/(len(new_verts)+1) # type: ignore
r = (g.row(v) + sum(g.row(n) for n in new_verts)) / (len(new_verts) + 1)
q = (g.qubit(v) + sum(g.qubit(n) for n in new_verts))/(len(new_verts)+1)
h = g.add_vertex(VertexType.H_BOX,q,r,Fraction(1))
for n in new_verts: etab[g.edge(h,n)] = [1,0]
return (etab, rem_verts, rem_edges, False)
Expand Down Expand Up @@ -369,4 +369,4 @@ def operations_to_js() -> str:
{"active":False,
"text":v["text"],
"tooltip":v["tooltip"]
} for k,v in operations.items()})
} for k,v in operations.items()})
6 changes: 3 additions & 3 deletions pyzx/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ def phase_poly_from_gadgets(n_qubits: int, n_gadgets: int) -> Circuit:
if n_qubits < 26:
for integer in np.random.choice(
2**n_qubits - 1, replace=False, size=n_gadgets
): # type: ignore # random.choice returns a list here
):
parities.add(Parity(integer + 1, n_qubits))
elif n_qubits < 64:
while len(parities) < n_gadgets:
Expand Down Expand Up @@ -683,7 +683,7 @@ def build_random_parity_map(qubits: int, n_cnots: int, circuit=None) -> MatLike:
for gate in c.gates:
if not hasattr(gate, "control") or not hasattr(gate, "target"):
continue
matrix.row_add(gate.control, gate.target) # type: ignore
matrix.row_add(gate.control, gate.target)
for c in circuit:
c.row_add(gate.control, gate.target) # type: ignore
c.row_add(gate.control, gate.target)
return matrix.data
2 changes: 1 addition & 1 deletion pyzx/graph/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def Graph(backend:Optional[str]=None) -> BaseGraph:
if backend == 'graph_tool':
return GraphGT()
if backend == 'igraph': return GraphIG()
if backend == 'quizx-vec': return quizx.VecGraph() # type: ignore
if backend == 'quizx-vec': return quizx.VecGraph()
return GraphS()

Graph.from_json = GraphS.from_json # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion pyzx/graph/jsonparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def graph_to_json(g: BaseGraph[VT,ET], include_scalar: bool=True) -> str:
else: name = freenamesv.pop(0)
else:
try:
freenamesb.remove(name) if t==VertexType.BOUNDARY else freenamesv.remove(name) # type: ignore
freenamesb.remove(name) if t==VertexType.BOUNDARY else freenamesv.remove(name)
except:
pass
#print("couldn't remove name '{}'".format(name))
Expand Down
2 changes: 1 addition & 1 deletion pyzx/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def graph_to_json(g: BaseGraph[VT,ET]) -> str:
else: name = freenamesv.pop(0)
else:
try:
freenamesb.remove(name) if t==VertexType.BOUNDARY else freenamesv.remove(name) # type: ignore
freenamesb.remove(name) if t==VertexType.BOUNDARY else freenamesv.remove(name)
except:
pass
#print("couldn't remove name '{}'".format(name))
Expand Down
24 changes: 12 additions & 12 deletions pyzx/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def stats(circ: Circuit) -> Tuple[int,int,int]:
two_qubit += 1
elif g.name == 'HAD':
had += 1
elif g.name != 'NOT' and g.phase != 1: # type: ignore
elif g.name != 'NOT' and g.phase != 1:
non_pauli += 1
return had, two_qubit, non_pauli

Expand Down Expand Up @@ -206,23 +206,23 @@ def topological_sort_gates(self) -> List[Gate]:
output.append(gs.pop(0))
elif g.index in available_indices:
available_indices.remove(g.index)
q2 = g.target if q == g.control else g.control # type: ignore
q2 = g.target if q == g.control else g.control
self.gates[q2].remove(g)
output.append(gs.pop(0))
else:
ty = 1 if (g.name == 'CZ' or g.control == q) else 2 # type: ignore
ty = 1 if (g.name == 'CZ' or g.control == q) else 2
available_indices.add(g.index)
remove = []
for i, g2 in enumerate(gs[1:]):
if (ty == 1 and isinstance(g2, ZPhase)) or (ty == 2 and isinstance(g2, XPhase)):
output.append(g2)
remove.append(i)
elif g2.name not in ('CZ', 'CNOT'): break
elif ((ty == 1 and (g2.name == 'CZ' or g2.control == q)) or # type: ignore
(ty == 2 and g2.name == 'CNOT' and g2.target == q)): # type: ignore
elif ((ty == 1 and (g2.name == 'CZ' or g2.control == q)) or
(ty == 2 and g2.name == 'CNOT' and g2.target == q)):
if g2.index in available_indices:
available_indices.remove(g2.index)
q2 = g2.target if q == g2.control else g2.control # type: ignore
q2 = g2.target if q == g2.control else g2.control
self.gates[q2].remove(g2)
output.append(g2)
remove.append(i)
Expand Down Expand Up @@ -262,7 +262,7 @@ def add_cz(self, cz: CZ) -> None:
if self.minimize_czs:
for c,t in [(t1,t2),(t2,t1)]:
for g in self.available[c]:
if g.name == 'CNOT' and g.control == c and g.target == t: # type: ignore[attr-defined]
if g.name == 'CNOT' and g.control == c and g.target == t:
if self.availty[t] == 2:
if g in self.available[t]: # The gate is also available on the target qubit
found_match = True
Expand Down Expand Up @@ -480,7 +480,7 @@ def parse_gate(self, g: Gate) -> None:
self.add_hadamard(t1)
self.add_hadamard(t2)
if t1 not in self.hadamards and t2 not in self.hadamards:
self.add_cz(g) # type: ignore
self.add_cz(g)
# Exactly one of t1 and t2 has a hadamard
# So the CZ commutes trough and becomes a CNOT
elif t1 in self.hadamards:
Expand All @@ -501,16 +501,16 @@ def parse_gate(self, g: Gate) -> None:
if c in self.hadamards and t in self.hadamards:
g.control = t
g.target = c
self.add_cnot(g) # type: ignore
self.add_cnot(g)
elif c not in self.hadamards and t not in self.hadamards:
self.add_cnot(g) # type: ignore
self.add_cnot(g)
# If there is a HAD on the target, the CNOT commutes trough to become a CZ
elif t in self.hadamards:
cz = CZ(c if c<t else t, c if c>t else t)
self.add_cz(cz)
else: # Only the control has a hadamard gate in front of it
self.add_hadamard(c)
self.add_cnot(g) # type: ignore
self.add_cnot(g)

else:
raise TypeError("Unknown gate {}".format(str(g)))
Expand Down Expand Up @@ -774,4 +774,4 @@ def phase_block_optimize(circuit: Circuit, pre_optimize:bool=True, quiet:bool=Tr
for g in consumed: g.index = 0
c = Circuit(qubits)
c.gates = consumed
return c
return c
8 changes: 4 additions & 4 deletions pyzx/routing/architecture.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,15 @@ def get_neighboring_vertices(self, vertex: int) -> Set[int]:
def to_quil_device(self):
# Only required here
import networkx as nx
from pyquil.device import NxDeviceA # type: ignore
from pyquil.device import NxDeviceA
edges = [edge for edge in self.graph.edges() if edge[0] in self.vertices]
topology = nx.from_edgelist(edges)
device = NxDevice(topology) # type: ignore
device = NxDevice(topology)
return device

def visualize(self, filename=None):
import networkx as nx
import matplotlib.pyplot as plt # type: ignore
import matplotlib.pyplot as plt
plt.switch_backend('agg')
g = nx.Graph()
g.add_nodes_from(self.vertices)
Expand Down Expand Up @@ -918,4 +918,4 @@ def colored_print_9X9(np_array):
arch.visualize()

arch = create_architecture(IBM_Q20_TOKYO)
arch.visualize()
arch.visualize()
6 changes: 3 additions & 3 deletions pyzx/routing/cnot_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,8 @@ def permuted_gauss(
else:
circuit = y
mat = Mat2([[matrix.data[r][c] for c in col_perm] for r in row_perm])
circuit.row_perm = row_perm # type: ignore
circuit.col_perm = col_perm # type: ignore
circuit.row_perm = row_perm
circuit.col_perm = col_perm
rank = gauss(
mode, mat, architecture, x=x, y=circuit, full_reduce=full_reduce, **kwargs
)
Expand Down Expand Up @@ -389,7 +389,7 @@ def sequential_gauss(
# perm = current_perm
circuits.append(circuit) # type: ignore # Store the extracted circuit
# Update the new permutation
current_perm = list(perm) # type: ignore
current_perm = list(perm)
if col:
permutations.append(current_perm) # Add optimized initial permutation
if not row:
Expand Down
4 changes: 2 additions & 2 deletions pyzx/routing/parity_maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def update_matrix(self):
self.matrix = Mat2.id(self.n_qubits)
for gate in self.gates:
if hasattr(gate, "name") and gate.name == "CNOT":
self.matrix.row_add(gate.control, gate.target) # type: ignore
self.matrix.row_add(gate.control, gate.target)
else:
print(
"Warning: CNOT tracker can only be used for circuits with only CNOT gates!"
Expand Down Expand Up @@ -188,4 +188,4 @@ def __eq__(self, other):
return False

def __hash__(self):
return hash(str(self))
return hash(str(self))
4 changes: 2 additions & 2 deletions pyzx/routing/phase_poly.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,7 @@ def recurse(
qubits,
column,
phase_qubit,
mode=mode, # type: ignore
mode=mode,
root_heuristic=RootHeuristic.RECURSIVE,
split_heuristic=SplitHeuristic.COUNT,
)
Expand Down Expand Up @@ -809,7 +809,7 @@ def recurse(
matrix,
cols_to_use,
qubits,
phase_qubit=phase_qubit, # type: ignore
phase_qubit=phase_qubit,
)
# Pick the qubit where the recursion split will be most skewed.
chosen_row = max(
Expand Down
12 changes: 6 additions & 6 deletions pyzx/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def tensorfy(g: 'BaseGraph[VT,ET]', preserve_scalar:bool=True) -> np.ndarray:
t = H_to_tensor(d,phase)
else:
raise ValueError("Vertex %s has non-ZXH type but is not an input or output" % str(v))
nn = list(filter(lambda n: rows[n]<r or (rows[n]==r and n<v), neigh)) # type: ignore # TODO: allow ordering on vertex indices?
nn = list(filter(lambda n: rows[n]<r or (rows[n]==r and n<v), neigh)) # TODO: allow ordering on vertex indices?
ety = {n:g.edge_type(g.edge(v,n)) for n in nn}
nn.sort(key=lambda n: ety[n])
for n in nn:
Expand Down Expand Up @@ -202,8 +202,8 @@ def compare_tensors(t1: TensorConvertible,t2: TensorConvertible, preserve_scalar
if preserve_scalar: return False # We do not check for equality up to scalar
epsilon = 10**-14
for i,a in enumerate(t1.flat):
if abs(a)>epsilon: # type: ignore #TODO: Figure out how numpy typing works
if abs(t2.flat[i])<epsilon: return False # type: ignore #TODO: Figure out how numpy typing works
if abs(a)>epsilon:
if abs(t2.flat[i])<epsilon: return False
break
else:
raise ValueError("Tensor is too close to zero")
Expand All @@ -225,9 +225,9 @@ def find_scalar_correction(t1: TensorConvertible, t2:TensorConvertible) -> compl

epsilon = 10**-14
for i,a in enumerate(t1.flat):
if abs(a)>epsilon: # type: ignore #TODO: Figure out how numpy typing works
if abs(t2.flat[i])<epsilon: return 0 # type: ignore #TODO: Figure out how numpy typing works
return a/t2.flat[i] # type: ignore #TODO: Figure out how numpy typing works
if abs(a)>epsilon:
if abs(t2.flat[i])<epsilon: return 0
return a/t2.flat[i]

return 0

Expand Down
6 changes: 3 additions & 3 deletions pyzx/tikz.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def _to_tikz(g: BaseGraph[VT,ET], draw_scalar:bool = False,
else: phase = r"$%s\pi$" % ns
x = g.row(v) + xoffset
y = - g.qubit(v) - yoffset
s = " \\node [style={}] ({:d}) at ({:.2f}, {:.2f}) {{{:s}}};".format(style,v+idoffset,x,y,phase) # type: ignore
s = " \\node [style={}] ({:d}) at ({:.2f}, {:.2f}) {{{:s}}};".format(style,v+idoffset,x,y,phase)
verts.append(s)
maxindex = max([v+idoffset,maxindex]) # type: ignore
maxindex = max([v+idoffset,maxindex])
edges = []
for e in g.edges():
v,w = g.edge_st(e)
Expand All @@ -104,7 +104,7 @@ def _to_tikz(g: BaseGraph[VT,ET], draw_scalar:bool = False,
else:
style = settings.tikz_classes['edge']
if style: s += "[style={:s}] ".format(style)
s += "({:d}) to ({:d});".format(v+idoffset,w+idoffset) # type: ignore
s += "({:d}) to ({:d});".format(v+idoffset,w+idoffset)
edges.append(s)

return (verts, edges)
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ sphinx>=2.3
sphinx_autodoc_typehints>=1.10
sphinx_rtd_theme>=0.4
tqdm>=4.56.0
mypy>=0.990

0 comments on commit 93f9a6b

Please sign in to comment.