IrregularLattice¶
full name: tenpy.models.lattice.IrregularLattice
parent module:
tenpy.models.lattice
type: class
Inheritance Diagram
Methods


Shallow copy of self. 


Count e.g. 
Calculate correct shape of the strengths for a coupling. 


Get the distance for a given coupling between two sites in the lattice. 

Repeat the unit cell for infinite MPS boundary conditions; in place. 

Extract a finite segment from an infinite/large system. 
Automatically find coupling pairs grouped by distances. 


Load instance from a HDF5 file. 

Translate lattice indices 
Translate MPS index i to lattice indices 


Reshape/reorder A to replace an MPS index by lattice indices. 
Reshape/reorder an array A to replace an MPS index by lattice indices. 

return an index array of MPS indices for which the site within the unit cell is u. 

Similar as 

Return a list of sites for all MPS indices. 

Calculate correct shape of the strengths for a multi_coupling. 

Deprecated. 

Deprecated. 


Provide possible orderings of the lattice sites. 

Plot arrows indicating the basis vectors of the lattice. 

Mark two sites indified by periodic boundary conditions. 

Plot lines connecting nearest neighbors of the lattice. 

Plot a line connecting sites in the specified “order” and text labels enumerating them. 

Plot the sites of the lattice with markers. 

return ‘space’ position of one or multiple sites. 

Find possible MPS indices for twosite couplings. 
Generalization of 


Export self into a HDF5 file. 
return 

Sanity check. 
Class Attributes and Properties

the (expected) number of sites in the unit cell, 
Humanreadable list of boundary conditions from 

The dimension of the lattice. 







Defines an ordering of the lattice sites, thus mapping the lattice to a 1D chain. 
 class tenpy.models.lattice.IrregularLattice(regular_lattice, remove=None, add=None, add_unit_cell=[], add_positions=None)[source]¶
Bases:
tenpy.models.lattice.Lattice
A variant of a regular lattice, where we might have extra sites or sites missing.
Note
The lattice defines only the geometry of the sites, not the couplings; you can have positiondependent couplings/onsite terms despite having a regular lattice.
By adjusting the
order
and a few private attributes and methods, we can make functions likepossible_couplings()
work with a more “irregular” lattice structure, where some of the sites are missing and other sites added instead. Parameters
regular_lattice (
Lattice
) – The lattice this is based on.remove (2D array  None) – Each row is a lattice index
(x_0, ..., x_{dim1}, u)
of a site to be removed. IfNone
, don’t remove something.add (Tuple[2D array, list]  None) – Each row of the 2D array is a lattice index
(x_0, ..., x_{dim1}, u)
specifiying where a site is to be added; u is the index of the site within the finalunit_cell
of the irregular lattice. For each row of the 2D array, there is one entry in the list specifying where the site is inserted in the MPS; the values are compared to the MPS indices of the regular lattice and sorted into it, so “2.5” goes between what was site 2 and 3 in the regular lattice. An entry None indicates that the site should be inserted after the lattice site(x_0, ..., x_{dim1}, 1)
of the regular_lattice.add_unit_cell (list of
Site
) – Extra sites to be added to the unit cell.add_positions (iterable of 1D arrays) – For each extra site in add_unit_cell the position within the unit cell. Defaults to
np.zeros((len(add_unit_cell), dim))
.
 remove, add
See above. Used in
ordering()
only. Type
2D array  None
Examples
Let’s imagine that we have two different sites; for concreteness we can thing of a fermion site, which we represent with
'F'
, and a spin site'S'
. If you want to preserve charges, take a look atset_common_charges()
for the proper way to initialize the sites.You could now imagine that to have fermion chain with spins on the “bonds”. In the periodic/infinite case, you would simply define
>>> lat = Lattice([2], unit_cell=['F', 'S'], bc='periodic', bc_MPS='infinite') >>> lat.mps_sites() ['F', 'S', 'F', 'S']
For a finite system, you don’t want to terminate with a spin on the right, so you need to remove the very last site by specifying the lattice index
[L1, 1]
of that site:>>> L = 4 >>> reg_lat = Lattice([L], unit_cell=['F', 'S'], bc='open', bc_MPS='finite') >>> irr_lat = IrregularLattice(reg_lat, remove=[[L  1, 1]]) >>> irr_lat.mps_sites() ['F', 'S', 'F', 'S', 'F', 'S', 'F']
Another simple example would be to add a spin in the center of a fermion chain. In that case, we add another site to the unit cell and specify the lattice index as
[(L1)//2, 1]
(where the 1 is the index of'S'
in the unit cell['F', 'S']
of the irregular lattice). The None for the MPS index is equivalent to(L1)/2
in this case.>>> reg_lat = Lattice([L], unit_cell=['F']) >>> irr_lat = IrregularLattice(reg_lat, add=([[(L  1)//2, 1]], [None]), ... add_unit_cell=['S']) >>> irr_lat.mps_sites() ['F', 'F', 'S', 'F', 'F']
 save_hdf5(hdf5_saver, h5gr, subpath)[source]¶
Export self into a HDF5 file.
This method saves all the data it needs to reconstruct self with
from_hdf5()
.Specifically, it saves
unit_cell
,Ls
,unit_cell_positions
,basis
,boundary_conditions
,pairs
under their name,bc_MPS
as"boundary_conditions_MPS"
, andorder
as"order_for_MPS"
. Moreover, it savesdim
andN_sites
as HDF5 attributes.
 classmethod from_hdf5(hdf5_loader, h5gr, subpath)[source]¶
Load instance from a HDF5 file.
This method reconstructs a class instance from the data saved with
save_hdf5()
. Parameters
hdf5_loader (
Hdf5Loader
) – Instance of the loading engine.h5gr (
Group
) – HDF5 group which is represent the object to be constructed.subpath (str) – The name of h5gr with a
'/'
in the end.
 Returns
obj – Newly generated class instance containing the required data.
 Return type
cls
 ordering(order)[source]¶
Provide possible orderings of the lattice sites.
 Parameters
order – Argument for the
Lattice.ordering()
of theregular_lattice
, or 2D ndarray providing the order of the regular lattice. Returns
order – The order to be used for
order
, i.e. order with added/removed sites as specified byremove
andadd
. Return type
array, shape (N, D+1)
 property order¶
Defines an ordering of the lattice sites, thus mapping the lattice to a 1D chain.
Each row of the array contains the lattice indices for one site, the order of the rows thus specifies a path through the lattice, along which an MPS will wind through through the lattice.
You can visualize the order with
plot_order()
.
 mps_idx_fix_u(u=None)[source]¶
return an index array of MPS indices for which the site within the unit cell is u.
If you have multiple sites in your unitcell, an onsite operator is in general not defined for all sites. This functions returns an index array of the mps indices which belong to sites given by
self.unit_cell[u]
.
 property boundary_conditions¶
Humanreadable list of boundary conditions from
bc
andbc_shift
. Returns
boundary_conditions – List of
"open"
or"periodic"
, one entry for each direction of the lattice. Return type
list of str
 count_neighbors(u=0, key='nearest_neighbors')[source]¶
Count e.g. the number of nearest neighbors for a site in the bulk.
 Parameters
 Returns
number – Number of nearest neighbors (or whatever key specified) for the uth site in the unit cell, somewhere in the bulk of the lattice. Note that it might not be the correct value at the edges of a lattice with open boundary conditions.
 Return type
 coupling_shape(dx)[source]¶
Calculate correct shape of the strengths for a coupling.
 Parameters
dx (tuple of int) – Translation vector in the lattice for a coupling of two operators. Corresponds to dx argument of
tenpy.models.model.CouplingModel.add_multi_coupling()
. Returns
coupling_shape (tuple of int) – Len
dim
. The correct shape for an array specifying the coupling strength. lat_indices has only rows within this shape.shift_lat_indices (array) – Translation vector from origin to the lower left corner of box spanned by dx.
 property dim¶
The dimension of the lattice.
 distance(u1, u2, dx)[source]¶
Get the distance for a given coupling between two sites in the lattice.
The u1, u2, dx parameters are defined in analogy with
add_coupling()
, i.e., this function calculates the distance between a pair of operators added with add_coupling (using thebasis
andunit_cell_positions
of the lattice).Warning
This function ignores “wrapping” arround the cylinder in the case of periodic boundary conditions.
 Parameters
u1 (int) – Indices within the unit cell; the u1 and u2 of
add_coupling()
u2 (int) – Indices within the unit cell; the u1 and u2 of
add_coupling()
dx (array) – Length
dim
. The translation in terms of basis vectors for the coupling.
 Returns
distance – The distance between site at lattice indices
[x, y, u1]
and[x + dx[0], y + dx[1], u2]
, ignoring any boundary effects. Return type
 enlarge_mps_unit_cell(factor=2)[source]¶
Repeat the unit cell for infinite MPS boundary conditions; in place.
 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 xdirection in our convetion, the lattice shape goes from(Lx, Ly, ..., Lu)
to(Lx*factor, Ly, ..., Lu)
.
 extract_segment(first=0, last=None, enlarge=None)[source]¶
Extract a finite segment from an infinite/large system.
 Parameters
first (int) – The first and last site to include into the segment. last defaults to
L
 1, i.e., the MPS unit cell for infinite MPS.last (int) – The first and last site to include into the segment. last defaults to
L
 1, i.e., the MPS unit cell for infinite MPS.enlarge (int) – Instead of specifying the first and last site, you can specify this factor by how much the MPS unit cell should be enlarged.
 Returns
copy – A copy of self with “segment”
bc_MPS
andsegment_first_last
set. Return type
 find_coupling_pairs(max_dx=3, cutoff=None, eps=1e10)[source]¶
Automatically find coupling pairs grouped by distances.
Given the
unit_cell_positions
andbasis
, the couplingpairs
of nearest_neighbors, next_nearest_neighbors etc at a given distance are basically fixed (although not uniquely, since we take out half of them to avoid doublecounting couplings in both directionsA_i B_j + B_i A_i
). This function iterates through all possible couplings up to a given cutoff distance and then determines the possiblepairs
at fixed distances (up to roundoff errors). Parameters
max_dx (int) – Maximal index for each index of dx to iterate over. You need large enough values to include every possible coupling up to the desired distance, but choosing it too large might make this function run for a long time.
cutoff (float) – Maximal distance (in the units in which
basis
andunit_cell_positions
is given).eps (float) – Tolerance up to which to distances are considered the same.
 Returns
coupling_pairs – Keys are distances of nearestneighbors, nextnearestneighbors etc. Values are
[(u1, u2, dx), ...]
as inpairs
. Return type
 lat2mps_idx(lat_idx)[source]¶
Translate lattice indices
(x_0, ..., x_{D1}, u)
to MPS index i. Parameters
lat_idx (array_like [..., dim+1]) – The last dimension corresponds to lattice indices
(x_0, ..., x_{D1}, u)
. All lattice indices should be positive and smaller than the corresponding entry inself.shape
. Exception: for “infinite” or “segment” bc_MPS, an x_0 outside indicates shifts accross the boundary. Returns
i – MPS index/indices corresponding to lat_idx. Has the same shape as lat_idx without the last dimension.
 Return type
array_like
 mps2lat_idx(i)[source]¶
Translate MPS index i to lattice indices
(x_0, ..., x_{dim1}, u)
. Parameters
i (int  array_like of int) – MPS index/indices.
 Returns
lat_idx – First dimensions like i, last dimension has len dim`+1 and contains the lattice indices ``(x_0, …, x_{dim1}, u)` corresponding to i. For i accross the MPS unit cell and “infinite” or “segment” bc_MPS, we shift x_0 accordingly.
 Return type
array
 mps2lat_values(A, axes=0, u=None)[source]¶
Reshape/reorder A to replace an MPS index by lattice indices.
 Parameters
A (ndarray) – Some values. Must have
A.shape[axes] = self.N_sites
if u isNone
, orA.shape[axes] = self.N_cells
if u is an int.axes ((iterable of) int) – chooses the axis which should be replaced.
u (
None
 int) – Optionally choose a subset of MPS indices present in the axes of A, namely the indices corresponding toself.unit_cell[u]
, as returned bymps_idx_fix_u()
. The resulting array will not have the additional dimension(s) of u.
 Returns
res_A – Reshaped and reordered verions of A. Such that MPS indices along the specified axes are replaced by lattice indices, i.e., if MPS index j maps to lattice site (x0, x1, x2), then
res_A[..., x0, x1, x2, ...] = A[..., j, ...]
. Return type
ndarray
Examples
Say you measure expection values of an onsite term for an MPS, which gives you an 1D array A, where A[i] is the expectation value of the site given by
self.mps2lat_idx(i)
. Then this function gives you the expectation values ordered by the lattice:>>> print(lat.shape, A.shape) (10, 3, 2) (60,) >>> A_res = lat.mps2lat_values(A) >>> A_res.shape (10, 3, 2) >>> A_res[tuple(lat.mps2lat_idx(5))] == A[5] True
If you have a correlation function
C[i, j]
, it gets just slightly more complicated:>>> print(lat.shape, C.shape) (10, 3, 2) (60, 60) >>> lat.mps2lat_values(C, axes=[0, 1]).shape (10, 3, 2, 10, 3, 2)
If the unit cell consists of different physical sites, an onsite operator might be defined only on one of the sites in the unit cell. Then you can use
mps_idx_fix_u()
to get the indices of sites it is defined on, measure the operator on these sites, and use the argument u of this function.>>> u = 0 >>> idx_subset = lat.mps_idx_fix_u(u) >>> A_u = A[idx_subset] >>> A_u_res = lat.mps2lat_values(A_u, u=u) >>> A_u_res.shape (10, 3) >>> np.all(A_res[:, :, u] == A_u_res[:, :]) True
 mps2lat_values_masked(A, axes= 1, mps_inds=None, include_u=None)[source]¶
Reshape/reorder an array A to replace an MPS index by lattice indices.
This is a generalization of
mps2lat_values()
allowing for the case of an arbitrary set of MPS indices present in each axis of A. Parameters
A (ndarray) – Some values.
axes ((iterable of) int) – Chooses the axis of A which should be replaced. If multiple axes are given, you also need to give multiple index arrays as mps_inds.
mps_inds ((list of) 1D ndarray) – Specifies for each axis in axes, for which MPS indices we have values in the corresponding axis of A. Defaults to
[np.arange(A.shape[ax]) for ax in axes]
. For indices accross the MPS unit cell and “infinite” bc_MPS, we shift x_0 accordingly.include_u ((list of) bool) – Specifies for each axis in axes, whether the u index of the lattice should be included into the output array res_A. Defaults to
len(self.unit_cell) > 1
.
 Returns
res_A – Reshaped and reordered copy of A. Such that MPS indices along the specified axes are replaced by lattice indices, i.e., if MPS index j maps to lattice site (x0, x1, x2), then
res_A[..., x0, x1, x2, ...] = A[..., mps_inds[j], ...]
. Return type
np.ma.MaskedArray
 mps_lat_idx_fix_u(u=None)[source]¶
Similar as
mps_idx_fix_u()
, but return also the corresponding lattice indices.
 mps_sites()[source]¶
Return a list of sites for all MPS indices.
Equivalent to
[self.site(i) for i in range(self.N_sites)]
.This should be used for sites of 1D tensor networks (MPS, MPO,…).
 multi_coupling_shape(dx)[source]¶
Calculate correct shape of the strengths for a multi_coupling.
 Parameters
dx (2D array, shape (N_ops,
dim
)) –dx[i, :]
is the translation vector in the lattice for the ith operator. Corresponds to the dx of each operator given in the argument ops oftenpy.models.model.CouplingModel.add_multi_coupling()
. Returns
coupling_shape (tuple of int) – Len
dim
. The correct shape for an array specifying the coupling strength. lat_indices has only rows within this shape.shift_lat_indices (array) – Translation vector from origin to the lower left corner of box spanned by dx. (Unlike for
coupling_shape()
it can also contain entries > 0)
 number_nearest_neighbors(u=0)[source]¶
Deprecated.
Deprecated since version 0.5.0: Use
count_neighbors()
instead.
 number_next_nearest_neighbors(u=0)[source]¶
Deprecated.
Deprecated since version 0.5.0: Use
count_neighbors()
instead.
 plot_basis(ax, origin=(0.0, 0.0), shade=None, **kwargs)[source]¶
Plot arrows indicating the basis vectors of the lattice.
 Parameters
ax (
matplotlib.axes.Axes
) – The axes on which we should plot.**kwargs – Keyword arguments for
ax.arrow
.
 plot_bc_identified(ax, direction= 1, origin=None, cylinder_axis=False, **kwargs)[source]¶
Mark two sites indified by periodic boundary conditions.
Works only for lattice with a 2dimensional basis.
 Parameters
ax (
matplotlib.axes.Axes
) – The axes on which we should plot.direction (int) – The direction of the lattice along which we should mark the idenitified sites. If
None
, mark it along all directions with periodic boundary conditions.cylinder_axis (bool) – Whether to plot the cylinder axis as well.
origin (None  np.ndarray) – The origin starting from where we mark the identified sites. Defaults to the first entry of
unit_cell_positions
.**kwargs – Keyword arguments for the used
ax.plot
.
 plot_coupling(ax, coupling=None, wrap=False, **kwargs)[source]¶
Plot lines connecting nearest neighbors of the lattice.
 Parameters
ax (
matplotlib.axes.Axes
) – The axes on which we should plot.coupling (list of (u1, u2, dx)) – By default (
None
), useself.pairs['nearest_neighbors']
. Specifies the connections to be plotted; iteating over lattice indices (i0, i1, …), we plot a connection from the site(i0, i1, ..., u1)
to the site(i0+dx[0], i1+dx[1], ..., u2)
, taking into account the boundary conditions.wrap (bool) – If
True
, plot couplings going around the boundary by directly connecting the sites it connects. This might be hard to see, as this puts lines from one end of the lattice to the other. IfFalse
, plot the couplings as dangling lines.**kwargs – Further keyword arguments given to
ax.plot()
.
 plot_order(ax, order=None, textkwargs={'color': 'r'}, **kwargs)[source]¶
Plot a line connecting sites in the specified “order” and text labels enumerating them.
 Parameters
ax (
matplotlib.axes.Axes
) – The axes on which we should plot.order (None  2D array (self.N_sites, self.dim+1)) – The order as returned by
ordering()
; by default (None
) useorder
.textkwargs (
None
 dict) – If notNone
, we add text labels enumerating the sites in the plot. The dictionary can contain keyword arguments forax.text()
.**kwargs – Further keyword arguments given to
ax.plot()
.
 plot_sites(ax, markers=['o', '^', 's', 'p', 'h', 'D'], **kwargs)[source]¶
Plot the sites of the lattice with markers.
 Parameters
ax (
matplotlib.axes.Axes
) – The axes on which we should plot.markers (list) – List of values for the keywork marker of
ax.plot()
to distinguish the different sites in the unit cell, a site u in the unit cell is plotted with a markermarkers[u % len(markers)]
.**kwargs – Further keyword arguments given to
ax.plot()
.
 position(lat_idx)[source]¶
return ‘space’ position of one or multiple sites.
 Parameters
lat_idx (ndarray,
(... , dim+1)
) – Lattice indices. Returns
pos – The position of the lattice sites specified by lat_idx in realspace.
 Return type
ndarray,
(..., dim)
 possible_couplings(u1, u2, dx, strength=None)[source]¶
Find possible MPS indices for twosite couplings.
For periodic boundary conditions (
bc[a] == False
) the indexx_a
is taken moduloLs[a]
and runs throughrange(Ls[a])
. For open boundary conditions,x_a
is limited to0 <= x_a < Ls[a]
and0 <= x_a+dx[a] < lat.Ls[a]
. Parameters
u1 (int) – Indices within the unit cell; the u1 and u2 of
add_coupling()
u2 (int) – Indices within the unit cell; the u1 and u2 of
add_coupling()
dx (array) – Length
dim
. The translation in terms of basis vectors for the coupling.strength (array_like  None) – If given, instead of returning lat_indices and coupling_shape directly return the correct strength_12.
 Returns
mps1, mps2 (1D array) – For each possible twosite coupling the MPS indices for the u1 and u2.
strength_vals (1D array) – (Only returend if strength is not None.) Such that
for (i, j, s) in zip(mps1, mps2, strength_vals):
iterates over all possible couplings with s being the strength of that coupling. Couplings wherestrength_vals == 0.
are filtered out.lat_indices (2D int array) – (Only returend if strength is None.) Rows of lat_indices correspond to entries of mps1 and mps2 and contain the lattice indices of the “lower left corner” of the box containing the coupling.
coupling_shape (tuple of int) – (Only returend if strength is None.) Len
dim
. The correct shape for an array specifying the coupling strength. lat_indices has only rows within this shape.
 possible_multi_couplings(ops, strength=None)[source]¶
Generalization of
possible_couplings()
to couplings with more than 2 sites. Parameters
ops (list of
(opname, dx, u)
) – Same as the argument ops ofadd_multi_coupling()
. Returns
mps_ijkl (2D int array) – Each row contains MPS indices i,j,k,l,…` for each of the operators positions. The positions are defined by dx (j,k,l,… relative to i) and boundary coundary conditions of self (how much the box for given dx can be shifted around without hitting a boundary  these are the different rows).
strength_vals (1D array) – (Only returend if strength is not None.) Such that
for (ijkl, s) in zip(mps_ijkl, strength_vals):
iterates over all possible couplings with s being the strength of that coupling. Couplings wherestrength_vals == 0.
are filtered out.lat_indices (2D int array) – (Only returend if strength is None.) Rows of lat_indices correspond to rows of mps_ijkl and contain the lattice indices of the “lower left corner” of the box containing the coupling.
coupling_shape (tuple of int) – (Only returend if strength is None.) Len
dim
. The correct shape for an array specifying the coupling strength. lat_indices has only rows within this shape.