/
dmrg.py
2014 lines (1809 loc) · 90.5 KB
/
dmrg.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
"""Density Matrix Renormalization Group (DMRG).
Although it was originally not formulated with tensor networks,
the DMRG algorithm (invented by Steven White in 1992 [White1992]_) opened the whole field
with its enormous success in finding ground states in 1D.
We implement DMRG in the modern formulation of matrix product states [Schollwoeck2011]_,
both for finite systems (``'finite'`` or ``'segment'`` boundary conditions)
and in the thermodynamic limit (``'infinite'`` b.c.).
The function :func:`run` - well - runs one DMRG simulation.
Internally, it generates an instance of an :class:`Sweep`.
This class implements the common functionality like defining a `sweep`,
but leaves the details of the contractions to be performed to the derived classes.
Currently, there are two derived classes implementing the contractions: :class:`SingleSiteDMRGEngine`
and :class:`TwoSiteDMRGEngine`. They differ (as their name implies) in the number of sites which
are optimized simultaneously.
They should both give the same results (up to rounding errors). However, if started from a product
state, :class:`SingleSiteDMRGEngine` depends critically on the use of a :class:`Mixer`, while
:class:`TwoSiteDMRGEngine` is in principle more computationally expensive to run and has
occasionally displayed some convergence issues..
Which one is preffered in the end is not obvious a priori and might depend on the used model.
Just try both of them.
A :class:`Mixer` should be used initially to avoid that the algorithm gets stuck in local energy
minima, and then slowly turned off in the end. For :class:`SingleSiteDMRGEngine`, using a mixer is
crucial, as the one-site algorithm cannot increase the MPS bond dimension by itself.
.. todo ::
Write UserGuide!!!
"""
# Copyright 2018-2020 TeNPy Developers, GNU GPLv3
import numpy as np
import time
import warnings
from ..linalg import np_conserved as npc
from ..networks.mps import MPSEnvironment
from ..networks.mpo import MPOEnvironment
from ..linalg.lanczos import lanczos, lanczos_arpack
from .truncation import truncate, svd_theta
from ..tools.params import asConfig
from ..tools.process import memory_usage
from .mps_sweeps import Sweep, OneSiteH, TwoSiteH
__all__ = [
'run', 'DMRGEngine', 'SingleSiteDMRGEngine', 'TwoSiteDMRGEngine', 'EngineCombine',
'EngineFracture', 'Mixer', 'SingleSiteMixer', 'TwoSiteMixer', 'DensityMatrixMixer', 'chi_list',
'full_diag_effH'
]
def run(psi, model, options):
r"""Run the DMRG algorithm to find the ground state of the given model.
Parameters
----------
psi : :class:`~tenpy.networks.mps.MPS`
Initial guess for the ground state, which is to be optimized in-place.
model : :class:`~tenpy.models.MPOModel`
The model representing the Hamiltonian for which we want to find the ground state.
options : dict
Further optional parameters as described in :cfg:config:`DMRGEngine`.
Use ``verbose>0`` to print the used parameters during runtime.
Returns
-------
info : dict
A dictionary with keys ``'E', 'shelve', 'bond_statistics', 'sweep_statistics'``
Options
-------
.. cfg:config :: DMRG
:include: SingleSiteDMRGEngine, TwoSiteDMRGEngine
active_sites
The number of active sites to be used by DMRG.
If set to 1, :class:`SingleSiteDMRGEngine` is used.
If set to 2, DMRG is handled by :class:`TwoSiteDMRGEngine`.
"""
# initialize the engine
options = asConfig(options, 'DMRG')
active_sites = options.get('active_sites', 2)
if active_sites == 1:
engine = SingleSiteDMRGEngine(psi, model, options)
elif active_sites == 2:
engine = TwoSiteDMRGEngine(psi, model, options)
else:
raise ValueError("For DMRG, can only use 1 or 2 active sites, not {}".format(active_sites))
E, _ = engine.run()
return {
'E': E,
'shelve': engine.shelve,
'bond_statistics': engine.update_stats,
'sweep_statistics': engine.sweep_stats
}
class DMRGEngine(Sweep):
"""DMRG base class.'Engine' for the DMRG algorithm.
This engine is implemented as a subclass of :class:`~tenpy.algorithms.mps_sweeps.Sweep`.
It contains all methods that are generic between
:class:`SingleSiteDMRGEngine` and :class:`TwoSiteDMRGEngine`.
.. deprecated :: 0.5.0
Renamed parameter/attribute `DMRG_params` to :attr:`options`.
Options
-------
.. cfg:config :: DMRGEngine
:include: Sweep
Attributes
----------
EffectiveH : class type
Class for the effective Hamiltonian, i.e., a subclass of
:class:`~tenpy.algorithms.mps_sweeps.EffectiveH`. Has a `length` class attribute which
specifies the number of sites updated at once (e.g., whether we do single-site vs. two-site
DMRG).
chi_list : dict | ``None``
See :cfg:option:`DMRGEngine.chi_list`
eff_H : :class:`~tenpy.algorithms.mps_sweeps.EffectiveH`
Effective two-site Hamiltonian.
mixer : :class:`Mixer` | ``None``
If ``None``, no mixer is used (anymore), otherwise the mixer instance.
shelve : bool
If a simulation runs out of time (`time.time() - start_time > max_seconds`), the run will
terminate with `shelve = True`.
sweeps : int
The number of sweeps already performed. (Useful for re-start).
time0 : float
Time marker for the start of the run.
update_stats : dict
A dictionary with detailed statistics of the convergence at local update-level.
For each key in the following table, the dictionary contains a list where one value is
added each time :meth:`DMRGEngine.update_bond` is called.
=========== ===================================================================
key description
=========== ===================================================================
i0 An update was performed on sites ``i0, i0+1``.
----------- -------------------------------------------------------------------
age The number of physical sites involved in the simulation.
----------- -------------------------------------------------------------------
E_total The total energy before truncation.
----------- -------------------------------------------------------------------
N_lanczos Dimension of the Krylov space used in the lanczos diagonalization.
----------- -------------------------------------------------------------------
time Wallclock time evolved since :attr:`time0` (in seconds).
----------- -------------------------------------------------------------------
ov_change ``1. - abs(<theta_guess|theta_diag>)``, where ``|theta_guess>`` is
the initial guess for the wave function and ``|theta_diag>`` is the
*untruncated* wave function returned by :meth:`diag`.
=========== ===================================================================
sweep_stats : dict
A dictionary with detailed statistics at the sweep level.
For each key in the following table, the dictionary contains a list where one value is
added each time :meth:`Engine.sweep` is called (with ``optimize=True``).
============= ===================================================================
key description
============= ===================================================================
sweep Number of sweeps (excluding environment sweeps) performed so far.
------------- -------------------------------------------------------------------
N_updates Number of updates (including environment sweeps) performed so far.
------------- -------------------------------------------------------------------
E The energy *before* truncation (as calculated by Lanczos).
------------- -------------------------------------------------------------------
S Maximum entanglement entropy.
------------- -------------------------------------------------------------------
time Wallclock time evolved since :attr:`time0` (in seconds).
------------- -------------------------------------------------------------------
max_trunc_err The maximum truncation error in the last sweep
------------- -------------------------------------------------------------------
max_E_trunc Maximum change or Energy due to truncation in the last sweep.
------------- -------------------------------------------------------------------
max_chi Maximum bond dimension used.
------------- -------------------------------------------------------------------
norm_err Error of canonical form ``np.linalg.norm(psi.norm_test())``.
============= ===================================================================
"""
@property
def DMRG_params(self):
warnings.warn("renamed self.DMRG_params -> self.options", FutureWarning, stacklevel=2)
return self.options
def run(self):
"""Run the DMRG simulation to find the ground state.
Returns
-------
E : float
The energy of the resulting ground state MPS.
psi : :class:`~tenpy.networks.mps.MPS`
The MPS representing the ground state after the simluation,
i.e. just a reference to :attr:`psi`.
Options
-------
.. cfg:configoptions :: DMRGEngine
diag_method : str
Method to be used for diagonalzation, default ``'default'``.
For possible arguments see :meth:`DMRGEngine.diag`.
E_tol_to_trunc : float
It's reasonable to choose the Lanczos convergence criteria
``'E_tol'`` not many magnitudes lower than the current
truncation error. Therefore, if `E_tol_to_trunc` is not
``None``, we update `E_tol` of `lanczos_params` to
``max_E_trunc*E_tol_to_trunc``,
restricted to the interval [`E_tol_min`, `E_tol_max`],
where ``max_E_trunc`` is the maximal energy difference due to
truncation right after each Lanczos optimization during the
sweeps.
E_tol_max : float
See `E_tol_to_trunc`
E_tol_min : float
See `E_tol_to_trunc`
max_E_err : float
Convergence if the change of the energy in each step
satisfies ``-Delta E / max(|E|, 1) < max_E_err``. Note that
this is also satisfied if ``Delta E > 0``,
i.e., if the energy increases (due to truncation).
max_hours : float
If the DMRG took longer (measured in wall-clock time),
'shelve' the simulation, i.e. stop and return with the flag
``shelve=True``.
max_S_err : float
Convergence if the relative change of the entropy in each step
satisfies ``|Delta S|/S < max_S_err``
max_sweeps : int
Maximum number of sweeps to be performed.
min_sweeps : int
Minimum number of sweeps to be performed.
Defaults to 1.5*N_sweeps_check.
N_sweeps_check : int
Number of sweeps to perform between checking convergence
criteria and giving a status update.
norm_tol : float
After the DMRG run, update the environment with at most
`norm_tol_iter` sweeps until
``np.linalg.norm(psi.norm_err()) < norm_tol``.
norm_tol_iter : float
Perform at most `norm_tol_iter`*`update_env` sweeps to
converge the norm error below `norm_tol`.
If the state is not converged after that, call
:meth:`~tenpy.networks.mps.canonical_form` instead.
P_tol_to_trunc : float
It's reasonable to choose the Lanczos convergence criteria
``'P_tol'`` not many magnitudes lower than the current
truncation error. Therefore, if `P_tol_to_trunc` is not
``None``, we update `P_tol` of `lanczos_params` to
``max_trunc_err*P_tol_to_trunc``,
restricted to the interval [`P_tol_min`, `P_tol_max`],
where ``max_trunc_err`` is the maximal truncation error
(discarded weight of the Schmidt values) due to truncation
right after each Lanczos optimization during the sweeps.
P_tol_max : float
See `P_tol_to_trunc`
P_tol_min : float
See `P_tol_to_trunc`
update_env : int
Number of sweeps without bond optimizaiton to update the
environment for infinite boundary conditions,
performed every `N_sweeps_check` sweeps.
"""
options = self.options
start_time = self.time0
self.shelve = False
# parameters for lanczos
p_tol_to_trunc = options.get('P_tol_to_trunc', 0.05)
if p_tol_to_trunc is not None:
p_tol_min = max(1.e-30,
self.lanczos_params.get('svd_min', 0.)**2 * p_tol_to_trunc,
self.lanczos_params.get('trunc_cut', 0.)**2 * p_tol_to_trunc)
p_tol_min = options.get('P_tol_min', p_tol_min)
p_tol_max = options.get('P_tol_max', 1.e-4)
e_tol_to_trunc = options.get('E_tol_to_trunc', None)
if e_tol_to_trunc is not None:
e_tol_min = options.get('E_tol_min', 5.e-16)
e_tol_max = options.get('E_tol_max', 1.e-4)
# parameters for DMRG convergence criteria
N_sweeps_check = options.get('N_sweeps_check', 10)
min_sweeps = int(1.5 * N_sweeps_check)
if self.chi_list is not None:
min_sweeps = max(max(self.chi_list.keys()), min_sweeps)
min_sweeps = options.get('min_sweeps', min_sweeps)
max_sweeps = options.get('max_sweeps', 1000)
max_E_err = options.get('max_E_err', 1.e-8)
max_S_err = options.get('max_S_err', 1.e-5)
max_seconds = 3600 * options.get('max_hours', 24 * 365)
norm_tol = options.get('norm_tol', 1.e-5)
if not self.finite:
update_env = options.get('update_env', N_sweeps_check // 2)
norm_tol_iter = options.get('norm_tol_iter', 5)
E_old, S_old = np.nan, np.nan # initial dummy values
E, Delta_E, Delta_S = 1., 1., 1.
self.diag_method = options.get('diag_method', 'default')
self.mixer_activate()
# loop over sweeps
while True:
# check convergence criteria
if self.sweeps >= max_sweeps:
break
if (self.sweeps > min_sweeps and -Delta_E < max_E_err * max(abs(E), 1.)
and abs(Delta_S) < max_S_err):
if self.mixer is None:
break
else:
if self.verbose >= 1:
print("Convergence criterium reached with enabled mixer.\n"
"disable mixer and continue")
self.mixer = None
if time.time() - start_time > max_seconds:
self.shelve = True
warnings.warn("DMRG: maximum time limit reached. Shelve simulation.")
break
# --------- the main work --------------
for i in range(N_sweeps_check - 1):
self.sweep(meas_E_trunc=False)
max_trunc_err, max_E_trunc = self.sweep(meas_E_trunc=True)
# --------------------------------------
# update lancos_params depending on truncation error(s)
if p_tol_to_trunc is not None and max_trunc_err > p_tol_min:
self.lanczos_params['P_tol'] = max(p_tol_min,
min(p_tol_max, max_trunc_err * p_tol_to_trunc))
if self.verbose > 3:
print("set lanczos_params['P_tol'] = {0:.2e}".format(
self.lanczos_params['P_tol']))
if e_tol_to_trunc is not None and max_E_trunc > e_tol_min:
self.lanczos_params['E_tol'] = max(e_tol_min,
min(e_tol_max, max_E_trunc * e_tol_to_trunc))
if self.verbose > 3:
print("set lanczos_params['E_tol'] = {0:.2e}".format(
self.lanczos_params['P_tol']))
# update environment
if not self.finite:
self.environment_sweeps(update_env)
# update values for checking the convergence
try:
S = np.average(self.psi.entanglement_entropy())
Delta_S = (S - S_old) / N_sweeps_check
except ValueError:
# with a mixer, psi._S can be 2D arrays s.t. entanglement_entropy() fails
S = np.nan
Delta_S = 0.
S_old = S
if not self.finite: # iDMRG: need energy density
Es = self.update_stats['E_total']
age = self.update_stats['age']
delta = min(1 + 2 * self.env.L, len(age))
growth = (age[-1] - age[-delta])
E = (Es[-1] - Es[-delta]) / growth
else:
E = self.update_stats['E_total'][-1]
Delta_E = (E - E_old) / N_sweeps_check
E_old = E
norm_err = np.linalg.norm(self.psi.norm_test())
# update statistics
self.sweep_stats['sweep'].append(self.sweeps)
self.sweep_stats['N_updates'].append(len(self.update_stats['i0']))
self.sweep_stats['E'].append(E)
self.sweep_stats['S'].append(S)
self.sweep_stats['time'].append(time.time() - start_time)
self.sweep_stats['max_trunc_err'].append(max_trunc_err)
self.sweep_stats['max_E_trunc'].append(max_E_trunc)
self.sweep_stats['max_chi'].append(np.max(self.psi.chi))
self.sweep_stats['norm_err'].append(norm_err)
# print status update
if self.verbose >= 1:
print("=" * 80)
msg = ("sweep {sweep:d}, age = {age:d}\n"
"Energy = {E:.16f}, S = {S:.16f}, norm_err = {norm_err:.1e}\n"
"Current memory usage {mem:.1f} MB, time elapsed: {time:.1f} s\n"
"Delta E = {DE:.4e}, Delta S = {DS:.4e} (per sweep)\n"
"max_trunc_err = {trerr:.4e}, max_E_trunc = {Eerr:.4e}\n"
"MPS bond dimensions: {chi!s}")
msg = msg.format(sweep=self.sweeps,
mem=memory_usage(),
time=time.time() - start_time,
chi=self.psi.chi,
age=self.update_stats['age'][-1],
E=E,
S=S,
DE=Delta_E,
DS=Delta_S,
trerr=max_trunc_err,
Eerr=max_E_trunc,
norm_err=norm_err)
print(msg, flush=True)
# clean up from mixer
self.mixer_cleanup()
# update environment until norm_tol is reached
if norm_tol is not None and norm_err > norm_tol:
msg = "final DMRG state not in canonical form within `norm_tol` = {nt:.2e}"
warnings.warn(msg.format(nt=norm_tol))
if self.verbose >= 1:
print("norm_tol={nt:.2e} not reached, norm_err={ne:.2e}".format(nt=norm_tol,
ne=norm_err))
if self.finite:
self.psi.canonical_form()
else:
for _ in range(norm_tol_iter):
self.environment_sweeps(update_env)
norm_err = np.linalg.norm(self.psi.norm_test())
if norm_err <= norm_tol:
break
else:
if self.verbose >= 1:
msg = ("DMRG: norm_tol {nt:.2e} not reached by updating the environment, "
"current norm_err = {ne:.2e}\n"
"Call psi.canonical_form()").format(nt=norm_tol, ne=norm_err)
print(msg)
self.psi.canonical_form()
if self.verbose >= 1:
print("=" * 80)
msg = ("DMRG finished after {sweep:d} sweeps.\n"
"total size = {age:d}, maximum chi = {chimax:d}")
print(
msg.format(sweep=self.sweeps,
age=self.update_stats['age'][-1],
chimax=np.max(self.psi.chi)))
print("=" * 80)
return E, self.psi
def reset_stats(self):
"""Reset the statistics, useful if you want to start a new sweep run.
.. cfg:configoptions :: DMRGEngine
chi_list : dict | None
A dictionary to gradually increase the `chi_max` parameter of
`trunc_params`. The key defines starting from which sweep
`chi_max` is set to the value, e.g. ``{0: 50, 20: 100}`` uses
``chi_max=50`` for the first 20 sweeps and ``chi_max=100``
afterwards. Overwrites `trunc_params['chi_list']``.
By default (``None``) this feature is disabled.
sweep_0 : int
The number of sweeps already performed. (Useful for re-start).
"""
self.sweeps = self.options.get('sweep_0', 0)
self.update_stats = {
'i0': [],
'age': [],
'E_total': [],
'N_lanczos': [],
'time': [],
'err': [],
'E_trunc': [],
'ov_change': []
}
self.sweep_stats = {
'sweep': [],
'N_updates': [],
'E': [],
'S': [],
'time': [],
'max_trunc_err': [],
'max_E_trunc': [],
'max_chi': [],
'norm_err': []
}
self.chi_list = self.options.get('chi_list', None)
if self.chi_list is not None:
chi_max = self.chi_list[max([k for k in self.chi_list.keys() if k <= self.sweeps])]
self.trunc_params['chi_max'] = chi_max
if self.verbose >= 1:
print("Setting chi_max =", chi_max)
self.time0 = time.time()
def post_update_local(self, update_data, meas_E_trunc=False):
"""Perform post-update actions.
Compute truncation energy, remove `LP`/`RP` that are no longer needed and collect
statistics.
Parameters
----------
update_data : dict
Data computed during the local update, as described in the following list.
meas_E_trunc : bool, optional
Wheter to measure the energy after truncation.
"""
E0 = update_data['E0']
i0 = self.i0
E_trunc = None
if meas_E_trunc or E0 is None:
E_trunc = self.env.full_contraction(i0).real # uses updated LP/RP (if calculated)
if E0 is None:
E0 = E_trunc
E_trunc = E_trunc - E0
# now we can also remove the LP and RP on outer bonds, which we don't need any more
if self.EffectiveH.length == 2:
# TODO: Do we need those for single site DMRG? In infinite case?
update_LP, update_RP = self.update_LP_RP
if update_RP: # we move to the left -> delete left LP
self.env.del_LP(i0)
for o_env in self.ortho_to_envs:
o_env.del_LP(i0)
if update_LP: # we move to the right -> delete right RP
self.env.del_RP(i0 + 1) # Always +1, even in single site.
for o_env in self.ortho_to_envs:
o_env.del_RP(i0 + 1)
# collect statistics
self.update_stats['i0'].append(i0)
self.update_stats['age'].append(update_data['age'])
self.update_stats['E_total'].append(E0)
self.update_stats['E_trunc'].append(E_trunc)
self.update_stats['N_lanczos'].append(update_data['N'])
self.update_stats['ov_change'].append(update_data['ov_change'])
self.update_stats['err'].append(update_data['err'])
self.update_stats['time'].append(time.time() - self.time0)
self.trunc_err_list.append(update_data['err'].eps)
self.E_trunc_list.append(E_trunc)
def diag(self, theta_guess):
"""Diagonalize the effective Hamiltonian represented by self.
.. cfg:configoptions :: DMRGEngine
max_N_for_ED : int
Maximum matrix dimension of the effective hamiltonian
up to which the ``'default'`` `diag_method` uses ED instead of
Lanczos.
diag_method : str
One of the folloing strings:
'default'
Same as ``'lanczos'`` for large bond dimensions, but if the
total dimension of the effective Hamiltonian does not exceed
the DMRG parameter ``'max_N_for_ED'`` it uses ``'ED_block'``.
'lanczos'
:func:`~tenpy.linalg.lanczos.lanczos`
Default, the Lanczos implementation in TeNPy.
'arpack'
:func:`~tenpy.linalg.lanczos.lanczos_arpack`
Based on :func:`scipy.linalg.sparse.eigsh`.
Slower than 'lanczos', since it needs to convert the npc arrays
to numpy arrays during *each* matvec, and possibly does many
more iterations.
'ED_block'
:func:`full_diag_effH`
Contract the effective Hamiltonian to a (large!) matrix and
diagonalize the block in the charge sector of the initial state.
Preserves the charge sector of the explicitly conserved charges.
However, if you don't preserve a charge explicitly, it can break
it.
For example if you use a ``SpinChain({'conserve': 'parity'})``,
it could change the total "Sz", but not the parity of 'Sz'.
'ED_all'
:func:`full_diag_effH`
Contract the effective Hamiltonian to a (large!) matrix and
diagonalize it completely.
Allows to change the charge sector *even for explicitly
conserved charges*.
For example if you use a ``SpinChain({'conserve': 'Sz'})``,
it **can** change the total "Sz".
Parameters
----------
theta_guess : :class:`~tenpy.linalg.np_conserved.Array`
Initial guess for the ground state of the effective Hamiltonian.
Returns
-------
E0 : float
Energy of the found ground state.
theta : :class:`~tenpy.linalg.np_conserved.Array`
Ground state of the effective Hamiltonian.
N : int
Number of Lanczos iterations used. ``-1`` if unknown.
ov_change : float
Change in the wave function ``1. - abs(<theta_guess|theta_diag>)``
"""
N = -1 # (unknown)
if self.diag_method == 'default':
# use ED for small matrix dimensions, but lanczos by default
max_N = self.options.get('max_N_for_ED', 400)
if self.eff_H.N < max_N:
E, theta = full_diag_effH(self.eff_H, theta_guess, keep_sector=True)
else:
E, theta, N = lanczos(self.eff_H, theta_guess, self.lanczos_params)
elif self.diag_method == 'lanczos':
E, theta, N = lanczos(self.eff_H, theta_guess, self.lanczos_params)
elif self.diag_method == 'arpack':
E, theta = lanczos_arpack(self.eff_H, theta_guess, self.lanczos_params)
elif self.diag_method == 'ED_block':
E, theta = full_diag_effH(self.eff_H, theta_guess, keep_sector=True)
elif self.diag_method == 'ED_all':
E, theta = full_diag_effH(self.eff_H, theta_guess, keep_sector=False)
else:
raise ValueError("Unknown diagonalization method: " + repr(self.diag_method))
ov_change = 1. - abs(npc.inner(theta_guess, theta, 'labels', do_conj=True))
return E, theta, N, ov_change
def plot_update_stats(self, axes, xaxis='time', yaxis='E', y_exact=None, **kwargs):
"""Plot :attr:`update_stats` to display the convergence during the sweeps.
Parameters
----------
axes : :class:`matplotlib.axes.Axes`
The axes to plot into. Defaults to :func:`matplotlib.pyplot.gca()`
xaxis : ``'N_updates' | 'sweep'`` | keys of :attr:`update_stats`
Key of :attr:`update_stats` to be used for the x-axis of the plots.
``'N_updates'`` is just enumerating the number of bond updates,
and ``'sweep'`` corresponds to the sweep number (including environment sweeps).
yaxis : ``'E'`` | keys of :attr:`update_stats`
Key of :attr:`update_stats` to be used for the y-axisof the plots.
For 'E', use the energy (per site for infinite systems).
y_exact : float
Exact value for the quantity on the y-axis for comparison.
If given, plot ``abs((y-y_exact)/y_exact)`` on a log-scale yaxis.
**kwargs :
Further keyword arguments given to ``axes.plot(...)``.
"""
if axes is None:
import matplotlib.pyplot as plt
axes = plt.gca()
stats = self.update_stats
L = self.psi.L
kwargs.setdefault('marker', 'x')
kwargs.setdefault('linestyle', '-')
E = np.array(stats['E_total'])
schedule = list(self.get_sweep_schedule())
N = len(schedule) # bond updates per sweep
if xaxis is None or xaxis == 'N_updates' or xaxis == 'index':
xaxis = 'N_updates'
x = np.arange(len(E))
elif xaxis == 'sweep':
x = np.arange(1, len(E) + 1) / N
else:
x = np.array(stats[xaxis])
if yaxis == 'E':
if not self.psi.finite:
# use energy per site instead of total energy
age = np.array(stats['age'])
d_age = age[N:] - age[:-N]
d_E = E[N:] - E[:-N]
y = d_E / d_age
x = x[N:]
else:
y = E
else:
y = np.array(stats[yaxis])
if y_exact is not None:
y = np.abs(y - y_exact) / np.abs(y_exact)
axes.set_yscale('log')
axes.plot(x, y, **kwargs)
axes.set_xlabel(xaxis)
axes.set_ylabel(yaxis)
def plot_sweep_stats(self, axes=None, xaxis='time', yaxis='E', y_exact=None, **kwargs):
"""Plot :attr:`sweep_stats` to display the convergence with the sweeps.
Parameters
----------
axes : :class:`matplotlib.axes.Axes`
The axes to plot into. Defaults to :func:`matplotlib.pyplot.gca()`
xaxis, yaxis : key of :attr:`sweep_stats`
Key of :attr:`sweep_stats` to be used for the x-axis and y-axis of the plots.
y_exact : float
Exact value for the quantity on the y-axis for comparison.
If given, plot ``abs((y-y_exact)/y_exact)`` on a log-scale yaxis.
**kwargs :
Further keyword arguments given to ``axes.plot(...)``.
"""
if axes is None:
import matplotlib.pyplot as plt
axes = plt.gca()
stats = self.sweep_stats
L = self.psi.L
kwargs.setdefault('marker', 'x')
kwargs.setdefault('linestyle', '-')
x = np.array(stats[xaxis])
y = np.array(stats[yaxis])
if y_exact is not None:
y = np.abs(y - y_exact) / np.abs(y_exact)
axes.set_yscale('log')
axes.plot(x, y, **kwargs)
axes.set_xlabel(xaxis)
axes.set_ylabel(yaxis)
class TwoSiteDMRGEngine(DMRGEngine):
"""'Engine' for the two-site DMRG algorithm.
Parameters
----------
psi : :class:`~tenpy.networks.mps.MPS`
Initial guess for the ground state, which is to be optimized in-place.
model : :class:`~tenpy.models.MPOModel`
The model representing the Hamiltonian for which we want to find the ground state.
options : dict
Further optional parameters.
Options
-------
.. cfg:config :: TwoSiteDMRGEngine
:include: DMRGEngine
Attributes
----------
EffectiveH : class type
Class for the effective Hamiltonian (i.e., a subclass of
:class:`~tenpy.algorithms.mps_sweeps.EffectiveH`. Has a `length` class attribute which
specifies the number of sites updated at once (e.g., whether we do single-site vs. two-site
DMRG).
chi_list : dict | ``None``
A dictionary to gradually increase the `chi_max` parameter of `trunc_params`. The key
defines starting from which sweep `chi_max` is set to the value, e.g. ``{0: 50, 20: 100}``
uses ``chi_max=50`` for the first 20 sweeps and ``chi_max=100`` afterwards. Overwrites
`trunc_params['chi_list']``. By default (``None``) this feature is disabled.
eff_H : :class:`~tenpy.algorithms.mps_sweeps.EffectiveH`
Effective two-site Hamiltonian.
mixer : :class:`Mixer` | ``None``
If ``None``, no mixer is used (anymore), otherwise the mixer instance.
shelve : bool
If a simulation runs out of time (`time.time() - start_time > max_seconds`), the run will
terminate with `shelve = True`.
sweeps : int
The number of sweeps already performed. (Useful for re-start).
time0 : float
Time marker for the start of the run.
update_stats : dict
A dictionary with detailed statistics of the convergence.
For each key in the following table, the dictionary contains a list where one value is
added each time :meth:`Engine.update_bond` is called.
=========== ===================================================================
key description
=========== ===================================================================
i0 An update was performed on sites ``i0, i0+1``.
----------- -------------------------------------------------------------------
age The number of physical sites involved in the simulation.
----------- -------------------------------------------------------------------
E_total The total energy before truncation.
----------- -------------------------------------------------------------------
N_lanczos Dimension of the Krylov space used in the lanczos diagonalization.
----------- -------------------------------------------------------------------
time Wallclock time evolved since :attr:`time0` (in seconds).
=========== ===================================================================
sweep_stats : dict
A dictionary with detailed statistics of the convergence.
For each key in the following table, the dictionary contains a list where one value is
added each time :meth:`Engine.sweep` is called (with ``optimize=True``).
============= ===================================================================
key description
============= ===================================================================
sweep Number of sweeps performed so far.
------------- -------------------------------------------------------------------
E The energy *before* truncation (as calculated by Lanczos).
------------- -------------------------------------------------------------------
S Maximum entanglement entropy.
------------- -------------------------------------------------------------------
time Wallclock time evolved since :attr:`time0` (in seconds).
------------- -------------------------------------------------------------------
max_trunc_err The maximum truncation error in the last sweep
------------- -------------------------------------------------------------------
max_E_trunc Maximum change or Energy due to truncation in the last sweep.
------------- -------------------------------------------------------------------
max_chi Maximum bond dimension used.
------------- -------------------------------------------------------------------
norm_err Error of canonical form ``np.linalg.norm(psi.norm_test())``.
============= ===================================================================
"""
def __init__(self, psi, model, options):
options = asConfig(options, 'TwoSiteDMRGEngine')
self.EffectiveH = TwoSiteH
super(TwoSiteDMRGEngine, self).__init__(psi, model, options)
def prepare_update(self):
"""Prepare `self` to represent the effective Hamiltonian on sites ``(i0, i0+1)``.
Returns
-------
theta : :class:`~tenpy.linalg.np_conserved.Array`
Current best guess for the ground state, which is to be optimized.
Labels ``'vL', 'p0', 'vR', 'p1'``.
"""
self.make_eff_H() # self.eff_H represents tensors LP, W0, W1, RP
# make theta
cutoff = 1.e-16 if self.mixer is None else 1.e-8
theta = self.psi.get_theta(self.i0, n=2, cutoff=cutoff) # 'vL', 'p0', 'p1', 'vR'
theta = self.eff_H.combine_theta(theta)
return theta
def update_local(self, theta, optimize=True, meas_E_trunc=False):
"""Perform bond-update on the sites ``(i0, i0+1)``.
Parameters
----------
theta : :class:`~tenpy.linalg.np_conserved.Array`
Initial guess for the ground state of the effective Hamiltonian.
optimize : bool
Wheter we actually optimize to find the ground state of the effective Hamiltonian.
(If False, just update the environments).
meas_E_trunc : bool
Wheter to measure the energy after truncation.
Returns
-------
update_data : dict
Data computed during the local update, as described in the following:
E0 : float
Total energy, obtained *before* truncation (if ``optimize=True``),
or *after* truncation (if ``optimize=False``) (but never ``None``).
N : int
Dimension of the Krylov space used for optimization in the lanczos algorithm.
0 if ``optimize=False``.
age : int
Current size of the DMRG simulation: number of physical sites involved
into the contraction.
U, VH: :class:`~tenpy.linalg.np_conserved.Array`
`U` and `VH` returned by :meth:`mixed_svd`.
ov_change: float
Change in the wave function ``1. - abs(<theta_guess|theta>)``
induced by :meth:`diag`, *not* including the truncation!
"""
i0 = self.i0
age = self.env.get_LP_age(i0) + 2 + self.env.get_RP_age(i0 + 1)
if optimize:
E0, theta, N, ov_change = self.diag(theta)
else:
E0, N, ov_change = None, 0, 0.
theta = self.prepare_svd(theta)
U, S, VH, err = self.mixed_svd(theta)
self.set_B(U, S, VH)
update_data = {
'E0': E0,
'err': err,
'N': N,
'age': age,
'U': U,
'VH': VH,
'ov_change': ov_change
}
return update_data
def prepare_svd(self, theta):
"""Transform theta into matrix for svd."""
if self.combine:
return theta # Theta is already combined.
else:
return theta.combine_legs([['vL', 'p0'], ['p1', 'vR']],
new_axes=[0, 1],
qconj=[+1, -1])
def mixed_svd(self, theta):
"""Get (truncated) `B` from the new theta (as returned by diag).
The goal is to split theta and truncate it::
| -- theta -- ==> -- U -- S -- VH -
| | | | |
Without a mixer, this is done by a simple svd and truncation of Schmidt values.
With a mixer, the state is perturbed before the SVD.
The details of the perturbation are defined by the :class:`Mixer` class.
Note that the returned `S` is a general (not diagonal) matrix, with labels ``'vL', 'vR'``.
Parameters
----------
theta : :class:`~tenpy.linalg.np_conserved.Array`
The optimized wave function, prepared for svd.
Returns
-------
U : :class:`~tenpy.linalg.np_conserved.Array`
Left-canonical part of `theta`. Labels ``'(vL.p0)', 'vR'``.
S : 1D ndarray | 2D :class:`~tenpy.linalg.np_conserved.Array`
Without mixer just the singluar values of the array; with mixer it might be a general
matrix with labels ``'vL', 'vR'``; see comment above.
VH : :class:`~tenpy.linalg.np_conserved.Array`
Right-canonical part of `theta`. Labels ``'vL', '(p1.vR)'``.
err : :class:`~tenpy.algorithms.truncation.TruncationError`
The truncation error introduced.
"""
i0 = self.i0
# get qtotal_LR from i0
if self.mixer is None:
# simple case: real svd, defined elsewhere.
qtotal_i0 = self.env.bra.get_B(i0, form=None).qtotal
U, S, VH, err, _ = svd_theta(theta,
self.trunc_params,
qtotal_LR=[qtotal_i0, None],
inner_labels=['vR', 'vL'])
return U, S, VH, err
update_LP, update_RP = self.update_LP_RP
return self.mixer.perturb_svd(self, theta, self.i0, update_LP, update_RP)
def set_B(self, U, S, VH):
"""Update the MPS with the ``U, S, VH`` returned by `self.mixed_svd`.
Parameters
----------
U, VH : :class:`~tenpy.linalg.np_conserved.Array`
Left and Right-canonical matrices as returned by the SVD.
S : 1D array | 2D :class:`~tenpy.linalg.np_conserved.Array`
The middle part returned by the SVD, ``theta = U S VH``.
Without a mixer just the singular values, with enabled `mixer` a 2D array.
"""
B0 = U.split_legs(['(vL.p0)']).replace_label('p0', 'p')
B1 = VH.split_legs(['(p1.vR)']).replace_label('p1', 'p')
i0 = self.i0
self.psi.set_B(i0, B0, form='A') # left-canonical
self.psi.set_B(i0 + 1, B1, form='B') # right-canonical
self.psi.set_SR(i0, S)
# the old stored environments are now invalid
# => delete them to ensure that they get calculated again in :meth:`update_LP` / RP
for o_env in self.ortho_to_envs:
o_env.del_LP(i0 + 1)
o_env.del_RP(i0)
self.env.del_LP(i0 + 1)
self.env.del_RP(i0)
def mixer_activate(self):
"""Set `self.mixer` to the class specified by `options['mixer']`.
.. cfg:configoptions :: TwoSiteDMRGEngine
mixer : str | class | bool
Chooses the :class:`Mixer` to be used.
A string stands for one of the mixers defined in this module,
a class is used as custom mixer.
Default (``None``) uses no mixer, ``True`` uses
:class:`DensityMatrixMixer` for the 2-site case and
:class:`SingleSiteMixer` for the 1-site case.
mixer_params : dict
Mixer parameters as described in :cfg:config:`Mixer`.
"""
Mixer_class = self.options.get('mixer', None)
if Mixer_class:
if Mixer_class is True:
Mixer_class = DensityMatrixMixer
if isinstance(Mixer_class, str):
if Mixer_class == "Mixer":
msg = ('Use `True` or `"DensityMatrixMixer"` instead of "Mixer" '
'for Sweep parameter "mixer"')
warnings.warn(msg, FutureWarning)
Mixer = "DensityMatrixMixer"
Mixer_class = globals()[Mixer_class]
mixer_params = self.options.subconfig('mixer_params')
mixer_params.setdefault('verbose', self.verbose / 10) # reduced verbosity
self.mixer = Mixer_class(mixer_params)
def update_LP(self, U):
"""Update left part of the environment.
We always update the environment at site i0 + 1: this environment then contains the site
where we just performed a local update (when sweeping right).
Parameters
----------
U : :class:`~tenpy.linalg.np_conserved.Array`
The U as returned by the SVD, with combined legs, labels ``'vL.p0', 'vR'``.
"""
i0 = self.i0
if self.combine:
LHeff = self.eff_H.LHeff
LP = npc.tensordot(LHeff, U, axes=['(vR.p0*)', '(vL.p0)'])
LP = npc.tensordot(U.conj(), LP, axes=['(vL*.p0*)', '(vR*.p0)'])
self.env.set_LP(i0 + 1, LP, age=self.env.get_LP_age(i0) + 1) # Always i0 + 1
else: # as implemented directly in the environment
self.env.get_LP(i0 + 1, store=True)
def update_RP(self, VH):
"""Update right part of the environment.
We always update the environment at site i0: this environment then contains the site
where we just performed a local update (when sweeping left).
Parameters
----------
VH : :class:`~tenpy.linalg.np_conserved.Array`
The VH as returned by SVD, with combined legs, labels ``'vL', '(vR.p1)'``.
"""
i0 = self.i0
if self.combine: