lattpy.lattice

This module contains the main Lattice object.

class lattpy.lattice.Lattice(basis, **kwargs)[source]

Bases: LatticeStructure

Main lattice object representing a Bravais lattice model.

Combines the LatticeBasis and the LatticeStructure class and adds the ability to construct finite lattice models.

Inheritance

Inheritance diagram of Lattice

Parameters
basis: array_like or float or LatticeBasis

The primitive basis vectors that define the unit cell of the lattice. If a LatticeBasis instance is passed it is copied and used as the new basis of the lattice.

**kwargs

Key-word arguments. Used for quickly configuring a Lattice instance. Allowed keywords are:

Properties: atoms: Dictionary containing the atoms to add to the lattice. cons: Dictionary containing the connections to add to the lattice. shape: int or tuple defining the shape of the finite size lattice to build. periodic: int or list defining the periodic axes to set up.

Examples

Two dimensional lattice with one atom in the unit cell and nearest neighbors

>>> import lattpy as lp
>>> latt = lp.Lattice(np.eye(2))
>>> latt.add_atom()
>>> latt.add_connections(1)
>>> _ = latt.build((5, 3))
>>> latt
Lattice(dim: 2, num_base: 1, num_neighbors: [4], shape: [5. 3.])

Quick-setup of the same lattice:

>>> import lattpy as lp
>>> import matplotlib.pyplot as plt
>>> latt = lp.Lattice.square(atoms={(0.0, 0.0): "A"}, cons={("A", "A"): 1})
>>> _ = latt.build((5, 3))
>>> _ = latt.plot()
>>> plt.show()

(png, pdf)

../_images/lattpy-lattice-1.png
property num_sites

int: Number of sites in lattice data (if lattice has been built).

property num_cells

int: Number of unit-cells in lattice data (if lattice has been built).

property indices

np.ndarray: The lattice indices of the cached lattice data.

property positions

np.ndarray: The lattice positions of the cached lattice data.

volume()[source]

The total volume (number of cells x cell-volume) of the built lattice.

Returns
volfloat

The volume of the finite lattice structure.

alpha(idx)[source]

Returns the atom component of the lattice index for a site in the lattice.

Parameters
idxint

The super-index of a site in the cached lattice data.

Returns
alphaint

The index of the atom in the unit cell.

atom(idx)[source]

Returns the atom of a given site in the cached lattice data.

Parameters
idxint

The super-index of a site in the cached lattice data.

Returns
atomAtom
position(idx)[source]

Returns the position of a given site in the cached lattice data.

Parameters
idxint

The super-index of a site in the cached lattice data.

Returns
pos(D, ) np.ndarray

The position of the lattice site.

limits()[source]

Returns the spatial limits of the lattice model.

Returns
limits(2, D) np.ndarray

An array of the limits of the lattice positions. The first axis contains the minimum position and the second the maximum position for all dimensions.

relative_position(fractions)[source]

Computes a relitve position in the lattice model.

Parameters
fractionsfloat or (D, ) array_like

The position relatice to the size of the lattice. The center of the lattice is returned for the fractions [0.5, …, 0.5].

Returns
relpos(D, ) np.ndarray

The relative position in the lattice model.

center()[source]

Returns the spatial center of the lattice.

Returns
center(D, ) np.ndarray

The position of the spatial center of the lattice.

center_of_gravity()[source]

Computes the center of gravity of the lattice model.

Returns
center(D, ) np.ndarray

The center of gravity of the lattice model.

Notes

Requires that the mass attribute is set for each atom. If no mass is set the default mass of 1.0 is used.

superindex_from_pos(pos, atol=0.0001)[source]

Returns the super-index of a given position.

Parameters
pos(D, ) array_like

The position of the site in cartesian coordinates.

atolfloat, optional

The absolute tolerance for comparing positions.

Returns
indexint or None

The super-index of the site in the cached lattice data.

superindex_from_index(ind)[source]

Returns the super-index of a site defined by the lattice index.

Parameters
ind(D + 1, ) array_like

The lattice index (n_1, ..., n_D, alpha) of the site.

Returns
indexint or None

The super-index of the site in the cached lattice data.

neighbors(site, distidx=None, unique=False)[source]

Returns the neighours of a given site in the cached lattice data.

Parameters
siteint

The super-index of a site in the cached lattice data.

distidxint, optional

Index of distance to the neighbors, default is 0 (nearest neighbors).

uniquebool, optional

If True, each unique pair is only returned once.

Returns
indicesnp.ndarray of int

The super-indices of the neighbors.

nearest_neighbors(idx, unique=False)[source]

Returns the nearest neighors of a given site in the cached lattice data.

Parameters
idxint

The super-index of a site in the cached lattice data.

uniquebool, optional

If True, each unique pair is only return once.

Returns
indices(N, ) np.ndarray of int

The super-indices of the nearest neighbors.

iter_neighbors(site, unique=False)[source]

Iterates over the neighbors of all distances of a given site.

Parameters
siteint

The super-index of a site in the cached lattice data.

uniquebool, optional

If True, each unique pair is only return once.

Yields
distidxint

The distance index of the neighbor indices.

neighbors(N, ) np.ndarray

The super-indices of the neighbors for the corresponding distance level.

check_neighbors(idx0, idx1)[source]

Checks if two sites are neighbors and returns the distance level if they are.

Parameters
idx0int

The first super-index of a site in the cached lattice data.

idx1int

The second super-index of a site in the cached lattice data.

Returns
distidxint or None

The distance index of the two sites if they are neighbors.

build(shape, primitive=False, pos=None, check=True, min_neighbors=None, num_jobs=-1, periodic=None, callback=None, dtype=None)[source]

Constructs the indices and neighbors of a finite size lattice.

Parameters
shape(N, ) array_like or float or AbstractShape

Shape of finite size lattice to build.

primitivebool, optional

If True the shape will be multiplied by the cell size of the model. The default is False.

pos(N, ) array_like or int, optional

Optional position of the section to build. If None the origin is used.

checkbool, optional

If True the positions of the translation vectors are checked and filtered. The default is True. This should only be disabled if filtered later.

min_neighborsint, optional

The minimum number of neighbors a site must have. This can be used to remove dangling sites at the edge of the lattice.

num_jobsint, optional

Number of jobs to schedule for parallel processing of neighbors. If -1 is given all processors are used. The default is -1.

periodicint or array_like, optional

Optional periodic axes to set. See set_periodic for mor details.

callbackcallable, optional

The indices and positions are passed as arguments.

dtypeint or str or np.dtype, optional

Optional data-type for storing the lattice indices. Using a smaller bit-size may help reduce memory usage. By default, the given limits are checked to determine the smallest possible data-type.

Raises
ValueError

Raised if the dimension of the position doesn’t match the dimension of the lattice.

NoConnectionsError

Raised if no connections have been set up.

NotAnalyzedError

Raised if the lattice distances and base-neighbors haven’t been computed.

periodic_translation_vectors(axes, primitive=False)[source]

Constrcuts all translation vectors for periodic boundary conditions.

Parameters
axesint or (N, ) array_like

One or multiple axises to compute the translation vectors for.

primitivebool, optional

Flag if the specified axes are in cartesian or lattice coordinates. If True the passed position will be multiplied with the lattice vectors. The default is False (cartesian coordinates).

Returns
nvecslist of tuple

The translation vectors for the periodic boundary conditions. The first item of each element is the axis, the second the corresponding translation vector.

kdtree(positions=None, eps=0.0, boxsize=None)[source]
set_periodic(axis=None, primitive=None)[source]

Sets periodic boundary conditions along the given axis.

Parameters
axisbool or int or (N, ) array_like

One or multiple axises to apply the periodic boundary conditions. If the axis is None the perodic boundary conditions will be removed.

primitivebool, optional

Flag if the specified axes are in cartesian or lattice coordinates. If True the passed position will be multiplied with the lattice vectors. The default is False (cartesian coordinates). .. deprecated:: 0.8.0

The primitive argument will be removed in lattpy 0.9.0

Raises
NotBuiltError

Raised if the lattice hasn’t been built yet.

Notes

The lattice has to be built before applying the periodic boundarie conditions. The lattice also has to be at least three atoms big in the specified directions. Uses the same coordinate system (cartesian or primtive basis vectors) as chosen for building the lattice.

compute_connections(latt)[source]

Computes the connections between the current and another lattice.

Parameters
lattLattice

The other lattice.

Returns
neighbors(N, 2) np.ndarray

The connecting pairs between the two lattices. The first index of each row is the index in the current lattice data, the second one is the index for the other lattice latt.

distances(N) np.ndarray

The corresponding distances for the connections.

minimum_distances(site, primitive=None)[source]

Computes the minimum distances between one site and the other lattice sites.

This method can be used to find the distances in a lattice with periodic boundary conditions.

Parameters
siteint

The super-index i of a site in the cached lattice data.

primitivebool, optional

Flag if the periopdic boundarey conditions are set up along cartesian or primitive basis vectors. The default is False (cartesian coordinates). .. deprecated:: 0.8.0

The primitive argument will be removed in lattpy 0.9.0

Returns
min_dists(N, ) np.ndarray

The minimum distances between the lattice site i and the other sites.

Notes

Uses the same coordinate system (cartesian or primtive basis vectors) as chosen for building the lattice.

append(latt, ax=0, side=1, sort_ax=None, sort_reverse=False, primitive=None)[source]

Append another Lattice-instance along an axis.

Parameters
lattLattice

The other lattice to append to this instance.

axint, optional

The axis along the other lattice is appended. The default is 0 (x-axis).

sideint, optional

The side at which the new lattice is appended. If, for example, axis 0 is used, the other lattice is appended on the right side if side=+1 and on the left side if side=-1.

sort_axint, optional

The axis to sort the lattice indices after the other lattice has been added. The default is the value specified for ax.

sort_reversebool, optional

If True, the lattice indices are sorted in reverse order.

primitivebool, optional

Flag if the periopdic boundarey conditions are set up along cartesian or primitive basis vectors. The default is False (cartesian coordinates). .. deprecated:: 0.8.0

The primitive argument will be removed in lattpy 0.9.0

Notes

Uses the same coordinate system (cartesian or primtive basis vectors) as chosen for building the lattice.

Examples

>>> latt = Lattice(np.eye(2))
>>> latt.add_atom(neighbors=1)
>>> latt.build((5, 2))
>>> latt.shape
[5. 2.]
>>> latt2 = Lattice(np.eye(2))
>>> latt2.add_atom(neighbors=1)
>>> latt2.build((2, 2))
>>> latt2.shape
[2. 2.]
>>> latt.append(latt2, ax=0)
>>> latt.shape
[8. 2.]
extend(size, ax=0, side=1, num_jobs=1, sort_ax=None, sort_reverse=False)[source]

Extend the lattice along an axis.

Parameters
sizefloat

The size of which the lattice will be extended in direction of ax.

axint, optional

The axis along the lattice is extended. The default is 0 (x-axis).

sideint, optional

The side at which the new lattice is appended. If, for example, axis 0 is used, the lattice is extended to the right side if side=+1 and to the left side if side=-1.

num_jobsint, optional

Number of jobs to schedule for parallel processing of neighbors for new sites. If -1 is given all processors are used. The default is -1.

sort_axint, optional

The axis to sort the lattice indices after the lattice has been extended. The default is the value specified for ax.

sort_reversebool, optional

If True, the lattice indices are sorted in reverse order.

Examples

>>> latt = Lattice(np.eye(2))
>>> latt.add_atom(neighbors=1)
>>> latt.build((5, 2))
>>> latt.shape
[5. 2.]
>>> latt.extend(2, ax=0)
[8. 2.]
>>> latt.extend(2, ax=1)
[8. 5.]
repeat(num=1, ax=0, side=1, sort_ax=None, sort_reverse=False)[source]

Repeat the lattice along an axis.

Parameters
numint

The number of times the lattice will be repeated in direction ax.

axint, optional

The axis along the lattice is extended. The default is 0 (x-axis).

sideint, optional

The side at which the new lattice is appended. If, for example, axis 0 is used, the lattice is extended to the right side if side=+1 and to the left side if side=-1.

sort_axint, optional

The axis to sort the lattice indices after the lattice has been extended. The default is the value specified for ax.

sort_reversebool, optional

If True, the lattice indices are sorted in reverse order.

Examples

>>> latt = Lattice(np.eye(2))
>>> latt.add_atom(neighbors=1)
>>> latt.build((5, 2))
>>> latt.shape
[5. 2.]
>>> latt.repeat()
[11.  2.]
>>> latt.repeat(3)
[35.  2.]
>>> latt.repeat(ax=1)
[35.  5.]
dmap()[source]

DataMap : Returns the data-map of the lattice model.

neighbor_pairs(unique=False)[source]

Returns all neighbor pairs with their corresponding distances in the lattice.

Parameters
uniquebool, optional

If True, only unique pairs with i < j are returned. The default is False.

Returns
pairs(N, 2) np.ndarray

An array containing all neighbor pairs of the lattice. If unique=True, the first index is always smaller than the second index in each element.

distindices(N, ) np.ndarray

The corresponding distance indices of the neighbor pairs.

Examples

>>> latt = Lattice.chain()
>>> latt.add_atom(neighbors=1)
>>> latt.build(5)
>>> idx, distidx = latt.neighbor_pairs()
>>> idx
array([[0, 1],
       [1, 2],
       [1, 0],
       [2, 3],
       [2, 1],
       [3, 2]], dtype=uint8)
>>> distidx
array([0, 0, 0, 0, 0, 0], dtype=uint8)
>>> idx, distidx = latt.neighbor_pairs(unique=True)
>>> idx
array([[0, 1],
       [1, 2],
       [2, 3]], dtype=uint8)
adjacency_matrix()[source]

Computes the adjacency matrix for the neighbor data of the lattice.

Returns
adj_mat(N, N) csr_matrix

The adjacency matrix of the lattice.

See also

neighbor_pairs

Generates a list of neighbor indices.

Examples

>>> latt = Lattice.chain()
>>> latt.add_atom(neighbors=1)
>>> latt.build(5)
>>> adj_mat = latt.adjacency_matrix()
>>> adj_mat.toarray()
array([[0, 1, 0, 0],
       [1, 0, 1, 0],
       [0, 1, 0, 1],
       [0, 0, 1, 0]], dtype=int8)
copy()[source]

Lattice : Creates a (deep) copy of the lattice instance.

todict()[source]

Creates a dictionary containing the information of the lattice instance.

Returns
ddict

The information defining the current instance.

dumps()[source]

Creates a string containing the information of the lattice instance.

Returns
sstr

The information defining the current instance.

dump(file)[source]

Save the data of the Lattice instance.

Parameters
filestr or int or bytes

File name to store the lattice. If None the hash of the lattice is used.

classmethod load(file)[source]

Load data of a saved Lattice instance.

Parameters
filestr or int or bytes

File name to load the lattice.

Returns
lattLattice

The lattice restored from the file content.

plot(lw=None, margins=0.1, legend=None, grid=False, pscale=0.5, show_periodic=True, show_indices=False, index_offset=0.1, con_colors=None, adjustable='box', ax=None, show=False)[source]

Plot the cached lattice.

Parameters
lwfloat, optional

Line width of the neighbor connections.

marginsSequence[float] or float, optional

The margins of the plot.

legendbool, optional

Flag if legend is shown

gridbool, optional

If True, draw a grid in the plot.

pscalefloat, optional

The scale for drawing periodic connections. The default is half of the normal length.

show_periodicbool, optional

If True the periodic connections will be shown.

show_indicesbool, optional

If True the index of the sites will be shown.

index_offsetfloat, optional

The positional offset of the index text labels. Only used if show_indices=True.

con_colorsSequence[tuple], optional

list of colors to override the defautl connection color. Each element has to be a tuple with the first two elements being the atom indices of the pair and the third element the color, for example [(0, 0, 'r')].

adjustableNone or {‘box’, ‘datalim’}, optional

If not None, this defines which parameter will be adjusted to meet the equal aspect ratio. If ‘box’, change the physical dimensions of the Axes. If ‘datalim’, change the x or y data limits. Only applied to 2D plots.

axplt.Axes or plt.Axes3D or None, optional

Parent plot. If None, a new plot is initialized.

showbool, optional

If True, show the resulting plot.