/
charges.py
1663 lines (1430 loc) · 64.9 KB
/
charges.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
r"""Basic definitions of a charge.
This module contains implementations for handling the quantum numbers ("charges") of
the :class:`~tenpy.linalg.np_conserved.Array`.
In particular, the classes :class:`ChargeInfo`, :class:`LegCharge` and :class:`LegPipe` are
implemented here.
.. note ::
The contents of this module are imported in :mod:`~tenpy.linalg.np_conserved`,
so you usually don't need to import this module in your application.
A detailed introduction to `np_conserved` can be found in :doc:`/intro/npc`.
In this module, some functions have the python decorator ``@use_cython``.
Functions with this decorator are replaced by the ones written in Cython, implemented in
the file ``tenpy/linalg/_npc_helper.pyx``.
For further details, see the definition of :func:`~tenpy.tools.optimization.use_cython`.
.. autodata:: QTYPE
"""
# Copyright 2018-2021 TeNPy Developers, GNU GPLv3
import numpy as np
import copy
import bisect
import warnings
from ..tools.misc import lexsort, inverse_permutation
from ..tools.string import vert_join
from ..tools.optimization import optimize, OptimizationFlag, use_cython
__all__ = ['ChargeInfo', 'LegCharge', 'LegPipe', 'QTYPE']
QTYPE = np.int_
"""Numpy data type for the charges."""
class ChargeInfo:
r"""Meta-data about the charge of a tensor.
Saves info about the nature of the charge of a tensor.
Provides :meth:`make_valid` for taking modulo `m`.
(This class is implemented in :mod:`tenpy.linalg.charges` but also imported in
:mod:`tenpy.linalg.np_conserved` for convenience.)
Parameters
----------
mod : iterable of QTYPE
The len gives the number of charges, `qnumber`.
Each entry is a positive integer, where
1 implies a :math:`U(1)` charge and `N`>1 implies a :math:`Z_N` symmetry.
Defaults to "trivial", i.e., no charge.
names : list of str
Descriptive names for the charges. Defaults to ``['']*qnumber``.
Attributes
----------
names : list of strings
A descriptive name for each of the charges. May have '' entries.
_mask : 1D array bool
mask ``(mod == 1)``, to speed up `make_valid` in pure python.
_mod_masked : 1D array QTYPE
Equivalent to ``self.mod[self._maks_mod1]``
_qnumber, _mod :
Storage of :attr:`qnumber` and :attr:`mod`.
Notes
-----
Instances of this class can (should) be shared between different `LegCharge` and `Array`'s.
"""
def __init__(self, mod=[], names=None):
mod = np.array(mod, dtype=QTYPE)
assert mod.ndim == 1
if names is None:
names = [''] * len(mod)
names = [str(n) for n in names]
self.__setstate__((len(mod), mod, names))
self.test_sanity() # checks for invalid arguments
def __getstate__(self):
"""Allow to pickle and copy."""
return (self._qnumber, self._mod, self.names)
def __setstate__(self, state):
"""Allow to pickle and copy."""
qnumber, mod, names = state
self._mod = mod
self._qnumber = mod.shape[0]
assert qnumber == self._qnumber
self._mask = np.not_equal(mod, 1) # where we need to take modulo in :meth:`make_valid`
self._mod_masked = mod[self._mask].copy() # only where mod != 1
self.names = names
def save_hdf5(self, hdf5_saver, h5gr, subpath):
"""Export `self` into a HDF5 file.
This method saves all the data it needs to reconstruct `self` with :meth:`from_hdf5`.
It stores the :attr:`names` under the path ``"names"``, and
:attr:`mod` as dataset ``"U1_ZN"``.
Parameters
----------
hdf5_saver : :class:`~tenpy.tools.hdf5_io.Hdf5Saver`
Instance of the saving engine.
h5gr : :class`Group`
HDF5 group which is supposed to represent `self`.
subpath : str
The `name` of `h5gr` with a ``'/'`` in the end.
"""
h5gr.attrs['num_charges'] = self._qnumber
hdf5_saver.save(self._mod, subpath + "U1_ZN")
hdf5_saver.save(self.names, subpath + "names")
@classmethod
def from_hdf5(cls, hdf5_loader, h5gr, subpath):
"""Load instance from a HDF5 file.
This method reconstructs a class instance from the data saved with :meth:`save_hdf5`.
The ``"U1_ZN"`` dataset is mandatory, ``'names'`` are optional.
Parameters
----------
hdf5_loader : :class:`~tenpy.tools.hdf5_io.Hdf5Loader`
Instance of the loading engine.
h5gr : :class:`Group`
HDF5 group which is represent the object to be constructed.
subpath : str
The `name` of `h5gr` with a ``'/'`` in the end.
Returns
-------
obj : cls
Newly generated class instance containing the required data.
"""
obj = cls.__new__(cls) # create class instance, no __init__() call
hdf5_loader.memorize_load(h5gr, obj)
qmod = hdf5_loader.load(subpath + "U1_ZN")
qmod = np.asarray(qmod, dtype=QTYPE)
qnumber = len(qmod)
if "names" in h5gr:
names = hdf5_loader.load(subpath + "names")
else:
names = [''] * qnumber
obj.__setstate__((qnumber, qmod, names))
obj.test_sanity()
return obj
@classmethod
def add(cls, chinfos):
"""Create a :class:`ChargeInfo` combining multiple charges.
Parameters
----------
chinfos : iterable of :class:`ChargeInfo`
ChargeInfo instances to be combined into a single one (in the given order).
Returns
-------
chinfo : :class:`ChargeInfo`
ChargeInfo combining all the given charges.
"""
charges = [ci.mod for ci in chinfos]
names = sum([ci.names for ci in chinfos], [])
return cls(np.concatenate(charges), names)
@classmethod
def drop(cls, chinfo, charge=None):
"""Remove a charge from a :class:`ChargeInfo`.
Parameters
----------
chinfo : :class:`ChargeInfo`
The ChargeInfo from where to drop/remove a charge.
charge : int | str
Number or `name` of the charge (within `chinfo`) which is to be dropped.
``None`` means dropping all charges.
Returns
-------
chinfo : :class:`ChargeInfo`
ChargeInfo where the specified charge is dropped.
"""
if charge is None:
return cls() # trivial charge
if isinstance(charge, str):
charge = chinfo.names.index(charge)
names = list(chinfo.names)
names.pop(charge)
return cls(np.delete(chinfo.mod, charge), names)
@classmethod
def change(cls, chinfo, charge, new_qmod, new_name=''):
"""Change the `qmod` of a given charge.
Parameters
----------
chinfo : :class:`ChargeInfo`
The ChargeInfo for which `qmod` of `charge` should be changed.
new_qmod : int
The new `qmod` to be set.
new_name : str
The new name of the charge.
Returns
-------
chinfo : :class:`ChargeInfo`
ChargeInfo where `qmod` of the specified charge was changed.
"""
if isinstance(charge, str):
charge = chinfo.names.index(charge)
names = list(chinfo.names)
names[charge] = new_name
mod = chinfo.mod.copy()
mod[charge] = new_qmod
return cls(mod, names)
def test_sanity(self):
"""Sanity check, raises ValueErrors, if something is wrong."""
if self._mod_masked.ndim != 1 or tuple(self.mod.shape) != (self.qnumber, ):
raise ValueError("mod has wrong shape")
if np.any(self._mod_masked <= 0):
raise ValueError("mod should be > 0")
if len(self.names) != self.qnumber:
raise ValueError("names has incompatible length with mod")
if np.any(self.mod < 0):
raise ValueError("mod with negative entries???")
@property
def qnumber(self):
"""The number of charges."""
return self._qnumber
@property
def mod(self):
"""Modulo how much each of the charges is taken.
Entries are 1 for a :math:`U(1)` charge, and N for a :math:`Z_N` symmetry.
"""
# The property makes `mod` readonly.
return self._mod
@use_cython(replacement='ChargeInfo_make_valid')
def make_valid(self, charges=None):
"""Take charges modulo self.mod.
Parameters
----------
charges : array_like or None
1D or 2D array of charges, last dimension `self.qnumber`
None defaults to trivial charges ``np.zeros(qnumber, dtype=QTYPE)``.
Returns
-------
charges :
A copy of `charges` taken modulo `mod`, but with ``x % 1 := x``
"""
if charges is None:
return np.zeros((self.qnumber, ), dtype=QTYPE)
charges = np.asarray(charges, dtype=QTYPE)
charges[..., self._mask] = np.mod(charges[..., self._mask], self._mod_masked)
return charges
@use_cython(replacement='ChargeInfo_check_valid')
def check_valid(self, charges):
r"""Check, if `charges` has all entries as expected from self.mod.
Parameters
----------
charges : 2D ndarray QTYPE_t
Charge values to be checked.
Returns
-------
res : bool
True, if all 0 <= charges <= self.mod (wherever self.mod != 1)
"""
charges = np.asarray(charges, dtype=QTYPE)[..., self._mask]
return np.all(np.logical_and(0 <= charges, charges < self._mod_masked))
def __repr__(self):
"""Full string representation."""
return "ChargeInfo({0!s}, {1!s})".format(list(self.mod), self.names)
def __eq__(self, other):
"""Compare self.mod and self.names for equality, ignore missing names."""
if self is other:
return True
if self.qnumber != other.qnumber:
return False
if not np.all(self.mod == other.mod):
return False
for l, r in zip(self.names, other.names):
if r != l and l != '' and r != '':
return False
return True
def __ne__(self, other):
r"""Define `self != other` as `not (self == other)`"""
return not self.__eq__(other)
class LegCharge:
r"""Save the charge data associated to a leg of a tensor.
This class is more or less a wrapper around a 2D numpy array `charges` and a 1D array `slices`.
See :doc:`/intro/npc` for more details.
(This class is implemented in :mod:`tenpy.linalg.charges` but also imported in
:mod:`tenpy.linalg.np_conserved` for convenience.)
Parameters
----------
chargeinfo : :class:`ChargeInfo`
The nature of the charge.
slices: 1D array_like, len(block_number+1)
A block with 'qindex' ``qi`` correspondes to the leg indices in
``slice(slices[qi], slices[qi+1])``.
charges : 2D array_like, shape(block_number, chargeinfo.qnumber)
``charges[qi]`` gives the charges for a block with 'qindex' ``qi``.
qconj : {+1, -1}
A flag telling whether the charge points inwards (+1, default) or outwards (-1).
Attributes
----------
ind_len: int
The number of indices for this leg.
block_number:
The number of blocks, i.e., a 'qindex' for this leg is in ``range(block_number)``.
chinfo : :class:`ChargeInfo` instance
The nature of the charge. Can be shared between LegCharges.
slices : ndarray[np.intp_t,ndim=1] (block_number+1)
A block with 'qindex' ``qi`` correspondes to the leg indices in
``slice(self.slices[qi], self.slices[qi+1])``. See :meth:`get_slice`.
charges : ndarray[QTYPE_t,ndim=1] (block_number, chinfo.qnumber)
``charges[qi]`` gives the charges for a block with 'qindex' ``qi``.
Note: the sign might be changed by `qconj`. See also :meth:`get_charge`.
qconj : {-1, 1}
A flag telling whether the charge points inwards (+1) or outwards (-1).
Whenever charges are added, they should be multiplied with their `qconj` value.
sorted : bool
Whether the charges are guaranteed to be sorted.
bunched : bool
Whether the charges are guaranteed to be bunched.
Notes
-----
Instances of this class can be shared between different `npc.Array`.
Thus, functions changing ``self.slices`` or ``self.charges`` *must* always make copies.
Further they *must* set `sorted` and `bunched` to ``False`` (if they might not preserve them).
"""
def __init__(self, chargeinfo, slices, charges, qconj=1):
self.chinfo = chargeinfo
self.slices = np.array(slices, dtype=np.intp)
self.ind_len = self.slices[-1]
self.charges = np.array(charges, dtype=QTYPE)
self.block_number = self.charges.shape[0]
self.qconj = int(qconj)
if self.block_number > 2:
self.sorted = False
self.bunched = False
else: # just one block: trivially sorted
self.sorted = True
self.bunched = True
LegCharge.test_sanity(self)
def copy(self):
"""Return a (shallow) copy of self."""
res = LegCharge.__new__(LegCharge)
res.__setstate__(self.__getstate__())
return res
def __getstate__(self):
"""Allow to pickle and copy."""
return (self.ind_len, self.block_number, self.chinfo, self.slices, self.charges,
self.qconj, self.sorted, self.bunched)
def __setstate__(self, state):
"""Allow to pickle and copy."""
ind_len, block_number, chinfo, slices, charges, qconj, sorted_, bunched = state
self.ind_len = ind_len
self.block_number = block_number
self.chinfo = chinfo
self.slices = slices
self.charges = charges
self.qconj = qconj
self.sorted = sorted_
self.bunched = bunched
def save_hdf5(self, hdf5_saver, h5gr, subpath):
"""Export `self` into a HDF5 file.
This method saves all the data it needs to reconstruct `self` with :meth:`from_hdf5`.
Checks :class:`~tenpy.tools.hdf5_io.Hdf5Saver.format` for an ouput format key ``"LegCharge"``.
Possible choices are:
``"blocks"`` (default)
Store :attr:`slices` and :attr:`charges` directly as datasets,
and :attr:`block_number`, :attr:`sorted`, :attr:`bunched` as further attributes.
``"compact"``
A single array ``np.hstack([self.slices[:-1], self.slices[1:], self.charges])``
as dataset ``"blockcharges"``,
and :attr:`block_number`, :attr:`sorted`, :attr:`bunched` as further attributes.
``"flat"``
Insufficient (!) to recover the exact blocks; saves only the array
returned by :meth:`to_flat` as dataset ``'charges'``.
The :attr:`ind_len`, :attr:`qconj`, and the `format` parameter are saved as group
attributes under the same names. :attr:`chinfo` is always saved as subgroup.
Parameters
----------
hdf5_saver : :class:`~tenpy.tools.hdf5_io.Hdf5Saver`
Instance of the saving engine.
h5gr : :class`Group`
HDF5 group which is supposed to represent `self`.
subpath : str
The `name` of `h5gr` with a ``'/'`` in the end.
"""
format = hdf5_saver.format_selection.get("LegCharge", "blocks")
h5gr.attrs["format"] = format
h5gr.attrs["ind_len"] = self.ind_len
h5gr.attrs["qconj"] = self.qconj
hdf5_saver.save(self.chinfo, subpath + "chinfo")
if format == "blocks":
h5gr.attrs["block_number"] = self.block_number
h5gr.attrs["sorted"] = self.sorted
h5gr.attrs["bunched"] = self.bunched
hdf5_saver.save(self.slices, subpath + "slices")
hdf5_saver.save(self.charges, subpath + "charges")
elif format == "compact":
h5gr.attrs["block_number"] = self.block_number
h5gr.attrs["sorted"] = self.sorted
h5gr.attrs["bunched"] = self.bunched
blockcharges = np.hstack(
[self.slices[:-1, np.newaxis], self.slices[1:, np.newaxis], self.charges])
hdf5_saver.save(blockcharges, subpath + "blockcharges")
elif format == "flat":
qflat = self.to_qflat()
hdf5_saver.save(qflat, subpath + "charges")
else:
raise ValueError("Unknown format")
@classmethod
def from_hdf5(cls, hdf5_loader, h5gr, subpath):
"""Load instance from a HDF5 file.
This method reconstructs a class instance from the data saved with :meth:`save_hdf5`.
Parameters
----------
hdf5_loader : :class:`~tenpy.tools.hdf5_io.Hdf5Loader`
Instance of the loading engine.
h5gr : :class:`Group`
HDF5 group which is represent the object to be constructed.
subpath : str
The `name` of `h5gr` with a ``'/'`` in the end.
Returns
-------
obj : cls
Newly generated class instance containing the required data.
"""
obj = cls.__new__(cls)
hdf5_loader.memorize_load(h5gr, obj)
format = hdf5_loader.get_attr(h5gr, "format")
obj.ind_len = hdf5_loader.get_attr(h5gr, "ind_len")
obj.qconj = hdf5_loader.get_attr(h5gr, "qconj")
obj.chinfo = hdf5_loader.load(subpath + "chinfo")
if format == "blocks":
obj.block_number = hdf5_loader.get_attr(h5gr, "block_number")
obj.sorted = hdf5_loader.get_attr(h5gr, "sorted")
obj.bunched = hdf5_loader.get_attr(h5gr, "bunched")
obj.slices = hdf5_loader.load(subpath + "slices")
obj.charges = hdf5_loader.load(subpath + "charges")
elif format == "compact":
obj.block_number = hdf5_loader.get_attr(h5gr, "block_number")
obj.sorted = hdf5_loader.get_attr(h5gr, "sorted")
obj.bunched = hdf5_loader.get_attr(h5gr, "bunched")
blockcharges = hdf5_loader.load(subpath + "blockcharges")
obj.slices = slices = np.zeros(obj.block_number + 1, dtype=np.intp)
slices[:-1] = blockcharges[:, 0]
slices[-1] = blockcharges[-1, 1]
obj.charges = np.asarray(blockcharges[:, 2:], dtype=QTYPE, order='C')
elif format == "flat":
obj.block_number = obj.ind_len
obj.slices = np.arange(obj.ind_len + 1)
obj.charges = hdf5_loader.load(subpath + "charges")
obj.bunched = obj.is_bunched()
obj.sorted = obj.is_sorted()
else:
raise ValueError("Unknown format")
obj.test_sanity()
return obj
@classmethod
def from_trivial(cls, ind_len, chargeinfo=None, qconj=1):
"""Create trivial (qnumber=0) LegCharge for given len of indices `ind_len`."""
if chargeinfo is None:
chargeinfo = ChargeInfo()
charges = [[]]
else:
charges = [[0] * chargeinfo.qnumber]
return cls(chargeinfo, [0, ind_len], charges, qconj)
@classmethod
def from_qflat(cls, chargeinfo, qflat, qconj=1):
"""Create a LegCharge from qflat form.
Does *neither* bunch *nor* sort. We recommend to sort (and bunch) afterwards,
if you expect that tensors using the LegCharge have entries at all positions compatible
with the charges.
Parameters
----------
chargeinfo : :class:`ChargeInfo`
The nature of the charge.
qflat : array_like (ind_len, `qnumber`)
`qnumber` charges for each index of the leg on entry.
qconj : {-1, 1}
A flag telling whether the charge points inwards (+1) or outwards (-1).
See also
--------
sort : sorts by charges
bunch : bunches contiguous blocks of the same charge.
"""
qflat = np.asarray(qflat, dtype=QTYPE)
if qflat.ndim == 1 and chargeinfo.qnumber == 1:
# accept also 1D arrays, if the qnumber is 1
qflat = qflat.reshape(-1, 1)
ind_len, qnum = qflat.shape
if qnum != chargeinfo.qnumber:
raise ValueError("qflat with second dimension != qnumber")
res = cls(chargeinfo, np.arange(ind_len + 1), qflat, qconj)
res.sorted = res.is_sorted()
res.bunched = res.is_bunched()
return res
@classmethod
def from_qind(cls, chargeinfo, slices, charges, qconj=1):
"""Just a wrapper around self.__init__(), see class doc-string for parameters.
See also
--------
sort : sorts by charges
bunch : bunches contiguous blocks of the same charge.
"""
res = cls(chargeinfo, slices, charges, qconj)
res.sorted = res.is_sorted()
res.bunched = res.is_bunched()
return res
@classmethod
def from_qdict(cls, chargeinfo, qdict, qconj=1):
"""Create a LegCharge from qdict form.
Parameters
----------
chargeinfo : :class:`ChargeInfo`
The nature of the charge.
qdict : dict
A dictionary mapping a tuple of charges to slices.
"""
slices = np.array([(sl.start, sl.stop) for sl in qdict.values()], np.intp)
charges = np.array(list(qdict.keys()), dtype=QTYPE).reshape((-1, chargeinfo.qnumber))
sort = np.argsort(slices[:, 0]) # sort by slice start
slices = slices[sort, :]
charges = charges[sort, :]
if np.any(slices[:-1, 1] != slices[1:, 0]):
raise ValueError("The slices are not contiguous.\n" + str(slices))
slices = np.append(slices[:, 0], [slices[-1, 1]])
res = cls(chargeinfo, slices, charges, qconj)
res.sorted = True
res.bunched = res.is_bunched()
return res
@classmethod
def from_add_charge(cls, legs, chargeinfo=None):
"""Add the (independent) charges of two or more legs to get larger `qnumber`.
Parameters
----------
legs : iterable of :class:`LegCharge`
The legs for which the charges are to be combined/added.
chargeinfo : :class:`ChargeInfo`
The ChargeInfo for all charges; create new if ``None``.
Returns
-------
combined : :class:`LegCharge`
A LegCharge with the charges of both legs. Is neither sorted nor bunched!
"""
legs = list(legs)
chinfo = ChargeInfo.add([leg.chinfo for leg in legs])
if chargeinfo is not None:
assert chinfo == chargeinfo
chinfo = chargeinfo
ind_len = legs[0].ind_len
qconj = legs[0].qconj
if any([ind_len != leg.ind_len for leg in legs]):
raise ValueError("different length")
if any([qconj != leg.qconj for leg in legs]):
raise ValueError("different qconj")
slices = [0]
qis = [0] * len(legs)
charges = []
def append_charges():
ch = []
for leg, qi in zip(legs, qis):
ch.extend(leg.charges[qi, :])
charges.append(ch)
append_charges()
next_inds = [leg.slices[qi + 1] for leg, qi in zip(legs, qis)]
while min(next_inds) < ind_len:
next_ind = min(next_inds)
for i, ind in enumerate(next_inds):
if ind == next_ind:
qis[i] = qis[i] + 1
next_inds[i] = legs[i].slices[qis[i] + 1]
append_charges()
slices.append(next_ind)
slices.append(ind_len)
return cls.from_qind(chinfo, slices, charges, qconj)
@classmethod
def from_drop_charge(cls, leg, charge=None, chargeinfo=None):
"""Remove a charge from a LegCharge.
Parameters
----------
leg : :class:`LegCharge`
The leg from which to drop/remove a charge.
charge : int | str
Number or `name` of the charge (within `chinfo`) which is to be dropped.
``None`` means dropping all charges.
chargeinfo : :class:`ChargeInfo`
The ChargeInfo with `charge` dropped; create new if ``None``.
Returns
-------
dropped : :class:`LegCharge`
A LegCharge with the specified charge dropped. Is neither sorted nor bunched!
"""
if charge is None:
return cls.from_trivial(leg.ind_len, chargeinfo, leg.qconj)
chinfo = ChargeInfo.drop(leg.chinfo, charge)
if chargeinfo is not None:
assert chinfo == chargeinfo
chinfo = chargeinfo
if isinstance(charge, str):
charge = chinfo.names.index(charge)
return cls.from_qind(chinfo, leg.slices, np.delete(leg.charges, charge, 1), leg.qconj)
@classmethod
def from_change_charge(cls, leg, charge, new_qmod, new_name='', chargeinfo=None):
"""Remove a charge from a LegCharge.
Parameters
----------
leg : :class:`LegCharge`
The leg from which to drop/remove a charge.
charge : int | str
Number or `name` of the charge (within `chinfo`) for which `mod` is to be changed.
new_qmod : int
The new `mod` to be set for `charge` in the :class:`ChargeInfo`.
new_name : str
The new name for `charge`.
chargeinfo : :class:`ChargeInfo`
The ChargeInfo with `charge` changed; create new if ``None``.
Returns
-------
leg : :class:`LegCharge`
A LegCharge with the specified charge changed. Is neither sorted nor bunched!
"""
chinfo = ChargeInfo.change(leg.chinfo, charge, new_qmod, new_name)
if chargeinfo is not None:
assert chinfo == chargeinfo
chinfo = chargeinfo
charges = chinfo.make_valid(leg.charges)
return cls.from_qind(chinfo, leg.slices, charges, leg.qconj)
def test_sanity(self):
"""Sanity check, raises ValueErrors, if something is wrong."""
if optimize(OptimizationFlag.skip_arg_checks):
return
sl = self.slices
ch = self.charges
if sl.ndim != 1 or sl.shape[0] != self.block_number + 1:
raise ValueError("wrong len of `slices`")
if sl[0] != 0:
raise ValueError("slices does not start with 0")
if ch.ndim != 2 or ch.shape[1] != self.chinfo.qnumber:
raise ValueError("shape of `charges` incompatible with qnumber")
if not self.chinfo.check_valid(ch):
raise ValueError("charges invalid for " + str(self.chinfo) + "\n" + str(self))
if self.qconj != -1 and self.qconj != 1:
raise ValueError("qconj has invalid value != +-1 :" + repr(self.qconj))
def conj(self):
"""Return a (shallow) copy with opposite ``self.qconj``.
Returns
-------
conjugated : :class:`LegCharge`
Shallow copy of `self` with flipped :attr:`qconj`.
:meth:`test_contractible` of `self` with `conjugated` will not raise an error.
"""
res = self.copy() # shallow copy
res.qconj = -self.qconj
return res
def flip_charges_qconj(self):
"""Return a copy with both negative `qconj` and `charges`.
Returns
-------
conj_charges : :class:`LegCharge`
(Shallow) copy of self with negative `qconj` and `charges`, thus representing the
very same charges.
:meth:`test_equal` of `self` with `conj_charges` will not raise an error.
"""
res = self.copy()
res.qconj = -self.qconj
res.charges = self.chinfo.make_valid(-self.charges)
res.sorted = False
return res
def to_qflat(self):
"""Return charges in `qflat` form."""
qflat = np.empty((self.ind_len, self.chinfo.qnumber), dtype=QTYPE)
for start, stop, ch in zip(self.slices[:-1], self.slices[1:], self.charges):
qflat[slice(start, stop)] = ch
return qflat
def to_qdict(self):
"""Return charges in `qdict` form.
Raises ValueError, if not blocked.
"""
res = dict()
for start, stop, ch in zip(self.slices[:-1], self.slices[1:], self.charges):
res[tuple(ch)] = slice(start, stop)
if len(res) < self.block_number: # ensures self is blocked
raise ValueError("can't convert qflat to qdict for non-blocked LegCharge")
return res
def is_blocked(self):
"""Returns whether self is blocked, i.e. qindex map 1:1 to charge values."""
if self.sorted and self.bunched:
return True
s = {tuple(c) for c in self.charges} # a set has unique elements
return (len(s) == self.block_number)
def is_sorted(self):
"""Returns whether `self.charges` is sorted lexiographically."""
if self.chinfo._qnumber == 0:
return True
res = lexsort(self.charges.T)
return np.all(res == np.arange(len(res)))
def is_bunched(self):
"""Checks whether :meth:`bunch` would change something."""
return len(_find_row_differences(self.charges)) == self.block_number + 1
def test_contractible(self, other):
"""Raises a ValueError if charges are incompatible for contraction with other.
Parameters
----------
other : :class:`LegCharge`
The LegCharge of the other leg condsidered for contraction.
Raises
------
ValueError
If the charges are incompatible for direct contraction.
Notes
-----
This function checks that two legs are `ready` for contraction.
This is the case, if all of the following conditions are met:
- the ``ChargeInfo`` is equal
- the `slices` are equal
- the `charges` are the same up to *opposite* signs ``qconj``::
self.charges * self.qconj = - other.charges * other.qconj
In general, there could also be a change of the total charge, see :doc:`/intro/npc`
This special case is not considered here - instead use
:meth:`~tenpy.linalg.np_conserved.gauge_total_charge`,
if a change of the charge is desired.
If you are sure that the legs should be contractable,
check whether the charges are actually valid
or whether ``self`` and ``other`` are blocked or should be sorted.
See also
--------
test_equal :
``self.test_contractible(other)`` just performs ``self.test_equal(other.conj())``.
"""
if optimize(OptimizationFlag.skip_arg_checks):
return
self.test_equal(other.conj())
def test_equal(self, other):
"""Test if charges are *equal* including `qconj`.
Check that all of the following conditions are met:
- the ``ChargeInfo`` is equal
- the `slices` are equal
- the `charges` are the same up to the signs ``qconj``::
self.charges * self.qconj = other.charges * other.qconj
See also
--------
test_contractible :
``self.test_equal(other)`` is equivalent to ``self.test_contractible(other.conj())``.
"""
if optimize(OptimizationFlag.skip_arg_checks):
return
if self.chinfo != other.chinfo:
raise ValueError(''.join(
["incompatible ChargeInfo\n",
str(self.chinfo),
str(other.chinfo)]))
if self.charges is other.charges and self.qconj == other.qconj and \
(self.slices is other.slices or np.all(self.slices == other.slices)):
return # optimize: don't need to check all charges explicitly
if not np.array_equal(self.slices, other.slices) or \
not np.array_equal(self.charges * self.qconj, other.charges * other.qconj):
raise ValueError("incompatible LegCharge\n" +
vert_join(["self\n" + str(self), "other\n" + str(other)], delim=' | '))
def get_block_sizes(self):
"""Return the sizes of the individual blocks.
Returns
-------
sizes : ndarray, shape (block_number,)
The sizes of the individual blocks; ``sizes[i] = slices[i+1] - slices[i]``.
"""
return self.slices[1:] - self.slices[:-1]
def get_slice(self, qindex):
"""Return slice selecting the block for a given `qindex`."""
return slice(self.slices[qindex], self.slices[qindex + 1])
def get_qindex(self, flat_index):
"""Find qindex containing a flat index.
Given a flat index, to find the corresponding entry in an Array, we need to determine the
block it is saved in. For example, if ``slices = [[0, 3], [3, 7], [7, 12]]``,
the flat index ``5`` corresponds to the second entry, ``qindex = 1`` (since 5 is in [3:7]),
and the index within the block would be ``2 = 5 - 3``.
Parameters
----------
flat_index : int
A flat index of the leg. Negative index counts from behind.
Returns
-------
qindex : int
The qindex, i.e. the index of the block containing `flat_index`.
index_within_block : int
The index of `flat_index` within the block given by `qindex`.
"""
if flat_index < 0:
flat_index += self.ind_len
if flat_index < 0:
raise IndexError("flat index {0:d} too negative for leg with ind_len {1:d}".format(
flat_index - self.ind_len, self.ind_len))
elif flat_index > self.ind_len:
raise IndexError("flat index {0:d} too large for leg with ind_len {1:d}".format(
flat_index, self.ind_len))
qind = bisect.bisect(self.slices, flat_index) - 1
return qind, flat_index - self.slices[qind]
def get_qindex_of_charges(self, charges):
"""Return the slice selecting the block for given charge values.
Inverse function of :meth:`get_charge`.
Parameters
----------
charges : 1D array_like
Charge values for which the slice of the block is to be determined.
Returns
-------
slice(i, j) : slice
Slice of the charge values for
Raises
------
ValueError : if the answer is not unique (because `self` is not blocked).
"""
charges = self.chinfo.make_valid(self.qconj * np.asarray(charges))
equal_rows = np.all(charges[np.newaxis, :] == self.charges, axis=1)
qinds = np.nonzero(equal_rows)[0]
if len(qinds) > 1:
raise ValueError("Non-unique answer: " + repr(qinds))
elif len(qinds) == 0:
raise ValueError("Charge block not found")
# else
return qinds[0]
def get_charge(self, qindex):
"""Return charge ``self.charges[qindex] * self.qconj`` for a given `qindex`."""
return self.charges[qindex] * self.qconj
def sort(self, bunch=True):
"""Return a copy of `self` sorted by charges (but maybe not bunched).
If bunch=True, the returned copy is completely blocked by charge.
Parameters
----------
bunch : bool
Whether `self.bunch` is called after sorting.
If True, the leg is guaranteed to be fully blocked by charge.
Returns
-------
perm_qind : array (self.block_len,)
The permutation of the qindices (before bunching) used for the sorting.
To obtain the flat permuation such that
``sorted_array[..., :] = unsorted_array[..., perm_flat]``, use
``perm_flat = unsorted_leg.perm_flat_from_perm_qind(perm_qind)``
sorted_copy : :class:`LegCharge`
A shallow copy of self, with new qind sorted (and thus blocked if bunch) by charges.
See also
--------
bunch : enlarge blocks for contiguous qind of the same charges.
numpy.take : can apply `perm_flat` to a given axis
tenpy.tools.misc.inverse_permutation : returns inverse of a permutation
"""
if self.sorted and ((not bunch) or self.bunched): # nothing to do
return np.arange(self.block_number, dtype=np.intp), self
perm_qind = lexsort(self.charges.T)
cp = self.copy()
cp._set_charges(self.charges[perm_qind, :])
block_sizes = self.get_block_sizes()
cp._set_block_sizes(block_sizes[perm_qind])
cp.sorted = True
cp.bunched = False # re-ordering can have brought together equal charges
if bunch:
_, cp = cp.bunch()
return perm_qind, cp
def bunch(self):
"""Return a copy with bunched self.charges: form blocks for contiguous equal charges.
Returns
-------
idx : 1D array
``idx[:-1]`` are the indices of the old qind which are kept,
``idx[-1] = old_block_number``.
cp : :class:`LegCharge`
A new LegCharge with the same charges at given indices of the leg,
but (possibly) shorter ``self.charges`` and ``self.slices``.
See also
--------
sort : sorts by charges, thus enforcing complete blocking in combination with bunch.
"""
if self.bunched: # nothing to do
return np.arange(self.block_number + 1, dtype=np.intp), self
cp = self.copy()
idx = _find_row_differences(self.charges)
cp._set_charges(cp.charges[idx[:-1]]) # avanced indexing -> copy
cp._set_slices(cp.slices[idx])
cp.bunched = True
return idx, cp
def project(self, mask):
"""Return copy keeping only the indices specified by `mask`.
Parameters
----------
mask : 1D array(bool)
Whether to keep of the indices.
Returns
-------