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

Melf/add ruff 2024 #162

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
5 changes: 4 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ jobs:
- name: Update pip
run: pip install --upgrade pip
- name: Install black and pylint
run: pip install black pylint
run: pip install black pylint ruff
- name: Check files are formatted with black
run: |
black --check .
- name: Run ruff
run: |
ruff check .
- name: Run pylint
run: |
pylint --recursive=y --ignore=ttn_tutorial.py,mps_tutorial.py */
7 changes: 3 additions & 4 deletions pytket/extensions/cutensornet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
# limitations under the License.
"""Module for conversion from tket primitives to cuQuantum primitives."""

from .backends import CuTensorNetStateBackend, CuTensorNetShotsBackend
from .general import CuTensorNetHandle

# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__ # type: ignore
from ._metadata import __extension_name__, __extension_version__ # type: ignore
from .backends import CuTensorNetShotsBackend, CuTensorNetStateBackend
from .general import CuTensorNetHandle
2 changes: 1 addition & 1 deletion pytket/extensions/cutensornet/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@
# limitations under the License.
"""Backend for utilising the cuQuantum simulator directly from pytket"""

from .cutensornet_backend import CuTensorNetStateBackend, CuTensorNetShotsBackend
from .cutensornet_backend import CuTensorNetShotsBackend, CuTensorNetStateBackend
55 changes: 27 additions & 28 deletions pytket/extensions/cutensornet/backends/cutensornet_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,44 +14,45 @@

"""Methods to allow tket circuits to be run on the cuTensorNet simulator."""

from abc import abstractmethod
import warnings

from typing import List, Union, Optional, Sequence
from abc import abstractmethod
from collections.abc import Sequence
from typing import Optional, Union
from uuid import uuid4
from pytket.circuit import Circuit, OpType
from pytket.backends import ResultHandle, CircuitStatus, StatusEnum, CircuitNotRunError
from pytket.backends.backend import KwargTypes, Backend, BackendResult

from pytket.backends import CircuitNotRunError, CircuitStatus, ResultHandle, StatusEnum
from pytket.backends.backend import Backend, BackendResult, KwargTypes
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.circuit import Circuit, OpType
from pytket.extensions.cutensornet.general import CuTensorNetHandle
from pytket.extensions.cutensornet.general_state import (
GeneralState,
)
from pytket.predicates import ( # type: ignore
Predicate,
NoSymbolsPredicate,
NoClassicalControlPredicate,
NoMidMeasurePredicate,
NoBarriersPredicate,
UserDefinedPredicate,
)
from pytket.passes import ( # type: ignore
BasePass,
SequencePass,
CustomPass,
DecomposeBoxes,
FullPeepholeOptimise,
RemoveRedundancies,
SequencePass,
SynthesiseTket,
FullPeepholeOptimise,
CustomPass,
)
from pytket.predicates import ( # type: ignore
NoBarriersPredicate,
NoClassicalControlPredicate,
NoMidMeasurePredicate,
NoSymbolsPredicate,
Predicate,
UserDefinedPredicate,
)

try:
from cuquantum.cutensornet import StateAttribute, SamplerAttribute # type: ignore
from cuquantum.cutensornet import SamplerAttribute, StateAttribute # type: ignore
except ImportError:
warnings.warn("local settings failed to import cuquantum", ImportWarning)

from .._metadata import __extension_version__, __extension_name__
from .._metadata import __extension_name__, __extension_version__


class _CuTensorNetBaseBackend(Backend):
Expand All @@ -68,7 +69,7 @@ def _result_id_type(self) -> _ResultIdTuple:
return (str,)

@property
def required_predicates(self) -> List[Predicate]:
def required_predicates(self) -> list[Predicate]:
"""Returns the minimum set of predicates that a circuit must satisfy.

Predicates need to be satisfied before the circuit can be successfully run on
Expand Down Expand Up @@ -144,7 +145,7 @@ def process_circuits(
n_shots: Optional[Union[int, Sequence[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
"""Submits circuits to the backend for running.

The results will be stored in the backend's result cache to be retrieved by the
Expand Down Expand Up @@ -196,7 +197,7 @@ def process_circuits(
n_shots: Optional[Union[int, Sequence[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
"""Submits circuits to the backend for running.

The results will be stored in the backend's result cache to be retrieved by the
Expand Down Expand Up @@ -273,7 +274,7 @@ def process_circuits(
n_shots: Optional[Union[int, Sequence[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
"""Submits circuits to the backend for running.

The results will be stored in the backend's result cache to be retrieved by the
Expand Down Expand Up @@ -312,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 @@ -339,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
8 changes: 4 additions & 4 deletions pytket/extensions/cutensornet/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations # type: ignore
import warnings

import logging
import warnings
from logging import Logger

from typing import Any, Optional
from typing import Any

try:
import cupy as cp # type: ignore
Expand All @@ -42,7 +42,7 @@ class CuTensorNetHandle:
If not provided, defaults to ``cp.cuda.Device()``.
"""

def __init__(self, device_id: Optional[int] = None):
def __init__(self, device_id: int | None = None):
self._is_destroyed = False

# Make sure CuPy uses the specified device
Expand Down
14 changes: 6 additions & 8 deletions pytket/extensions/cutensornet/general_state/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,14 @@
# limitations under the License.
"""Module for simulating circuits with no predetermined tensor network structure."""

from .utils import circuit_statevector_postselect

from .tensor_network_convert import (
TensorNetwork,
PauliOperatorTensorNetwork,
ExpectationValueTensorNetwork,
tk_to_tensor_network,
measure_qubits_state,
get_operator_expectation_value,
PauliOperatorTensorNetwork,
TensorNetwork,
get_circuit_overlap,
get_operator_expectation_value,
measure_qubits_state,
tk_to_tensor_network,
)

from .tensor_network_state import GeneralState
from .utils import circuit_statevector_postselect
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,25 @@
except ImportError:
warnings.warn("local settings failed to import cutensornet", ImportWarning)

from collections import defaultdict
import logging
from collections import defaultdict
from logging import Logger
from typing import List, Tuple, Union, Any, DefaultDict, Optional
from typing import Any, Optional, Union

import networkx as nx # type: ignore
from networkx.classes.reportviews import OutMultiEdgeView, OutMultiEdgeDataView # type: ignore
import numpy as np
from networkx.classes.reportviews import ( # type: ignore
OutMultiEdgeDataView,
OutMultiEdgeView,
)
from numpy.typing import NDArray
from sympy import Expr # type: ignore

from pytket.utils import Graph
from pytket.pauli import QubitPauliString
from pytket.circuit import Circuit, Qubit
from pytket.utils import permute_rows_cols_in_unitary
from pytket.utils.operators import QubitPauliOperator
from pytket.extensions.cutensornet.general import set_logger
from pytket.pauli import QubitPauliString
from pytket.utils import Graph, permute_rows_cols_in_unitary
from pytket.utils.operators import QubitPauliOperator


class TensorNetwork:
Expand Down Expand Up @@ -85,7 +88,7 @@ def cuquantum_interleaved(self) -> list:
"""Returns an interleaved format of the circuit tensor network."""
return self._cuquantum_interleaved

def _get_gate_tensors(self, adj: bool = False) -> DefaultDict[Any, List[Any]]:
def _get_gate_tensors(self, adj: bool = False) -> defaultdict[Any, list[Any]]:
"""Computes and stores tensors for each gate type from the circuit.

The unitaries are reshaped into tensors of bond dimension two prior to being
Expand Down Expand Up @@ -156,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 @@ -165,13 +169,14 @@ 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")
return gate_tensors

def _assign_node_tensors(self, adj: bool = False) -> List[Any]:
def _assign_node_tensors(self, adj: bool = False) -> list[Any]:
"""Creates a list of tensors representing circuit gates (tensor network nodes).

Args:
Expand Down Expand Up @@ -208,17 +213,18 @@ 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])
self._logger.debug(f"Adding an upward gate tensor")
self._logger.debug("Adding an upward gate tensor")
else:
node_tensors.append(self._gate_tensors[node[1]["desc"]][0])
self._logger.debug(f"Adding a downward gate tensor")
self._logger.debug("Adding a downward gate tensor")
else:
node_tensors.append(self._gate_tensors[node[1]["desc"]][0])
self._logger.debug(f"Adding a 1-qubit gate tensor")
self._logger.debug("Adding a 1-qubit gate tensor")
else:
if node[1]["desc"] == "Output":
self._output_nodes.append(i)
Expand All @@ -233,7 +239,7 @@ def _assign_node_tensors(self, adj: bool = False) -> List[Any]:

def _get_tn_indices(
self, net: nx.MultiDiGraph, adj: bool = False
) -> Tuple[List[Any], dict[Qubit, int]]:
) -> tuple[list[Any], dict[Qubit, int]]:
"""Computes indices of the edges of the tensor network nodes (tensors).

Indices are computed such that they range from high (for circuit leftmost gates)
Expand Down Expand Up @@ -280,7 +286,7 @@ def _get_tn_indices(
]
eids_sorted = sorted(eids, key=abs)
qnames_graph_ordered = [qname for qname in self._graph.output_names.values()]
oids_graph_ordered = [oid for oid in self._graph.output_names.keys()]
oids_graph_ordered = [oid for oid in self._graph.output_names]
eids_qubit_ordered = [
eids_sorted[qnames_graph_ordered.index(q)] for q in self._qubit_names_ilo
] # Order eid's in the same way as qnames_graph_ordered as compared to ILO
Expand Down Expand Up @@ -360,7 +366,7 @@ def _get_tn_indices(

@staticmethod
def _order_edges_for_multiqubit_gate(
edge_indices: DefaultDict[Any, List[Tuple[Any, int]]],
edge_indices: defaultdict[Any, list[tuple[Any, int]]],
edges: OutMultiEdgeView,
edges_data: OutMultiEdgeDataView,
offset: int,
Expand Down Expand Up @@ -574,7 +580,7 @@ def __init__(
self._logger = set_logger("PauliOperatorTensorNetwork", loglevel)
self._pauli_tensors = [self.PAULI[pauli.name] for pauli in paulis.map.values()]
self._logger.debug(f"Pauli tensors: {self._pauli_tensors}")
qubits = [q for q in paulis.map.keys()]
qubits = [q for q in paulis.map]
# qubit_names = [
# "".join([q.reg_name, "".join([f"[{str(i)}]" for i in q.index])])
# for q in paulis.map.keys()
Expand Down Expand Up @@ -652,7 +658,7 @@ def _make_interleaved(self) -> list:
return tn_concatenated


def tk_to_tensor_network(tkc: Circuit) -> List[Union[NDArray, List]]:
def tk_to_tensor_network(tkc: Circuit) -> list[Union[NDArray, list]]:
"""Converts pytket circuit into a tensor network.

Args:
Expand Down
Loading
Loading