From 2eac0ca9a61655b58d95e18c816fcdce5cdeabf8 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Mon, 4 Nov 2019 16:22:32 -0800 Subject: [PATCH 01/39] Initial attempt at quantum classes. --- tensornetwork/quantum/quantum.py | 189 +++++++++++++++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 tensornetwork/quantum/quantum.py diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py new file mode 100644 index 000000000..08f482c8b --- /dev/null +++ b/tensornetwork/quantum/quantum.py @@ -0,0 +1,189 @@ +# Copyright 2019 The TensorNetwork Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Abstractions for quantum states and operators.""" + +from tensornetwork.network_components import connect +from tensornetwork.network_operations import reachable, get_all_nodes, copy, get_subgraph_dangling + + +def QuantumConstructor(out_edges, in_edges, ref_nodes=None): + if len(out_edges) == 0 and len(in_edges) == 0: + return QuantumScalar(ref_nodes) + elif len(out_edges) == 0: + return QuantumBra(in_edges) + elif len(in_edges) == 0: + return QuantumKet(out_edges) + return QuantumOperator(out_edges, in_edges) + + +def check_hilberts(edges_1, edges_2): + if len(edges_1) != len(edges_2): + raise ValueError("Hilbert-space mismatch: Cannot connect {} subsystems " + "with {} subsystems.".format(len(edges_1), len(edges_2))) + + for (i, (e1, e2)) in enumerate(zip(edges_1, edges_2)): + if e1.dimension != e2.dimension: + raise ValueError("Hilbert-space mismatch on subsystems {}: Input " + "dimension {} != output dimension {}.".format( + i, e1.dimension, e2.dimension)) + + +class QuantumScalar(): + def __init__(self, ref_nodes): + self.ref_nodes = ref_nodes + self.check_scalar() + + @property + def nodes(self): + """All tensor-network nodes involved in the scalar. + """ + return reachable(self.ref_nodes) + + def check_scalar(self): + """Check that the defining network is scalar valued. + """ + dangling_edges = get_subgraph_dangling(self.nodes()) + return len(dangling_edges) == 0 + + +class QuantumOperator(): + """Represents an operator via a tensor network. + + Can be used to do simple linear algebra with tensor networks. + """ + def __init__(self, out_edges, in_edges): + self.out_edges = list(out_edges) + self.in_edges = list(in_edges) + + @classmethod + def from_local(cls, operator, out_indices, in_indices, system_edges): + """Construct a global operator from a local one. + """ + # FIXME: Would be natural to do this with nodeless Edges, but an Edge + # is currently assumed to have at least one Node attached. + raise NotImplementedError() + + @property + def nodes(self): + """All tensor-network nodes involved in the operator. + """ + return reachable(get_all_nodes(self.out_edges + self.in_edges)) + + @property + def shape_in(self): + return [e.dimension for e in self.in_edges] + + @property + def shape_out(self): + return [e.dimension for e in self.out_edges] + + def adjoint(self): + """The adjoint of the operator. + + This creates a new `QuantumOperator` with complex-conjugate copies of all + tensors in the network and with the input and output edges switched. + """ + _, edge_dict = copy(self.nodes, True) + out_edges = [edge_dict[e] for e in self.in_edges] + in_edges = [edge_dict[e] for e in self.out_edges] + return QuantumConstructor(out_edges, in_edges) + + def trace(self): + """The trace of the operator. + """ + return self.partial_trace(range(len(self.in_edges))) + + def norm(self): + """The norm of the operator. + This is the 2-norm (Frobenius norm), or Hilbert-Schmidt norm. + """ + return (self.adjoint() @ self).trace() + + def partial_trace(self, subsystems_to_trace_out): + """The partial trace of the operator. + + Subsystems to trace out are supplied as indicies, so that dangling edges + are connected to eachother as: + `out_edges[i] ^ in_edges[i] for i in subsystems_to_trace_out` + + This does not modify the original network. The original ordering of the + remaining subsystems is maintained. + + Args: + subsystems_to_trace_out: Indices of subsystems to trace out. + Returns: + A new QuantumOperator or QuantumScalar representing the result. + """ + check_hilberts(self.in_edges, self.out_edges) + + out_edges_trace = [self.out_edges[i] for i in subsystems_to_trace_out] + in_edges_trace = [self.in_edges[i] for i in subsystems_to_trace_out] + + nodes_dict, edge_dict = copy(self.nodes, False) + for (e1, e2) in zip(out_edges_trace, in_edges_trace): + edge_dict[e1] = edge_dict[e1] ^ edge_dict[e2] + + # get leftover edges in the original order + out_edges_trace = set(out_edges_trace) + in_edges_trace = set(in_edges_trace) + out_edges = [edge_dict[e] for e in self.out_edges + if e not in out_edges_trace] + in_edges = [edge_dict[e] for e in self.in_edges + if e not in in_edges_trace] + ref_nodes = [n for _, n in nodes_dict.items()] + + return QuantumConstructor(out_edges, in_edges, ref_nodes) + + def __matmul__(self, other): + check_hilberts(self.in_edges, other.out_edges) + + # copy all nodes involved in the two operators + net = reachable(get_all_nodes( + self.out_edges + self.in_edges + other.out_edges + other.in_edges)) + + _, edge_dict = copy(net, False) + + # connect edges to create network for the result + for (e1, e2) in zip(self.in_edges, other.out_edges): + edge_dict[e1] = edge_dict[e1] ^ edge_dict[e2] + + in_edges = [edge_dict[e] for e in other.in_edges] + out_edges = [edge_dict[e] for e in self.out_edges] + + return QuantumConstructor(out_edges, in_edges) + + +class QuantumKet(QuantumOperator): + def __init__(self, subsystem_edges): + super().__init__(subsystem_edges, []) + + @property + def subsystem_edges(self): + return self.out_edges + + def projector(self): + return self @ self.adjoint() + + def reduced_density(self, subsystems_to_trace_out): + rho = self.projector() + return rho.partial_trace(subsystems_to_trace_out) + + +class QuantumBra(QuantumOperator): + def __init__(self, subsystem_edges): + super().__init__([], subsystem_edges) + + @property + def subsystem_edges(self): + return self.in_edges \ No newline at end of file From 8fdb613b4fb7c3d36a657ccebfbaa32e4d4f2c1e Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Mon, 4 Nov 2019 17:04:54 -0800 Subject: [PATCH 02/39] .tensor() and QuantumIdentity. --- tensornetwork/quantum/quantum.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 08f482c8b..d9ef212ce 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -13,7 +13,7 @@ # limitations under the License. """Abstractions for quantum states and operators.""" -from tensornetwork.network_components import connect +from tensornetwork.network_components import Edge, connect from tensornetwork.network_operations import reachable, get_all_nodes, copy, get_subgraph_dangling @@ -66,14 +66,6 @@ def __init__(self, out_edges, in_edges): self.out_edges = list(out_edges) self.in_edges = list(in_edges) - @classmethod - def from_local(cls, operator, out_indices, in_indices, system_edges): - """Construct a global operator from a local one. - """ - # FIXME: Would be natural to do this with nodeless Edges, but an Edge - # is currently assumed to have at least one Node attached. - raise NotImplementedError() - @property def nodes(self): """All tensor-network nodes involved in the operator. @@ -163,6 +155,22 @@ def __matmul__(self, other): return QuantumConstructor(out_edges, in_edges) + def tensor(self, other): + """Tensor product with another operator. + """ + _, edges_dict = copy(self.nodes | other.nodes, False) + + in_edges = [edges_dict[e] for e in (self.in_edges + other.in_edges)] + out_edges = [edges_dict[e] for e in (self.out_edges + other.out_edges)] + + return QuantumConstructor(out_edges, in_edges) + + +class QuantumIdentity(QuantumOperator): + def __init__(self, num_subsystems): + edges = [Edge(None, None) for _ in range(num_subsystems)] + super().__init__(edges, edges) + class QuantumKet(QuantumOperator): def __init__(self, subsystem_edges): From 164a859244862db4019151ad6dbab001f6a6c42a Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Tue, 5 Nov 2019 16:51:22 -0800 Subject: [PATCH 03/39] check_hilberts -> check_spaces --- tensornetwork/quantum/quantum.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index d9ef212ce..98c77d180 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -27,7 +27,16 @@ def QuantumConstructor(out_edges, in_edges, ref_nodes=None): return QuantumOperator(out_edges, in_edges) -def check_hilberts(edges_1, edges_2): +def check_spaces(edges_1, edges_2): + """Check the vector spaces represented by two lists of edges are compatible. + + The number of edges must be the same and the dimensions of each pair of edges + must match. Otherwise, an exception is raised. + + Args: + edges_1: List of edges representing a many-body Hilbert space. + edges_2: List of edges representing a many-body Hilbert space. + """ if len(edges_1) != len(edges_2): raise ValueError("Hilbert-space mismatch: Cannot connect {} subsystems " "with {} subsystems.".format(len(edges_1), len(edges_2))) @@ -117,7 +126,7 @@ def partial_trace(self, subsystems_to_trace_out): Returns: A new QuantumOperator or QuantumScalar representing the result. """ - check_hilberts(self.in_edges, self.out_edges) + check_spaces(self.in_edges, self.out_edges) out_edges_trace = [self.out_edges[i] for i in subsystems_to_trace_out] in_edges_trace = [self.in_edges[i] for i in subsystems_to_trace_out] @@ -138,7 +147,7 @@ def partial_trace(self, subsystems_to_trace_out): return QuantumConstructor(out_edges, in_edges, ref_nodes) def __matmul__(self, other): - check_hilberts(self.in_edges, other.out_edges) + check_spaces(self.in_edges, other.out_edges) # copy all nodes involved in the two operators net = reachable(get_all_nodes( From 04d6fc370132e13628f8e45429526eac65b9a5ae Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 18:56:06 -0800 Subject: [PATCH 04/39] Add some blurb. --- tensornetwork/quantum/quantum.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 98c77d180..971a83718 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -11,7 +11,14 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Abstractions for quantum states and operators.""" +"""Abstractions for quantum vectors and operators. + +Quantum mechanics involves a lot of linear algebra on vector spaces that often +have a preferred tensor-product factorization. Tensor networks are a natural +way to represent vectors and operators (matrices) involving these spaces. Hence +we provide some simple abstractions to ease linear algebra operations in which +the vectors and operators are represented by tensor networks. +""" from tensornetwork.network_components import Edge, connect from tensornetwork.network_operations import reachable, get_all_nodes, copy, get_subgraph_dangling From d8a7eec09f3942d2b5b245cd33497dec33cd5d46 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 18:59:02 -0800 Subject: [PATCH 05/39] Rename to Qu. --- tensornetwork/quantum/quantum.py | 69 +++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 24 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 971a83718..ec1390228 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -21,17 +21,31 @@ """ from tensornetwork.network_components import Edge, connect -from tensornetwork.network_operations import reachable, get_all_nodes, copy, get_subgraph_dangling +from tensornetwork.network_operations import reachable, get_all_nodes, copy +from tensornetwork.network_operations import get_subgraph_dangling -def QuantumConstructor(out_edges, in_edges, ref_nodes=None): +def quantum_constructor(out_edges, in_edges, ref_nodes=None): + """Constructs an appropriately specialized QuOperator or QuScalar. + + If there are no edges, creates a QuScalar. If the are only output (input) + edges, construct a QuVector (QuAdjointVector). Otherwise construct a + QuOperator. + + Args: + out_edges: output edges. + in_edges: in edges. + ref_nodes: reference nodes for the tensor network (in case scalar). + Returns: + The object. + """ if len(out_edges) == 0 and len(in_edges) == 0: - return QuantumScalar(ref_nodes) + return QuScalar(ref_nodes) elif len(out_edges) == 0: - return QuantumBra(in_edges) + return QuAdjointVector(in_edges) elif len(in_edges) == 0: - return QuantumKet(out_edges) - return QuantumOperator(out_edges, in_edges) + return QuVector(out_edges) + return QuOperator(out_edges, in_edges) def check_spaces(edges_1, edges_2): @@ -46,18 +60,21 @@ def check_spaces(edges_1, edges_2): """ if len(edges_1) != len(edges_2): raise ValueError("Hilbert-space mismatch: Cannot connect {} subsystems " - "with {} subsystems.".format(len(edges_1), len(edges_2))) + "with {} subsystems.".format(len(edges_1), len(edges_2))) for (i, (e1, e2)) in enumerate(zip(edges_1, edges_2)): if e1.dimension != e2.dimension: raise ValueError("Hilbert-space mismatch on subsystems {}: Input " - "dimension {} != output dimension {}.".format( - i, e1.dimension, e2.dimension)) + "dimension {} != output dimension {}.".format( + i, e1.dimension, e2.dimension)) -class QuantumScalar(): +class QuScalar(): def __init__(self, ref_nodes): - self.ref_nodes = ref_nodes + if not ref_nodes: + raise ValueError("At least one reference node is required for a " + "QuScalar. None provided!") + self.ref_nodes = set(ref_nodes) self.check_scalar() @property @@ -69,16 +86,20 @@ def nodes(self): def check_scalar(self): """Check that the defining network is scalar valued. """ - dangling_edges = get_subgraph_dangling(self.nodes()) + dangling_edges = get_subgraph_dangling(self.nodes) return len(dangling_edges) == 0 -class QuantumOperator(): +class QuOperator(): """Represents an operator via a tensor network. Can be used to do simple linear algebra with tensor networks. """ def __init__(self, out_edges, in_edges): + # TODO: Decide whether the user must also supply all nodes involved. + # More flexible if not (e.g. a QuOperator can represent a vector + # of operators if there is an extra dangling Edge), better error + # checking if so. self.out_edges = list(out_edges) self.in_edges = list(in_edges) @@ -99,13 +120,13 @@ def shape_out(self): def adjoint(self): """The adjoint of the operator. - This creates a new `QuantumOperator` with complex-conjugate copies of all + This creates a new `QuOperator` with complex-conjugate copies of all tensors in the network and with the input and output edges switched. """ _, edge_dict = copy(self.nodes, True) out_edges = [edge_dict[e] for e in self.in_edges] in_edges = [edge_dict[e] for e in self.out_edges] - return QuantumConstructor(out_edges, in_edges) + return quantum_constructor(out_edges, in_edges) def trace(self): """The trace of the operator. @@ -121,7 +142,7 @@ def norm(self): def partial_trace(self, subsystems_to_trace_out): """The partial trace of the operator. - Subsystems to trace out are supplied as indicies, so that dangling edges + Subsystems to trace out are supplied as indices, so that dangling edges are connected to eachother as: `out_edges[i] ^ in_edges[i] for i in subsystems_to_trace_out` @@ -131,7 +152,7 @@ def partial_trace(self, subsystems_to_trace_out): Args: subsystems_to_trace_out: Indices of subsystems to trace out. Returns: - A new QuantumOperator or QuantumScalar representing the result. + A new QuOperator or QuScalar representing the result. """ check_spaces(self.in_edges, self.out_edges) @@ -146,12 +167,12 @@ def partial_trace(self, subsystems_to_trace_out): out_edges_trace = set(out_edges_trace) in_edges_trace = set(in_edges_trace) out_edges = [edge_dict[e] for e in self.out_edges - if e not in out_edges_trace] + if e not in out_edges_trace] in_edges = [edge_dict[e] for e in self.in_edges - if e not in in_edges_trace] + if e not in in_edges_trace] ref_nodes = [n for _, n in nodes_dict.items()] - return QuantumConstructor(out_edges, in_edges, ref_nodes) + return quantum_constructor(out_edges, in_edges, ref_nodes) def __matmul__(self, other): check_spaces(self.in_edges, other.out_edges) @@ -169,7 +190,7 @@ def __matmul__(self, other): in_edges = [edge_dict[e] for e in other.in_edges] out_edges = [edge_dict[e] for e in self.out_edges] - return QuantumConstructor(out_edges, in_edges) + return quantum_constructor(out_edges, in_edges, ref_nodes) def tensor(self, other): """Tensor product with another operator. @@ -182,13 +203,13 @@ def tensor(self, other): return QuantumConstructor(out_edges, in_edges) -class QuantumIdentity(QuantumOperator): +class QuIdentity(QuOperator): def __init__(self, num_subsystems): edges = [Edge(None, None) for _ in range(num_subsystems)] super().__init__(edges, edges) -class QuantumKet(QuantumOperator): +class QuVector(QuOperator): def __init__(self, subsystem_edges): super().__init__(subsystem_edges, []) @@ -204,7 +225,7 @@ def reduced_density(self, subsystems_to_trace_out): return rho.partial_trace(subsystems_to_trace_out) -class QuantumBra(QuantumOperator): +class QuAdjointVector(QuOperator): def __init__(self, subsystem_edges): super().__init__([], subsystem_edges) From 76d682b246b1389b9d6964173be82a45d529f46e Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 18:59:46 -0800 Subject: [PATCH 06/39] Finish Qu. --- tensornetwork/quantum/quantum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index ec1390228..7e09437e7 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -200,7 +200,7 @@ def tensor(self, other): in_edges = [edges_dict[e] for e in (self.in_edges + other.in_edges)] out_edges = [edges_dict[e] for e in (self.out_edges + other.out_edges)] - return QuantumConstructor(out_edges, in_edges) + return quantum_constructor(out_edges, in_edges) class QuIdentity(QuOperator): From 52ac9e192d6df24c82dbb5f045e60e54804aeecf Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 19:00:14 -0800 Subject: [PATCH 07/39] Fix matmul in case operators share network components. --- tensornetwork/quantum/quantum.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 7e09437e7..acea76112 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -177,28 +177,33 @@ def partial_trace(self, subsystems_to_trace_out): def __matmul__(self, other): check_spaces(self.in_edges, other.out_edges) - # copy all nodes involved in the two operators - net = reachable(get_all_nodes( - self.out_edges + self.in_edges + other.out_edges + other.in_edges)) - - _, edge_dict = copy(net, False) + # Copy all nodes involved in the two operators. + # We must do this separately for self and other, in case self and other + # were define via the same network components (e.g. if self === other). + nodes_dict1, edge_dict1 = copy(self.nodes, False) + nodes_dict2, edge_dict2 = copy(other.nodes, False) # connect edges to create network for the result for (e1, e2) in zip(self.in_edges, other.out_edges): - edge_dict[e1] = edge_dict[e1] ^ edge_dict[e2] + _ = edge_dict1[e1] ^ edge_dict2[e2] - in_edges = [edge_dict[e] for e in other.in_edges] - out_edges = [edge_dict[e] for e in self.out_edges] + in_edges = [edge_dict2[e] for e in other.in_edges] + out_edges = [edge_dict1[e] for e in self.out_edges] + ref_nodes = [n for _, n in nodes_dict1.items()] + ref_nodes += [n for _, n in nodes_dict2.items()] return quantum_constructor(out_edges, in_edges, ref_nodes) def tensor(self, other): """Tensor product with another operator. """ - _, edges_dict = copy(self.nodes | other.nodes, False) + _, edges_dict1 = copy(self.nodes, False) + _, edges_dict2 = copy(other.nodes, False) - in_edges = [edges_dict[e] for e in (self.in_edges + other.in_edges)] - out_edges = [edges_dict[e] for e in (self.out_edges + other.out_edges)] + in_edges = ([edges_dict1[e] for e in self.in_edges] + + [edges_dict2[e] for e in other.in_edges]) + out_edges = ([edges_dict1[e] for e in self.out_edges] + + [edges_dict2[e] for e in other.out_edges]) return quantum_constructor(out_edges, in_edges) From 6deb6489771547ba95a6e9a7f84adca74c641443 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 19:01:30 -0800 Subject: [PATCH 08/39] Add some scalar methods. --- tensornetwork/quantum/quantum.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index acea76112..24f3e5e15 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -89,6 +89,21 @@ def check_scalar(self): dangling_edges = get_subgraph_dangling(self.nodes) return len(dangling_edges) == 0 + def trace(self): + return self + + def __mul__(self, other): + if isinstance(other, QuScalar): + nodes_dict1, _ = copy(self.nodes, False) + nodes_dict2, _ = copy(other.nodes, False) + ref_nodes = ([n for _, n in nodes_dict1.items()] + + [n for _, n in nodes_dict2.items()]) + return QuScalar(ref_nodes) + elif isinstance(other, QuOperator): + raise NotImplementedError("Not yet sure how best to handle scalars... " + "Perhaps they should be folded into " + "QuOperator.") + class QuOperator(): """Represents an operator via a tensor network. From f020c4893c8d1cd4a7bf5c3ff07458211385e765 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 6 Nov 2019 19:02:08 -0800 Subject: [PATCH 09/39] Improve a docstring. --- tensornetwork/quantum/quantum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 24f3e5e15..0bb2abcc8 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -150,7 +150,7 @@ def trace(self): def norm(self): """The norm of the operator. - This is the 2-norm (Frobenius norm), or Hilbert-Schmidt norm. + This is the 2-norm (also known as the Frobenius or Hilbert-Schmidt norm). """ return (self.adjoint() @ self).trace() From d121a5f2ecc2072b5e1ce0582d5a25a35279b870 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 16:12:36 -0800 Subject: [PATCH 10/39] Redo scalars and make identity work using copy tensors. A QuOperator can now have a scalar component (disconnected scalar subnetwork). Also introduce `ignore_edges` for power users. --- tensornetwork/quantum/quantum.py | 184 +++++++++++++++++++------------ 1 file changed, 111 insertions(+), 73 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 0bb2abcc8..00c572772 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -20,12 +20,12 @@ the vectors and operators are represented by tensor networks. """ -from tensornetwork.network_components import Edge, connect -from tensornetwork.network_operations import reachable, get_all_nodes, copy +from tensornetwork.network_components import Edge, connect, CopyNode +from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling -def quantum_constructor(out_edges, in_edges, ref_nodes=None): +def quantum_constructor(out_edges, in_edges, ref_nodes=None, ignore_edges=None): """Constructs an appropriately specialized QuOperator or QuScalar. If there are no edges, creates a QuScalar. If the are only output (input) @@ -35,17 +35,27 @@ def quantum_constructor(out_edges, in_edges, ref_nodes=None): Args: out_edges: output edges. in_edges: in edges. - ref_nodes: reference nodes for the tensor network (in case scalar). + ref_nodes: reference nodes for the tensor network (needed if there is a + scalar component). + ignore_edges: edges to ignore when checking the dimensionality of the + tensor network. Returns: The object. """ if len(out_edges) == 0 and len(in_edges) == 0: - return QuScalar(ref_nodes) + return QuScalar(ref_nodes, ignore_edges) elif len(out_edges) == 0: - return QuAdjointVector(in_edges) + return QuAdjointVector(in_edges, ref_nodes, ignore_edges) elif len(in_edges) == 0: - return QuVector(out_edges) - return QuOperator(out_edges, in_edges) + return QuVector(out_edges, ref_nodes, ignore_edges) + return QuOperator(out_edges, in_edges, ref_nodes, ignore_edges) + + +def identity(shape): + nodes = [CopyNode(2, d) for d in shape] + out_edges = [n[0] for n in nodes] + in_edges = [n[1] for n in nodes] + return quantum_constructor(out_edges, in_edges) def check_spaces(edges_1, edges_2): @@ -69,60 +79,31 @@ def check_spaces(edges_1, edges_2): i, e1.dimension, e2.dimension)) -class QuScalar(): - def __init__(self, ref_nodes): - if not ref_nodes: - raise ValueError("At least one reference node is required for a " - "QuScalar. None provided!") - self.ref_nodes = set(ref_nodes) - self.check_scalar() - - @property - def nodes(self): - """All tensor-network nodes involved in the scalar. - """ - return reachable(self.ref_nodes) - - def check_scalar(self): - """Check that the defining network is scalar valued. - """ - dangling_edges = get_subgraph_dangling(self.nodes) - return len(dangling_edges) == 0 - - def trace(self): - return self - - def __mul__(self, other): - if isinstance(other, QuScalar): - nodes_dict1, _ = copy(self.nodes, False) - nodes_dict2, _ = copy(other.nodes, False) - ref_nodes = ([n for _, n in nodes_dict1.items()] + - [n for _, n in nodes_dict2.items()]) - return QuScalar(ref_nodes) - elif isinstance(other, QuOperator): - raise NotImplementedError("Not yet sure how best to handle scalars... " - "Perhaps they should be folded into " - "QuOperator.") - - class QuOperator(): """Represents an operator via a tensor network. Can be used to do simple linear algebra with tensor networks. """ - def __init__(self, out_edges, in_edges): + def __init__(self, out_edges, in_edges, ref_nodes=None, ignore_edges=None): # TODO: Decide whether the user must also supply all nodes involved. # More flexible if not (e.g. a QuOperator can represent a vector # of operators if there is an extra dangling Edge), better error # checking if so. + if len(in_edges) == 0 and len(out_edges) == 0 and not ref_nodes: + raise ValueError("At least one reference node is required to specify a " + "scalar. None provided!") self.out_edges = list(out_edges) self.in_edges = list(in_edges) + self.ignore_edges = set(ignore_edges) if ignore_edges else set() + self.ref_nodes = set(ref_nodes) if ref_nodes else set() + self.check_network() @property def nodes(self): """All tensor-network nodes involved in the operator. """ - return reachable(get_all_nodes(self.out_edges + self.in_edges)) + return reachable( + get_all_nodes(self.out_edges + self.in_edges) | self.ref_nodes) @property def shape_in(self): @@ -132,16 +113,38 @@ def shape_in(self): def shape_out(self): return [e.dimension for e in self.out_edges] + @property + def is_scalar(self): + return len(self.out_edges) == 0 and len(self.in_edges) == 0 + + @property + def is_vector(self): + return len(self.out_edges) > 0 and len(self.in_edges) == 0 + + @property + def is_adjoint_vector(self): + return len(self.out_edges) == 0 and len(self.in_edges) > 0 + + def check_network(self): + known_edges = set(self.in_edges) | set(self.out_edges) | self.ignore_edges + all_dangling_edges = get_subgraph_dangling(self.nodes) + if known_edges != all_dangling_edges: + raise ValueError("The network includes unexpected dangling edges (that " + "are not members of ignore_edges).") + def adjoint(self): """The adjoint of the operator. This creates a new `QuOperator` with complex-conjugate copies of all tensors in the network and with the input and output edges switched. """ - _, edge_dict = copy(self.nodes, True) + nodes_dict, edge_dict = copy(self.nodes, True) out_edges = [edge_dict[e] for e in self.in_edges] in_edges = [edge_dict[e] for e in self.out_edges] - return quantum_constructor(out_edges, in_edges) + ref_nodes = [nodes_dict[n] for n in self.ref_nodes] + ignore_edges = [edge_dict[e] for e in self.ignore_edges] + return quantum_constructor( + out_edges, in_edges, ref_nodes, ignore_edges) def trace(self): """The trace of the operator. @@ -186,52 +189,59 @@ def partial_trace(self, subsystems_to_trace_out): in_edges = [edge_dict[e] for e in self.in_edges if e not in in_edges_trace] ref_nodes = [n for _, n in nodes_dict.items()] + ignore_edges = [edge_dict[e] for e in self.ignore_edges] - return quantum_constructor(out_edges, in_edges, ref_nodes) + return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) def __matmul__(self, other): check_spaces(self.in_edges, other.out_edges) # Copy all nodes involved in the two operators. # We must do this separately for self and other, in case self and other - # were define via the same network components (e.g. if self === other). - nodes_dict1, edge_dict1 = copy(self.nodes, False) - nodes_dict2, edge_dict2 = copy(other.nodes, False) + # are defined via the same network components (e.g. if self === other). + nodes_dict1, edges_dict1 = copy(self.nodes, False) + nodes_dict2, edges_dict2 = copy(other.nodes, False) # connect edges to create network for the result for (e1, e2) in zip(self.in_edges, other.out_edges): - _ = edge_dict1[e1] ^ edge_dict2[e2] + _ = edges_dict1[e1] ^ edges_dict2[e2] - in_edges = [edge_dict2[e] for e in other.in_edges] - out_edges = [edge_dict1[e] for e in self.out_edges] - ref_nodes = [n for _, n in nodes_dict1.items()] - ref_nodes += [n for _, n in nodes_dict2.items()] + in_edges = [edges_dict2[e] for e in other.in_edges] + out_edges = [edges_dict1[e] for e in self.out_edges] + ref_nodes = ([n for _, n in nodes_dict1.items()] + + [n for _, n in nodes_dict2.items()]) + ignore_edges = ([edges_dict1[e] for e in self.ignore_edges] + + [edges_dict2[e] for e in other.ignore_edges]) - return quantum_constructor(out_edges, in_edges, ref_nodes) + return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def tensor(self, other): + def __mul__(self, other): + if self.is_scalar or other.is_scalar: + return self @ other + raise ValueError("Elementwise multiplication is only supported if at " + "least one of the arguments is a scalar.") + + def tensor_prod(self, other): """Tensor product with another operator. """ - _, edges_dict1 = copy(self.nodes, False) - _, edges_dict2 = copy(other.nodes, False) + nodes_dict1, edges_dict1 = copy(self.nodes, False) + nodes_dict2, edges_dict2 = copy(other.nodes, False) in_edges = ([edges_dict1[e] for e in self.in_edges] + [edges_dict2[e] for e in other.in_edges]) out_edges = ([edges_dict1[e] for e in self.out_edges] + [edges_dict2[e] for e in other.out_edges]) + ref_nodes = ([n for _, n in nodes_dict1.items()] + + [n for _, n in nodes_dict2.items()]) + ignore_edges = ([edges_dict1[e] for e in self.ignore_edges] + + [edges_dict2[e] for e in other.ignore_edges]) - return quantum_constructor(out_edges, in_edges) - - -class QuIdentity(QuOperator): - def __init__(self, num_subsystems): - edges = [Edge(None, None) for _ in range(num_subsystems)] - super().__init__(edges, edges) + return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) class QuVector(QuOperator): - def __init__(self, subsystem_edges): - super().__init__(subsystem_edges, []) + def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): + super().__init__(subsystem_edges, [], ref_nodes, ignore_edges) @property def subsystem_edges(self): @@ -246,9 +256,37 @@ def reduced_density(self, subsystems_to_trace_out): class QuAdjointVector(QuOperator): - def __init__(self, subsystem_edges): - super().__init__([], subsystem_edges) + def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): + super().__init__([], subsystem_edges, ref_nodes, ignore_edges) @property def subsystem_edges(self): - return self.in_edges \ No newline at end of file + return self.in_edges + + def projector(self): + return self.adjoint() @ self + + def reduced_density(self, subsystems_to_trace_out): + rho = self.projector() + return rho.partial_trace(subsystems_to_trace_out) + + +class QuScalar(QuOperator): + def __init__(self, ref_nodes, ignore_edges=None): + super().__init__([], [], ref_nodes, ignore_edges) + self.check_scalar() + + @property + def nodes(self): + """All tensor-network nodes involved in the scalar. + """ + return reachable(self.ref_nodes) + + def check_scalar(self): + """Check that the defining network is scalar valued. + """ + dangling_edges = get_subgraph_dangling(self.nodes) + return len(dangling_edges) == 0 + + def trace(self): + return self From c47aef61d526f4b761642338bcaf8b82031156e6 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 16:16:30 -0800 Subject: [PATCH 11/39] Remove obsolete parts of QuScalar. --- tensornetwork/quantum/quantum.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 00c572772..42977f771 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -274,19 +274,3 @@ def reduced_density(self, subsystems_to_trace_out): class QuScalar(QuOperator): def __init__(self, ref_nodes, ignore_edges=None): super().__init__([], [], ref_nodes, ignore_edges) - self.check_scalar() - - @property - def nodes(self): - """All tensor-network nodes involved in the scalar. - """ - return reachable(self.ref_nodes) - - def check_scalar(self): - """Check that the defining network is scalar valued. - """ - dangling_edges = get_subgraph_dangling(self.nodes) - return len(dangling_edges) == 0 - - def trace(self): - return self From 68cf9ad6ef32f5c2c174552744c753a311681a7d Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 16:46:27 -0800 Subject: [PATCH 12/39] Add contraction stuff. --- tensornetwork/quantum/quantum.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 42977f771..68ac0dee4 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -23,6 +23,7 @@ from tensornetwork.network_components import Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling +from tensornetwork.contractors import greedy def quantum_constructor(out_edges, in_edges, ref_nodes=None, ignore_edges=None): @@ -126,6 +127,13 @@ def is_adjoint_vector(self): return len(self.out_edges) == 0 and len(self.in_edges) > 0 def check_network(self): + for (i, e) in enumerate(self.out_edges): + if not e.is_dangling(): + raise ValueError("Output edge {} is not dangling!".format(i)) + for (i, e) in enumerate(self.in_edges): + if not e.is_dangling(): + raise ValueError("Input edge {} is not dangling!".format(i)) + known_edges = set(self.in_edges) | set(self.out_edges) | self.ignore_edges all_dangling_edges = get_subgraph_dangling(self.nodes) if known_edges != all_dangling_edges: @@ -238,6 +246,22 @@ def tensor_prod(self, other): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) + def contract(self, contractor=greedy): + """Contract the tensor network in place. + """ + self.ref_nodes = set([contractor(self.nodes)]) + return self + + def eval(self): + """Contracts the tensor network in place and returns the final tensor. + """ + self.contract() + nodes = self.nodes + if len(nodes) != 1: + raise ValueError("Node count '{}' > 1 after contraction!".format( + len(nodes))) + return list(nodes)[0].tensor + class QuVector(QuOperator): def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): From 3dac3b0554697147eab860193778c1796a84828a Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 17:05:30 -0800 Subject: [PATCH 13/39] Add from_tensor() constructors. --- tensornetwork/quantum/quantum.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 68ac0dee4..0f8df1363 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -20,7 +20,7 @@ the vectors and operators are represented by tensor networks. """ -from tensornetwork.network_components import Edge, connect, CopyNode +from tensornetwork.network_components import Node, Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling from tensornetwork.contractors import greedy @@ -99,6 +99,13 @@ def __init__(self, out_edges, in_edges, ref_nodes=None, ignore_edges=None): self.ref_nodes = set(ref_nodes) if ref_nodes else set() self.check_network() + @classmethod + def from_tensor(cls, tensor, out_axes, in_axes, backend=None): + n = Node(tensor, backend=backend) + out_edges = [n[i] for i in out_axes] + in_edges = [n[i] for i in in_axes] + return cls(out_edges, in_edges, set(n)) + @property def nodes(self): """All tensor-network nodes involved in the operator. @@ -267,6 +274,11 @@ class QuVector(QuOperator): def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): super().__init__(subsystem_edges, [], ref_nodes, ignore_edges) + @classmethod + def from_tensor(cls, tensor, backend=None): + n = Node(tensor, backend=backend) + return cls(n.get_all_edges()) + @property def subsystem_edges(self): return self.out_edges @@ -283,6 +295,11 @@ class QuAdjointVector(QuOperator): def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): super().__init__([], subsystem_edges, ref_nodes, ignore_edges) + @classmethod + def from_tensor(cls, tensor, backend=None): + n = Node(tensor, backend=backend) + return cls(n.get_all_edges()) + @property def subsystem_edges(self): return self.in_edges @@ -298,3 +315,8 @@ def reduced_density(self, subsystems_to_trace_out): class QuScalar(QuOperator): def __init__(self, ref_nodes, ignore_edges=None): super().__init__([], [], ref_nodes, ignore_edges) + + @classmethod + def from_tensor(cls, tensor, backend=None): + n = Node(tensor, backend=backend) + return cls(set(n)) From 93f459cbff77a34f648422b4c9e4c3344fb52b8d Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 17:12:30 -0800 Subject: [PATCH 14/39] Doctstring. --- tensornetwork/quantum/quantum.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 0f8df1363..62d6d7af7 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -26,7 +26,8 @@ from tensornetwork.contractors import greedy -def quantum_constructor(out_edges, in_edges, ref_nodes=None, ignore_edges=None): +def quantum_constructor(out_edges, in_edges, ref_nodes=None, + ignore_edges=None): """Constructs an appropriately specialized QuOperator or QuScalar. If there are no edges, creates a QuScalar. If the are only output (input) @@ -134,6 +135,12 @@ def is_adjoint_vector(self): return len(self.out_edges) == 0 and len(self.in_edges) > 0 def check_network(self): + """Check that the network has the expected dimensionality. + + This checks that all input and output edges are dangling and that there + are no other dangling edges (except any specified in `ignore_edges`). + If not, an exception is raised. + """ for (i, e) in enumerate(self.out_edges): if not e.is_dangling(): raise ValueError("Output edge {} is not dangling!".format(i)) From ecded14350355553746cf0715db4352bc004f706 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 17:15:02 -0800 Subject: [PATCH 15/39] Doc/comments fixes. --- tensornetwork/quantum/quantum.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 62d6d7af7..011811612 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -28,10 +28,10 @@ def quantum_constructor(out_edges, in_edges, ref_nodes=None, ignore_edges=None): - """Constructs an appropriately specialized QuOperator or QuScalar. + """Constructs an appropriately specialized QuOperator. If there are no edges, creates a QuScalar. If the are only output (input) - edges, construct a QuVector (QuAdjointVector). Otherwise construct a + edges, creates a QuVector (QuAdjointVector). Otherwise creates a QuOperator. Args: @@ -88,9 +88,8 @@ class QuOperator(): """ def __init__(self, out_edges, in_edges, ref_nodes=None, ignore_edges=None): # TODO: Decide whether the user must also supply all nodes involved. - # More flexible if not (e.g. a QuOperator can represent a vector - # of operators if there is an extra dangling Edge), better error - # checking if so. + # This would enable extra error checking and is probably clearer + # than `ref_nodes`. if len(in_edges) == 0 and len(out_edges) == 0 and not ref_nodes: raise ValueError("At least one reference node is required to specify a " "scalar. None provided!") From 8841d603d89cbca2d3a8a4ffcb4d0afd4a6dc096 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 17:33:34 -0800 Subject: [PATCH 16/39] Add typing. --- tensornetwork/quantum/quantum.py | 50 +++++++++++++++++++------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 011811612..88cd31c16 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -19,15 +19,17 @@ we provide some simple abstractions to ease linear algebra operations in which the vectors and operators are represented by tensor networks. """ - +from typing import Any, Callable, Optional, Sequence, Collection, Text from tensornetwork.network_components import Node, Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling from tensornetwork.contractors import greedy +Tensor = Any -def quantum_constructor(out_edges, in_edges, ref_nodes=None, - ignore_edges=None): +def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], + ref_nodes: Optional[Collection[Node]] = None, + ignore_edges: Optional[Collection[Edge]] = None): """Constructs an appropriately specialized QuOperator. If there are no edges, creates a QuScalar. If the are only output (input) @@ -53,14 +55,14 @@ def quantum_constructor(out_edges, in_edges, ref_nodes=None, return QuOperator(out_edges, in_edges, ref_nodes, ignore_edges) -def identity(shape): +def identity(shape: Sequence[int]): nodes = [CopyNode(2, d) for d in shape] out_edges = [n[0] for n in nodes] in_edges = [n[1] for n in nodes] return quantum_constructor(out_edges, in_edges) -def check_spaces(edges_1, edges_2): +def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]): """Check the vector spaces represented by two lists of edges are compatible. The number of edges must be the same and the dimensions of each pair of edges @@ -86,7 +88,9 @@ class QuOperator(): Can be used to do simple linear algebra with tensor networks. """ - def __init__(self, out_edges, in_edges, ref_nodes=None, ignore_edges=None): + def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], + ref_nodes: Optional[Collection[Node]] = None, + ignore_edges: Optional[Collection[Edge]] = None): # TODO: Decide whether the user must also supply all nodes involved. # This would enable extra error checking and is probably clearer # than `ref_nodes`. @@ -100,7 +104,8 @@ def __init__(self, out_edges, in_edges, ref_nodes=None, ignore_edges=None): self.check_network() @classmethod - def from_tensor(cls, tensor, out_axes, in_axes, backend=None): + def from_tensor(cls, tensor: Tensor, out_axes: Sequence[int], + in_axes: Sequence[int], backend: Optional[Text] = None): n = Node(tensor, backend=backend) out_edges = [n[i] for i in out_axes] in_edges = [n[i] for i in in_axes] @@ -178,7 +183,7 @@ def norm(self): """ return (self.adjoint() @ self).trace() - def partial_trace(self, subsystems_to_trace_out): + def partial_trace(self, subsystems_to_trace_out: Collection[int]): """The partial trace of the operator. Subsystems to trace out are supplied as indices, so that dangling edges @@ -214,7 +219,7 @@ def partial_trace(self, subsystems_to_trace_out): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __matmul__(self, other): + def __matmul__(self, other: "QuOperator"): check_spaces(self.in_edges, other.out_edges) # Copy all nodes involved in the two operators. @@ -236,13 +241,13 @@ def __matmul__(self, other): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __mul__(self, other): + def __mul__(self, other: "QuOperator"): if self.is_scalar or other.is_scalar: return self @ other raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") - def tensor_prod(self, other): + def tensor_prod(self, other: "QuOperator"): """Tensor product with another operator. """ nodes_dict1, edges_dict1 = copy(self.nodes, False) @@ -259,7 +264,7 @@ def tensor_prod(self, other): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def contract(self, contractor=greedy): + def contract(self, contractor: Callable = greedy): """Contract the tensor network in place. """ self.ref_nodes = set([contractor(self.nodes)]) @@ -277,11 +282,13 @@ def eval(self): class QuVector(QuOperator): - def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): + def __init__(self, subsystem_edges: Sequence[Edge], + ref_nodes: Optional[Collection[Node]] = None, + ignore_edges: Optional[Collection[Edge]] = None): super().__init__(subsystem_edges, [], ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor, backend=None): + def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): n = Node(tensor, backend=backend) return cls(n.get_all_edges()) @@ -292,17 +299,19 @@ def subsystem_edges(self): def projector(self): return self @ self.adjoint() - def reduced_density(self, subsystems_to_trace_out): + def reduced_density(self, subsystems_to_trace_out: Collection[int]): rho = self.projector() return rho.partial_trace(subsystems_to_trace_out) class QuAdjointVector(QuOperator): - def __init__(self, subsystem_edges, ref_nodes=None, ignore_edges=None): + def __init__(self, subsystem_edges: Sequence[Edge], + ref_nodes: Optional[Collection[Node]] = None, + ignore_edges: Optional[Collection[Edge]] = None): super().__init__([], subsystem_edges, ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor, backend=None): + def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): n = Node(tensor, backend=backend) return cls(n.get_all_edges()) @@ -313,16 +322,17 @@ def subsystem_edges(self): def projector(self): return self.adjoint() @ self - def reduced_density(self, subsystems_to_trace_out): + def reduced_density(self, subsystems_to_trace_out: Collection[int]): rho = self.projector() return rho.partial_trace(subsystems_to_trace_out) class QuScalar(QuOperator): - def __init__(self, ref_nodes, ignore_edges=None): + def __init__(self, ref_nodes: Collection[Node], + ignore_edges: Optional[Collection[Edge]] = None): super().__init__([], [], ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor, backend=None): + def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): n = Node(tensor, backend=backend) return cls(set(n)) From 4b53b1aa8bf64a31ded81b90cef11baeb91ba80f Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 17:37:18 -0800 Subject: [PATCH 17/39] Remove some lint. --- tensornetwork/quantum/quantum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 88cd31c16..53aafb066 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -48,9 +48,9 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], """ if len(out_edges) == 0 and len(in_edges) == 0: return QuScalar(ref_nodes, ignore_edges) - elif len(out_edges) == 0: + if len(out_edges) == 0: return QuAdjointVector(in_edges, ref_nodes, ignore_edges) - elif len(in_edges) == 0: + if len(in_edges) == 0: return QuVector(out_edges, ref_nodes, ignore_edges) return QuOperator(out_edges, in_edges, ref_nodes, ignore_edges) From 29604247722b768f33fcd3232ebe472bbe635b3d Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 18:01:33 -0800 Subject: [PATCH 18/39] Fix a bug. --- tensornetwork/quantum/quantum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 53aafb066..c3b4a8adb 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -109,7 +109,7 @@ def from_tensor(cls, tensor: Tensor, out_axes: Sequence[int], n = Node(tensor, backend=backend) out_edges = [n[i] for i in out_axes] in_edges = [n[i] for i in in_axes] - return cls(out_edges, in_edges, set(n)) + return cls(out_edges, in_edges, set([n])) @property def nodes(self): @@ -335,4 +335,4 @@ def __init__(self, ref_nodes: Collection[Node], @classmethod def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): n = Node(tensor, backend=backend) - return cls(set(n)) + return cls(set([n])) From 05c2aff8b0f28ae65d94a24ffadac8c724c88651 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Thu, 7 Nov 2019 18:01:42 -0800 Subject: [PATCH 19/39] Add very simple constructor tests. --- tensornetwork/quantum/quantum_test.py | 56 +++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 tensornetwork/quantum/quantum_test.py diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py new file mode 100644 index 000000000..5d6a43045 --- /dev/null +++ b/tensornetwork/quantum/quantum_test.py @@ -0,0 +1,56 @@ +# Copyright 2019 The TensorNetwork Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +import numpy as np +import tensornetwork as tn +import quantum as qu + + +def test_constructor(): + psi_tensor = np.random.rand(2,2) + psi_node = tn.Node(psi_tensor) + + op = qu.quantum_constructor([psi_node[0]], [psi_node[1]]) + assert not op.is_scalar + assert not op.is_vector + assert not op.is_adjoint_vector + + op = qu.quantum_constructor([psi_node[0], psi_node[1]], []) + assert not op.is_scalar + assert op.is_vector + assert not op.is_adjoint_vector + + op = qu.quantum_constructor([], [psi_node[0], psi_node[1]]) + assert not op.is_scalar + assert not op.is_vector + assert op.is_adjoint_vector + +def test_from_tensor(): + psi_tensor = np.random.rand(2,2) + + op = qu.QuOperator.from_tensor(psi_tensor, [0], [1]) + assert not op.is_scalar + assert not op.is_vector + assert not op.is_adjoint_vector + + op = qu.QuVector.from_tensor(psi_tensor) + assert not op.is_scalar + assert op.is_vector + assert not op.is_adjoint_vector + + op = qu.QuAdjointVector.from_tensor(psi_tensor) + assert not op.is_scalar + assert not op.is_vector + assert op.is_adjoint_vector \ No newline at end of file From ac0429db3f528b3fbd754c0cdc6f307527238de3 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Fri, 8 Nov 2019 18:00:26 -0800 Subject: [PATCH 20/39] Default edge ordering for eval(). Better docstrings. --- tensornetwork/quantum/quantum.py | 44 +++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index c3b4a8adb..8fcd9c71f 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -264,16 +264,52 @@ def tensor_prod(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def contract(self, contractor: Callable = greedy): + def contract(self, contractor: Callable = greedy, + final_edge_order: Optional[Sequence[Edge]] = None): """Contract the tensor network in place. + + This modifies the tensor network representation of the operator (or vector, + or scalar), reducing it to a single tensor, without changing the value. + + Args: + contractor: A function that performs the contraction. Defaults to + `greedy`, which uses the greedy algorithm from `opt_einsum` to + determine a contraction order. + final_edge_order: Manually specify the axis ordering of the final tensor. + Returns: + The present object. """ - self.ref_nodes = set([contractor(self.nodes)]) + if final_edge_order: + self.ref_nodes = set( + [contractor(self.nodes, output_edge_order=final_edge_order)]) + else: + self.ref_nodes = set([contractor(self.nodes, ignore_edge_order=True)]) return self - def eval(self): + def eval(self, contractor: Callable = greedy, + final_edge_order: Optional[Sequence[Edge]] = None): """Contracts the tensor network in place and returns the final tensor. + + Note that this modifies the tensor network representing the operator. + + The default ordering for the axes of the final tensor is: + `out_edges + in_edges` + If there are any "ignored" edges, their axes come first: + `ignored_edges + out_edges + in_edges` + + Args: + contractor: A function that performs the contraction. Defaults to + `greedy`, which uses the greedy algorithm from `opt_einsum` to + determine a contraction order. + final_edge_order: Manually specify the axis ordering of the final tensor. + Returns: + The final tensor representing the operator. """ - self.contract() + if not final_edge_order: + # TODO: Perhaps support using no assigned ordering at all here? + final_edge_order = (list(self.ignore_edges) + self.out_edges + + self.in_edges) + self.contract(contractor, final_edge_order) nodes = self.nodes if len(nodes) != 1: raise ValueError("Node count '{}' > 1 after contraction!".format( From d02927742275f0c43f6c2540cd3ce44dc357882a Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Fri, 8 Nov 2019 18:01:08 -0800 Subject: [PATCH 21/39] A bunch more tests. --- tensornetwork/quantum/quantum_test.py | 85 ++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index 5d6a43045..a2bd95f3e 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -37,6 +37,33 @@ def test_constructor(): assert not op.is_vector assert op.is_adjoint_vector + with pytest.raises(ValueError): + op = qu.quantum_constructor([], [], [psi_node]) + + _ = psi_node[0] ^ psi_node[1] + op = qu.quantum_constructor([], [], [psi_node]) + assert op.is_scalar + assert not op.is_vector + assert not op.is_adjoint_vector + + +def test_checks(): + node1 = tn.Node(np.random.rand(2,2)) + node2 = tn.Node(np.random.rand(2,2)) + _ = node1[1] ^ node2[0] + + # extra edges must be explicitly ignored + with pytest.raises(ValueError): + _ = qu.QuVector([node1[0]]) + + # correctly ignore the extra edge + op = qu.QuVector([node1[0]], ignore_edges=[node2[1]]) + + # in/out edges must be dangling + with pytest.raises(ValueError): + _ = qu.QuVector([node1[0], node1[1], node2[1]]) + + def test_from_tensor(): psi_tensor = np.random.rand(2,2) @@ -44,13 +71,69 @@ def test_from_tensor(): assert not op.is_scalar assert not op.is_vector assert not op.is_adjoint_vector + np.testing.assert_almost_equal(op.eval(), psi_tensor) op = qu.QuVector.from_tensor(psi_tensor) assert not op.is_scalar assert op.is_vector assert not op.is_adjoint_vector + np.testing.assert_almost_equal(op.eval(), psi_tensor) op = qu.QuAdjointVector.from_tensor(psi_tensor) assert not op.is_scalar assert not op.is_vector - assert op.is_adjoint_vector \ No newline at end of file + assert op.is_adjoint_vector + np.testing.assert_almost_equal(op.eval(), psi_tensor) + + op = qu.QuScalar.from_tensor(1.0) + assert op.is_scalar + assert not op.is_vector + assert not op.is_adjoint_vector + assert op.eval() == 1.0 + + +def test_identity(): + E = qu.identity((2,3,4)) + assert E.trace().eval() == 24 + + psi = qu.QuVector.from_tensor(np.random.rand(2,2)) + E = qu.identity((2,2)) + np.testing.assert_almost_equal((E @ psi).norm().eval(), psi.norm().eval()) + + +def test_tensor_prod(): + psi = qu.QuVector.from_tensor(np.random.rand(2,2)) + psi_psi = psi.tensor_prod(psi) + np.testing.assert_almost_equal(psi_psi.norm().eval(), psi.norm().eval()**2) + + +def test_matmul(): + mat = np.random.rand(2,2) + op = qu.QuOperator.from_tensor(mat, [0], [1]) + res = (op @ op).eval() + np.testing.assert_almost_equal(res, mat @ mat) + + +def test_expectations(): + psi_tensor = np.random.rand(2,2,2) + 1.j * np.random.rand(2,2,2) + op_tensor = np.random.rand(2,2) + 1.j * np.random.rand(2,2) + psi = qu.QuVector.from_tensor(psi_tensor) + op = qu.QuOperator.from_tensor(op_tensor, [0], [1]) + + op_3 = op.tensor_prod(qu.identity((2,2))) + res1 = (psi.adjoint() @ op_3 @ psi).eval() + + rho_1 = psi.reduced_density([1, 2]) # trace out sites 2 and 3 + res2 = (op @ rho_1).trace().eval() + + np.testing.assert_almost_equal(res1, res2) + + +def test_projector(): + psi_tensor = np.random.rand(2,2) + psi_tensor /= np.linalg.norm(psi_tensor) + psi = qu.QuVector.from_tensor(psi_tensor) + P = psi.projector() + np.testing.assert_almost_equal((P @ psi).eval(), psi_tensor) + + np.testing.assert_almost_equal((P @ P).eval(), P.eval()) From 8d8bb8c7c8a3ee8a26d7775379d3a1f00374a7f9 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Fri, 15 Nov 2019 12:13:58 -0800 Subject: [PATCH 22/39] tensor_prod -> tensor_product, outer_product --- tensornetwork/quantum/quantum.py | 8 +++++++- tensornetwork/quantum/quantum_test.py | 6 +++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 8fcd9c71f..eb23f7497 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -247,7 +247,7 @@ def __mul__(self, other: "QuOperator"): raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") - def tensor_prod(self, other: "QuOperator"): + def tensor_product(self, other: "QuOperator"): """Tensor product with another operator. """ nodes_dict1, edges_dict1 = copy(self.nodes, False) @@ -264,6 +264,12 @@ def tensor_prod(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) + def outer_product(self, other: "QuOperator"): + """Outer product with another operator. + Synonym for `tensor_product()`. + """ + return self.tensor_product(other) + def contract(self, contractor: Callable = greedy, final_edge_order: Optional[Sequence[Edge]] = None): """Contract the tensor network in place. diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index a2bd95f3e..850ca81af 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -101,9 +101,9 @@ def test_identity(): np.testing.assert_almost_equal((E @ psi).norm().eval(), psi.norm().eval()) -def test_tensor_prod(): +def test_tensor_product(): psi = qu.QuVector.from_tensor(np.random.rand(2,2)) - psi_psi = psi.tensor_prod(psi) + psi_psi = psi.tensor_product(psi) np.testing.assert_almost_equal(psi_psi.norm().eval(), psi.norm().eval()**2) @@ -120,7 +120,7 @@ def test_expectations(): psi = qu.QuVector.from_tensor(psi_tensor) op = qu.QuOperator.from_tensor(op_tensor, [0], [1]) - op_3 = op.tensor_prod(qu.identity((2,2))) + op_3 = op.tensor_product(qu.identity((2,2))) res1 = (psi.adjoint() @ op_3 @ psi).eval() rho_1 = psi.reduced_density([1, 2]) # trace out sites 2 and 3 From 53c142bc141766adc85ebe3ae7c5078ece6dbc52 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Tue, 19 Nov 2019 14:13:14 -0800 Subject: [PATCH 23/39] .is_scalar -> is_scalar() etc. --- tensornetwork/quantum/quantum.py | 5 +-- tensornetwork/quantum/quantum_test.py | 48 +++++++++++++-------------- 2 files changed, 25 insertions(+), 28 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index eb23f7497..88d6d630a 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -126,15 +126,12 @@ def shape_in(self): def shape_out(self): return [e.dimension for e in self.out_edges] - @property def is_scalar(self): return len(self.out_edges) == 0 and len(self.in_edges) == 0 - @property def is_vector(self): return len(self.out_edges) > 0 and len(self.in_edges) == 0 - @property def is_adjoint_vector(self): return len(self.out_edges) == 0 and len(self.in_edges) > 0 @@ -242,7 +239,7 @@ def __matmul__(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) def __mul__(self, other: "QuOperator"): - if self.is_scalar or other.is_scalar: + if self.is_scalar() or other.is_scalar(): return self @ other raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index 850ca81af..e6444670b 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -23,28 +23,28 @@ def test_constructor(): psi_node = tn.Node(psi_tensor) op = qu.quantum_constructor([psi_node[0]], [psi_node[1]]) - assert not op.is_scalar - assert not op.is_vector - assert not op.is_adjoint_vector + assert not op.is_scalar() + assert not op.is_vector() + assert not op.is_adjoint_vector() op = qu.quantum_constructor([psi_node[0], psi_node[1]], []) - assert not op.is_scalar - assert op.is_vector - assert not op.is_adjoint_vector + assert not op.is_scalar() + assert op.is_vector() + assert not op.is_adjoint_vector() op = qu.quantum_constructor([], [psi_node[0], psi_node[1]]) - assert not op.is_scalar - assert not op.is_vector - assert op.is_adjoint_vector + assert not op.is_scalar() + assert not op.is_vector() + assert op.is_adjoint_vector() with pytest.raises(ValueError): op = qu.quantum_constructor([], [], [psi_node]) _ = psi_node[0] ^ psi_node[1] op = qu.quantum_constructor([], [], [psi_node]) - assert op.is_scalar - assert not op.is_vector - assert not op.is_adjoint_vector + assert op.is_scalar() + assert not op.is_vector() + assert not op.is_adjoint_vector() def test_checks(): @@ -68,27 +68,27 @@ def test_from_tensor(): psi_tensor = np.random.rand(2,2) op = qu.QuOperator.from_tensor(psi_tensor, [0], [1]) - assert not op.is_scalar - assert not op.is_vector - assert not op.is_adjoint_vector + assert not op.is_scalar() + assert not op.is_vector() + assert not op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) op = qu.QuVector.from_tensor(psi_tensor) - assert not op.is_scalar - assert op.is_vector - assert not op.is_adjoint_vector + assert not op.is_scalar() + assert op.is_vector() + assert not op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) op = qu.QuAdjointVector.from_tensor(psi_tensor) - assert not op.is_scalar - assert not op.is_vector - assert op.is_adjoint_vector + assert not op.is_scalar() + assert not op.is_vector() + assert op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) op = qu.QuScalar.from_tensor(1.0) - assert op.is_scalar - assert not op.is_vector - assert not op.is_adjoint_vector + assert op.is_scalar() + assert not op.is_vector() + assert not op.is_adjoint_vector() assert op.eval() == 1.0 From f7e70fd18f25b9cd2ee19e35274e4c1c449aa32f Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Tue, 19 Nov 2019 14:19:16 -0800 Subject: [PATCH 24/39] Improve docstrings on axis ordering. --- tensornetwork/quantum/quantum.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 88d6d630a..4cc24e605 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -296,20 +296,22 @@ def eval(self, contractor: Callable = greedy, Note that this modifies the tensor network representing the operator. The default ordering for the axes of the final tensor is: - `out_edges + in_edges` + `*out_edges, *in_edges`. + If there are any "ignored" edges, their axes come first: - `ignored_edges + out_edges + in_edges` + `*ignored_edges, *out_edges, *in_edges`. Args: contractor: A function that performs the contraction. Defaults to `greedy`, which uses the greedy algorithm from `opt_einsum` to determine a contraction order. final_edge_order: Manually specify the axis ordering of the final tensor. + The default ordering is determined by `out_edges` and `in_edges` (see + above). Returns: The final tensor representing the operator. """ if not final_edge_order: - # TODO: Perhaps support using no assigned ordering at all here? final_edge_order = (list(self.ignore_edges) + self.out_edges + self.in_edges) self.contract(contractor, final_edge_order) From c349667bf7d90c7744008e0d9ea2c63d6b1814d6 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Tue, 19 Nov 2019 14:53:39 -0800 Subject: [PATCH 25/39] Improve and fix scalar multiplication. --- tensornetwork/quantum/quantum.py | 17 ++++++++++++++--- tensornetwork/quantum/quantum_test.py | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 4cc24e605..4a519587a 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -19,7 +19,7 @@ we provide some simple abstractions to ease linear algebra operations in which the vectors and operators are represented by tensor networks. """ -from typing import Any, Callable, Optional, Sequence, Collection, Text +from typing import Any, Union, Callable, Optional, Sequence, Collection, Text from tensornetwork.network_components import Node, Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling @@ -238,12 +238,23 @@ def __matmul__(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __mul__(self, other: "QuOperator"): + def __mul__(self, other: Union["QuOperator", Tensor]): + if not isinstance(other, QuOperator): + node = Node(other, backend=self.nodes.pop().backend) + if node.shape: + raise ValueError("Cannot perform elementwise multiplication by a " + "non-scalar tensor.") + other = QuScalar([node]) + if self.is_scalar() or other.is_scalar(): - return self @ other + return self.tensor_product(other) + raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") + def __rmul__(self, other: Union["QuOperator", Tensor]): + return self.__mul__(other) + def tensor_product(self, other: "QuOperator"): """Tensor product with another operator. """ diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index e6444670b..dee7956b1 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -114,6 +114,32 @@ def test_matmul(): np.testing.assert_almost_equal(res, mat @ mat) +def test_mul(): + mat = np.eye(2) + op = qu.QuOperator.from_tensor(mat, [0], [1]) + scal_op = qu.QuScalar.from_tensor(0.5) + + res = (op * scal_op).eval() + np.testing.assert_almost_equal(res, mat * 0.5) + + res = (scal_op * op).eval() + np.testing.assert_almost_equal(res, mat * 0.5) + + res = (scal_op * scal_op).eval() + np.testing.assert_almost_equal(res, 0.25) + + res = (op * 0.5).eval() + np.testing.assert_almost_equal(res, mat * 0.5) + + res = (0.5 * op).eval() + np.testing.assert_almost_equal(res, mat * 0.5) + + with pytest.raises(ValueError): + _ = (op * op) + + with pytest.raises(ValueError): + _ = (op * mat) + def test_expectations(): psi_tensor = np.random.rand(2,2,2) + 1.j * np.random.rand(2,2,2) op_tensor = np.random.rand(2,2) + 1.j * np.random.rand(2,2) From bf999305cb50edabb3e44eaeb9349103db6d76e9 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Tue, 19 Nov 2019 14:54:15 -0800 Subject: [PATCH 26/39] Kill outer_product(). --- tensornetwork/quantum/quantum.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 4a519587a..86b6cbb32 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -272,12 +272,6 @@ def tensor_product(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def outer_product(self, other: "QuOperator"): - """Outer product with another operator. - Synonym for `tensor_product()`. - """ - return self.tensor_product(other) - def contract(self, contractor: Callable = greedy, final_edge_order: Optional[Sequence[Edge]] = None): """Contract the tensor network in place. From 254ded8711253d477cd1e535dbc75d7c2cf619d4 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 20 Nov 2019 10:48:09 -0800 Subject: [PATCH 27/39] CopyNode needs a backend and dtype. --- tensornetwork/quantum/quantum.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 86b6cbb32..fc70dc465 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -20,6 +20,8 @@ the vectors and operators are represented by tensor networks. """ from typing import Any, Union, Callable, Optional, Sequence, Collection, Text +from typing import Type +import numpy as np from tensornetwork.network_components import Node, Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling @@ -55,8 +57,9 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], return QuOperator(out_edges, in_edges, ref_nodes, ignore_edges) -def identity(shape: Sequence[int]): - nodes = [CopyNode(2, d) for d in shape] +def identity(shape: Sequence[int], backend: Optional[Text] = None, + dtype: Type[np.number] = np.float64): + nodes = [CopyNode(2, d, backend=backend, dtype=dtype) for d in shape] out_edges = [n[0] for n in nodes] in_edges = [n[1] for n in nodes] return quantum_constructor(out_edges, in_edges) From d87e9d1ea1466d968d8487af7a4775140d15e53e Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 20 Nov 2019 10:48:41 -0800 Subject: [PATCH 28/39] Fix __mul__ and add __rmul__. --- tensornetwork/quantum/quantum.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index fc70dc465..cd937537d 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -91,6 +91,8 @@ class QuOperator(): Can be used to do simple linear algebra with tensor networks. """ + __array_priority__ = 100.0 # for correct __rmul__ with scalar ndarrays + def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], ref_nodes: Optional[Collection[Node]] = None, ignore_edges: Optional[Collection[Edge]] = None): @@ -241,9 +243,12 @@ def __matmul__(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __mul__(self, other: Union["QuOperator", Tensor]): + def __mul__(self, other: Union["QuOperator", Node, Tensor]): if not isinstance(other, QuOperator): - node = Node(other, backend=self.nodes.pop().backend) + if isinstance(other, Node): + node = other + else: + node = Node(other, backend=self.nodes.pop().backend) if node.shape: raise ValueError("Cannot perform elementwise multiplication by a " "non-scalar tensor.") @@ -255,7 +260,7 @@ def __mul__(self, other: Union["QuOperator", Tensor]): raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") - def __rmul__(self, other: Union["QuOperator", Tensor]): + def __rmul__(self, other: Union["QuOperator", Node, Tensor]): return self.__mul__(other) def tensor_product(self, other: "QuOperator"): From f457bc9bbd3f5b39c5b664a896684f301b5b56af Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 20 Nov 2019 11:53:53 -0800 Subject: [PATCH 29/39] More docstrings and add axis arguments to vector from_tensor()s. --- tensornetwork/quantum/quantum.py | 191 ++++++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 5 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index cd937537d..c035f1457 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -59,6 +59,19 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], def identity(shape: Sequence[int], backend: Optional[Text] = None, dtype: Type[np.number] = np.float64): + """Construct a `QuOperator` representing the identity on a given space. + + Internally, this is done by constructing `CopyNode`s for each edge, with + dimension according to `shape`. + + Args: + shape: A sequence of integers for the dimensions of the tensor product + factors of the space (the edges in the tensor network). + backend: Optionally specify the backend to use for computations. + dtype: The data type (for conversion to dense). + Returns: + The desired identity operator. + """ nodes = [CopyNode(2, d, backend=backend, dtype=dtype) for d in shape] out_edges = [n[0] for n in nodes] in_edges = [n[1] for n in nodes] @@ -87,7 +100,17 @@ def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]): class QuOperator(): - """Represents an operator via a tensor network. + """Represents a linear operator via a tensor network. + + To interpret a tensor network as a linear operator, some of the dangling + edges must be designated as `out_edges` (output edges) and the rest as + `in_edges` (input edges). + + Considered as a matrix, the `out_edges` represent the row index and the + `in_edges` represent the column index. + + The (right) action of the operator on another then consists of connecting + the `in_edges` of the first operator to the `out_edges` of the second. Can be used to do simple linear algebra with tensor networks. """ @@ -96,6 +119,23 @@ class QuOperator(): def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], ref_nodes: Optional[Collection[Node]] = None, ignore_edges: Optional[Collection[Edge]] = None): + """Creates a new `QuOperator` from a tensor network. + + This encapsulates an existing tensor network, interpreting it as a linear + operator. + + The network is checked for consistency: All dangling edges must either be + in `out_edges`, `in_edges`, or `ignore_edges`. + + Args: + out_edges: The edges of the network to be used as the output edges. + in_edges: The edges of the network to be used as the input edges. + ref_nodes: Nodes used to refer to parts of the tensor network that are + not connected to any input or output edges (for example: a scalar + factor). + ignore_edges: Optional collection of edges to ignore when performing + consistency checks. + """ # TODO: Decide whether the user must also supply all nodes involved. # This would enable extra error checking and is probably clearer # than `ref_nodes`. @@ -111,6 +151,19 @@ def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], @classmethod def from_tensor(cls, tensor: Tensor, out_axes: Sequence[int], in_axes: Sequence[int], backend: Optional[Text] = None): + """Construct a `QuOperator` directly from a single tensor. + + This first wraps the tensor in a `Node`, then constructs the `QuOperator` + from that `Node`. + + Args: + tensor: The tensor. + out_axes: The axis indices of `tensor` to use as `out_edges`. + in_axes: The axis indices of `tensor` to use as `in_edges`. + backend: Optionally specify the backend to use for computations. + Returns: + The new operator. + """ n = Node(tensor, backend=backend) out_edges = [n[i] for i in out_axes] in_edges = [n[i] for i in in_axes] @@ -222,6 +275,15 @@ def partial_trace(self, subsystems_to_trace_out: Collection[int]): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) def __matmul__(self, other: "QuOperator"): + """The action of this operator on another. + + Given `QuOperator`s `A` and `B`, produces a new `QuOperator` for `A @ B`, + where `A @ B` means: "the action of A, as a linear operator, on B". + + Under the hood, this produces copies of the tensor networks defining `A` + and `B` and then connects the copies by hooking up the `in_edges` of + `A.copy()` to the `out_edges` of `B.copy()`. + """ check_spaces(self.in_edges, other.out_edges) # Copy all nodes involved in the two operators. @@ -244,6 +306,17 @@ def __matmul__(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) def __mul__(self, other: Union["QuOperator", Node, Tensor]): + """Scalar multiplication of operators. + + Given two operators `A` and `B`, one of the which is a scalar (it has no + input or output edges), `A * B` produces a new operator representing the + scalar multiplication of `A` and `B`. + + For convenience, one of `A` or `B` may be a number or scalar-valued tensor + or `Node` (it will automatically be wrapped in a `QuScalar`). + + Note: This is a special case of `tensor_product()`. + """ if not isinstance(other, QuOperator): if isinstance(other, Node): node = other @@ -261,10 +334,25 @@ def __mul__(self, other: Union["QuOperator", Node, Tensor]): "least one of the arguments is a scalar.") def __rmul__(self, other: Union["QuOperator", Node, Tensor]): + """Scalar multiplication of operators. See `.__mul__()`. + """ return self.__mul__(other) def tensor_product(self, other: "QuOperator"): """Tensor product with another operator. + + Given two operators `A` and `B`, produces a new operator `AB` representing + `A` ⊗ `B`. The `out_edges` (`in_edges`) of `AB` is simply the + concatenation of the `out_edges` (`in_edges`) of `A.copy()` with that of + `B.copy()`: + + `new_out_edges = [*out_edges_A_copy, *out_edges_B_copy]` + `new_in_edges = [*in_edges_A_copy, *in_edges_B_copy]` + + Args: + other: The other operator (`B`). + Returns: + The result (`AB`). """ nodes_dict1, edges_dict1 = copy(self.nodes, False) nodes_dict2, edges_dict2 = copy(other.nodes, False) @@ -336,15 +424,50 @@ def eval(self, contractor: Callable = greedy, class QuVector(QuOperator): + """Represents a (column) vector via a tensor network. + """ def __init__(self, subsystem_edges: Sequence[Edge], ref_nodes: Optional[Collection[Node]] = None, ignore_edges: Optional[Collection[Edge]] = None): + """Constructs a new `QuVector` from a tensor network. + + This encapsulates an existing tensor network, interpreting it as a (column) + vector. + + Args: + subsystem_edges: The edges of the network to be used as the output edges. + ref_nodes: Nodes used to refer to parts of the tensor network that are + not connected to any input or output edges (for example: a scalar + factor). + ignore_edges: Optional collection of edges to ignore when performing + consistency checks. + """ super().__init__(subsystem_edges, [], ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): + def from_tensor(cls, tensor: Tensor, + subsystem_axes: Optional[Sequence[int]] = None, + backend: Optional[Text] = None): + """Construct a `QuVector` directly from a single tensor. + + This first wraps the tensor in a `Node`, then constructs the `QuVector` + from that `Node`. + + Args: + tensor: The tensor. + subsystem_axes: Sequence of integer indices specifying the order in which + to interpret the axes as subsystems (output edges). If not specified, + the axes are taken in ascending order. + backend: Optionally specify the backend to use for computations. + Returns: + The new operator. + """ n = Node(tensor, backend=backend) - return cls(n.get_all_edges()) + if subsystem_axes is not None: + subsystem_edges = [n[i] for i in subsystem_axes] + else: + subsystem_edges = n.get_all_edges() + return cls(subsystem_edges) @property def subsystem_edges(self): @@ -359,15 +482,50 @@ def reduced_density(self, subsystems_to_trace_out: Collection[int]): class QuAdjointVector(QuOperator): + """Represents an adjoint (row) vector via a tensor network. + """ def __init__(self, subsystem_edges: Sequence[Edge], ref_nodes: Optional[Collection[Node]] = None, ignore_edges: Optional[Collection[Edge]] = None): + """Constructs a new `QuAdjointVector` from a tensor network. + + This encapsulates an existing tensor network, interpreting it as an adjoint + vector (row vector). + + Args: + subsystem_edges: The edges of the network to be used as the input edges. + ref_nodes: Nodes used to refer to parts of the tensor network that are + not connected to any input or output edges (for example: a scalar + factor). + ignore_edges: Optional collection of edges to ignore when performing + consistency checks. + """ super().__init__([], subsystem_edges, ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): + def from_tensor(cls, tensor: Tensor, + subsystem_axes: Optional[Sequence[int]] = None, + backend: Optional[Text] = None): + """Construct a `QuAdjointVector` directly from a single tensor. + + This first wraps the tensor in a `Node`, then constructs the + `QuAdjointVector` from that `Node`. + + Args: + tensor: The tensor. + subsystem_axes: Sequence of integer indices specifying the order in which + to interpret the axes as subsystems (input edges). If not specified, + the axes are taken in ascending order. + backend: Optionally specify the backend to use for computations. + Returns: + The new operator. + """ n = Node(tensor, backend=backend) - return cls(n.get_all_edges()) + if subsystem_axes is not None: + subsystem_edges = [n[i] for i in subsystem_axes] + else: + subsystem_edges = n.get_all_edges() + return cls(subsystem_edges) @property def subsystem_edges(self): @@ -382,11 +540,34 @@ def reduced_density(self, subsystems_to_trace_out: Collection[int]): class QuScalar(QuOperator): + """Represents a scalar via a tensor network. + """ def __init__(self, ref_nodes: Collection[Node], ignore_edges: Optional[Collection[Edge]] = None): + """Constructs a new `QuScalar` from a tensor network. + + This encapsulates an existing tensor network, interpreting it as a scalar. + + Args: + ref_nodes: Nodes used to refer to the tensor network (need not be + exhaustive - one node from each disconnected subnetwork is sufficient). + ignore_edges: Optional collection of edges to ignore when performing + consistency checks. + """ super().__init__([], [], ref_nodes, ignore_edges) @classmethod def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): + """Construct a `QuScalar` directly from a single tensor. + + This first wraps the tensor in a `Node`, then constructs the + `QuScalar` from that `Node`. + + Args: + tensor: The tensor. + backend: Optionally specify the backend to use for computations. + Returns: + The new operator. + """ n = Node(tensor, backend=backend) return cls(set([n])) From 5af882c5f69e2071fc37ee92a2da7854eadf049c Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 20 Nov 2019 11:54:37 -0800 Subject: [PATCH 30/39] Add backends to tests. --- tensornetwork/quantum/quantum_test.py | 83 +++++++++++++++------------ 1 file changed, 45 insertions(+), 38 deletions(-) diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index dee7956b1..ee18e851b 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -18,9 +18,9 @@ import quantum as qu -def test_constructor(): +def test_constructor(backend): psi_tensor = np.random.rand(2,2) - psi_node = tn.Node(psi_tensor) + psi_node = tn.Node(psi_tensor, backend=backend) op = qu.quantum_constructor([psi_node[0]], [psi_node[1]]) assert not op.is_scalar() @@ -47,9 +47,9 @@ def test_constructor(): assert not op.is_adjoint_vector() -def test_checks(): - node1 = tn.Node(np.random.rand(2,2)) - node2 = tn.Node(np.random.rand(2,2)) +def test_checks(backend): + node1 = tn.Node(np.random.rand(2,2), backend=backend) + node2 = tn.Node(np.random.rand(2,2), backend=backend) _ = node1[1] ^ node2[0] # extra edges must be explicitly ignored @@ -64,75 +64,76 @@ def test_checks(): _ = qu.QuVector([node1[0], node1[1], node2[1]]) -def test_from_tensor(): +def test_from_tensor(backend): psi_tensor = np.random.rand(2,2) - op = qu.QuOperator.from_tensor(psi_tensor, [0], [1]) + op = qu.QuOperator.from_tensor(psi_tensor, [0], [1], backend=backend) assert not op.is_scalar() assert not op.is_vector() assert not op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) - op = qu.QuVector.from_tensor(psi_tensor) + op = qu.QuVector.from_tensor(psi_tensor, [0, 1], backend=backend) assert not op.is_scalar() assert op.is_vector() assert not op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) - op = qu.QuAdjointVector.from_tensor(psi_tensor) + op = qu.QuAdjointVector.from_tensor(psi_tensor, [0, 1], backend=backend) assert not op.is_scalar() assert not op.is_vector() assert op.is_adjoint_vector() np.testing.assert_almost_equal(op.eval(), psi_tensor) - op = qu.QuScalar.from_tensor(1.0) + op = qu.QuScalar.from_tensor(1.0, backend=backend) assert op.is_scalar() assert not op.is_vector() assert not op.is_adjoint_vector() assert op.eval() == 1.0 -def test_identity(): - E = qu.identity((2,3,4)) +def test_identity(backend): + E = qu.identity((2,3,4), backend=backend) assert E.trace().eval() == 24 - psi = qu.QuVector.from_tensor(np.random.rand(2,2)) - E = qu.identity((2,2)) + psi = qu.QuVector.from_tensor(np.random.rand(2,2), backend=backend) + E = qu.identity((2,2), backend=backend) np.testing.assert_almost_equal((E @ psi).norm().eval(), psi.norm().eval()) -def test_tensor_product(): - psi = qu.QuVector.from_tensor(np.random.rand(2,2)) +def test_tensor_product(backend): + psi = qu.QuVector.from_tensor(np.random.rand(2,2), backend=backend) psi_psi = psi.tensor_product(psi) np.testing.assert_almost_equal(psi_psi.norm().eval(), psi.norm().eval()**2) -def test_matmul(): +def test_matmul(backend): mat = np.random.rand(2,2) - op = qu.QuOperator.from_tensor(mat, [0], [1]) + op = qu.QuOperator.from_tensor(mat, [0], [1], backend=backend) res = (op @ op).eval() - np.testing.assert_almost_equal(res, mat @ mat) + np.testing.assert_allclose(res, mat @ mat) -def test_mul(): +def test_mul(backend): mat = np.eye(2) - op = qu.QuOperator.from_tensor(mat, [0], [1]) - scal_op = qu.QuScalar.from_tensor(0.5) + scal = np.float64(0.5) + op = qu.QuOperator.from_tensor(mat, [0], [1], backend=backend) + scal_op = qu.QuScalar.from_tensor(scal, backend=backend) res = (op * scal_op).eval() - np.testing.assert_almost_equal(res, mat * 0.5) + np.testing.assert_allclose(res, mat * 0.5) res = (scal_op * op).eval() - np.testing.assert_almost_equal(res, mat * 0.5) + np.testing.assert_allclose(res, mat * 0.5) res = (scal_op * scal_op).eval() np.testing.assert_almost_equal(res, 0.25) - res = (op * 0.5).eval() - np.testing.assert_almost_equal(res, mat * 0.5) + res = (op * np.float64(0.5)).eval() + np.testing.assert_allclose(res, mat * 0.5) - res = (0.5 * op).eval() - np.testing.assert_almost_equal(res, mat * 0.5) + res = (np.float64(0.5) * op).eval() + np.testing.assert_allclose(res, mat * 0.5) with pytest.raises(ValueError): _ = (op * op) @@ -140,13 +141,19 @@ def test_mul(): with pytest.raises(ValueError): _ = (op * mat) -def test_expectations(): - psi_tensor = np.random.rand(2,2,2) + 1.j * np.random.rand(2,2,2) - op_tensor = np.random.rand(2,2) + 1.j * np.random.rand(2,2) - psi = qu.QuVector.from_tensor(psi_tensor) - op = qu.QuOperator.from_tensor(op_tensor, [0], [1]) +def test_expectations(backend): + if backend == 'pytorch': + psi_tensor = np.random.rand(2,2,2) + op_tensor = np.random.rand(2,2) + else: + psi_tensor = np.random.rand(2,2,2) + 1.j * np.random.rand(2,2,2) + op_tensor = np.random.rand(2,2) + 1.j * np.random.rand(2,2) - op_3 = op.tensor_product(qu.identity((2,2))) + psi = qu.QuVector.from_tensor(psi_tensor, backend=backend) + op = qu.QuOperator.from_tensor(op_tensor, [0], [1], backend=backend) + + op_3 = op.tensor_product( + qu.identity((2,2), backend=backend, dtype=psi_tensor.dtype)) res1 = (psi.adjoint() @ op_3 @ psi).eval() rho_1 = psi.reduced_density([1, 2]) # trace out sites 2 and 3 @@ -155,11 +162,11 @@ def test_expectations(): np.testing.assert_almost_equal(res1, res2) -def test_projector(): +def test_projector(backend): psi_tensor = np.random.rand(2,2) psi_tensor /= np.linalg.norm(psi_tensor) - psi = qu.QuVector.from_tensor(psi_tensor) + psi = qu.QuVector.from_tensor(psi_tensor, backend=backend) P = psi.projector() - np.testing.assert_almost_equal((P @ psi).eval(), psi_tensor) + np.testing.assert_allclose((P @ psi).eval(), psi_tensor) - np.testing.assert_almost_equal((P @ P).eval(), P.eval()) + np.testing.assert_allclose((P @ P).eval(), P.eval()) From 6d1496f016f509a4913399a27fc787c1ad3ea229 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 20 Nov 2019 17:17:01 -0800 Subject: [PATCH 31/39] Delint. --- tensornetwork/quantum/quantum_test.py | 32 +++++++++++++-------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index ee18e851b..f774c5e29 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -19,7 +19,7 @@ def test_constructor(backend): - psi_tensor = np.random.rand(2,2) + psi_tensor = np.random.rand(2, 2) psi_node = tn.Node(psi_tensor, backend=backend) op = qu.quantum_constructor([psi_node[0]], [psi_node[1]]) @@ -48,8 +48,8 @@ def test_constructor(backend): def test_checks(backend): - node1 = tn.Node(np.random.rand(2,2), backend=backend) - node2 = tn.Node(np.random.rand(2,2), backend=backend) + node1 = tn.Node(np.random.rand(2, 2), backend=backend) + node2 = tn.Node(np.random.rand(2, 2), backend=backend) _ = node1[1] ^ node2[0] # extra edges must be explicitly ignored @@ -57,7 +57,7 @@ def test_checks(backend): _ = qu.QuVector([node1[0]]) # correctly ignore the extra edge - op = qu.QuVector([node1[0]], ignore_edges=[node2[1]]) + _ = qu.QuVector([node1[0]], ignore_edges=[node2[1]]) # in/out edges must be dangling with pytest.raises(ValueError): @@ -65,7 +65,7 @@ def test_checks(backend): def test_from_tensor(backend): - psi_tensor = np.random.rand(2,2) + psi_tensor = np.random.rand(2, 2) op = qu.QuOperator.from_tensor(psi_tensor, [0], [1], backend=backend) assert not op.is_scalar() @@ -93,22 +93,22 @@ def test_from_tensor(backend): def test_identity(backend): - E = qu.identity((2,3,4), backend=backend) + E = qu.identity((2, 3, 4), backend=backend) assert E.trace().eval() == 24 - psi = qu.QuVector.from_tensor(np.random.rand(2,2), backend=backend) - E = qu.identity((2,2), backend=backend) + psi = qu.QuVector.from_tensor(np.random.rand(2, 2), backend=backend) + E = qu.identity((2, 2), backend=backend) np.testing.assert_almost_equal((E @ psi).norm().eval(), psi.norm().eval()) def test_tensor_product(backend): - psi = qu.QuVector.from_tensor(np.random.rand(2,2), backend=backend) + psi = qu.QuVector.from_tensor(np.random.rand(2, 2), backend=backend) psi_psi = psi.tensor_product(psi) np.testing.assert_almost_equal(psi_psi.norm().eval(), psi.norm().eval()**2) def test_matmul(backend): - mat = np.random.rand(2,2) + mat = np.random.rand(2, 2) op = qu.QuOperator.from_tensor(mat, [0], [1], backend=backend) res = (op @ op).eval() np.testing.assert_allclose(res, mat @ mat) @@ -143,17 +143,17 @@ def test_mul(backend): def test_expectations(backend): if backend == 'pytorch': - psi_tensor = np.random.rand(2,2,2) - op_tensor = np.random.rand(2,2) + psi_tensor = np.random.rand(2, 2, 2) + op_tensor = np.random.rand(2, 2) else: - psi_tensor = np.random.rand(2,2,2) + 1.j * np.random.rand(2,2,2) - op_tensor = np.random.rand(2,2) + 1.j * np.random.rand(2,2) + psi_tensor = np.random.rand(2, 2, 2) + 1.j * np.random.rand(2, 2, 2) + op_tensor = np.random.rand(2, 2) + 1.j * np.random.rand(2, 2) psi = qu.QuVector.from_tensor(psi_tensor, backend=backend) op = qu.QuOperator.from_tensor(op_tensor, [0], [1], backend=backend) op_3 = op.tensor_product( - qu.identity((2,2), backend=backend, dtype=psi_tensor.dtype)) + qu.identity((2, 2), backend=backend, dtype=psi_tensor.dtype)) res1 = (psi.adjoint() @ op_3 @ psi).eval() rho_1 = psi.reduced_density([1, 2]) # trace out sites 2 and 3 @@ -163,7 +163,7 @@ def test_expectations(backend): def test_projector(backend): - psi_tensor = np.random.rand(2,2) + psi_tensor = np.random.rand(2, 2) psi_tensor /= np.linalg.norm(psi_tensor) psi = qu.QuVector.from_tensor(psi_tensor, backend=backend) P = psi.projector() From 4c54a6880ab0ab76ccd9797003d29bdc6c0eeaaa Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:04:18 -0800 Subject: [PATCH 32/39] CopyNode should not inflate its tensor just to tell you the dtype. --- tensornetwork/network_components.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tensornetwork/network_components.py b/tensornetwork/network_components.py index 1c9fa5c45..f8d713f58 100644 --- a/tensornetwork/network_components.py +++ b/tensornetwork/network_components.py @@ -626,6 +626,11 @@ def __init__(self, backend=backend_obj, shape=(dimension,) * rank) + @property + def dtype(self): + # Override so we don't construct the dense tensor when asked for the dtype! + return self.copy_node_dtype + def get_tensor(self) -> Tensor: return self.tensor From eb99692b17db6eee4f448463a0aa846a5b546edb Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:05:11 -0800 Subject: [PATCH 33/39] Correct two docstrings. --- tensornetwork/network_operations.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tensornetwork/network_operations.py b/tensornetwork/network_operations.py index 040a82ebb..c7547dc05 100644 --- a/tensornetwork/network_operations.py +++ b/tensornetwork/network_operations.py @@ -184,9 +184,6 @@ def remove_node(node: BaseNode) -> Tuple[Dict[Text, Edge], Dict[int, Edge]]: the newly broken edges. disconnected_edges_by_axis: A Dictionary mapping `node`'s axis numbers to the newly broken edges. - - Raises: - ValueError: If the node isn't in the network. """ disconnected_edges_by_name = {} disconnected_edges_by_axis = {} @@ -607,7 +604,7 @@ def reachable(inputs: Union[BaseNode, Iterable[BaseNode], Edge, Iterable[Edge]] Args: inputs: A `BaseNode`/`Edge` or collection of `BaseNodes`/`Edges` Returns: - A list of `BaseNode` objects that can be reached from `node` + A set of `BaseNode` objects that can be reached from `node` via connected edges. Raises: ValueError: If an unknown value for `strategy` is passed. From 5ff4a66239b92ff2b6883b44fd51af380cfd0791 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:06:30 -0800 Subject: [PATCH 34/39] Improve some tests. Particulary, test identity some more, since we now try to be efficient with CopyNode identity tensors. --- tensornetwork/quantum/quantum_test.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index f774c5e29..fa2af1eea 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -26,16 +26,28 @@ def test_constructor(backend): assert not op.is_scalar() assert not op.is_vector() assert not op.is_adjoint_vector() + assert len(op.out_edges) == 1 + assert len(op.in_edges) == 1 + assert op.out_edges[0] is psi_node[0] + assert op.in_edges[0] is psi_node[1] op = qu.quantum_constructor([psi_node[0], psi_node[1]], []) assert not op.is_scalar() assert op.is_vector() assert not op.is_adjoint_vector() + assert len(op.out_edges) == 2 + assert len(op.in_edges) == 0 + assert op.out_edges[0] is psi_node[0] + assert op.out_edges[1] is psi_node[1] op = qu.quantum_constructor([], [psi_node[0], psi_node[1]]) assert not op.is_scalar() assert not op.is_vector() assert op.is_adjoint_vector() + assert len(op.out_edges) == 0 + assert len(op.in_edges) == 2 + assert op.in_edges[0] is psi_node[0] + assert op.in_edges[1] is psi_node[1] with pytest.raises(ValueError): op = qu.quantum_constructor([], [], [psi_node]) @@ -45,6 +57,8 @@ def test_constructor(backend): assert op.is_scalar() assert not op.is_vector() assert not op.is_adjoint_vector() + assert len(op.out_edges) == 0 + assert len(op.in_edges) == 0 def test_checks(backend): @@ -52,7 +66,7 @@ def test_checks(backend): node2 = tn.Node(np.random.rand(2, 2), backend=backend) _ = node1[1] ^ node2[0] - # extra edges must be explicitly ignored + # extra dangling edges must be explicitly ignored with pytest.raises(ValueError): _ = qu.QuVector([node1[0]]) @@ -96,14 +110,21 @@ def test_identity(backend): E = qu.identity((2, 3, 4), backend=backend) assert E.trace().eval() == 24 - psi = qu.QuVector.from_tensor(np.random.rand(2, 2), backend=backend) + tensor = np.random.rand(2, 2) + psi = qu.QuVector.from_tensor(tensor, backend=backend) E = qu.identity((2, 2), backend=backend) - np.testing.assert_almost_equal((E @ psi).norm().eval(), psi.norm().eval()) + np.testing.assert_allclose((E @ psi).eval(), psi.eval()) + + op = qu.QuOperator.from_tensor(tensor, [0], [1], backend=backend) + op_I = op.tensor_product(E) + op_times_4 = op_I.partial_trace([1, 2]) + np.testing.assert_allclose(op_times_4.eval(), 4 * op.eval()) def test_tensor_product(backend): psi = qu.QuVector.from_tensor(np.random.rand(2, 2), backend=backend) psi_psi = psi.tensor_product(psi) + assert len(psi_psi.subsystem_edges) == 4 np.testing.assert_almost_equal(psi_psi.norm().eval(), psi.norm().eval()**2) From 00c88c0d2c450f88d3ccae7bd9964d255bb76678 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:07:29 -0800 Subject: [PATCH 35/39] Treat CopyNode identity tensors efficiently. Also rename shape -> space. --- tensornetwork/quantum/quantum.py | 66 +++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 9 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index c035f1457..e852aa8fa 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -24,7 +24,7 @@ import numpy as np from tensornetwork.network_components import Node, Edge, connect, CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable -from tensornetwork.network_operations import get_subgraph_dangling +from tensornetwork.network_operations import get_subgraph_dangling, remove_node from tensornetwork.contractors import greedy Tensor = Any @@ -57,22 +57,22 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], return QuOperator(out_edges, in_edges, ref_nodes, ignore_edges) -def identity(shape: Sequence[int], backend: Optional[Text] = None, +def identity(space: Sequence[int], backend: Optional[Text] = None, dtype: Type[np.number] = np.float64): """Construct a `QuOperator` representing the identity on a given space. Internally, this is done by constructing `CopyNode`s for each edge, with - dimension according to `shape`. + dimension according to `space`. Args: - shape: A sequence of integers for the dimensions of the tensor product + space: A sequence of integers for the dimensions of the tensor product factors of the space (the edges in the tensor network). backend: Optionally specify the backend to use for computations. dtype: The data type (for conversion to dense). Returns: The desired identity operator. """ - nodes = [CopyNode(2, d, backend=backend, dtype=dtype) for d in shape] + nodes = [CopyNode(2, d, backend=backend, dtype=dtype) for d in space] out_edges = [n[0] for n in nodes] in_edges = [n[1] for n in nodes] return quantum_constructor(out_edges, in_edges) @@ -99,6 +99,44 @@ def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]): i, e1.dimension, e2.dimension)) +def eliminate_identities(nodes: Collection[Node]): + """Eliminates any connected CopyNodes that are identity matrices. + + This will modify the network represented by `nodes`. + Only identities that are connected to other nodes are eliminated. + + Args: + nodes: Collection of nodes to search. + Returns: + nodes_dict: Dictionary mapping remaining Nodes to any replacements. + dangling_edges_dict: Dictionary specifying all dangling-edge replacements. + """ + nodes_dict = {} + dangling_edges_dict = {} + for n in nodes: + if isinstance(n, CopyNode) and n.get_rank() == 2 and not ( + n[0].is_dangling() and n[1].is_dangling()): + old_edges = [n[0], n[1]] + _, new_edges = remove_node(n) + if 0 in new_edges and 1 in new_edges: + e = connect(new_edges[0], new_edges[1]) + elif 0 in new_edges: # 1 was dangling + dangling_edges_dict[old_edges[1]] = new_edges[0] + elif 1 in new_edges: # 0 was dangling + dangling_edges_dict[old_edges[0]] = new_edges[1] + else: + # Trace of identity, so replace with a scalar node! + d = n.get_dimension(0) + # NOTE: Assume CopyNodes have numpy dtypes. + nodes_dict[n] = Node(np.array(d, dtype=n.dtype), backend=n.backend) + else: + for e in n.get_all_dangling(): + dangling_edges_dict[e] = e + nodes_dict[n] = n + + return nodes_dict, dangling_edges_dict + + class QuOperator(): """Represents a linear operator via a tensor network. @@ -133,8 +171,8 @@ def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], ref_nodes: Nodes used to refer to parts of the tensor network that are not connected to any input or output edges (for example: a scalar factor). - ignore_edges: Optional collection of edges to ignore when performing - consistency checks. + ignore_edges: Optional collection of dangling edges to ignore when + performing consistency checks. """ # TODO: Decide whether the user must also supply all nodes involved. # This would enable extra error checking and is probably clearer @@ -206,6 +244,10 @@ def check_network(self): for (i, e) in enumerate(self.in_edges): if not e.is_dangling(): raise ValueError("Input edge {} is not dangling!".format(i)) + for e in self.ignore_edges: + if not e.is_dangling(): + raise ValueError("ignore_edges contains non-dangling edge: {}".format( + str(e))) known_edges = set(self.in_edges) | set(self.out_edges) | self.ignore_edges all_dangling_edges = get_subgraph_dangling(self.nodes) @@ -253,11 +295,11 @@ def partial_trace(self, subsystems_to_trace_out: Collection[int]): Returns: A new QuOperator or QuScalar representing the result. """ - check_spaces(self.in_edges, self.out_edges) - out_edges_trace = [self.out_edges[i] for i in subsystems_to_trace_out] in_edges_trace = [self.in_edges[i] for i in subsystems_to_trace_out] + check_spaces(in_edges_trace, out_edges_trace) + nodes_dict, edge_dict = copy(self.nodes, False) for (e1, e2) in zip(out_edges_trace, in_edges_trace): edge_dict[e1] = edge_dict[e1] ^ edge_dict[e2] @@ -383,6 +425,12 @@ def contract(self, contractor: Callable = greedy, Returns: The present object. """ + nodes_dict, dangling_edges_dict = eliminate_identities(self.nodes) + self.in_edges = [dangling_edges_dict[e] for e in self.in_edges] + self.out_edges = [dangling_edges_dict[e] for e in self.out_edges] + self.ignore_edges = set(dangling_edges_dict[e] for e in self.ignore_edges) + self.check_network() + if final_edge_order: self.ref_nodes = set( [contractor(self.nodes, output_edge_order=final_edge_order)]) From fb4645660c84e90cda47e45f882e130ab585a5cb Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:41:41 -0800 Subject: [PATCH 36/39] Add support for copying CopyNodes. --- tensornetwork/network_operations.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tensornetwork/network_operations.py b/tensornetwork/network_operations.py index abc8a6241..fa718a430 100644 --- a/tensornetwork/network_operations.py +++ b/tensornetwork/network_operations.py @@ -125,23 +125,29 @@ def copy(nodes: Iterable[BaseNode], node_dict: A dictionary mapping the nodes to their copies. edge_dict: A dictionary mapping the edges to their copies. """ - #TODO: add support for copying CopyTensor - if conjugate: - node_dict = { - node: Node( + node_dict = {} + for node in nodes: + if isinstance(node, CopyNode): + node_dict[node] = CopyNode( + node.rank, + node.dimension, + name=node.name, + axis_names=node.axis_names, + backend=node.backend, + dtype=node.dtype) + else: + if conjugate: + node_dict[node] = Node( node.backend.conj(node.tensor), name=node.name, axis_names=node.axis_names, - backend=node.backend) for node in nodes - } - else: - node_dict = { - node: Node( + backend=node.backend) + else: + node_dict[node] = Node( node.tensor, name=node.name, axis_names=node.axis_names, - backend=node.backend) for node in nodes - } + backend=node.backend) edge_dict = {} for edge in get_all_edges(nodes): node1 = edge.node1 From f4630055757155cce23f5975f4f8fccea0ad2bd7 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:42:15 -0800 Subject: [PATCH 37/39] Propagate output edges properly. --- tensornetwork/quantum/quantum.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index e852aa8fa..089e6e933 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -429,9 +429,12 @@ def contract(self, contractor: Callable = greedy, self.in_edges = [dangling_edges_dict[e] for e in self.in_edges] self.out_edges = [dangling_edges_dict[e] for e in self.out_edges] self.ignore_edges = set(dangling_edges_dict[e] for e in self.ignore_edges) + self.ref_nodes = set( + nodes_dict[n] for n in self.ref_nodes if n in nodes_dict) self.check_network() if final_edge_order: + final_edge_order = [dangling_edges_dict[e] for e in final_edge_order] self.ref_nodes = set( [contractor(self.nodes, output_edge_order=final_edge_order)]) else: From 7ef2ba38dc9bbbc422c2dc6874362b24de4cdffb Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 16:45:02 -0800 Subject: [PATCH 38/39] Test that CopyNodes are propagated. Also do a CopyNode sandwich test. --- tensornetwork/quantum/quantum_test.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tensornetwork/quantum/quantum_test.py b/tensornetwork/quantum/quantum_test.py index fa2af1eea..4a9ae113d 100644 --- a/tensornetwork/quantum/quantum_test.py +++ b/tensornetwork/quantum/quantum_test.py @@ -108,13 +108,21 @@ def test_from_tensor(backend): def test_identity(backend): E = qu.identity((2, 3, 4), backend=backend) - assert E.trace().eval() == 24 + for n in E.nodes: + assert isinstance(n, tn.CopyNode) + twentyfour = E.trace() + for n in twentyfour.nodes: + assert isinstance(n, tn.CopyNode) + assert twentyfour.eval() == 24 tensor = np.random.rand(2, 2) psi = qu.QuVector.from_tensor(tensor, backend=backend) E = qu.identity((2, 2), backend=backend) np.testing.assert_allclose((E @ psi).eval(), psi.eval()) + np.testing.assert_allclose( + (psi.adjoint() @ E @ psi).eval(), psi.norm().eval()) + op = qu.QuOperator.from_tensor(tensor, [0], [1], backend=backend) op_I = op.tensor_product(E) op_times_4 = op_I.partial_trace([1, 2]) From cb9189c2addb79fc5baa4e9fbc5039281a205612 Mon Sep 17 00:00:00 2001 From: Ashley Milsted Date: Wed, 11 Dec 2019 17:12:06 -0800 Subject: [PATCH 39/39] Improve typing. Also more shape -> space. --- tensornetwork/quantum/quantum.py | 103 ++++++++++++++++++------------- 1 file changed, 60 insertions(+), 43 deletions(-) diff --git a/tensornetwork/quantum/quantum.py b/tensornetwork/quantum/quantum.py index 089e6e933..33b1313d5 100644 --- a/tensornetwork/quantum/quantum.py +++ b/tensornetwork/quantum/quantum.py @@ -20,9 +20,10 @@ the vectors and operators are represented by tensor networks. """ from typing import Any, Union, Callable, Optional, Sequence, Collection, Text -from typing import Type +from typing import Tuple, Set, List, Type import numpy as np -from tensornetwork.network_components import Node, Edge, connect, CopyNode +from tensornetwork.network_components import BaseNode, Node, Edge, connect +from tensornetwork.network_components import CopyNode from tensornetwork.network_operations import get_all_nodes, copy, reachable from tensornetwork.network_operations import get_subgraph_dangling, remove_node from tensornetwork.contractors import greedy @@ -30,8 +31,9 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], - ref_nodes: Optional[Collection[Node]] = None, - ignore_edges: Optional[Collection[Edge]] = None): + ref_nodes: Optional[Collection[BaseNode]] = None, + ignore_edges: Optional[Collection[Edge]] = None +) -> "QuOperator": """Constructs an appropriately specialized QuOperator. If there are no edges, creates a QuScalar. If the are only output (input) @@ -58,7 +60,7 @@ def quantum_constructor(out_edges: Sequence[Edge], in_edges: Sequence[Edge], def identity(space: Sequence[int], backend: Optional[Text] = None, - dtype: Type[np.number] = np.float64): + dtype: Type[np.number] = np.float64) -> "QuOperator": """Construct a `QuOperator` representing the identity on a given space. Internally, this is done by constructing `CopyNode`s for each edge, with @@ -78,7 +80,7 @@ def identity(space: Sequence[int], backend: Optional[Text] = None, return quantum_constructor(out_edges, in_edges) -def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]): +def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]) -> None: """Check the vector spaces represented by two lists of edges are compatible. The number of edges must be the same and the dimensions of each pair of edges @@ -99,7 +101,7 @@ def check_spaces(edges_1: Sequence[Edge], edges_2: Sequence[Edge]): i, e1.dimension, e2.dimension)) -def eliminate_identities(nodes: Collection[Node]): +def eliminate_identities(nodes: Collection[BaseNode]) -> Tuple[dict, dict]: """Eliminates any connected CopyNodes that are identity matrices. This will modify the network represented by `nodes`. @@ -155,8 +157,8 @@ class QuOperator(): __array_priority__ = 100.0 # for correct __rmul__ with scalar ndarrays def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], - ref_nodes: Optional[Collection[Node]] = None, - ignore_edges: Optional[Collection[Edge]] = None): + ref_nodes: Optional[Collection[BaseNode]] = None, + ignore_edges: Optional[Collection[Edge]] = None) -> None: """Creates a new `QuOperator` from a tensor network. This encapsulates an existing tensor network, interpreting it as a linear @@ -188,7 +190,8 @@ def __init__(self, out_edges: Sequence[Edge], in_edges: Sequence[Edge], @classmethod def from_tensor(cls, tensor: Tensor, out_axes: Sequence[int], - in_axes: Sequence[int], backend: Optional[Text] = None): + in_axes: Sequence[int], backend: Optional[Text] = None + ) -> "QuOperator": """Construct a `QuOperator` directly from a single tensor. This first wraps the tensor in a `Node`, then constructs the `QuOperator` @@ -208,30 +211,30 @@ def from_tensor(cls, tensor: Tensor, out_axes: Sequence[int], return cls(out_edges, in_edges, set([n])) @property - def nodes(self): + def nodes(self) -> Set[BaseNode]: """All tensor-network nodes involved in the operator. """ return reachable( get_all_nodes(self.out_edges + self.in_edges) | self.ref_nodes) @property - def shape_in(self): + def in_space(self) -> List[int]: return [e.dimension for e in self.in_edges] @property - def shape_out(self): + def out_space(self) -> List[int]: return [e.dimension for e in self.out_edges] - def is_scalar(self): + def is_scalar(self) -> bool: return len(self.out_edges) == 0 and len(self.in_edges) == 0 - def is_vector(self): + def is_vector(self) -> bool: return len(self.out_edges) > 0 and len(self.in_edges) == 0 - def is_adjoint_vector(self): + def is_adjoint_vector(self) -> bool: return len(self.out_edges) == 0 and len(self.in_edges) > 0 - def check_network(self): + def check_network(self) -> None: """Check that the network has the expected dimensionality. This checks that all input and output edges are dangling and that there @@ -255,7 +258,7 @@ def check_network(self): raise ValueError("The network includes unexpected dangling edges (that " "are not members of ignore_edges).") - def adjoint(self): + def adjoint(self) -> "QuOperator": """The adjoint of the operator. This creates a new `QuOperator` with complex-conjugate copies of all @@ -269,18 +272,19 @@ def adjoint(self): return quantum_constructor( out_edges, in_edges, ref_nodes, ignore_edges) - def trace(self): + def trace(self) -> "QuOperator": """The trace of the operator. """ return self.partial_trace(range(len(self.in_edges))) - def norm(self): + def norm(self) -> "QuOperator": """The norm of the operator. This is the 2-norm (also known as the Frobenius or Hilbert-Schmidt norm). """ return (self.adjoint() @ self).trace() - def partial_trace(self, subsystems_to_trace_out: Collection[int]): + def partial_trace(self, subsystems_to_trace_out: Collection[int] + ) -> "QuOperator": """The partial trace of the operator. Subsystems to trace out are supplied as indices, so that dangling edges @@ -316,7 +320,7 @@ def partial_trace(self, subsystems_to_trace_out: Collection[int]): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __matmul__(self, other: "QuOperator"): + def __matmul__(self, other: "QuOperator") -> "QuOperator": """The action of this operator on another. Given `QuOperator`s `A` and `B`, produces a new `QuOperator` for `A @ B`, @@ -347,7 +351,8 @@ def __matmul__(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) - def __mul__(self, other: Union["QuOperator", Node, Tensor]): + def __mul__(self, other: Union["QuOperator", BaseNode, Tensor] + ) -> "QuOperator": """Scalar multiplication of operators. Given two operators `A` and `B`, one of the which is a scalar (it has no @@ -360,7 +365,7 @@ def __mul__(self, other: Union["QuOperator", Node, Tensor]): Note: This is a special case of `tensor_product()`. """ if not isinstance(other, QuOperator): - if isinstance(other, Node): + if isinstance(other, BaseNode): node = other else: node = Node(other, backend=self.nodes.pop().backend) @@ -375,12 +380,12 @@ def __mul__(self, other: Union["QuOperator", Node, Tensor]): raise ValueError("Elementwise multiplication is only supported if at " "least one of the arguments is a scalar.") - def __rmul__(self, other: Union["QuOperator", Node, Tensor]): + def __rmul__(self, other: Union["QuOperator", BaseNode, Tensor]) -> "QuOperator": """Scalar multiplication of operators. See `.__mul__()`. """ return self.__mul__(other) - def tensor_product(self, other: "QuOperator"): + def tensor_product(self, other: "QuOperator") -> "QuOperator": """Tensor product with another operator. Given two operators `A` and `B`, produces a new operator `AB` representing @@ -411,7 +416,8 @@ def tensor_product(self, other: "QuOperator"): return quantum_constructor(out_edges, in_edges, ref_nodes, ignore_edges) def contract(self, contractor: Callable = greedy, - final_edge_order: Optional[Sequence[Edge]] = None): + final_edge_order: Optional[Sequence[Edge]] = None + ) -> "QuOperator": """Contract the tensor network in place. This modifies the tensor network representation of the operator (or vector, @@ -442,7 +448,7 @@ def contract(self, contractor: Callable = greedy, return self def eval(self, contractor: Callable = greedy, - final_edge_order: Optional[Sequence[Edge]] = None): + final_edge_order: Optional[Sequence[Edge]] = None) -> Tensor: """Contracts the tensor network in place and returns the final tensor. Note that this modifies the tensor network representing the operator. @@ -478,8 +484,8 @@ class QuVector(QuOperator): """Represents a (column) vector via a tensor network. """ def __init__(self, subsystem_edges: Sequence[Edge], - ref_nodes: Optional[Collection[Node]] = None, - ignore_edges: Optional[Collection[Edge]] = None): + ref_nodes: Optional[Collection[BaseNode]] = None, + ignore_edges: Optional[Collection[Edge]] = None) -> None: """Constructs a new `QuVector` from a tensor network. This encapsulates an existing tensor network, interpreting it as a (column) @@ -498,7 +504,7 @@ def __init__(self, subsystem_edges: Sequence[Edge], @classmethod def from_tensor(cls, tensor: Tensor, subsystem_axes: Optional[Sequence[int]] = None, - backend: Optional[Text] = None): + backend: Optional[Text] = None) -> "QuVector": """Construct a `QuVector` directly from a single tensor. This first wraps the tensor in a `Node`, then constructs the `QuVector` @@ -521,13 +527,18 @@ def from_tensor(cls, tensor: Tensor, return cls(subsystem_edges) @property - def subsystem_edges(self): + def subsystem_edges(self) -> List[Edge]: return self.out_edges - def projector(self): + @property + def space(self) -> List[int]: + return self.out_space + + def projector(self) -> "QuOperator": return self @ self.adjoint() - def reduced_density(self, subsystems_to_trace_out: Collection[int]): + def reduced_density(self, subsystems_to_trace_out: Collection[int] + ) -> "QuOperator": rho = self.projector() return rho.partial_trace(subsystems_to_trace_out) @@ -536,8 +547,8 @@ class QuAdjointVector(QuOperator): """Represents an adjoint (row) vector via a tensor network. """ def __init__(self, subsystem_edges: Sequence[Edge], - ref_nodes: Optional[Collection[Node]] = None, - ignore_edges: Optional[Collection[Edge]] = None): + ref_nodes: Optional[Collection[BaseNode]] = None, + ignore_edges: Optional[Collection[Edge]] = None) -> None: """Constructs a new `QuAdjointVector` from a tensor network. This encapsulates an existing tensor network, interpreting it as an adjoint @@ -556,7 +567,7 @@ def __init__(self, subsystem_edges: Sequence[Edge], @classmethod def from_tensor(cls, tensor: Tensor, subsystem_axes: Optional[Sequence[int]] = None, - backend: Optional[Text] = None): + backend: Optional[Text] = None) -> "QuAdjointVector": """Construct a `QuAdjointVector` directly from a single tensor. This first wraps the tensor in a `Node`, then constructs the @@ -579,13 +590,18 @@ def from_tensor(cls, tensor: Tensor, return cls(subsystem_edges) @property - def subsystem_edges(self): + def subsystem_edges(self) -> List[Edge]: return self.in_edges - def projector(self): + @property + def space(self) -> List[int]: + return self.in_space + + def projector(self) -> "QuOperator": return self.adjoint() @ self - def reduced_density(self, subsystems_to_trace_out: Collection[int]): + def reduced_density(self, subsystems_to_trace_out: Collection[int] + ) -> "QuOperator": rho = self.projector() return rho.partial_trace(subsystems_to_trace_out) @@ -593,8 +609,8 @@ def reduced_density(self, subsystems_to_trace_out: Collection[int]): class QuScalar(QuOperator): """Represents a scalar via a tensor network. """ - def __init__(self, ref_nodes: Collection[Node], - ignore_edges: Optional[Collection[Edge]] = None): + def __init__(self, ref_nodes: Collection[BaseNode], + ignore_edges: Optional[Collection[Edge]] = None) -> None: """Constructs a new `QuScalar` from a tensor network. This encapsulates an existing tensor network, interpreting it as a scalar. @@ -608,7 +624,8 @@ def __init__(self, ref_nodes: Collection[Node], super().__init__([], [], ref_nodes, ignore_edges) @classmethod - def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None): + def from_tensor(cls, tensor: Tensor, backend: Optional[Text] = None + ) -> "QuScalar": """Construct a `QuScalar` directly from a single tensor. This first wraps the tensor in a `Node`, then constructs the