-
Notifications
You must be signed in to change notification settings - Fork 122
/
model.py
2045 lines (1793 loc) · 92.2 KB
/
model.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
"""This module contains some base classes for models.
A 'model' is supposed to represent a Hamiltonian in a generalized way.
The :class:`~tenpy.models.lattice.Lattice` specifies the geometry and
underlying Hilbert space, and is thus common to all models.
It is needed to initialize the common base class :class:`Model` of all models.
Different algorithms require different representations of the Hamiltonian.
For example for DMRG, the Hamiltonian needs to be given as an MPO,
while TEBD needs the Hamiltonian to be represented by 'nearest neighbor' bond terms.
This module contains the base classes defining these possible representations,
namely the :class:`MPOModel` and :class:`NearestNeighborModel`.
A particular model like the :class:`~tenpy.models.models.xxz_chain.XXZChain` should then
yet another class derived from these classes. In it's __init__, it needs to explicitly call
the ``MPOModel.__init__(self, lattice, H_MPO)``, providing an MPO representation of H,
and also the ``NearestNeighborModel.__init__(self, lattice, H_bond)``,
providing a representation of H by bond terms `H_bond`.
The :class:`CouplingModel` is the attempt to generalize the representation of `H`
by explicitly specifying the couplings in a general way, and providing functionality
for converting them into `H_MPO` and `H_bond`.
This allows to quickly generate new model classes for a very broad class of Hamiltonians.
The :class:`CouplingMPOModel` aims at structuring the initialization for most models and is used
as base class in (most of) the predefined models in TeNPy.
See also the introduction in :doc:`/intro/model`.
"""
# Copyright (C) TeNPy Developers, GNU GPLv3
import numpy as np
import warnings
import inspect
from functools import wraps
import copy
import logging
logger = logging.getLogger(__name__)
from .lattice import (get_lattice, Lattice, MultiSpeciesLattice, TrivialLattice, HelicalLattice,
IrregularLattice)
from ..linalg import np_conserved as npc
from ..linalg.charges import LegCharge
from ..tools.misc import to_array, add_with_None_0
from ..tools.params import asConfig
from ..networks import mpo # used to construct the Hamiltonian as MPO
from ..networks.terms import OnsiteTerms, CouplingTerms, MultiCouplingTerms
from ..networks.terms import ExponentiallyDecayingTerms, order_combine_term
from ..networks.site import Site, group_sites
from ..tools.hdf5_io import Hdf5Exportable
__all__ = [
'Model', 'NearestNeighborModel', 'MPOModel', 'CouplingModel', 'CouplingMPOModel'
]
class Model(Hdf5Exportable):
"""Base class for all models.
The common base to all models is the underlying Hilbert space and geometry, specified by a
:class:`~tenpy.model.lattice.Lattice`.
Parameters
----------
lattice : :class:`~tenpy.model.lattice.Lattice`
The lattice defining the geometry and the local Hilbert space(s).
Attributes
----------
lat : :class:`~tenpy.model.lattice.Lattice`
The lattice defining the geometry and the local Hilbert space(s).
dtype : :class:`~numpy.dtype`
The data type of the Hamiltonian
"""
#: logging.Logger : An instance of a logger; see :doc:`/intro/logging`. NB: class attribute.
logger = logging.getLogger(__name__ + ".Model")
def __init__(self, lattice):
# NOTE: every subclass like CouplingModel, MPOModel, NearestNeighborModel calls this
# __init__, so it gets called multiple times when a user implements e.g. a
# class MyModel(CouplingModel, NearestNeighborModel, MPOModel).
if not hasattr(self, 'lat'):
# first call: initialize everything
self.lat = lattice
self.dtype = None
else:
# Model.__init__() got called before
if self.lat is not lattice: # expect the *same instance*!
raise ValueError("Model.__init__() called with different lattice instances.")
@property
def rng(self):
"""Reproducible numpy pseudo random number generator.
If you want to add randomness/disorder to your model,
it is recommended use this random number generator for reproducibility of the model::
self.rng.random(size=[3, 5])
Especially for models with time-dependence, you can/will otherwise end up generating a new
disordered at each time-step!
Options
-------
.. cfg:configoptions :: CouplingMPOModel
random_seed :: None | int
Defaults to 123456789. Seed for numpy pseudo random number generator which can
be used as e.g. ``self.rng.random(...)``.
"""
rng = getattr(self, "_rng", None)
if rng is None:
seed = getattr(self, 'options', {}).get('random_seed', 123456789)
self._rng = rng = np.random.default_rng(seed=seed)
return rng
def copy(self):
"""Shallow copy of self."""
cp = copy.copy(self)
if hasattr(self, '_rng'):
cp._rng = copy.deepcopy(self._rng)
return cp
def save_hdf5(self, hdf5_saver, h5gr, subpath):
"""Export `self` into a HDF5 file.
Same as :meth:`~tenpy.tools.hdf5_io.Hdf5Exportable.save_hdf5`, but handle :attr:`rng`.
"""
if hasattr(self, "_rng"):
rng = self._rng
del self._rng
try:
self._rng_state = rng.bit_generator.state
super().save_hdf5(hdf5_saver, h5gr, subpath)
finally:
self._rng = rng
del self._rng_state
else:
super().save_hdf5(hdf5_saver, h5gr, subpath)
@classmethod
def from_hdf5(cls, hdf5_loader, h5gr, subpath):
"""Load instance from a HDF5 file.
Same as :meth:`~tenpy.tools.hdf5_io.Hdf5Exportable.from_hdf5`, but handle :attr:`rng`.
"""
obj = super().from_hdf5(hdf5_loader, h5gr, subpath)
if hasattr(obj, '_rng_state'):
rng_state = obj._rng_state
# reconstruct random number generator from pickle state
# Will fail for custom RNGs, but I hope nobody needs that.
# If you do, simply remove the :attr:`from_hdf5` and :attr:`save_hdf5` methods
# altogether, such that it falls back to pickle protocol (with a warning...)
rng = np.random.Generator(getattr(np.random, rng_state['bit_generator'])())
rng.__setstate__(rng_state)
obj._rng = rng #np.random.Generator(bg)
del obj._rng_state
return obj
def extract_segment(self, first=0, last=None, enlarge=None):
"""Return a (shallow) copy with extracted segment of MPS.
Parameters
----------
first, last, enlarge : int
See :meth:`~tenpy.models.lattice.Lattice.extract_segment`.
Returns
-------
cp : :class:`Model`
A shallow copy of `self` with MPO and lattice extracted for the segment.
"""
cp = self.copy()
cp.lat = self.lat.extract_segment(first, last, enlarge)
return cp
def enlarge_mps_unit_cell(self, factor=2):
"""Repeat the unit cell for infinite MPS boundary conditions; in place.
This has to be done after finishing initialization and can not be reverted.
Parameters
----------
factor : int
The new number of sites in the MPS unit cell will be increased from `N_sites` to
``factor*N_sites_per_ring``. Since MPS unit cells are repeated in the `x`-direction
in our convention, the lattice shape goes from
``(Lx, Ly, ..., Lu)`` to ``(Lx*factor, Ly, ..., Lu)``.
"""
self.lat.enlarge_mps_unit_cell(factor)
def group_sites(self, n=2, grouped_sites=None):
"""Modify `self` in place to group sites.
Group each `n` sites together using the :class:`~tenpy.networks.site.GroupedSite`.
This might allow to do TEBD with a Trotter decomposition,
or help the convergence of DMRG (in case of too long range interactions).
This has to be done after finishing initialization and can not be reverted.
.. todo :
We could actually keep the lattice structure if the order is (default) Cstyle.
Parameters
----------
n : int
Number of sites to be grouped together.
grouped_sites : None | list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
Returns
-------
grouped_sites : list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
"""
if grouped_sites is None:
grouped_sites = group_sites(self.lat.mps_sites(), n, charges='same')
else:
assert grouped_sites[0].n_sites == n
self.lat = TrivialLattice(grouped_sites, bc_MPS=self.lat.bc_MPS, bc='periodic')
return grouped_sites
def get_extra_default_measurements(self):
"""Get list of model-dependent extra default measurements.
Extra measurements for a :class:`~tenpy.simulations.simulation.Simulation`, which depend on the
model itself - subclasses should override this method).
E.g., a :class:`~tenpy.models.model.MPOModel` should measure the energy w.r.t.
the `MPO` (See :func:`~tenpy.simulation.measurement.m_energy_MPO`). However, a
:class:`~tenpy.models.model.NearestNeighborModel` should use the function
:func:`~tenpy.simulation.measurement.m_bond_energies`. The extra measurements are
added to the default measurements in :func:`~tenpy.simulation.Simulation._connect_measurements`.
Returns
-------
m_extra_default_list : list
"""
m_extra_default_list = []
return m_extra_default_list
def update_time_parameter(self, new_time):
"""Reconstruct Hamiltonian for time-dependent models, potentially (!) in-place.
For :class:`~tenpy.algorithms.algorithm.TimeDependentHAlgorithm`, we assume that the model
reads out the parameter ``self.options['time']``, and reinitialize/update the model
calling this method.
Parameters
----------
new_time : float
Time at which the (time-dependent) Hamiltonian should be constructed.
Returns
-------
updated_model : :class:`model`
Model of the same class as `self` with Hamiltonian at time `new_time`.
Note that it *can* just be a reference to `self` if modified in place, or an entirely
new constructed model.
"""
# eventually, we should implement
if not hasattr(self, 'options'):
msg = ("update_time_parameter assumes that the model has `options` defined, reads out "
"`options['time']` and can be reinitialized from the options alone. "
"However, the model {name:s} does not define options.")
raise NotImplementedError(msg.format(name=self.__class__.__name__))
cls = self.__class__
model_params = self.options
model_params['time'] = new_time
return cls(model_params)
def estimate_RAM_saving_factor(self):
"""Returns the expected saving factor for RAM based on charge conservation.
Returns
-------
factor : int
saving factor, due to conservation
Options
-------
.. cfg:configoptions :: Model
mem_saving_factor :: None | float
Quantizes the RAM saving, due to conservation laws, to be used by
:func:`~tenpy.simulations.simulation.estimate_simulation_RAM`.
By default it is 1/mod, or 1/4 in case of mod=1.
However, for some classes this factor might be overwritten,
if a better approximation is known.
In the best case, the user can adjust this model parameter to enhance the estimate.
"""
chinfo = self.lat.unit_cell[0].leg.chinfo
savings = 1
for mod in chinfo.mod:
if mod == 1:
savings *= 1/4 # this is what we found empirically
else:
savings *= 1/mod
if hasattr(self, 'options'):
savings = self.options.get("mem_saving_factor", savings)
return savings
class NearestNeighborModel(Model):
r"""Base class for a model of nearest neighbor interactions w.r.t. the MPS index.
In this class, the Hamiltonian :math:`H = \sum_{i} H_{i,i+1}` is represented by
"bond terms" :math:`H_{i,i+1}` acting only on two neighboring sites `i` and `i+1`,
where `i` is an integer.
Instances of this class are suitable for :mod:`~tenpy.algorithms.tebd`.
Note that the "nearest-neighbor" in the name refers to the MPS index, not the lattice.
In short, this works only for 1-dimensional (1D) nearest-neighbor models:
A 2D lattice is internally mapped to a 1D MPS "snake", and even a nearest-neighbor coupling
in 2D becomes long-range in the MPS chain.
Parameters
----------
lattice : :class:`tenpy.model.lattice.Lattice`
The lattice defining the geometry and the local Hilbert space(s).
H_bond : list of {:class:`~tenpy.linalg.np_conserved.Array` | None}
The Hamiltonian rewritten as ``sum_i H_bond[i]`` for MPS indices ``i``.
``H_bond[i]`` acts on sites ``(i-1, i)``; we require ``len(H_bond) == lat.N_sites``.
Legs of each ``H_bond[i]`` are ``['p0', 'p0*', 'p1', 'p1*']``.
Attributes
----------
H_bond : list of {:class:`~tenpy.linalg.np_conserved.Array` | None}
The Hamiltonian rewritten as ``sum_i H_bond[i]`` for MPS indices ``i``.
``H_bond[i]`` acts on sites ``(i-1, i)``, ``None`` represents 0.
Legs of each ``H_bond[i]`` are ``['p0', 'p0*', 'p1', 'p1*']``.
`H_bond` is not affected by the `explicit_plus_hc` flag of a :class:`CouplingModel`.
"""
def __init__(self, lattice, H_bond):
Model.__init__(self, lattice)
self.H_bond = list(H_bond)
for Hb in H_bond:
if Hb is not None:
self.dtype = Hb.dtype
break
else:
raise ValueError("All H_bond are `None`!")
if self.lat.bc_MPS == 'finite':
assert self.H_bond[0] is None
NearestNeighborModel.test_sanity(self)
# like self.test_sanity(), but use the version defined below even for derived class
@classmethod
def from_MPOModel(cls, mpo_model):
"""Initialize a NearestNeighborModel from a model class defining an MPO.
This is especially useful in combination with :meth:`MPOModel.group_sites`.
Parameters
----------
mpo_model : :class:`MPOModel`
A model instance implementing the MPO.
Does not need to be a :class:`NearestNeighborModel`, but should only have
nearest-neighbor couplings.
Examples
--------
The `SpinChainNNN2` has next-nearest-neighbor couplings and thus only implements an MPO:
.. testsetup :: from_MPOModel
from tenpy.models.model import NearestNeighborModel
.. doctest :: from_MPOModel
>>> from tenpy.models.spins_nnn import SpinChainNNN2
>>> nnn_chain = SpinChainNNN2({'L': 20, 'sort_charge': True})
>>> print(isinstance(nnn_chain, NearestNeighborModel))
False
>>> print("range before grouping:", nnn_chain.H_MPO.max_range)
range before grouping: 2
By grouping each two neighboring sites, we can bring it down to nearest neighbors.
.. doctest :: from_MPOModel
>>> grouped_sites = nnn_chain.group_sites(2)
>>> print("range after grouping:", nnn_chain.H_MPO.max_range)
range after grouping: 1
Yet, TEBD will not yet work, as the model doesn't define `H_bond`.
However, we can initialize a NearestNeighborModel from the MPO:
.. doctest :: from_MPOModel
>>> nnn_chain_for_tebd = NearestNeighborModel.from_MPOModel(nnn_chain)
>>> isinstance(nnn_chain_for_tebd, NearestNeighborModel)
True
"""
return cls(mpo_model.lat, mpo_model.calc_H_bond_from_MPO())
def test_sanity(self):
if len(self.H_bond) != self.lat.N_sites:
raise ValueError("wrong len of H_bond")
def trivial_like_NNModel(self):
"""Return a NearestNeighborModel with same lattice, but trivial (H=0) bonds."""
triv_H = [H.zeros_like() if H is not None else None for H in self.H_bond]
return NearestNeighborModel(self.lat, triv_H)
def bond_energies(self, psi):
"""Calculate bond energies <psi|H_bond|psi>.
Parameters
----------
psi : :class:`~tenpy.networks.mps.MPS`
The MPS for which the bond energies should be calculated.
Returns
-------
E_bond : 1D ndarray
List of bond energies: for finite bc, ``E_Bond[i]`` is the energy of bond ``i, i+1``.
(i.e. we omit bond 0 between sites L-1 and 0);
for infinite bc ``E_bond[i]`` is the energy of bond ``i-1, i``.
"""
if self.lat.bc_MPS == 'infinite':
return psi.expectation_value(self.H_bond, axes=(['p0', 'p1'], ['p0*', 'p1*']))
# else
return psi.expectation_value(self.H_bond[1:], axes=(['p0', 'p1'], ['p0*', 'p1*']))
def extract_segment(self, *args, **kwargs):
cp = super().extract_segment(*args, **kwargs)
first, last = cp.lat.segment_first_last
H_bond = self.H_bond
L = len(H_bond)
cp.H_bond = [H_bond[i % L] for i in range(first, last + 1)]
return cp
def enlarge_mps_unit_cell(self, factor=2):
"""Repeat the unit cell for infinite MPS boundary conditions; in place.
This has to be done after finishing initialization and can not be reverted.
Parameters
----------
factor : int
The new number of sites in the MPS unit cell will be increased from `N_sites` to
``factor*N_sites_per_ring``. Since MPS unit cells are repeated in the `x`-direction
in our convention, the lattice shape goes from
``(Lx, Ly, ..., Lu)`` to ``(Lx*factor, Ly, ..., Lu)``.
"""
super().enlarge_mps_unit_cell(factor)
self.H_bond = self.H_bond * factor
def group_sites(self, n=2, grouped_sites=None):
"""Modify `self` in place to group sites.
Group each `n` sites together using the :class:`~tenpy.networks.site.GroupedSite`.
This might allow to do TEBD with a Trotter decomposition,
or help the convergence of DMRG (in case of too long range interactions).
This has to be done after finishing initialization and can not be reverted.
Parameters
----------
n : int
Number of sites to be grouped together.
grouped_sites : None | list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
Returns
-------
grouped_sites : list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
"""
grouped_sites = super().group_sites(n, grouped_sites)
old_L = len(self.H_bond)
new_L = len(grouped_sites)
finite = self.H_bond[0] is None
H_bond = [None] * new_L
i = 0 # old index
for k, gs in enumerate(grouped_sites):
# calculate new_Hb on bond (k, k+1)
k2 = (k + 1) % new_L
next_gs = grouped_sites[k2]
new_H_onsite = None # collect old H_bond terms inside `gs`
for j in range(1, gs.n_sites):
old_Hb = self.H_bond[(i + j) % old_L]
add_H_onsite = self._group_sites_Hb_to_onsite(gs, j, old_Hb)
new_H_onsite = add_with_None_0(new_H_onsite, add_H_onsite)
old_Hb = self.H_bond[(i + gs.n_sites) % old_L]
new_Hb = self._group_sites_Hb_to_bond(gs, next_gs, old_Hb)
if new_H_onsite is not None:
if k + 1 != new_L or not finite:
# infinite or in the bulk: add new_H_onsite to new_Hb
add_Hb = npc.outer(new_H_onsite, next_gs.Id.transpose(['p', 'p*']))
new_Hb = add_with_None_0(new_Hb, add_Hb)
else: # finite and k = new_L - 1
# the new_H_onsite needs to be added to the right-most Hb
prev_gs = grouped_sites[k - 1]
add_Hb = npc.outer(prev_gs.Id.transpose(['p', 'p*']), new_H_onsite)
H_bond[-1] = add_with_None_0(H_bond[-1], add_Hb)
H_bond[k2] = add_with_None_0(H_bond[k2], new_Hb)
i += gs.n_sites
for Hb in H_bond:
if Hb is None:
continue
Hb.iset_leg_labels(['p0', 'p0*', 'p1', 'p1*']).itranspose(['p0', 'p1', 'p0*', 'p1*'])
self.H_bond = H_bond
return grouped_sites
def _group_sites_Hb_to_onsite(self, gr_site, j, old_Hb):
"""kroneckerproduct for H_bond term within a GroupedSite.
`old_Hb` acts on sites (j-1, j) of `gr_sites`.
"""
if old_Hb is None:
return None
old_Hb = old_Hb.transpose(['p0', 'p0*', 'p1', 'p1*'])
ops = [s.Id
for s in gr_site.sites[:j - 1]] + [old_Hb] + [s.Id for s in gr_site.sites[j + 1:]]
Hb = ops[0]
for op in ops[1:]:
Hb = npc.outer(Hb, op)
combine = [list(range(0, 2 * gr_site.n_sites, 2)), list(range(1, 2 * gr_site.n_sites, 2))]
pipe = gr_site.leg
Hb = Hb.combine_legs(combine, pipes=[pipe, pipe.conj()])
return Hb # labels would be 'p', 'p*' w.r.t. gr_site.
def _group_sites_Hb_to_bond(self, gr_site_L, gr_site_R, old_Hb):
"""Kroneckerproduct for H_bond term acting on two GroupedSites.
`old_Hb` acts on the right-most site of `gr_site_L` and left-most site of `gr_site_R`.
"""
if old_Hb is None:
return None
old_Hb = old_Hb.transpose(['p0', 'p0*', 'p1', 'p1*'])
ops = [s.Id for s in gr_site_L.sites[:-1]] + [old_Hb] + [s.Id for s in gr_site_R.sites[1:]]
Hb = ops[0]
for op in ops[1:]:
Hb = npc.outer(Hb, op)
NL, NR = gr_site_L.n_sites, gr_site_R.n_sites
pipeL, pipeR = gr_site_L.leg, gr_site_R.leg
combine = [
list(range(0, 2 * NL, 2)),
list(range(1, 2 * NL, 2)),
list(range(2 * NL, 2 * (NL + NR), 2)),
list(range(2 * NL + 1, 2 * (NL + NR), 2))
]
Hb = Hb.combine_legs(combine, pipes=[pipeL, pipeL.conj(), pipeR, pipeR.conj()])
return Hb # labels would be 'p0', 'p0*', 'p1', 'p1*' w.r.t. gr_site_{L,R}
def calc_H_MPO_from_bond(self, tol_zero=1.e-15):
"""Calculate the MPO Hamiltonian from the bond Hamiltonian.
Parameters
----------
tol_zero : float
Arrays with norm < `tol_zero` are considered to be zero.
Returns
-------
H_MPO : :class:`~tenpy.networks.mpo.MPO`
MPO representation of the Hamiltonian.
"""
H_bond = self.H_bond # entry i acts on sites (i-1,i)
dtype = np.result_type(*[Hb.dtype for Hb in H_bond if Hb is not None])
bc = self.lat.bc_MPS
sites = self.lat.mps_sites()
L = len(sites)
onsite_terms = [None] * L # onsite terms on each site `i`
bond_XYZ = [None] * L # svd of couplings on each bond (i-1, i)
chis = [2] * (L + 1)
assert len(self.H_bond) == L
for i, Hb in enumerate(H_bond):
if Hb is None:
continue
j = (i - 1) % L
Hb = Hb.transpose(['p0', 'p0*', 'p1', 'p1*'])
d_L, d_R = sites[j].dim, sites[i].dim # dimension of local hilbert space:
Id_L, Id_R = sites[i].Id, sites[j].Id
# project on onsite-terms by contracting with identities; Tr(Id_{L/R}) = d_{L/R}
onsite_L = npc.tensordot(Hb, Id_R, axes=(['p1', 'p1*'], ['p*', 'p'])) / d_R
if npc.norm(onsite_L) > tol_zero:
Hb -= npc.outer(onsite_L, Id_R)
onsite_terms[j] = add_with_None_0(onsite_terms[j], onsite_L)
onsite_R = npc.tensordot(Id_L, Hb, axes=(['p*', 'p'], ['p0', 'p0*'])) / d_L
if npc.norm(onsite_R) > tol_zero:
Hb -= npc.outer(Id_L, onsite_R)
onsite_terms[i] = add_with_None_0(onsite_terms[i], onsite_R)
if npc.norm(Hb) < tol_zero:
continue
Hb = Hb.combine_legs([['p0', 'p0*'], ['p1', 'p1*']])
chinfo = Hb.chinfo
qtotal = [chinfo.make_valid(), chinfo.make_valid()] # zero charge
X, Y, Z = npc.svd(Hb, cutoff=tol_zero, inner_labels=['wR', 'wL'], qtotal_LR=qtotal)
assert len(Y) > 0
chis[i] = len(Y) + 2
X = X.split_legs([0])
YZ = Z.iscale_axis(Y, axis=0).split_legs([1])
bond_XYZ[i] = (X, YZ)
# construct the legs
legs = [None] * (L + 1) # legs[i] is leg 'wL' left of site i with qconj=+1
for i in range(L + 1):
if i == L and bc == 'infinite':
legs[i] = legs[0]
break
chi = chis[i]
triv_1 = LegCharge.from_trivial(1, chinfo, qconj=+1)
leg = triv_1
if chi > 2:
leg = leg.extend(bond_XYZ[i][1].get_leg('wL'))
leg = leg.extend(triv_1)
legs[i] = leg
# now construct the W tensors
Ws = [None] * L
for i in range(L):
wL, wR = legs[i], legs[i + 1].conj()
p = sites[i].leg
W = npc.zeros([wL, wR, p, p.conj()], dtype, labels=['wL', 'wR', 'p', 'p*'])
W[0, 0, :, :] = sites[i].Id
W[-1, -1, :, :] = sites[i].Id
onsite = onsite_terms[i]
if onsite is not None:
W[0, -1, :, :] = onsite
if bond_XYZ[i] is not None:
_, YZ = bond_XYZ[i]
W[1:-1, -1, :, :] = YZ.itranspose(['wL', 'p1', 'p1*'])
j = (i + 1) % L
if bond_XYZ[j] is not None:
X, _ = bond_XYZ[j]
W[0, 1:-1, :, :] = X.itranspose(['wR', 'p0', 'p0*'])
Ws[i] = W
H_MPO = mpo.MPO(sites, Ws, bc, 0, -1, max_range=2)
return H_MPO
def get_extra_default_measurements(self):
m_extra_default_list = super().get_extra_default_measurements()
m_extra_default_list.append(('tenpy.simulations.measurement', 'm_bond_energies'))
return m_extra_default_list
class MPOModel(Model):
"""Base class for a model with an MPO representation of the Hamiltonian.
In this class, the Hamiltonian gets represented by an :class:`~tenpy.networks.mpo.MPO`.
Thus, instances of this class are suitable for MPO-based algorithms like DMRG
:mod:`~tenpy.algorithms.dmrg` and MPO time evolution.
Parameters
----------
H_MPO : :class:`~tenpy.networks.mpo.MPO`
The Hamiltonian rewritten as an MPO.
Attributes
----------
H_MPO : :class:`tenpy.networks.mpo.MPO`
MPO representation of the Hamiltonian. If the `explicit_plus_hc` flag of the MPO is `True`,
the represented Hamiltonian is ``H_MPO + hermitian_conjugate(H_MPO)``.
"""
def __init__(self, lattice, H_MPO):
Model.__init__(self, lattice)
self.H_MPO = H_MPO
MPOModel.test_sanity(self)
# like self.test_sanity(), but use the version defined below even for derived class
def copy(self):
cp = super().copy()
cp.H_MPO = self.H_MPO.copy()
return cp
def test_sanity(self):
if self.H_MPO.sites != self.lat.mps_sites():
raise ValueError("lattice incompatible with H_MPO.sites")
def extract_segment(self, *args, **kwargs):
cp = super().extract_segment(*args, **kwargs)
first, last = cp.lat.segment_first_last
cp.H_MPO = self.H_MPO.extract_segment(first, last)
return cp
def enlarge_mps_unit_cell(self, factor=2):
"""Repeat the unit cell for infinite MPS boundary conditions; in place.
This has to be done after finishing initialization and can not be reverted.
Parameters
----------
factor : int
The new number of sites in the MPS unit cell will be increased from `N_sites` to
``factor*N_sites_per_ring``. Since MPS unit cells are repeated in the `x`-direction
in our convention, the lattice shape goes from
``(Lx, Ly, ..., Lu)`` to ``(Lx*factor, Ly, ..., Lu)``.
"""
super().enlarge_mps_unit_cell(factor)
self.H_MPO.enlarge_mps_unit_cell(factor)
def group_sites(self, n=2, grouped_sites=None):
"""Modify `self` in place to group sites.
Group each `n` sites together using the :class:`~tenpy.networks.site.GroupedSite`.
This might allow to do TEBD with a Trotter decomposition,
or help the convergence of DMRG (in case of too long range interactions).
This has to be done after finishing initialization and can not be reverted.
Parameters
----------
n : int
Number of sites to be grouped together.
grouped_sites : None | list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
Returns
-------
grouped_sites : list of :class:`~tenpy.networks.site.GroupedSite`
The sites grouped together.
"""
grouped_sites = super().group_sites(n, grouped_sites)
self.H_MPO = self.H_MPO.copy()
self.H_MPO.group_sites(n, grouped_sites)
return grouped_sites
def calc_H_bond_from_MPO(self, tol_zero=1.e-15):
"""Calculate the bond Hamiltonian from the MPO Hamiltonian.
Parameters
----------
tol_zero : float
Arrays with norm < `tol_zero` are considered to be zero.
Returns
-------
H_bond : list of :class:`~tenpy.linalg.np_conserved.Array`
Bond terms as required by the constructor of :class:`NearestNeighborModel`.
Legs are ``['p0', 'p0*', 'p1', 'p1*']``
Raises
------
ValueError : if the Hamiltonian contains longer-range terms.
"""
H_MPO = self.H_MPO
sites = H_MPO.sites
finite = (H_MPO.bc == 'finite')
L = H_MPO.L
Ws = [H_MPO.get_W(i, copy=True) for i in range(L)]
# Copy of Ws: we set everything to zero, which we take out and add to H_bond, such that
# we can check that Ws is zero in the end to ensure that H didn't have long range couplings
H_onsite = [None] * L
H_bond = [None] * L
# first take out onsite terms and identities
for i, W in enumerate(Ws):
# bond `a` is left of site i, bond `b` is right
IdL_a = H_MPO.IdL[i]
IdR_a = H_MPO.IdR[i]
IdL_b = H_MPO.IdL[i + 1]
IdR_b = H_MPO.IdR[i + 1]
W.itranspose(['wL', 'wR', 'p', 'p*'])
H_onsite[i] = W[IdL_a, IdR_b, :, :]
W[IdL_a, IdR_b, :, :] *= 0
# remove Identities
if IdR_a is not None:
W[IdR_a, IdR_b, :, :] *= 0.
if IdL_b is not None:
W[IdL_a, IdL_b, :, :] *= 0.
# now multiply together the bonds
for j, Wj in enumerate(Ws):
# for bond (i, j) == (j-1, j) == (i, i+1)
if finite and j == 0:
continue
i = (j - 1) % L
Wi = Ws[i]
IdL_a = H_MPO.IdL[i]
IdR_c = H_MPO.IdR[j + 1]
Hb = npc.tensordot(Wi[IdL_a, :, :, :], Wj[:, IdR_c, :, :], axes=('wR', 'wL'))
Wi[IdL_a, :, :, :] *= 0.
Wj[:, IdR_c, :, :] *= 0.
# Hb has legs p0, p0*, p1, p1*
H_bond[j] = Hb
# check that nothing is left
for W in Ws:
if npc.norm(W) > tol_zero:
raise ValueError("Bond couplings didn't capture everything. "
"Either H is long range or IdL/IdR is wrong!")
# now merge the onsite terms to H_bond
for j in range(L):
if finite and j == 0:
continue
i = (j - 1) % L
strength_i = 1. if finite and i == 0 else 0.5
strength_j = 1. if finite and j == L - 1 else 0.5
Hb = (npc.outer(sites[i].Id, strength_j * H_onsite[j]) +
npc.outer(strength_i * H_onsite[i], sites[j].Id))
Hb = add_with_None_0(H_bond[j], Hb)
Hb.iset_leg_labels(['p0', 'p0*', 'p1', 'p1*'])
H_bond[j] = Hb
if finite:
assert H_bond[0] is None
if self.explicit_plus_hc:
# represented H = H_MPO + h.c.
# so we need to explicitly add the hermitian conjugate terms
for i, Hb in enumerate(H_bond):
if Hb is not None:
H_bond[i] = Hb + Hb.conj().itranspose(Hb.get_leg_labels())
return H_bond
def get_extra_default_measurements(self):
m_extra_default_list = super().get_extra_default_measurements()
m_extra_default_list.append(('tenpy.simulations.measurement', 'm_energy_MPO'))
return m_extra_default_list
class CouplingModel(Model):
"""Base class for a general model of a Hamiltonian consisting of two-site couplings.
In this class, the terms of the Hamiltonian are specified explicitly as
:class:`~tenpy.networks.terms.OnsiteTerms` or :class:`~tenpy.networks.terms.CouplingTerms`.
Parameters
----------
lattice : :class:`~tenpy.model.lattice.Lattice`
The lattice defining the geometry and the local Hilbert space(s).
explicit_plus_hc : bool
If True, the Hermitian conjugate of the MPO is computed at runtime,
rather than saved in the MPO.
Attributes
----------
onsite_terms : {'category': :class:`~tenpy.networks.terms.OnsiteTerms`}
The :class:`~tenpy.networks.terms.OnsiteTerms` ordered by category.
coupling_terms : {'category': :class:`~tenpy.networks.terms.CouplingTerms`}
The :class:`~tenpy.networks.terms.CouplingTerms` ordered by category.
In case we've added terms with more than 2 operators,
e.g. with :meth:`add_multi_coupling`, the values of the dictionary may also be
:class:`~tenpy.networks.terms.MultiCouplingTerms`.
exp_decaying_terms : :class:`~tenpy.networks.terms.ExponentiallyDecayingTerms`
Collection of coupling terms with exponentially decaying long-range interactions.
Filled by :meth:`add_exponentially_decaying_coupling`.
explicit_plus_hc : bool
If `True`, `self` represents the terms in :attr:`onsite_terms`, :attr:`coupling_terms`
and :attr:`exp_decaying_terms` *plus* their hermitian conjugate added.
The flag will be carried on to the MPO, which will have a reduced bond dimension if
``self.add_coupling(..., plus_hc=True)`` was used.
Note that :meth:`add_onsite`, :meth:`add_coupling`, :meth:`add_multi_coupling`
and :meth:`add_exponentially_decaying_coupling` respect this flag, ensuring that the
*represented* Hamiltonian is independent of the `explicit_plus_hc` flag.
"""
def __init__(self, lattice, explicit_plus_hc=False):
Model.__init__(self, lattice)
L = self.lat.N_sites
self.onsite_terms = {}
self.coupling_terms = {}
self.exp_decaying_terms = ExponentiallyDecayingTerms(L)
self.explicit_plus_hc = explicit_plus_hc
CouplingModel.test_sanity(self)
# like self.test_sanity(), but use the version defined below even for derived class
def test_sanity(self):
"""Sanity check, raises ValueErrors, if something is wrong."""
sites = self.lat.mps_sites()
for ot in self.onsite_terms.values():
ot._test_terms(sites)
for ct in self.coupling_terms.values():
ct._test_terms(sites)
def add_local_term(self, strength, term, category=None, plus_hc=False):
"""Add a single term to `self`.
The represented term is `strength` times the product of the operators given in `terms`.
Each operator is specified by the name and the site it acts on; the latter given by
a lattice index, see :class:`~tenpy.models.lattice.Lattice`.
Depending on the length of `term`, it can add an onsite term or a coupling term to
:attr:`onsite_terms` or :attr:`coupling_terms`, respectively.
Parameters
----------
strength : float/complex
The prefactor of the term.
term : list of (str, array_like)
List of tuples ``(opname, lat_idx)`` where `opname` is a string describing the operator
acting on the site given by the lattice index `lat_idx`. Here, `lat_idx` is for
example `[x, y, u]` for a 2D lattice, with `u` being the index within the unit cell.
category:
Descriptive name used as key for :attr:`onsite_terms` or :attr:`coupling_terms`.
plus_hc : bool
If `True`, the hermitian conjugate of the terms is added automatically.
"""
if self.explicit_plus_hc:
if plus_hc:
plus_hc = False # explicitly add the h.c. later; don't do it here.
else:
strength /= 2 # avoid double-counting this term: add the h.c. explicitly later on
# convert lattice to MPS index
term = [(op, self.lat.lat2mps_idx(idx)) for op, idx in term]
if category is None:
category = "local " + " ".join([op for op, i in term])
sites = self.lat.mps_sites()
term, sign = order_combine_term(term, sites)
strength = strength * sign
N = len(sites)
if len(term) == 1:
ot = self.onsite_terms.setdefault(category, OnsiteTerms(N))
op, i = term[0]
if sites[i].op_needs_JW(op):
raise ValueError("can't add onsite operator which needs a Jordan-Wigner string!")
ot.add_onsite_term(strength, i, op)
elif len(term) == 2:
ct = self.coupling_terms.setdefault(category, CouplingTerms(N))
args = ct.coupling_term_handle_JW(strength, term, sites)
ct.add_coupling_term(*args)
elif len(term) > 2:
ct = self.coupling_terms.setdefault(category, MultiCouplingTerms(N))
if not isinstance(ct, MultiCouplingTerms):
# convert ct to MultiCouplingTerms
self.coupling_terms[category] = new_ct = MultiCouplingTerms(self.lat.N_sites)
new_ct += ct
ct = new_ct
args = ct.multi_coupling_term_handle_JW(strength, term, sites)
ct.add_multi_coupling_term(*args)
else:
raise ValueError("empty term!")
if plus_hc:
hc_term = [(sites[i % N].get_hc_op_name(op), self.lat.mps2lat_idx(i))
for op, i in reversed(term)]
self.add_local_term(np.conj(strength), hc_term, category, plus_hc=False)
def add_onsite(self, strength, u, opname, category=None, plus_hc=False):
r"""Add onsite terms to :attr:`onsite_terms`.
Adds :math:`\sum_{\vec{x}} strength[\vec{x}] * OP`` to the represented Hamiltonian,
where the operator ``OP=lat.unit_cell[u].get_op(opname)``
acts on the site given by a lattice index ``(x_0, ..., x_{dim-1}, u)``,
The necessary terms are just added to :attr:`onsite_terms`; doesn't rebuild the MPO.
Parameters
----------
strength : scalar | array
Prefactor of the onsite term. May vary spatially. If an array of smaller size
is provided, it gets tiled to the required shape.
u : int
Picks a :class:`~tenpy.model.lattice.Site` ``lat.unit_cell[u]`` out of the unit cell.
opname : str
valid operator name of an onsite operator in ``lat.unit_cell[u]``.
category : str
Descriptive name used as key for :attr:`onsite_terms`. Defaults to `opname`.
plus_hc : bool
If `True`, the hermitian conjugate of the terms is added automatically.
See also
--------
add_coupling : Add a terms acting on two sites.
add_onsite_term : Add a single term without summing over :math:`vec{x}`.
"""
strength = to_array(strength, self.lat.Ls) # tile to lattice shape
if not np.any(strength != 0.):
return # nothing to do: can even accept non-defined `opname`.
if self.explicit_plus_hc:
if plus_hc:
plus_hc = False # explicitly add the h.c. later; don't do it here.
else:
strength /= 2 # avoid double-counting this term: add the h.c. explicitly later on
if not self.lat.unit_cell[u].valid_opname(opname):
raise ValueError("unknown onsite operator {0!r} for u={1:d}\n"
"{2!r}".format(opname, u, self.lat.unit_cell[u]))
if self.lat.unit_cell[u].op_needs_JW(opname):
raise ValueError("can't add onsite operator which needs a Jordan-Wigner string!")
if category is None:
category = opname
ot = self.onsite_terms.setdefault(category, OnsiteTerms(self.lat.N_sites))
for i, i_lat in zip(*self.lat.mps_lat_idx_fix_u(u)):
ot.add_onsite_term(strength[tuple(i_lat)], i, opname)
if plus_hc:
hc_op = self.lat.unit_cell[u].get_hc_op_name(opname)
self.add_onsite(np.conj(strength), u, hc_op, category, plus_hc=False)
def add_onsite_term(self, strength, i, op, category=None, plus_hc=False):
"""Add an onsite term on a given MPS site.
Wrapper for ``self.onsite_terms[category].add_onsite_term(...)``.
Parameters
----------
strength : float
The strength of the term.
i : int
The MPS index of the site on which the operator acts.
We require ``0 <= i < L``.
op : str
Name of the involved operator.
category : str
Descriptive name used as key for :attr:`onsite_terms`. Defaults to `op`.
plus_hc : bool
If `True`, the hermitian conjugate of the term is added automatically.
"""
if self.explicit_plus_hc:
if plus_hc:
plus_hc = False # explicitly add the h.c. later; don't do it here.
else:
strength /= 2 # avoid double-counting this term: add the h.c. explicitly later on
if category is None: