Skip to content

Commit

Permalink
Renamed tnstate to structured_state
Browse files Browse the repository at this point in the history
  • Loading branch information
PabloAndresCQ committed Feb 2, 2024
1 parent 3f1a946 commit 1221eac
Show file tree
Hide file tree
Showing 15 changed files with 1,223 additions and 1,225 deletions.
2 changes: 1 addition & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ API documentation

.. toctree::
modules/fullTN.rst
modules/tnstate.rst
modules/structured_state.rst
61 changes: 61 additions & 0 deletions docs/modules/structured_state.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
Structured state evolution
==========================

.. automodule:: pytket.extensions.cutensornet.structured_state


Simulation
~~~~~~~~~~

.. autofunction:: pytket.extensions.cutensornet.structured_state.simulate

.. autoenum:: pytket.extensions.cutensornet.structured_state.SimulationAlgorithm()
:members:

.. autoclass:: pytket.extensions.cutensornet.structured_state.Config()

.. automethod:: __init__

.. autoclass:: pytket.extensions.cutensornet.structured_state.CuTensorNetHandle


Classes
~~~~~~~

.. autoclass:: pytket.extensions.cutensornet.structured_state.StructuredState()

.. automethod:: __init__
.. automethod:: is_valid
.. automethod:: apply_gate
.. automethod:: apply_scalar
.. automethod:: vdot
.. automethod:: sample
.. automethod:: measure
.. automethod:: postselect
.. automethod:: expectation_value
.. automethod:: get_fidelity
.. automethod:: get_statevector
.. automethod:: get_amplitude
.. automethod:: get_qubits
.. automethod:: get_byte_size
.. automethod:: get_device_id
.. automethod:: update_libhandle
.. automethod:: copy

.. autoclass:: pytket.extensions.cutensornet.structured_state.TTNxGate()

.. automethod:: __init__

.. autoclass:: pytket.extensions.cutensornet.structured_state.MPSxGate()

.. automethod:: __init__

.. autoclass:: pytket.extensions.cutensornet.structured_state.MPSxMPO()

.. automethod:: __init__


Miscellaneous
~~~~~~~~~~~~~

.. autofunction:: pytket.extensions.cutensornet.structured_state.prepare_circuit_mps
61 changes: 0 additions & 61 deletions docs/modules/tnstate.rst

This file was deleted.

2 changes: 1 addition & 1 deletion examples/mpi/mpi_overlap_bcast_mps.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@

from pytket.circuit import Circuit, fresh_symbol

from pytket.extensions.cutensornet.tnstate import (
from pytket.extensions.cutensornet.structured_state import (
simulate,
Config,
SimulationAlgorithm,
Expand Down
2,190 changes: 1,094 additions & 1,096 deletions examples/mps_tutorial.ipynb

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
https://github.com/CQCL/pytket-cutensornet.
"""

from .general import CuTensorNetHandle, Config, TNState
from .general import CuTensorNetHandle, Config, StructuredState
from .simulation import SimulationAlgorithm, simulate, prepare_circuit_mps

from .mps import DirMPS, MPS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None:


class Config:
"""Configuration class for simulation using ``TNState``."""
"""Configuration class for simulation using ``StructuredState``."""

def __init__(
self,
Expand All @@ -85,7 +85,7 @@ def __init__(
optim_delta: float = 1e-5,
loglevel: int = logging.WARNING,
):
"""Instantiate a configuration object for ``TNState`` simulation.
"""Instantiate a configuration object for ``StructuredState`` simulation.
Note:
Providing both a custom ``chi`` and ``truncation_fidelity`` will raise an
Expand Down Expand Up @@ -192,7 +192,7 @@ def copy(self) -> Config:
)


class TNState(ABC):
class StructuredState(ABC):
"""Class representing a Tensor Network state."""

@abstractmethod
Expand All @@ -205,8 +205,8 @@ def is_valid(self) -> bool:
raise NotImplementedError(f"Method not implemented in {type(self).__name__}.")

@abstractmethod
def apply_gate(self, gate: Command) -> TNState:
"""Applies the gate to the TNState.
def apply_gate(self, gate: Command) -> StructuredState:
"""Applies the gate to the StructuredState.
Args:
gate: The gate to be applied.
Expand All @@ -221,7 +221,7 @@ def apply_gate(self, gate: Command) -> TNState:
raise NotImplementedError(f"Method not implemented in {type(self).__name__}.")

@abstractmethod
def apply_scalar(self, scalar: complex) -> TNState:
def apply_scalar(self, scalar: complex) -> StructuredState:
"""Multiplies the state by a complex number.
Args:
Expand All @@ -233,17 +233,17 @@ def apply_scalar(self, scalar: complex) -> TNState:
raise NotImplementedError(f"Method not implemented in {type(self).__name__}.")

@abstractmethod
def vdot(self, other: TNState) -> complex:
def vdot(self, other: StructuredState) -> complex:
"""Obtain the inner product of the two states: ``<self|other>``.
It can be used to compute the squared norm of a state ``tnstate`` as
``tnstate.vdot(tnstate)``. The tensors within the state are not modified.
It can be used to compute the squared norm of a state ``state`` as
``state.vdot(state)``. The tensors within the state are not modified.
Note:
The state that is conjugated is ``self``.
Args:
other: The other ``TNState``.
other: The other ``StructuredState``.
Returns:
The resulting complex number.
Expand All @@ -260,7 +260,7 @@ def sample(self) -> dict[Qubit, int]:
Notes:
The contents of ``self`` are not updated. This is equivalent to applying
``tnstate = self.copy()`` then ``tnstate.measure(tnstate.get_qubits())``.
``state = self.copy()`` then ``state.measure(state.get_qubits())``.
Returns:
A dictionary mapping each qubit in the state to its 0 or 1 outcome.
Expand Down Expand Up @@ -348,7 +348,7 @@ def get_amplitude(self, state: int) -> complex:
"""Returns the amplitude of the chosen computational state.
Notes:
The result is equivalent to ``tnstate.get_statevector[b]``, but this method
The result is equivalent to ``state.get_statevector[b]``, but this method
is faster when querying a single amplitude (or just a few).
Args:
Expand Down Expand Up @@ -390,7 +390,7 @@ def update_libhandle(self, libhandle: CuTensorNetHandle) -> None:
raise NotImplementedError(f"Method not implemented in {type(self).__name__}.")

@abstractmethod
def copy(self) -> TNState:
def copy(self) -> StructuredState:
"""Returns a deep copy of ``self`` on the same device."""
raise NotImplementedError(f"Method not implemented in {type(self).__name__}.")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

from pytket.extensions.cutensornet.general import set_logger

from .general import CuTensorNetHandle, Config, TNState, Tensor
from .general import CuTensorNetHandle, Config, StructuredState, Tensor


class DirMPS(Enum):
Expand All @@ -44,7 +44,7 @@ class DirMPS(Enum):
RIGHT = 1


class MPS(TNState):
class MPS(StructuredState):
"""Represents a state as a Matrix Product State.
Attributes:
Expand Down Expand Up @@ -205,7 +205,7 @@ def apply_gate(self, gate: Command) -> MPS:

return self

def apply_scalar(self, scalar: complex) -> TNState:
def apply_scalar(self, scalar: complex) -> MPS:
"""Multiplies the state by a complex number.
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@
from pytket.predicates import CompilationUnit

from pytket.extensions.cutensornet.general import set_logger
from .general import CuTensorNetHandle, Config, TNState
from .general import CuTensorNetHandle, Config, StructuredState
from .mps_gate import MPSxGate
from .mps_mpo import MPSxMPO
from .ttn_gate import TTNxGate


class SimulationAlgorithm(Enum):
"""An enum to refer to the TNState contraction algorithm.
"""An enum to refer to the StructuredState contraction algorithm.
Each enum value corresponds to the class with the same name; see its docs for
information about the algorithm.
Expand All @@ -51,12 +51,12 @@ def simulate(
circuit: Circuit,
algorithm: SimulationAlgorithm,
config: Config,
) -> TNState:
"""Simulates the circuit and returns the ``TNState`` representing the final state.
) -> StructuredState:
"""Simulates the circuit and returns the ``StructuredState`` representing the final state.
Note:
A ``libhandle`` should be created via a ``with CuTensorNet() as libhandle:``
statement. The device where the ``TNState`` is stored will match the one
statement. The device where the ``StructuredState`` is stored will match the one
specified by the library handle.
The input ``circuit`` must be composed of one-qubit and two-qubit gates only.
Expand All @@ -70,7 +70,7 @@ def simulate(
config: The configuration object for simulation.
Returns:
An instance of ``TNState`` containing (an approximation of) the final state
An instance of ``StructuredState`` containing (an approximation of) the final state
of the circuit. The instance be of the class matching ``algorithm``.
"""
logger = set_logger("Simulation", level=config.loglevel)
Expand All @@ -79,15 +79,15 @@ def simulate(
"Ordering the gates in the circuit to reduce canonicalisation overhead."
)
if algorithm == SimulationAlgorithm.MPSxGate:
tnstate = MPSxGate( # type: ignore
state = MPSxGate( # type: ignore
libhandle,
circuit.qubits,
config,
)
sorted_gates = _get_sorted_gates(circuit, algorithm)

elif algorithm == SimulationAlgorithm.MPSxMPO:
tnstate = MPSxMPO( # type: ignore
state = MPSxMPO( # type: ignore
libhandle,
circuit.qubits,
config,
Expand All @@ -96,7 +96,7 @@ def simulate(

elif algorithm == SimulationAlgorithm.TTNxGate:
qubit_partition = _get_qubit_partition(circuit, config.leaf_size)
tnstate = TTNxGate( # type: ignore
state = TTNxGate( # type: ignore
libhandle,
qubit_partition,
config,
Expand All @@ -106,19 +106,19 @@ def simulate(
logger.info("Running simulation...")
# Apply the gates
for i, g in enumerate(sorted_gates):
tnstate.apply_gate(g)
state.apply_gate(g)
logger.info(f"Progress... {(100*i) // len(sorted_gates)}%")

# Apply the batched operations that are left (if any)
tnstate._flush()
state._flush()

# Apply the circuit's phase to the state
tnstate.apply_scalar(np.exp(1j * np.pi * circuit.phase))
state.apply_scalar(np.exp(1j * np.pi * circuit.phase))

logger.info("Simulation completed.")
logger.info(f"Final TNState size={tnstate.get_byte_size() / 2**20} MiB")
logger.info(f"Final TNState fidelity={tnstate.fidelity}")
return tnstate
logger.info(f"Final StructuredState size={state.get_byte_size() / 2**20} MiB")
logger.info(f"Final StructuredState fidelity={state.fidelity}")
return state


def prepare_circuit_mps(circuit: Circuit) -> tuple[Circuit, dict[Qubit, Qubit]]:
Expand Down
Loading

0 comments on commit 1221eac

Please sign in to comment.