Skip to content

Commit

Permalink
ruff updates III
Browse files Browse the repository at this point in the history
  • Loading branch information
cqc-melf committed Oct 4, 2024
1 parent cc3f319 commit 0441ef9
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 32 deletions.
8 changes: 3 additions & 5 deletions pytket/extensions/cutensornet/backends/cutensornet_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,8 @@ def process_circuits(
raise ValueError(
"You must specify n_shots when using CuTensorNetShotsBackend."
)
if type(n_shots) == int:
all_shots = [n_shots] * len(circuits)
else:
all_shots = n_shots # type: ignore

all_shots = [n_shots] * len(circuits) if type(n_shots) is int else n_shots

circuit_list = list(circuits)
if valid_check:
Expand All @@ -340,5 +338,5 @@ def _check_all_unitary_or_measurements(circuit: Circuit) -> bool:
if cmd.op.type != OpType.Measure:
cmd.op.get_unitary()
return True
except:
except: # noqa: E722
return False
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ def _get_gate_tensors(self, adj: bool = False) -> defaultdict[Any, list[Any]]:
.reshape([2] * (2 * com.op.n_qubits))
)
self._logger.debug(
f"Adding unitary: \n {permute_rows_cols_in_unitary(com.op.get_unitary(), com_qix_permut).T.conjugate()}" # type: ignore
f"Adding unitary:\
\n {permute_rows_cols_in_unitary(com.op.get_unitary(), com_qix_permut).T.conjugate()}" # type: ignore
)
else:
gate_tensors[i].append(
Expand All @@ -168,7 +169,8 @@ def _get_gate_tensors(self, adj: bool = False) -> defaultdict[Any, list[Any]]:
).reshape([2] * (2 * com.op.n_qubits))
)
self._logger.debug( # type: ignore
f"Adding unitary: \n {permute_rows_cols_in_unitary(com.op.get_unitary(),com_qix_permut)}" # type: ignore
f"Adding unitary:\
\n {permute_rows_cols_in_unitary(com.op.get_unitary(),com_qix_permut)}" # type: ignore
)
break
self._logger.debug(f"Gate tensors: \n{gate_tensors}\n")
Expand Down Expand Up @@ -211,7 +213,8 @@ def _assign_node_tensors(self, adj: bool = False) -> list[Any]:
)
self._logger.debug(
f"criteria: "
f"{(src_ports[0] < src_ports[1]) != (unit_idx[0] < unit_idx[1])}" # pylint: disable=line-too-long
f"{(src_ports[0] < src_ports[1]) !=
(unit_idx[0] < unit_idx[1])}" # pylint: disable=line-too-long
)
if (src_ports[0] < src_ports[1]) != (unit_idx[0] < unit_idx[1]):
node_tensors.append(self._gate_tensors[node[1]["desc"]][1])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def __init__(
for com in self._circuit.get_commands():
try:
gate_unitary = com.op.get_unitary()
except:
except: # noqa: E722
raise ValueError(
"All commands in the circuit must be unitary gates. The circuit "
f"contains {com}; no unitary matrix could be retrived for it."
Expand Down
2 changes: 1 addition & 1 deletion pytket/extensions/cutensornet/structured_state/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def _apply_command(
elif op.is_gate(): # Either a unitary gate or a not supported "gate"
try:
unitary = op.get_unitary()
except:
except: # noqa E722
raise ValueError(f"The command {op.type} introduced is not supported.")

# Load the gate's unitary to the GPU memory
Expand Down
10 changes: 2 additions & 8 deletions pytket/extensions/cutensornet/structured_state/mps_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,7 @@ def _apply_2q_unitary(self, unitary: cp.ndarray, q0: Qubit, q1: Qubit) -> MPSxGa
# S -> shared bond of the gate tensor's SVD
# a,b,c -> the virtual bonds of the tensors

if l_pos == positions[0]:
gate_bonds = "LRlr"
else: # Implicit swap
gate_bonds = "RLrl"
gate_bonds = "LRlr" if l_pos == positions[0] else "RLrl"

# Apply SVD on the gate tensor to remove any zero singular values ASAP
svd_method = tensor.SVDMethod(
Expand Down Expand Up @@ -255,10 +252,7 @@ def _apply_2q_unitary_nonadjacent(
# a,b -> virtual bonds of the MPS
# m,M -> virtual bonds connected to the "message tensor"

if l_pos == positions[0]:
gate_bonds = "LRlr"
else: # Implicit swap
gate_bonds = "RLrl"
gate_bonds = "LRlr" if l_pos == positions[0] else "RLrl"

# Apply SVD on the gate tensor to remove any zero singular values ASAP
svd_method = tensor.SVDMethod(
Expand Down
15 changes: 6 additions & 9 deletions pytket/extensions/cutensornet/structured_state/mps_mpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,7 @@ def _apply_2q_unitary(self, unitary: cp.ndarray, q0: Qubit, q1: Qubit) -> MPSxMP
# s -> virtual bond after QR decomposition

# Assign the bond IDs for the gate
if l_pos == positions[0]:
gate_bonds = "LRlr"
else: # Implicit swap
gate_bonds = "RLrl"
gate_bonds = "LRlr" if l_pos == positions[0] else "RLrl"

# Apply SVD on the gate tensor to remove any zero singular values ASAP
svd_method = tensor.SVDMethod(
Expand Down Expand Up @@ -450,11 +447,11 @@ def update_sweep_cache(pos: int, direction: DirMPS) -> None:
interleaved_rep.append(r_cached_tensors[-1])
r_cached_bonds = self._get_column_bonds(pos + 1, DirMPS.LEFT)
interleaved_rep.append(["r", "R"] + r_cached_bonds)
elif direction == DirMPS.RIGHT:
if pos != 0: # Otherwise, there is nothing cached yet
interleaved_rep.append(l_cached_tensors[-1])
l_cached_bonds = self._get_column_bonds(pos - 1, DirMPS.RIGHT)
interleaved_rep.append(["l", "L"] + l_cached_bonds)
elif direction == DirMPS.RIGHT and pos != 0:
# Otherwise, there is nothing cached yet
interleaved_rep.append(l_cached_tensors[-1])
l_cached_bonds = self._get_column_bonds(pos - 1, DirMPS.RIGHT)
interleaved_rep.append(["l", "L"] + l_cached_bonds)

# Figure out the ID of the bonds of the contracted tensor
if direction == DirMPS.LEFT:
Expand Down
8 changes: 4 additions & 4 deletions pytket/extensions/cutensornet/structured_state/ttn.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,12 @@ def __init__(

# Calculate the root path of this group
path = []
for l in reversed(range(n_levels)):
if k < 2**l:
for le in reversed(range(n_levels)):
if k < 2**le:
path.append(DirTTN.LEFT)
else:
path.append(DirTTN.RIGHT)
k -= 2**l
k -= 2**le

# Add each qubit to the qubit_position dictionary
for i, q in enumerate(qubits):
Expand Down Expand Up @@ -371,7 +371,7 @@ def canonicalise(self, center: RootPath | Qubit, unsafe: bool = False) -> Tensor
for path in self.nodes:
# Nodes towards children are closer to the root and coincide in the path
if len(path) < len(target_path) and all(
path[l] == target_path[l] for l in range(len(path))
path[le] == target_path[le] for le in range(len(path))
):
towards_child.append(path)
# If the center is a physical bond (qubit), its node is skipped
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ def test_device_properties_logger() -> None:
try:
with CuTensorNetHandle() as libhandle:
libhandle.print_device_properties(set_logger("GeneralState", 10))
except:
except: # noqa: E722
pytest.fail("Could not print device properties")

0 comments on commit 0441ef9

Please sign in to comment.