/
tensor_arbgeom.py
2121 lines (1807 loc) · 70.9 KB
/
tensor_arbgeom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Classes and algorithms related to arbitrary geometry tensor networks."""
import contextlib
import functools
from operator import add
from autoray import dag, do, size
from ..utils import check_opt, deprecated, ensure_dict
from ..utils import progbar as Progbar
from . import decomp
from .contraction import get_symbol
from .tensor_core import (
TensorNetwork,
group_inds,
oset,
rand_uuid,
tags_to_oset,
)
def get_coordinate_formatter(ndims):
return ",".join("{}" for _ in range(ndims))
def tensor_network_align(*tns, ind_ids=None, trace=False, inplace=False):
r"""Align an arbitrary number of tensor networks in a stack-like geometry::
a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a
| | | | | | | | | | | | | | | | | | <- ind_ids[0] (defaults to 1st id)
b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b
| | | | | | | | | | | | | | | | | | <- ind_ids[1]
...
| | | | | | | | | | | | | | | | | | <- ind_ids[-2]
y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y
| | | | | | | | | | | | | | | | | | <- ind_ids[-1]
z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z
Parameters
----------
tns : sequence of TensorNetwork
The TNs to align, should be structured and either effective 'vectors'
(have a ``site_ind_id``) or 'operators' (have a ``up_ind_id`` and
``lower_ind_id``).
ind_ids : None, or sequence of str
String with format specifiers to id each level of sites with. Will be
automatically generated like ``(tns[0].site_ind_id, "__ind_a{}__",
"__ind_b{}__", ...)`` if not given.
inplace : bool
Whether to modify the input tensor networks inplace.
Returns
-------
tns_aligned : sequence of TensorNetwork
"""
if not inplace:
tns = [tn.copy() for tn in tns]
n = len(tns)
coordinate_formatter = get_coordinate_formatter(tns[0]._NDIMS)
if ind_ids is None:
if hasattr(tns[0], "site_ind_id"):
ind_ids = [tns[0].site_ind_id]
else:
ind_ids = [tns[0].lower_ind_id]
ind_ids.extend(
f"__ind_{get_symbol(i)}{coordinate_formatter}__"
for i in range(n - 2)
)
else:
ind_ids = tuple(ind_ids)
for i, tn in enumerate(tns):
if hasattr(tn, "site_ind_id"):
if i == 0:
tn.site_ind_id = ind_ids[i]
elif i == n - 1:
tn.site_ind_id = ind_ids[i - 1]
else:
raise ValueError(
"An TN 'vector' can only be aligned as the "
"first or last TN in a sequence."
)
elif hasattr(tn, "upper_ind_id") and hasattr(tn, "lower_ind_id"):
if i != 0:
tn.upper_ind_id = ind_ids[i - 1]
if i != n - 1:
tn.lower_ind_id = ind_ids[i]
else:
raise ValueError("Can only align vectors and operators currently.")
if trace:
tns[-1].lower_ind_id = tns[0].upper_ind_id
return tns
def tensor_network_apply_op_vec(
A,
x,
which_A="lower",
contract=False,
fuse_multibonds=True,
compress=False,
inplace=False,
inplace_A=False,
**compress_opts,
):
"""Apply a general a general tensor network representing an operator (has
``upper_ind_id`` and ``lower_ind_id``) to a tensor network representing a
vector (has ``site_ind_id``), by contracting each pair of tensors at each
site then compressing the resulting tensor network. How the compression
takes place is determined by the type of tensor network passed in. The
returned tensor network has the same site indices as ``x``, and it is
the ``lower_ind_id`` of ``A`` that is contracted.
This is like performing ``A.to_dense() @ x.to_dense()``, or the transpose
thereof, depending on the value of ``which_A``.
Parameters
----------
A : TensorNetworkGenOperator
The tensor network representing the operator.
x : TensorNetworkGenVector
The tensor network representing the vector.
which_A : {"lower", "upper"}, optional
Whether to contract the lower or upper indices of ``A`` with the site
indices of ``x``.
contract : bool
Whether to contract the tensors at each site after applying the
operator, yielding a single tensor at each site.
fuse_multibonds : bool
If ``contract=True``, whether to fuse any multibonds after contracting
the tensors at each site.
compress : bool
Whether to compress the resulting tensor network.
inplace : bool
Whether to modify ``x``, the input vector tensor network inplace.
inplace_A : bool
Whether to modify ``A``, the operator tensor network inplace.
compress_opts
Options to pass to ``tn.compress``, where ``tn`` is the resulting
tensor network, if ``compress=True``.
Returns
-------
TensorNetworkGenVector
The same type as ``x``.
"""
x = x if inplace else x.copy()
A = A if inplace_A else A.copy()
coordinate_formatter = get_coordinate_formatter(A._NDIMS)
inner_ind_id = rand_uuid() + f"{coordinate_formatter}"
if which_A == "lower":
# align the indices
#
# | <- upper_ind_id to be site_ind_id (outerid)
# -A- ...
# | <- lower_ind_id to be innerid
# :
# | <- site_ind_id to be innerid
# -x- ...
#
A.lower_ind_id = inner_ind_id
A.upper_ind_id = x.site_ind_id
elif which_A == "upper":
# transposed application
A.upper_ind_id = inner_ind_id
A.lower_ind_id = x.site_ind_id
else:
raise ValueError(
f"Invalid `which_A`: {which_A}, should be 'lower' or 'upper'."
)
# only want to reindex on sites that being acted on
sites_present_in_A = tuple(A.gen_sites_present())
x.reindex_sites_(inner_ind_id, where=sites_present_in_A)
# combine the tensor networks
x |= A
if contract:
# optionally contract all tensor at each site
for site in sites_present_in_A:
x ^= site
if fuse_multibonds:
x.fuse_multibonds_()
# optionally compress
if compress:
x.compress(**compress_opts)
return x
def tensor_network_apply_op_op(
A,
B,
which_A="lower",
which_B="upper",
contract=False,
fuse_multibonds=True,
compress=False,
inplace=False,
inplace_A=False,
**compress_opts,
):
"""Apply the operator (has upper and lower site inds) represented by tensor
network ``A`` to the operator represented by tensor network ``B``. The
resulting tensor network has the same upper and lower indices as ``B``.
Optionally contract the tensors at each site, fuse any multibonds, and
compress the resulting tensor network.
This is like performing ``A.to_dense() @ B.to_dense()``, or various
combinations of tranposes thereof, depending on the values of ``which_A``
and ``which_B``.
Parameters
----------
A : TensorNetworkGenOperator
The tensor network representing the operator to apply.
B : TensorNetworkGenOperator
The tensor network representing the target operator.
which_A : {"lower", "upper"}, optional
Whether to contract the lower or upper indices of ``A``.
which_B : {"lower", "upper"}, optional
Whether to contract the lower or upper indices of ``B``.
contract : bool
Whether to contract the tensors at each site after applying the
operator, yielding a single tensor at each site.
fuse_multibonds : bool
If ``contract=True``, whether to fuse any multibonds after contracting
the tensors at each site.
compress : bool
Whether to compress the resulting tensor network.
inplace : bool
Whether to modify ``B``, the target tensor network inplace.
inplace_A : bool
Whether to modify ``A``, the applied operator tensor network inplace.
compress_opts
Options to pass to ``tn.compress``, where ``tn`` is the resulting
tensor network, if ``compress=True``.
Returns
-------
TensorNetworkGenOperator
The same type as ``B``.
"""
B = B if inplace else B.copy()
A = A if inplace_A else A.copy()
coordinate_formatter = get_coordinate_formatter(A._NDIMS)
inner_ind_id = rand_uuid() + f"{coordinate_formatter}"
if (which_A, which_B) == ("lower", "upper"):
# align the indices (by default lower of A joined with upper of B
# which corresponds to matrix multiplication):
#
# | <- A upper_ind_id to be upper_ind_id
# -A- ...
# | <- A lower_ind_id to be innerid
# :
# | <- B upper_ind_id to be innerid
# -B- ...
# | <- B lower_ind_id to be lower_ind_id
#
A.lower_ind_id = inner_ind_id
A.upper_ind_id = B.upper_ind_id
B.reindex_upper_sites_(inner_ind_id)
elif (which_A, which_B) == ("lower", "lower"):
# rest are just permutations of above ...
A.lower_ind_id = inner_ind_id
A.upper_ind_id = B.lower_ind_id
B.reindex_lower_sites_(inner_ind_id)
elif (which_A, which_B) == ("upper", "upper"):
A.upper_ind_id = inner_ind_id
A.lower_ind_id = B.upper_ind_id
B.reindex_upper_sites_(inner_ind_id)
elif (which_A, which_B) == ("upper", "lower"):
A.upper_ind_id = inner_ind_id
A.lower_ind_id = B.lower_ind_id
B.reindex_lower_sites_(inner_ind_id)
else:
raise ValueError("Invalid `which_A` and `which_B` combination.")
# combine the tensor networks
B |= A
if contract:
# optionally contract all tensor at each site
for site in B.gen_sites_present():
B ^= site
if fuse_multibonds:
B.fuse_multibonds_()
if compress:
B.compress(**compress_opts)
return B
def create_lazy_edge_map(tn, site_tags=None):
"""Given a tensor network, where each tensor is in exactly one group or
'site', compute which sites are connected to each other, without checking
each pair.
Parameters
----------
tn : TensorNetwork
The tensor network to analyze.
site_tags : None or sequence of str, optional
Which tags to consider as 'sites', by default uses ``tn.site_tags``.
Returns
-------
edges : dict[tuple[str, str], list[str]]
Each key is a sorted pair of tags, which are connected, and the value
is a list of the indices connecting them.
neighbors : dict[str, list[str]]
For each site tag, the other site tags it is connected to.
"""
if site_tags is None:
site_tags = set(tn.site_tags)
else:
site_tags = set(site_tags)
edges = {}
neighbors = {}
for ix in tn.ind_map:
ts = tn._inds_get(ix)
tags = {tag for t in ts for tag in t.tags if tag in site_tags}
if len(tags) >= 2:
# index spans multiple sites
i, j = tuple(sorted(tags))
if (i, j) not in edges:
# record indices per edge
edges[(i, j)] = [ix]
# add to neighbor map
neighbors.setdefault(i, []).append(j)
neighbors.setdefault(j, []).append(i)
else:
# already processed this edge
edges[(i, j)].append(ix)
return edges, neighbors
def tensor_network_ag_sum(
tna,
tnb,
site_tags=None,
negate=False,
compress=False,
inplace=False,
**compress_opts,
):
"""Add two tensor networks with arbitrary, but matching, geometries. They
should have the same site tags, with a single tensor per site and sites
connected by a single index only (but the name of this index can differ in
the two TNs).
Parameters
----------
tna : TensorNetworkGen
The first tensor network to add.
tnb : TensorNetworkGen
The second tensor network to add.
site_tags : None or sequence of str, optional
Which tags to consider as 'sites', by default uses ``tna.site_tags``.
negate : bool, optional
Whether to negate the second tensor network before adding.
compress : bool, optional
Whether to compress the resulting tensor network, by calling the
``compress`` method with the given options.
inplace : bool, optional
Whether to modify the first tensor network inplace.
Returns
-------
TensorNetworkGen
The resulting tensor network.
"""
tna = tna if inplace else tna.copy()
edges_a, neighbors_a = create_lazy_edge_map(tna, site_tags)
edges_b, _ = create_lazy_edge_map(tnb, site_tags)
reindex_map = {}
for (si, sj), inds in edges_a.items():
(ixa,) = inds
(ixb,) = edges_b.pop((si, sj))
reindex_map[ixb] = ixa
if edges_b:
raise ValueError("Not all edges matched.")
for si in neighbors_a:
ta, tb = tna[si], tnb[si]
# the local outer indices
sum_inds = [ix for ix in tb.inds if ix not in reindex_map]
tb = tb.reindex(reindex_map)
if negate:
tb.negate_()
# only need to negate a single tensor
negate = False
ta.direct_product_(tb, sum_inds)
if compress:
tna.compress(**compress_opts)
return tna
class TensorNetworkGen(TensorNetwork):
"""A tensor network which notionally has a single tensor per 'site',
though these could be labelled arbitrarily could also be linked in an
arbitrary geometry by bonds.
"""
_NDIMS = 1
_EXTRA_PROPS = (
"_sites",
"_site_tag_id",
)
def _compatible_arbgeom(self, other):
"""Check whether ``self`` and ``other`` represent the same set of
sites and are tagged equivalently.
"""
return isinstance(other, TensorNetworkGen) and all(
getattr(self, e, 0) == getattr(other, e, 1)
for e in TensorNetworkGen._EXTRA_PROPS
)
def combine(self, other, *, virtual=False, check_collisions=True):
"""Combine this tensor network with another, returning a new tensor
network. If the two are compatible, cast the resulting tensor network
to a :class:`TensorNetworkGen` instance.
Parameters
----------
other : TensorNetworkGen or TensorNetwork
The other tensor network to combine with.
virtual : bool, optional
Whether the new tensor network should copy all the incoming tensors
(``False``, the default), or view them as virtual (``True``).
check_collisions : bool, optional
Whether to check for index collisions between the two tensor
networks before combining them. If ``True`` (the default), any
inner indices that clash will be mangled.
Returns
-------
TensorNetworkGen or TensorNetwork
"""
new = super().combine(
other, virtual=virtual, check_collisions=check_collisions
)
if self._compatible_arbgeom(other):
new.view_as_(TensorNetworkGen, like=self)
return new
@property
def nsites(self):
"""The total number of sites."""
return len(self._sites)
def gen_site_coos(self):
"""Generate the coordinates of all sites, same as ``self.sites``."""
return self._sites
@property
def sites(self):
"""Tuple of the possible sites in this tensor network."""
sites = getattr(self, "_sites", None)
if sites is None:
sites = tuple(self.gen_site_coos())
return sites
def _get_site_set(self):
"""The set of all sites."""
if getattr(self, "_site_set", None) is None:
self._site_set = set(self.sites)
return self._site_set
def gen_sites_present(self):
"""Generate the sites which are currently present (e.g. if a local view
of a larger tensor network), based on whether their tags are present.
Examples
--------
>>> tn = qtn.TN3D_rand(4, 4, 4, 2)
>>> tn_sub = tn.select_local('I1,2,3', max_distance=1)
>>> list(tn_sub.gen_sites_present())
[(0, 2, 3), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 3)]
"""
return (
site
for site in self.gen_site_coos()
if self.site_tag(site) in self.tag_map
)
@property
def site_tag_id(self):
"""The string specifier for tagging each site of this tensor network."""
return self._site_tag_id
def site_tag(self, site):
"""The name of the tag specifiying the tensor at ``site``."""
return self.site_tag_id.format(site)
def retag_sites(self, new_id, where=None, inplace=False):
"""Modify the site tags for all or some tensors in this tensor network
(without changing the ``site_tag_id``).
Parameters
----------
new_id : str
A string with a format placeholder to accept a site, e.g. "S{}".
where : None or sequence
Which sites to update the index labels on. If ``None`` (default)
all sites.
inplace : bool
Whether to retag in place.
"""
if where is None:
where = self.gen_sites_present()
return self.retag(
{self.site_tag(x): new_id.format(x) for x in where},
inplace=inplace,
)
@property
def site_tags(self):
"""All of the site tags."""
if getattr(self, "_site_tags", None) is None:
self._site_tags = tuple(map(self.site_tag, self.gen_site_coos()))
return self._site_tags
@property
def site_tags_present(self):
"""All of the site tags still present in this tensor network."""
return tuple(map(self.site_tag, self.gen_sites_present()))
@site_tag_id.setter
def site_tag_id(self, new_id):
if self._site_tag_id != new_id:
self.retag_sites(new_id, inplace=True)
self._site_tag_id = new_id
self._site_tags = None
def retag_all(self, new_id, inplace=False):
"""Retag all sites and change the ``site_tag_id``."""
tn = self if inplace else self.copy()
tn.site_tag_id = new_id
return tn
retag_all_ = functools.partialmethod(retag_all, inplace=True)
def _get_site_tag_set(self):
"""The oset of all site tags."""
if getattr(self, "_site_tag_set", None) is None:
self._site_tag_set = set(self.site_tags)
return self._site_tag_set
def filter_valid_site_tags(self, tags):
"""Get the valid site tags from ``tags``."""
return oset(sorted(self._get_site_tag_set().intersection(tags)))
def maybe_convert_coo(self, x):
"""Check if ``x`` is a valid site and convert to the corresponding site
tag if so, else return ``x``.
"""
try:
if x in self._get_site_set():
return self.site_tag(x)
except TypeError:
pass
return x
def gen_tags_from_coos(self, coos):
"""Generate the site tags corresponding to the given coordinates."""
return map(self.site_tag, coos)
def _get_tids_from_tags(self, tags, which="all"):
"""This is the function that lets coordinates such as ``site`` be
used for many 'tag' based functions.
"""
tags = self.maybe_convert_coo(tags)
return super()._get_tids_from_tags(tags, which=which)
def reset_cached_properties(self):
"""Reset any cached properties, one should call this when changing the
actual geometry of a TN inplace, for example.
"""
self._site_set = None
self._site_tag_set = None
self._site_tags = None
@functools.wraps(tensor_network_align)
def align(self, *args, inplace=False, **kwargs):
return tensor_network_align(self, *args, inplace=inplace, **kwargs)
align_ = functools.partialmethod(align, inplace=True)
def __add__(self, other):
return tensor_network_ag_sum(self, other)
def __sub__(self, other):
return tensor_network_ag_sum(self, other, negate=True)
def __iadd__(self, other):
return tensor_network_ag_sum(self, other, inplace=True)
def __isub__(self, other):
return tensor_network_ag_sum(self, other, negate=True, inplace=True)
def gauge_product_boundary_vector(
tn,
tags,
which="all",
max_bond=1,
smudge=1e-6,
canonize_distance=0,
select_local_distance=None,
select_local_opts=None,
**contract_around_opts,
):
tids = tn._get_tids_from_tags(tags, which)
# form the double layer tensor network - this is the TN we will
# generate the actual gauges with
if select_local_distance is None:
# use the whole tensor network ...
outer_inds = tn.outer_inds()
dtn = tn.H & tn
else:
# ... or just a local patch
select_local_opts = ensure_dict(select_local_opts)
ltn = tn._select_local_tids(
tids,
max_distance=select_local_distance,
virtual=False,
**select_local_opts,
)
outer_inds = ltn.outer_inds()
dtn = ltn.H | ltn
# get all inds in the tagged region
region_inds = set.union(*(set(tn.tensor_map[tid].inds) for tid in tids))
# contract all 'physical' indices so that we have a single layer TN
# outside region and double layer sandwich inside region
for ix in outer_inds:
if (ix in region_inds) or (ix not in dtn.ind_map):
# 1st condition - don't contract region sandwich
# 2nd condition - if local selecting, will get multibonds so
# some indices already contracted
continue
dtn.contract_ind(ix)
# form the single layer boundary of double layer tagged region
dtids = dtn._get_tids_from_tags(tags, which)
dtn._contract_around_tids(
dtids,
min_distance=1,
max_bond=max_bond,
canonize_distance=canonize_distance,
**contract_around_opts,
)
# select this boundary and compress to ensure it is a product operator
dtn = dtn._select_without_tids(dtids, virtual=True)
dtn.compress_all_(max_bond=1)
dtn.squeeze_()
# each tensor in the boundary should now have exactly two inds
# connecting to the top and bottom of the tagged region double
# layer. Iterate over these, inserting the gauge into the original
# tensor network that would turn each of these boundary tensors
# into identities.
for t in dtn:
(ix,) = [i for i in t.inds if i in region_inds]
_, s, VH = do("linalg.svd", t.data)
s = s + smudge
G = do("reshape", s**0.5, (-1, 1)) * VH
Ginv = dag(VH) * do("reshape", s**-0.5, (1, -1))
tid_l, tid_r = sorted(tn.ind_map[ix], key=lambda tid: tid in tids)
tn.tensor_map[tid_l].gate_(Ginv.T, ix)
tn.tensor_map[tid_r].gate_(G, ix)
return tn
_VALID_GATE_PROPAGATE = {"sites", "register", False, True}
_LAZY_GATE_CONTRACT = {
False,
"split-gate",
"swap-split-gate",
"auto-split-gate",
}
class TensorNetworkGenVector(TensorNetworkGen):
"""A tensor network which notionally has a single tensor and outer index
per 'site', though these could be labelled arbitrarily and could also be
linked in an arbitrary geometry by bonds.
"""
_EXTRA_PROPS = (
"_sites",
"_site_tag_id",
"_site_ind_id",
)
@property
def site_ind_id(self):
"""The string specifier for the physical indices."""
return self._site_ind_id
def site_ind(self, site):
return self.site_ind_id.format(site)
@property
def site_inds(self):
"""Return a tuple of all site indices."""
if getattr(self, "_site_inds", None) is None:
self._site_inds = tuple(map(self.site_ind, self.gen_site_coos()))
return self._site_inds
@property
def site_inds_present(self):
"""All of the site inds still present in this tensor network."""
return tuple(map(self.site_ind, self.gen_sites_present()))
def reset_cached_properties(self):
"""Reset any cached properties, one should call this when changing the
actual geometry of a TN inplace, for example.
"""
self._site_inds = None
return super().reset_cached_properties()
def reindex_sites(self, new_id, where=None, inplace=False):
"""Modify the site indices for all or some tensors in this vector
tensor network (without changing the ``site_ind_id``).
Parameters
----------
new_id : str
A string with a format placeholder to accept a site, e.g. "ket{}".
where : None or sequence
Which sites to update the index labels on. If ``None`` (default)
all sites.
inplace : bool
Whether to reindex in place.
"""
if where is None:
where = self.gen_sites_present()
return self.reindex(
{self.site_ind(x): new_id.format(x) for x in where},
inplace=inplace,
)
reindex_sites_ = functools.partialmethod(reindex_sites, inplace=True)
@site_ind_id.setter
def site_ind_id(self, new_id):
if self._site_ind_id != new_id:
self.reindex_sites_(new_id)
self._site_ind_id = new_id
self._site_inds = None
def reindex_all(self, new_id, inplace=False):
"""Reindex all physical sites and change the ``site_ind_id``."""
tn = self if inplace else self.copy()
tn.site_ind_id = new_id
return tn
reindex_all_ = functools.partialmethod(reindex_all, inplace=True)
def gen_inds_from_coos(self, coos):
"""Generate the site inds corresponding to the given coordinates."""
return map(self.site_ind, coos)
def phys_dim(self, site=None):
"""Get the physical dimension of ``site``, defaulting to the first site
if not specified.
"""
if site is None:
site = next(iter(self.gen_sites_present()))
return self.ind_size(self.site_ind(site))
def to_dense(
self, *inds_seq, to_qarray=False, to_ket=None, **contract_opts
):
"""Contract this tensor network 'vector' into a dense array. By
default, turn into a 'ket' ``qarray``, i.e. column vector of shape
``(d, 1)``.
Parameters
----------
inds_seq : sequence of sequences of str
How to group the site indices into the dense array. By default,
use a single group ordered like ``sites``, but only containing
those sites which are still present.
to_qarray : bool
Whether to turn the dense array into a ``qarray``, if the backend
would otherwise be ``'numpy'``.
to_ket : None or str
Whether to reshape the dense array into a ket (shape ``(d, 1)``
array). If ``None`` (default), do this only if the ``inds_seq`` is
not supplied.
contract_opts
Options to pass to
:meth:`~quimb.tensor.tensor_core.TensorNewtork.contract`.
Returns
-------
array
"""
if not inds_seq:
inds_seq = (self.site_inds_present,)
if to_ket is None:
to_ket = True
x = TensorNetwork.to_dense(
self, *inds_seq, to_qarray=to_qarray, **contract_opts
)
if to_ket:
x = do("reshape", x, (-1, 1))
return x
to_qarray = functools.partialmethod(to_dense, to_qarray=True)
def gate_with_op_lazy(self, A, transpose=False, inplace=False, **kwargs):
r"""Act lazily with the operator tensor network ``A``, which should
have matching structure, on this vector/state tensor network, like
``A @ x``. The returned tensor network will have the same structure as
this one, but with the operator gated in lazily, i.e. uncontracted.
.. math::
| x \rangle \rightarrow A | x \rangle
or (if ``transpose=True``):
.. math::
| x \rangle \rightarrow A^T | x \rangle
Parameters
----------
A : TensorNetworkGenOperator
The operator tensor network to gate with, or apply to this tensor
network.
transpose : bool, optional
Whether to contract the lower or upper indices of ``A`` with the
site indices of ``x``. If ``False`` (the default), the lower
indices of ``A`` will be contracted with the site indices of ``x``,
if ``True`` the upper indices of ``A`` will be contracted with
the site indices of ``x``, which is like applying ``A.T @ x``.
inplace : bool, optional
Whether to perform the gate operation inplace on this tensor
network.
Returns
-------
TensorNetworkGenVector
"""
return tensor_network_apply_op_vec(
A=A,
x=self,
which_A="upper" if transpose else "lower",
contract=False,
inplace=inplace,
**kwargs
)
gate_with_op_lazy_ = functools.partialmethod(
gate_with_op_lazy, inplace=True
)
def gate(
self,
G,
where,
contract=False,
tags=None,
propagate_tags=False,
info=None,
inplace=False,
**compress_opts,
):
r"""Apply a gate to this vector tensor network at sites ``where``. This
is essentially a wrapper around
:meth:`~quimb.tensor.tensor_core.TensorNetwork.gate_inds` apart from
``where`` can be specified as a list of sites, and tags can be
optionally, intelligently propagated to the new gate tensor.
.. math::
| \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle
Parameters
----------
G : array_ike
The gate array to apply, should match or be factorable into the
shape ``(*phys_dims, *phys_dims)``.
where : node or sequence[node]
The sites to apply the gate to.
contract : {False, True, 'split', 'reduce-split', 'split-gate',
'swap-split-gate', 'auto-split-gate'}, optional
How to apply the gate, see
:meth:`~quimb.tensor.tensor_core.TensorNetwork.gate_inds`.
tags : str or sequence of str, optional
Tags to add to the new gate tensor.
propagate_tags : {False, True, 'register', 'sites'}, optional
Whether to propagate tags to the new gate tensor::
- False: no tags are propagated
- True: all tags are propagated
- 'register': only site tags corresponding to ``where`` are
added.
- 'sites': all site tags on the current sites are propgated,
resulting in a lightcone like tagging.
info : None or dict, optional
Used to store extra optional information such as the singular
values if not absorbed.
inplace : bool, optional
Whether to perform the gate operation inplace on the tensor network
or not.
compress_opts
Supplied to :func:`~quimb.tensor.tensor_core.tensor_split` for any
``contract`` methods that involve splitting. Ignored otherwise.
Returns
-------
TensorNetworkGenVector
See Also
--------
TensorNetwork.gate_inds
"""
check_opt("propagate_tags", propagate_tags, _VALID_GATE_PROPAGATE)
tn = self if inplace else self.copy()
if not isinstance(where, (tuple, list)):
where = (where,)
inds = tuple(map(tn.site_ind, where))
# potentially add tags from current tensors to the new ones,
# only do this if we are lazily adding the gate tensor(s)
if (contract in _LAZY_GATE_CONTRACT) and (
propagate_tags in (True, "sites")
):
old_tags = oset.union(*(t.tags for t in tn._inds_get(*inds)))
if propagate_tags == "sites":
old_tags = tn.filter_valid_site_tags(old_tags)
tags = tags_to_oset(tags)
tags.update(old_tags)
# perform the actual gating
tn.gate_inds_(
G, inds, contract=contract, tags=tags, info=info, **compress_opts
)
# possibly add tags based on where the gate was applied
if propagate_tags == "register":
for ix, site in zip(inds, where):
(t,) = tn._inds_get(ix)
t.add_tag(tn.site_tag(site))
return tn
gate_ = functools.partialmethod(gate, inplace=True)