/
np_conserved.py
4630 lines (4112 loc) · 188 KB
/
np_conserved.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"""A module to handle charge conservation in tensor networks.
A detailed introduction to this module (including notations) can be found in :doc:`/intro/npc`.
This module `np_conserved` implements a class :class:`Array`
designed to make use of charge conservation in tensor networks.
The idea is that the `Array` class is used in a fashion very similar to
the :class:`numpy.ndarray`, e.g you can call the functions :func:`tensordot` or :func:`svd`
(of this module) on them.
The structure of the algorithms (as DMRG) is thus the same as with basic numpy ndarrays.
Internally, an :class:`Array` saves charge meta data to keep track of blocks which are nonzero.
All possible operations (e.g. tensordot, svd, ...) on such arrays preserve the total charge
structure. In addition, these operations make use of the charges to figure out which of the blocks
it has to use/combine - this is the basis for the speed-up.
.. autodata:: QCUTOFF
.. autodata:: QTYPE
Overview
^^^^^^^^
.. rubric:: Classes
.. autosummary::
Array
~tenpy.linalg.charges.ChargeInfo
~tenpy.linalg.charges.LegCharge
~tenpy.linalg.charges.LegPipe
.. rubric:: Array creation
.. autosummary::
Array.from_ndarray_trivial
Array.from_ndarray
Array.from_func
Array.from_func_square
zeros
eye_like
diag
.. rubric:: Concatenation
.. autosummary::
concatenate
grid_concat
grid_outer
.. rubric:: Detecting charges of flat arrays
.. autosummary::
detect_qtotal
detect_legcharge
detect_grid_outer_legcharge
.. rubric:: Contraction of some legs
.. autosummary::
tensordot
outer
inner
trace
.. rubric:: Linear algebra
.. autosummary::
svd
pinv
norm
qr
expm
.. rubric:: Eigen systems
.. autosummary::
eigh
eig
eigvalsh
eigvals
speigs
"""
# Copyright 2018-2020 TeNPy Developers, GNU GPLv3
import numpy as np
import scipy.linalg
from scipy.linalg import blas as BLAS # python interface to BLAS
import warnings
import itertools
from numbers import Integral
# import public API from charges
from .charges import ChargeInfo, LegCharge, LegPipe
from . import charges # for private functions
from .svd_robust import svd as svd_flat
from ..tools.misc import to_iterable, anynan, argsort, inverse_permutation, list_to_dict_list
from ..tools.math import speigs as _sp_speigs
from ..tools.math import qr_li, rq_li
from ..tools.string import vert_join, is_non_string_iterable
from ..tools.optimization import optimize, OptimizationFlag, use_cython
__all__ = [
'QCUTOFF', 'ChargeInfo', 'LegCharge', 'LegPipe', 'Array', 'zeros', 'ones', 'eye_like', 'diag',
'concatenate', 'grid_concat', 'grid_outer', 'detect_grid_outer_legcharge', 'detect_qtotal',
'detect_legcharge', 'trace', 'outer', 'inner', 'tensordot', 'svd', 'pinv', 'norm', 'eigh',
'eig', 'eigvalsh', 'eigvals', 'speigs', 'qr', 'expm', 'to_iterable_arrays'
]
#: A cutoff to ignore machine precision rounding errors when determining charges
QCUTOFF = np.finfo(np.float64).eps * 10
#: the type used for charges
QTYPE = charges.QTYPE
# ##################################
# Array class
# ##################################
class Array:
r"""A multidimensional array (=tensor) for using charge conservation.
An `Array` represents a multi-dimensional tensor,
together with the charge structure of its legs (for abelian charges).
Further information can be found in :doc:`/intro/npc`.
The default :meth:`__init__` (i.e. ``Array(...)``) does not insert any data,
and thus yields an Array 'full' of zeros, equivalent to :func:`zeros()`.
Further, new arrays can be created with one of :meth:`from_ndarray_trivial`,
:meth:`from_ndarray`, or :meth:`from_func`, and of course by copying/tensordot/svd etc.
In-place methods are indicated by a name starting with ``i``.
(But `is_completely_blocked` is not inplace...)
Parameters
----------
legcharges : list of :class:`~tenpy.linalg.charges.LegCharge`
The leg charges for each of the legs. The :class:`ChargeInfo` is read out from it.
dtype : type or string
The data type of the array entries. Defaults to np.float64.
qtotal : 1D array of QTYPE
The total charge of the array. Defaults to 0.
labels : list of {str | None}
Labels associated to each leg, ``None`` for non-named labels.
Attributes
----------
rank : int
The rank or "number of dimensions", equivalent to ``len(shape)``.
shape : tuple(int)
The number of indices for each of the legs.
dtype : np.dtype
The data type of the entries.
chinfo : :class:`~tenpy.linalg.charges.ChargeInfo`
The nature of the charge.
qtotal : 1D array
The total charge of the tensor.
legs : list of :class:`~tenpy.linalg.charges.LegCharge`
The leg charges for each of the legs.
_labels : list of { str | None }
Labels for the different legs, None for non-labeled legs.
_data : list of arrays
The actual entries of the tensor.
_qdata : 2D array (len(_data), rank), dtype np.intp
For each of the _data entries the qindices of the different legs.
_qdata_sorted : Bool
Whether self._qdata is lexsorted. Defaults to `True`,
but *must* be set to `False` by algorithms changing _qdata.
"""
def __init__(self, legcharges, dtype=np.float64, qtotal=None, labels=None):
"""see help(self)"""
self.legs = list(legcharges)
if len(self.legs) == 0:
raise ValueError("can't have 0-rank Tensor")
self.chinfo = self.legs[0].chinfo
self._set_shape()
self.dtype = np.dtype(dtype)
self.qtotal = self.chinfo.make_valid(qtotal)
self._labels = [None] * len(self.legs)
if labels is not None:
self.iset_leg_labels(labels)
self._data = []
self._qdata = np.empty((0, self.rank), dtype=np.intp, order='C')
self._qdata_sorted = True
self.test_sanity()
def test_sanity(self):
"""Sanity check.
Raises ValueErrors, if something is wrong.
"""
if optimize(OptimizationFlag.skip_arg_checks):
return
if len(self.legs) == 0:
raise ValueError("We don't allow rank-0 tensors without legs")
for l in self.legs:
if l.chinfo != self.chinfo:
raise ValueError("leg has different ChargeInfo:\n{0!s}\n vs {1!s}".format(
l.chinfo, self.chinfo))
if self.shape != tuple([lc.ind_len for lc in self.legs]):
raise ValueError("shape mismatch with LegCharges\n self.shape={0!s} != {1!s}".format(
self.shape, tuple([lc.ind_len for lc in self.legs])))
for l in self.legs:
l.test_sanity()
if any([self.dtype != d.dtype for d in self._data]):
raise ValueError("wrong dtype: {0!s} vs\n {1!s}".format(
self.dtype, [self.dtype != d.dtype for d in self._data]))
if self._qdata.shape != (self.stored_blocks, self.rank):
raise ValueError("_qdata shape wrong")
if self._qdata.dtype != np.intp:
raise ValueError("wront dtype of _qdata")
if np.any(self._qdata < 0) or np.any(self._qdata >= [l.block_number for l in self.legs]):
raise ValueError("invalid qind in _qdata")
if not self._qdata.flags['C_CONTIGUOUS']:
raise ValueError("qdata is not C-contiguous")
if self._qdata_sorted:
perm = np.lexsort(self._qdata.T)
if np.any(perm != np.arange(len(perm))):
raise ValueError("_qdata_sorted == True, but _qdata is not sorted")
# check total charge
block_q = np.sum([l.get_charge(qi) for l, qi in zip(self.legs, self._qdata.T)], axis=0)
block_q = self.chinfo.make_valid(block_q)
if np.any(block_q != self.qtotal):
raise ValueError("some row of _qdata is incompatible with total charge")
# check block_sizes
block_sizes = [l.get_block_sizes()[qi] for l, qi in zip(self.legs, self._qdata.T)]
for block, block_shape in zip(self._data, zip(*block_sizes)):
assert block.shape == block_shape
# test labels
assert len(self._labels) == self.rank
for lbl in self._labels:
if not isinstance(lbl, (type(None), str)):
raise ValueError("label not string: " + repr(self.labels))
def copy(self, deep=True):
"""Return a (deep or shallow) copy of self.
**Both** deep and shallow copies will share ``chinfo`` and the `LegCharges` in ``legs``.
In contrast to a deep copy, the shallow copy will also share the tensor entries,
namely the *same* instances of ``_qdata`` and ``_data`` and ``labels``
(and other 'immutable' properties like the shape or dtype).
.. note ::
Shallow copies are *not* recommended unless you know the consequences!
See the following examples illustrating some of the pitfalls.
Examples
--------
Be (very!) careful when making non-deep copies: In the following example,
the original `a` is changed if and only if the corresponding block existed in `a` before.
>>> b = a.copy(deep=False) # shallow copy
>>> b[1, 2] = 4.
Other `inplace` operations might have no effect at all (although we don't guarantee that):
>>> a *= 2 # has no effect on `b`
>>> b.iconj() # nor does this change `a`
"""
cp = Array.__new__(Array)
cp.__setstate__(self.__getstate__())
cp.legs = list(self.legs) # different list but same instances
cp._set_shape()
cp._labels = cp._labels[:] # list copy
if deep:
cp._data = [b.copy() for b in self._data]
cp._qdata = self._qdata.copy('C')
cp.qtotal = self.qtotal.copy()
# even deep copies share legs & chinfo (!)
else:
cp._data = self._data[:]
return cp
def __getstate__(self):
"""Allow to pickle and copy."""
return self.__dict__
def __setstate__(self, state):
"""Allow to pickle and copy."""
# order is important for import of old version!
if isinstance(state, dict): # allow to import from the non-compiled version
self.__dict__.update(state)
self._set_shape()
elif isinstance(state, tuple): # allow to import from the compiled versions of TenPy 0.3.0
self._data, self._qdata, self._qdata_sorted, self.chinfo, self.dtype, labels, \
self.legs, self.qtotal, self.rank, self.shape = state
self.labels = labels # property, requires rank to be set already
else:
raise ValueError("setstate with incompatible type of state")
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`.
Specifically, it saves :attr:`chinfo`, :attr:`legs`, :attr:`dtype` under these names,
:attr:`qtotal` as ``"total_charge"``,
:attr:`_data` as ``"blocks"``, :attr:`_qdata` as ``:block_inds"``,
the :attr:`labels` in the list-form (as returned by :meth:`get_leg_labels`).
Moreover, it saves :attr:`rank`, :attr:`shape` and
:attr:`_qdata_sorted` (under the name ``"block_inds_sorted"``) as HDF5 attributes.
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.
"""
hdf5_saver.save(self.chinfo, subpath + "chinfo")
hdf5_saver.save(self.legs, subpath + "legs")
hdf5_saver.save(self.dtype, subpath + "dtype")
hdf5_saver.save(self.qtotal, subpath + "total_charge")
hdf5_saver.save(self._labels, subpath + "labels")
hdf5_saver.save(self._data, subpath + "blocks")
hdf5_saver.save(self._qdata, subpath + "block_inds")
h5gr.attrs["block_inds_sorted"] = self._qdata_sorted
h5gr.attrs["rank"] = self.rank # not needed for loading, but still usefull metadata
h5gr.attrs["shape"] = np.array(self.shape, np.intp) # same
@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) # create class instance, no __init__() call
hdf5_loader.memorize_load(h5gr, obj)
obj.chinfo = hdf5_loader.load(subpath + "chinfo")
obj.legs = hdf5_loader.load(subpath + "legs")
obj.dtype = hdf5_loader.load(subpath + "dtype")
obj.qtotal = hdf5_loader.load(subpath + "total_charge")
obj._labels = hdf5_loader.load(subpath + "labels")
obj._data = hdf5_loader.load(subpath + "blocks")
obj._qdata = hdf5_loader.load(subpath + "block_inds")
obj._qdata_sorted = hdf5_loader.get_attr(h5gr, "block_inds_sorted")
obj._set_shape()
obj.test_sanity()
return obj
@classmethod
def from_ndarray_trivial(cls, data_flat, dtype=None, labels=None):
"""convert a flat numpy ndarray to an Array with trivial charge conservation.
Parameters
----------
data_flat : array_like
The data to be converted to a Array.
dtype : ``np.dtype``
The data type of the array entries. Defaults to dtype of `data_flat`.
labels : list of {str | None}
Labels associated to each leg, ``None`` for non-named labels.
Returns
-------
res : :class:`Array`
An Array with data of data_flat.
"""
data_flat = np.asarray(data_flat) # unspecified dtype
if dtype is None:
dtype = data_flat.dtype
data_flat = data_flat.astype(dtype, copy=False)
chinfo = ChargeInfo()
legs = [LegCharge.from_trivial(s, chinfo) for s in data_flat.shape]
res = cls(legs, dtype, labels=labels)
res._data = [data_flat]
res._qdata = np.zeros((1, res.rank), np.intp)
res._qdata_sorted = True
res.test_sanity()
return res
@classmethod
def from_ndarray(cls, data_flat, legcharges, dtype=None, qtotal=None, cutoff=None,
labels=None):
"""convert a flat (numpy) ndarray to an Array.
Parameters
----------
data_flat : array_like
The flat ndarray which should be converted to a npc `Array`.
The shape has to be compatible with legcharges.
legcharges : list of :class:`LegCharge`
The leg charges for each of the legs. The :class:`ChargeInfo` is read out from it.
dtype : ``np.dtype``
The data type of the array entries. Defaults to dtype of `data_flat`.
qtotal : None | charges
The total charge of the new array.
cutoff : float
Blocks with ``np.max(np.abs(block)) > cutoff`` are considered as zero.
Defaults to :data:`QCUTOFF`.
labels : list of {str | None}
Labels associated to each leg, ``None`` for non-named labels.
Returns
-------
res : :class:`Array`
An Array with data of `data_flat`.
See also
--------
detect_qtotal : used to detect ``qtotal`` if not given.
"""
if cutoff is None:
cutoff = QCUTOFF
data_flat = np.asarray(data_flat) # unspecified dtype
if dtype is None:
dtype = data_flat.dtype
data_flat = data_flat.astype(dtype, copy=False)
res = cls(legcharges, dtype, qtotal, labels) # without any data
if res.shape != data_flat.shape:
raise ValueError("Incompatible shapes: legcharges {0!s} vs flat {1!s} ".format(
res.shape, data_flat.shape))
if qtotal is None:
res.qtotal = qtotal = detect_qtotal(data_flat, legcharges, cutoff)
data = []
qdata = []
for qindices in res._iter_all_blocks():
sl = res._get_block_slices(qindices)
if np.all(res._get_block_charge(qindices) == qtotal):
data.append(np.array(data_flat[sl], dtype=res.dtype)) # copy data
qdata.append(qindices)
elif np.any(np.abs(data_flat[sl]) > cutoff):
warnings.warn("flat array has non-zero entries in blocks incompatible with charge",
stacklevel=2)
res._data = data
res._qdata = np.array(qdata, dtype=np.intp, order='C').reshape((len(qdata), res.rank))
res._qdata_sorted = True
res.test_sanity()
return res
@classmethod
def from_func(cls,
func,
legcharges,
dtype=None,
qtotal=None,
func_args=(),
func_kwargs={},
shape_kw=None,
labels=None):
"""Create an Array from a numpy func.
This function creates an array and fills the blocks *compatible* with the charges
using `func`, where `func` is a function returning a `array_like` when given a shape,
e.g. one of ``np.ones`` or ``np.random.standard_normal``.
Parameters
----------
func : callable
A function-like object which is called to generate the data blocks.
We expect that `func` returns a flat array of the given `shape` convertible to `dtype`.
If no `shape_kw` is given, it is called as
``func(shape, *func_args, **func_kwargs)``,
otherwise as ``func(*func_args, `shape_kw`=shape, **func_kwargs)``.
`shape` is a tuple of int.
legcharges : list of :class:`LegCharge`
The leg charges for each of the legs. The :class:`ChargeInfo` is read out from it.
dtype : None | type | string
The data type of the output entries. Defaults to np.float64.
Defaults to `None`: obtain it from the return value of the function.
Note that this argument is not given to func, but rather a type conversion
is performed afterwards. You might want to set a `dtype` in `func_kwargs` as well.
qtotal : None | charges
The total charge of the new array. Defaults to charge 0.
func_args : iterable
Additional arguments given to `func`.
func_kwargs : dict
Additional keyword arguments given to `func`.
shape_kw : None | str
If given, the keyword with which shape is given to `func`.
labels : list of {str | None}
Labels associated to each leg, ``None`` for non-named labels.
Returns
-------
res : :class:`Array`
An Array with blocks filled using `func`.
"""
if dtype is None:
# create a small test block to derive the dtype
shape = (2, 2)
if shape_kw is None:
block = func(shape, *func_args, **func_kwargs)
else:
kws = func_kwargs.copy()
kws[shape_kw] = shape
block = func(*func_args, **kws)
block = np.asarray(block)
dtype = block.dtype
res = cls(legcharges, dtype, qtotal, labels) # without any data yet.
data = []
qdata = []
# iterate over all qindices compatible with qtotal
qindices = np.array([qi for qi in res._iter_all_blocks()], dtype=np.intp)
block_charges = res._get_block_charge(qindices.T) # .T: allows to use 2D `qindices`
compatible = np.all(block_charges == res.qtotal, axis=1)
for qindices in qindices[compatible]:
shape = res._get_block_shape(qindices)
if shape_kw is None:
block = func(shape, *func_args, **func_kwargs)
else:
kws = func_kwargs.copy()
kws[shape_kw] = shape
block = func(*func_args, **kws)
block = np.asarray(block, dtype=res.dtype)
data.append(block)
qdata.append(qindices)
res._data = data
res._qdata = np.array(qdata, dtype=np.intp, order='C').reshape((len(qdata), res.rank))
res._qdata_sorted = True # _iter_all_blocks is in lexiographic order
res.test_sanity()
return res
@classmethod
def from_func_square(cls,
func,
leg,
dtype=None,
func_args=(),
func_kwargs={},
shape_kw=None,
labels=None):
"""Create an Array from a (numpy) function.
This function creates an array and fills the blocks *compatible* with the charges
using `func`, where `func` is a function returning a `array_like` when given a shape,
e.g. one of ``np.ones`` or ``np.random.standard_normal`` or the functions defined in
:mod:`~tenpy.linalg.random_matrix`.
Parameters
----------
func : callable
A function-like object which is called to generate the data blocks.
We expect that `func` returns a flat array of the given `shape` convertible to `dtype`.
If no `shape_kw` is given, it is called like ``func(shape, *fargs, **fkwargs)``,
otherwise as ``func(*fargs, `shape_kw`=shape, **fkwargs)``.
`shape` is a tuple of int.
leg : :class:`LegCharge`
The leg charges for the first leg; the second leg is set to ``leg.conj()``.
The :class:`ChargeInfo` is read out from it.
dtype : None | type | string
The data type of the output entries.
Defaults to `None`: obtain it from the return value of the function.
Note that this argument is not given to func, but rather a type conversion
is performed afterwards. You might want to set a `dtype` in `func_kwargs` as well.
func_args : iterable
Additional arguments given to `func`.
func_kwargs : dict
Additional keyword arguments given to `func`.
shape_kw : None | str
If given, the keyword with which shape is given to `func`.
labels : list of {str | None}
Labels associated to each leg, ``None`` for non-named labels.
Returns
-------
res : :class:`Array`
An Array with blocks filled using `func`.
"""
blocked = leg.is_blocked()
if not blocked:
pipe = LegPipe([leg])
legs = [pipe, pipe.conj()]
else:
legs = [leg, leg.conj()]
res = Array.from_func(func, legs, dtype, None, func_args, func_kwargs, shape_kw, labels)
if not blocked:
return res.split_legs()
return res
def zeros_like(self):
"""Return a copy of self with only zeros as entries, containing no `_data`."""
res = self.copy(deep=False)
res._data = []
res._qdata = np.empty((0, res.rank), dtype=np.intp)
res._qdata_sorted = True
return res
# properties ==============================================================
@property
def size(self):
"""The number of dtype-objects stored."""
return np.sum([t.size for t in self._data], dtype=np.int_)
@property
def stored_blocks(self):
"""The number of (non-zero) blocks stored in :attr:`_data`."""
return len(self._data)
@property
def ndim(self):
"""Alias for :attr:`rank` or ``len(self.shape)``."""
return self.rank
@property
def labels(self):
warnings.warn("Deprecated access of Array.labels as dictionary.",
category=FutureWarning,
stacklevel=2)
dict_lab = {}
for i, l in enumerate(self._labels):
if l is not None:
dict_lab[l] = i
return dict_lab
@labels.setter
def labels(self, dict_lab):
warnings.warn("Deprecated setting of Array.labels with dictionary.",
category=FutureWarning,
stacklevel=2)
list_lab = [None] * self.rank
for k, v in dict_lab.items():
if list_lab[v] is not None:
raise ValueError("Two labels point to the same index " + repr(dict_lab))
list_lab[v] = str(k)
self._labels = list_lab
# labels ==================================================================
def get_leg_index(self, label):
"""translate a leg-index or leg-label to a leg-index.
Parameters
----------
label : int | string
The leg-index directly or a label (string) set before.
Returns
-------
leg_index : int
The index of the label.
See also
--------
get_leg_indices : calls get_leg_index for a list of labels.
iset_leg_labels : set the labels of different legs.
"""
if not isinstance(label, Integral):
try:
label = self._labels.index(label)
except ValueError: # not in List
msg = "Label not found: {0!r}, current labels: {1!r}".format(label, self._labels)
raise KeyError(msg) from None
else:
if label < 0:
label += self.rank
if label > self.rank or label < 0:
raise ValueError("axis {0:d} out of rank {1:d}".format(label, self.rank))
return label
def get_leg_indices(self, labels):
"""Translate a list of leg-indices or leg-labels to leg indices.
Parameters
----------
labels : iterable of string/int
The leg-labels (or directly indices) to be translated in leg-indices.
Returns
-------
leg_indices : list of int
The translated labels.
See also
--------
get_leg_index : used to translate each of the single entries.
iset_leg_labels : set the labels of different legs.
"""
return [self.get_leg_index(l) for l in labels]
def iset_leg_labels(self, labels):
"""Set labels for the different axes/legs; in place.
Introduction to leg labeling can be found in :doc:`/intro/npc`.
Parameters
----------
labels : iterable (strings | None), len=self.rank
One label for each of the legs.
An entry can be None for an anonymous leg.
See also
--------
get_leg: translate the labels to indices.
"""
if len(labels) != self.rank:
raise ValueError("Need one leg label for each of the legs, got: " + str(list(labels)))
for i, l in enumerate(labels):
if l is None:
continue
if l == '':
raise ValueError("use `None` for empty labels")
if l in labels[i + 1:]:
raise ValueError("Duplicate label entry in " + repr(labels))
self._labels = list(labels)
return self
def get_leg_labels(self):
"""Return list of the leg labels, with `None` for anonymous legs."""
return self._labels[:]
def has_label(self, label):
"""Check whether a given label exists."""
return (label in self._labels)
def get_leg(self, label):
"""Return ``self.legs[self.get_leg_index(label)]``.
Convenient function returning the leg corresponding to a leg label/index.
"""
return self.legs[self.get_leg_index(label)]
def ireplace_label(self, old_label, new_label):
"""Replace the leg label `old_label` with `new_label`; in place."""
old_index = self.get_leg_index(old_label)
labels = self._labels[:]
labels[old_index] = None
new_label = str(new_label)
if new_label in labels:
msg = "Duplicate label: trying to set {0!r} in {1!r}".format(new_label, labels)
raise ValueError(msg)
labels[old_index] = new_label
self._labels = labels
return self
def replace_label(self, old_label, new_label):
"""Return a shallow copy with the leg label `old_label` replaced by `new_label`."""
return self.copy(deep=False).ireplace_label(old_label, new_label)
def ireplace_labels(self, old_labels, new_labels):
"""Replace leg label ``old_labels[i]`` with ``new_labels[i]``; in place."""
old_inds = self.get_leg_indices(old_labels)
labels = self._labels[:]
for i in old_inds:
labels[i] = None
for i, new_label in zip(old_inds, new_labels):
new_label = str(new_label)
if new_label in labels:
msg = "Duplicate label: trying to set {0!r} in {1!r}".format(new_label, labels)
raise ValueError(msg)
labels[i] = new_label
self._labels = labels
return self
def replace_labels(self, old_labels, new_labels):
"""Return a shallow copy with ``old_labels[i]`` replaced by ``new_labels[i]``."""
return self.copy(deep=False).ireplace_labels(old_labels, new_labels)
def idrop_labels(self, old_labels=None):
"""Remove leg labels from self; in place.
Parameters
----------
old_labels : list of str|int
The leg labels/indices for which the label should be removed.
By default (None), remove all labels.
"""
if old_labels is None:
self._labels = [None] * self.rank
return self
old_inds = self.get_leg_indices(old_labels)
labels = self._labels[:]
for i in old_inds:
labels[i] = None
self._labels = labels
return self
# string output ===========================================================
def __repr__(self):
return "<npc.Array shape={0!s} charge={1!s} labels={2!s}>".format(
self.shape, self.chinfo, self.get_leg_labels())
def __str__(self):
res = [repr(self)[:-1], vert_join([str(l) for l in self.legs], delim='|')]
if np.prod(self.shape) < 100:
res.append(str(self.to_ndarray()))
res.append('>')
return '\n'.join(res)
def sparse_stats(self):
"""Returns a string detailing the sparse statistics."""
total = np.prod(self.shape)
if total == 0:
return "Array without entries, one axis is empty."
nblocks = self.stored_blocks
stored = self.size
nonzero = np.sum([np.count_nonzero(t) for t in self._data], dtype=np.int_)
bs = np.array([t.size for t in self._data], dtype=np.float)
if nblocks > 0:
captsparse = float(nonzero) / stored
bs_min = int(np.min(bs))
bs_max = int(np.max(bs))
bs_mean = np.sum(bs) / nblocks
bs_med = np.median(bs)
bs_var = np.var(bs)
else:
captsparse = 1.
bs_min = bs_max = bs_mean = bs_med = bs_var = 0
res = "{nonzero:d} of {total:d} entries (={nztotal:g}) nonzero,\n" \
"stored in {nblocks:d} blocks with {stored:d} entries.\n" \
"Captured sparsity: {captsparse:g}\n" \
"Block sizes min:{bs_min:d} mean:{bs_mean:.2f} median:{bs_med:.1f} " \
"max:{bs_max:d} var:{bs_var:.2f}"
return res.format(nonzero=nonzero,
total=total,
nztotal=nonzero / total,
nblocks=nblocks,
stored=stored,
captsparse=captsparse,
bs_min=bs_min,
bs_max=bs_max,
bs_mean=bs_mean,
bs_med=bs_med,
bs_var=bs_var)
# accessing entries =======================================================
def to_ndarray(self):
"""Convert self to a dense numpy ndarray."""
res = np.zeros(self.shape, dtype=self.dtype)
for block, slices, _, _ in self: # that's elegant! :)
res[slices] = block
return res
def __iter__(self):
"""Allow to iterate over the non-zero blocks, giving all `_data`.
Yields
------
block : ndarray
the actual entries of a charge block
blockslices : tuple of slices
for each of the legs a slice giving the range of the block in the original tensor
charges : list of charges
the charge value(s) for each of the legs (taking `qconj` into account)
qdat : ndarray
the qindex for each of the legs
"""
for block, qdat in zip(self._data, self._qdata):
blockslices = []
qs = []
for (qi, l) in zip(qdat, self.legs):
blockslices.append(l.get_slice(qi))
qs.append(l.get_charge(qi))
yield block, tuple(blockslices), qs, qdat
def __getitem__(self, inds):
"""Acces entries with ``self[inds]``.
Parameters
----------
inds : tuple
A tuple specifying the `index` for each leg.
An ``Ellipsis`` (written as ``...``) replaces ``slice(None)`` for missing axes.
For a single `index`, we currently support:
- A single integer, choosing an index of the axis,
reducing the dimension of the resulting array.
- A ``slice(None)`` specifying the complete axis.
- A ``slice``, which acts like a `mask` in :meth:`iproject`.
- A 1D array_like(bool): acts like a `mask` in :meth:`iproject`.
- A 1D array_like(int): acts like a `mask` in :meth:`iproject`,
and if not orderd, a subsequent permuation with :meth:`permute`
Returns
-------
res : `dtype`
Only returned, if a single integer is given for all legs.
It is the entry specified by `inds`, giving ``0.`` for non-saved blocks.
or
sliced : :class:`Array`
A copy with some of the data removed by :meth:`take_slice` and/or :meth:`project`.
Notes
-----
``self[i]`` is equivalent to ``self[i, ...]``.
``self[i, ..., j]`` is syntactic sugar for ``self[(i, Ellipsis, i2)]``
Raises
------
IndexError
If the number of indices is too large, or
if an index is out of range.
"""
int_only, inds = self._pre_indexing(inds)
if int_only:
pos = np.array([l.get_qindex(i) for i, l in zip(inds, self.legs)])
try:
block = self.get_block(pos[:, 0])
except IndexError:
return self.dtype.type(0)
if block is None:
return self.dtype.type(0)
else:
return block[tuple(pos[:, 1])]
# advanced indexing
return self._advanced_getitem(inds)
def __setitem__(self, inds, other):
"""Assign ``self[inds] = other``.
Should work as expected for both basic and advanced indexing as described in
:meth:`__getitem__`.
`other` can be:
- a single value (if all of `inds` are integer)
or for slicing/advanced indexing:
- a :class:`Array`, with charges as ``self[inds]`` returned by :meth:`__getitem__`.
- or a flat numpy array, assuming the charges as with ``self[inds]``.
"""
int_only, inds = self._pre_indexing(inds)
if int_only:
pos = np.array([l.get_qindex(i) for i, l in zip(inds, self.legs)])
block = self.get_block(pos[:, 0], insert=True)
block[tuple(pos[:, 1])] = other
return
# advanced indexing
if not isinstance(other, Array):
# if other is a flat array, convert it to an npc Array
like_other = self.zeros_like()
for i, leg in enumerate(like_other.legs):
if isinstance(leg, LegPipe):
like_other.legs[i] = leg.to_LegCharge()
like_other = like_other._advanced_getitem(inds)
other = Array.from_ndarray(other, like_other.legs, self.dtype, like_other.qtotal)
self._advanced_setitem_npc(inds, other)
def get_block(self, qindices, insert=False):
"""Return the ndarray in ``_data`` representing the block corresponding to `qindices`.
Parameters
----------
qindices : 1D array of np.intp
The qindices, for which we need to look in _qdata.
insert : bool
If True, insert a new (zero) block, if `qindices` is not existent in ``self._data``.
Otherwise just return ``None``.
Returns
-------
block: ndarray | ``None``
The block in ``_data`` corresponding to qindices.
If `insert`=False and there is not block with qindices, return ``None``.
Raises
------
IndexError
If `qindices` are incompatible with charge and `raise_incomp_q`.
"""
if not np.all(self._get_block_charge(qindices) == self.qtotal):
raise IndexError("trying to get block for qindices incompatible with charges")
# find qindices in self._qdata
match = np.argwhere(np.all(self._qdata == qindices, axis=1))[:, 0]
if len(match) == 0:
if insert:
res = np.zeros(self._get_block_shape(qindices), dtype=self.dtype)
self._data.append(res)
self._qdata = np.append(self._qdata, [qindices], axis=0)
self._qdata_sorted = False
return res
else:
return None
return self._data[match[0]]
def take_slice(self, indices, axes):
"""Return a copy of self fixing `indices` along one or multiple `axes`.
For a rank-4 Array ``A.take_slice([i, j], [1,2])`` is equivalent to ``A[:, i, j, :]``.
Parameters
----------
indices : (iterable of) int
The (flat) index for each of the legs specified by `axes`.
axes : (iterable of) str/int
Leg labels or indices to specify the legs for which the indices are given.
Returns
-------