This page was generated from exercise_tenpy.ipynb (download).

Exercises similar to exercise_toycodes.ipynb using TeNPy

Uncomment and run the cells below (removing the #) when running this notebook on

Alternatively, you can run this notebook locally with jupyter, provided that you have the toycodes subfolder from in the same folder as your notebook.

[ ]:
#!pip install git+
#!pip install git+

# use `pip uninstall tenpy-toycodes physics-tenpy` to remove them again.

You can add your code below by inserting additional cells as neccessary and running them (press Shift+Enter).

DISCLAIMER: Like for the toy codes, we only use very small bond dimensions here. For state-of-the-art MPS calculations (especially for cylinders towards 2D), chi should be significantly larger, often on the order of several 1000s.

[ ]:
import numpy as np
import scipy
import matplotlib.pyplot as plt
from pprint import pprint

np.set_printoptions(precision=5, suppress=True, linewidth=100)
plt.rcParams['figure.dpi'] = 150
[ ]:
import tenpy
import tenpy.linalg.np_conserved as npc
from tenpy.algorithms import tebd, dmrg, tdvp
from import SpinHalfSite, SpinSite, FermionSite
from tenpy.networks.mps import MPS
from tenpy.models.tf_ising import TFIChain"INFO")


The source code of TeNPy is at; you can find links to the documentation and the forum in the Readme there.

The **documentation** is roughly split into the “User guide” (upper part in the left side-bar) and the reference of all the functions and classes (lower part).


Read the overview of the TeNPy documentation.

Whenever you hit an example code, try to copy it here and run it.

Try to modify it slightly and try to rerun it; for example try to calculate the overlap <v|v> in the first example.

[ ]:

Initializing a Model

In TeNPy, the model defines the Hilbert space and local operators, and ultimately fixes whether charge conservation is used. Therefore, you should usually start with the initialization of the model. There are many predefined models in tenpy.models, that you can often just use.

We will first initialize the transverse field Ising model. One advantage of TeNPy is that it can exploit (abelian) charge conservation for speedups, e.g. the transverse field Ising model preserves an overall spin parity. However, this requires the form

\[ \begin{align}\begin{aligned}H = - J \sum_{i} \sigma^x_i \sigma^x_{i+1} - g \sum_{i} \sigma^z_i \textrm{ in TeNPy}\\compared to the form\end{aligned}\end{align} \]
\[ \begin{align}\begin{aligned}H = - J \sum_{i} \sigma^z_i \sigma^z_{i+1} - g \sum_{i} \sigma^x_i \textrm{ (not suitable for charge conservation)}\\you might be more familiar with, where X and Z are exchanged.\end{aligned}\end{align} \]

In TeNPy, allmost all parmaters can be changed dynamically through options. Default parameters are written back into the dictionaries.

[ ]:
model_params = {
    'L': 20,
    'g': 1.0,
    'bc_MPS': 'finite',
    'conserve': 'best'
model = TFIChain(model_params)
# you can now print the default parameters used:
print("used parameters, including default/not specified ones:")

Given the model, one can easily initialize a product state, e.g. for the Neel state:

[ ]:
p_state = ['up', 'down'] * (
psi = MPS.from_product_state(, p_state,

Measuring expectation values is also similar to the toycode. However, we can even specify the local operators (defined in the sites) as strings:

[ ]:
print("<sigmaz> = ", psi.expectation_value('Sigmaz'))
print("S = ", psi.entanglement_entropy())


Check the Model.bond_energies for the Neel state and make sure it matches what you expect.

[ ]:
E = model.bond_energies(psi)
print("energy Neel:", E)
[ ]:

Running DMRG

Given the model and state, running DMRG isn’t hard. Again, there are many (default) parameters for fine-tuning, see this full option list for details.

[ ]:
p_state = ['up'] *
psi = MPS.from_product_state(, p_state,
algorithm_params = {
    'trunc_params': {
        'chi_max': 30,
        'svd_min': 1.e-7,
    'max_sweeps': 40,
eng = dmrg.TwoSiteDMRGEngine(psi, model, algorithm_params)
E, psi =
[ ]:


Run DMRG for 'infinite' MPS. (You need to initialize a new model, state, and DMRG engine for this.)

[ ]:
from toycodes import tfi_exact

print("E_exact =", tfi_exact.infinite_gs_energy(model_params['J'], model_params['g']))
[ ]:

[ ]:


Reproduce the phase-diagram plot of the transverse field Ising model from the toy code noteboook with TeNPy.

[ ]:

[ ]:

[ ]:

Advanced exercises - if you’re an expert and have time left ;-)

These examples only scratch on the surface of what you can do with TeNPy. - There are plenty of more examples in the documentation. Take a look at them! - Try to learn how to define your own model from the TeNPy documentation. Define a model for the XX Chain. - Look at the documentation how to run TEBD and TDVP and reproduce the time-evolution plot for S(t) from the toy code notebook. - Learn how to save and load data in TeNPy.

[ ]: