core Package

core Package

Core objects.

abinit_units Module

This module defines constants and conversion factors matching those present in abinit that can be used when it is important to preserve consistency with the results produced by abinit.

abipy.core.abinit_units.phfactor_ev2units(units)[source]

Return conversion factor eV –> units for phonons (case-insensitive)

abipy.core.abinit_units.phunit_tag(units, unicode=False)[source]

Mainly used for phonons. Return latex string from units. If unicode is True, replace Latex superscript with unitcode.

abipy.core.abinit_units.wlabel_from_units(units, unicode=False)[source]

Return latex string for phonon frequencies in units.

abipy.core.abinit_units.phdos_label_from_units(units, unicode=False)[source]

Return latex string for phonon DOS values in units.

abipy.core.abinit_units.s2itup(comp)[source]

Convert string in the form xx, xyz into tuple of two (three) indices that can be used to slice susceptibility tensors (numpy array).

>>> assert s2itup("yy") == (1, 1)
>>> assert s2itup("xyz") == (0, 1, 2)
abipy.core.abinit_units.itup2s(t)[source]

Convert tuple of 2 (3) integers into string in the form xx (xyz). Assume C-indexing e.g. 0 –> x

>>> assert itup2s((0, 1)) == "xy"
>>> assert itup2s((0, 1, 2)) == "xyz"

fields Module

This module contains the class describing densities in real space on uniform 3D meshes.

class abipy.core.fields.Density(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]

Bases: abipy.core.fields._DensityField

Electronic density.

Note

Unlike in Abinit, datar[nspden] contains the up/down components if nsppol = 2

Inheritance Diagram

Inheritance diagram of Density
netcdf_name = 'density'
latex_label = 'Density [$e/A^3$]'
classmethod ae_core_density_on_mesh(valence_density, structure, rhoc, maxr=2.0, nelec=None, tol=0.01, method='get_sites_in_sphere', small_dist_mesh=(8, 8, 8), small_dist_factor=1.5)[source]

Initialize the all electron core density of the structure from the pseudopotentials rhoc files. For points close to the atoms, the value at the grid point would be defined as the average on a finer grid in the neghibourhood of the point.

Parameters
  • valence_density – a Density object representing the valence charge density

  • structure – the structure for which the total core density will be calculated

  • rhocrhoc files for the elements in structure. Can be a list with len=len(structure) or a dictionary {element: rhoc}. Distances should be in Angstrom and densities in e/A^3.

  • maxr – maximum radius for the distance between grid points and atoms.

  • nelec – if given a check will be perfomed to verify that the integrated density will be within 1% error with respect to nelec. The total density will also be rescaled to fit exactly the given number.

  • tol – tolerance above which the system will raise an exception if the integrated density doesn’t sum up to the value specified in nelec. Default 0.01 (1% error).

  • method

    different methods to perform the calculation:

    • get_sites_in_sphere: based on Structure.get_sites_in_sphere.

    • mesh3d_dist_gridpoints: based on Mesh3D.dist_gridpoints_in_spheres. Generally faster than

      get_sites_in_sphere, but tests can be made for specific cases.

    • get_sites_in_sphere_legacy: as get_sites_in_sphere, but part of the procedure is not vectorized

    • mesh3d_dist_gridpoints_legacy: as mesh3d_dist_gridpoints, but part of the procedure is not vectorized

  • small_dist_mesh – defines the finer mesh.

  • small_dist_factor – defines the maximum distance for which a point should be considered close enough to switch to the finer grid method. Note that this is a factor, the distance is defined with respect to the size of the cell.

get_nelect(spin=None)[source]

Returns the number of electrons with given spin.

If spin is None, the total number of electrons is computed.

total_rhor()[source]

numpy.ndarray with the total density in real space on the FFT mesh.

total_rhor_as_density()[source]

Return a Density object with the total density.

total_rhog()[source]

numpy.ndarray with the total density in G-space.

magnetization_field()[source]

numpy.ndarray with the magnetization field in real space on the FFT mesh:

  • 0 if spin-unpolarized calculation

  • spin_up - spin_down if collinear spin-polarized

  • numpy array with (mx, my, mz) components if non-collinear magnetism

magnetization()[source]

Magnetization field integrated over the unit cell. Scalar if collinear, vector with (mx, my, mz) components if non-collinear.

nelect_updown()[source]

Tuple with the number of electrons in the up/down channel. Return (None, None) if non-collinear.

zeta()[source]

numpy.ndarray with Magnetization(r) / total_density(r)

export_to_cube(filename, spin='total')[source]

Export real space density to CUBE file filename.

classmethod from_cube(filename, spin='total')[source]

Read real space density to CUBE file filename. Return new Density instance.

to_chgcar(filename=None)[source]

Convert a Density object into a Chgar object. If filename is not None, density is written to this file in Chgar format

Returns

Chgcar instance.

Note

From: http://cms.mpi.univie.ac.at/vasp/vasp/CHGCAR_file.html:

This file contains the total charge density multiplied by the volume For spinpolarized calculations, two sets of data can be found in the CHGCAR file. The first set contains the total charge density (spin up plus spin down), the second one the magnetization density (spin up minus spin down). For non collinear calculations the CHGCAR file contains the total charge density and the magnetisation density in the x, y and z direction in this order.

classmethod from_chgcar_poscar(chgcar, poscar)[source]

Build a :class`Density` object from Vasp data.

Parameters
  • chgcar – Either string with the name of a CHGCAR file or Chgcar pymatgen object.

  • poscar – Either string with the name of a POSCAR file or Poscar pymatgen object.

class abipy.core.fields.VxcPotential(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]

Bases: abipy.core.fields._PotentialField

XC Potential.

Inheritance Diagram

Inheritance diagram of VxcPotential
netcdf_name = 'exchange_correlation_potential'
latex_label = 'vxc $[eV/A^3]$'
class abipy.core.fields.VhartreePotential(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]

Bases: abipy.core.fields._PotentialField

Hartree Potential.

Inheritance Diagram

Inheritance diagram of VhartreePotential
netcdf_name = 'vhartree'
latex_label = 'vh $[eV/A^3]$'
class abipy.core.fields.VhxcPotential(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]

Bases: abipy.core.fields._PotentialField

Hartree + XC

Inheritance Diagram

Inheritance diagram of VhxcPotential
netcdf_name = 'vhxc'
latex_label = 'vhxc $[eV/A^3]$'
class abipy.core.fields.VksPotential(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]

Bases: abipy.core.fields._PotentialField

Hartree + XC + sum of local pseudo-potential terms.

Inheritance Diagram

Inheritance diagram of VksPotential
netcdf_name = 'vtrial'
latex_label = 'vks $[eV/A^3]$'

func1d Module

Function1D describes a function of a single variable and provides an easy-to-use API for performing common tasks such as algebraic operations, integrations, differentiations, plots …

class abipy.core.func1d.Function1D(mesh, values)[source]

Bases: object

Immutable object representing a (real|complex) function of real variable.

classmethod from_constant(mesh, const)[source]

Build a constant function from the mesh and the scalar const

property mesh

numpy.ndarray with the mesh points

property values

Values of the functions.

property real

Return new Function1D with the real part of self.

property imag

Return new Function1D with the imaginary part of self.

conjugate()[source]

Return new Function1D with the complex conjugate.

abs()[source]

Return Function1D with the absolute value.

classmethod from_func(func, mesh)[source]

Initialize the object from a callable.

Example

Function1D.from_func(np.sin, mesh=np.arange(1,10))

classmethod from_file(path, comments='#', delimiter=None, usecols=(0, 1))[source]

Initialize an instance by reading data from path (txt format) see also np.loadtxt()

Parameters
  • path – Path to the file containing data.

  • comments – The character used to indicate the start of a comment; default: ‘#’.

  • delimiter – str, optional The string used to separate values. By default, this is any whitespace.

  • usecols – sequence, optional. Which columns to read, with 0 being the first. For example, usecols = (1,4) will extract data from the 2nd, and 5th columns.

to_file(path, fmt='%.18e', header='')[source]

Save data in a text file. Use format fmr. A header is added at the beginning.

has_same_mesh(other)[source]

True if self and other have the same mesh.

property bma

Return b-a. f(x) is defined in [a,b]

property max

Max of f(x) if f is real, max of \(|f(x)|\) if complex.

property min

Min of f(x) if f is real, min of \(|f(x)|\) if complex.

property iscomplexobj

Check if values is array of complex numbers. The type of the input is checked, not the value. Even if the input has an imaginary part equal to zero, np.iscomplexobj evaluates to True.

h()[source]

The spacing of the mesh. None if mesh is not homogeneous.

dx()[source]

numpy.ndarray of len(self) - 1 elements giving the distance between two consecutive points of the mesh, i.e. dx[i] = ||x[i+1] - x[i]||.

find_mesh_index(value)[source]

Return the index of the first point in the mesh whose value is >= value -1 if not found

finite_diff(order=1, acc=4)[source]

Compute the derivatives by finite differences.

Parameters
  • order – Order of the derivative.

  • acc – Accuracy. 4 is fine in many cases.

Returns

Function1D instance with the derivative.

integral(start=0, stop=None)[source]

Cumulatively integrate y(x) from start to stop using the composite trapezoidal rule.

Returns

Function1D with \(\int y(x) dx\)

spline()[source]

Cubic spline with s=0

property spline_roots

Zeros of the spline.

spline_on_mesh(mesh)[source]

Spline the function on the given mesh, returns Function1D object.

spline_derivatives(x)[source]

Returns all derivatives of the spline at point x.

spline_integral(a=None, b=None)[source]

Returns the definite integral of the spline of f between two given points a and b

Parameters
  • a – First point. mesh[0] if a is None

  • b – Last point. mesh[-1] if a is None

integral_value()[source]

Compute \(\int f(x) dx\).

l1_norm()[source]

Compute \(\int |f(x)| dx\).

l2_norm()[source]

Compute \(\sqrt{\int |f(x)|^2 dx}\).

fft()[source]

Compute the FFT transform (negative sign).

ifft(x0=None)[source]

Compute the FFT transform \(\int e+i\)

plot_ax(ax, exchange_xy=False, xfactor=1, yfactor=1, *args, **kwargs)[source]

Helper function to plot self on axis ax.

Parameters
  • axmatplotlib.axes.Axes.

  • exchange_xy – True to exchange the axis in the plot.

  • args – Positional arguments passed to ax.plot

  • xfactor – xvalues and yvalues are multiplied by this factor before plotting.

  • yfactor – xvalues and yvalues are multiplied by this factor before plotting.

  • kwargs – Keyword arguments passed to matplotlib. Accepts

kwargs

Meaning

cplx_mode

string defining the data to print. Possible choices are (case-insensitive): re for the real part “im” for the imaginary part, “abs” for the absolute value. “angle” to display the phase of the complex number in radians. Options can be concatenated with “-“

Returns

List of lines added.

plotly_traces(fig, rcd=None, exchange_xy=False, xfactor=1, yfactor=1, *args, **kwargs)[source]

Helper function to plot the function with plotly.

Parameters
  • figplotly.graph_objects.Figure.

  • rcd – PlotlyRowColDesc object used when fig is not None to specify the (row, col) of the subplot in the grid.

  • exchange_xy – True to exchange the x and y in the plot.

  • xfactor – xvalues and yvalues are multiplied by this factor before plotting.

  • yfactor – xvalues and yvalues are multiplied by this factor before plotting.

  • args – Positional arguments passed to ‘plotly.graph_objects.Scatter’

  • kwargs – Keyword arguments passed to ‘plotly.graph_objects.Scatter’. Accepts also AbiPy specific kwargs:

kwargs

Meaning

cplx_mode

string defining the data to print. Possible choices are (case-insensitive): re for the real part “im” for the imaginary part, “abs” for the absolute value. “angle” to display the phase of the complex number in radians. Options can be concatenated with “-“

plot(ax=None, **kwargs)[source]

Plot the function with matplotlib.

Parameters

axmatplotlib.axes.Axes or None if a new figure should be created.

kwargs

Meaning

exchange_xy

True to exchange x- and y-axis (default: False)

Returns: matplotlib.figure.Figure.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

globals Module

Global variables used to initialize AbiPy environment in notebooks.

abipy.core.globals.in_notebook()[source]

True if we are running inside a jupyter notebook (and enable_notebook has been called).

abipy.core.globals.disable_notebook()[source]

Set in_notebook flag to False.

abipy.core.globals.enable_notebook(with_seaborn=True)[source]

Set in_notebook flag to True and activate seaborn settings for notebooks if with_seaborn.

abipy.core.globals.get_abinb_workdir()[source]

Return the absolute path of the scratch directory used to produce and save temporary files when we are runnning inside a jupyter notebook.

abipy.core.globals.abinb_mkstemp(force_abinb_workdir=False, use_relpath=False, **kwargs)[source]

Invoke mkstep with kwargs, return the (fd, name) of the temporary file. kwargs are passed to mkstemp except for dir if we are inside a jupyter notebook.

Parameters
  • use_abipy_nbworkdir

  • use_relpath – Return relative path (os.path.relpath) if True else absolute (default) Relative paths are required if we are gonna use the temporary file in notebooks or in web browers. In this case, the caller is responsbile for calling the function with the correct flag.

abipy.core.globals.get_workdir(workdir)[source]

Return temporary directory if workdir is None else workdir. Allow users to specify the temporary directory via ABIPY_TMPDIR env variable.

gsphere Module

This module contains the class defining the G-sphere for wavefunctions, densities and potentials

class abipy.core.gsphere.GSphere(ecut, lattice, kpoint, gvecs, istwfk=1)[source]

Bases: collections.abc.Sequence

Descriptor-class for the G-sphere.

property gvecs

numpy.ndarray with the G-vectors in reduced coordinates.

index(gvec)[source]

return the index of the G-vector gvec in self. Raises: ValueError if the value is not present.

count(gvec)[source]

Return number of occurrences of gvec.

copy()[source]

shallow copy.

to_string(verbose=0)[source]

String representation.

zeros(dtype=<class 'float'>, extra_dims=())[source]

Returns new zeroed 1D numpy.ndarray.

The type can be set with the dtype keyword. Extra dimensions can be added with extra_dims.

czeros(extra_dims=())[source]

New zeroed 1D complex numpy.ndarray.

empty(dtype=<class 'float'>, extra_dims=())[source]

Returns new uninitialized 1D numpy.ndarray.

The type can be set with the dtype keyword. Extra dimensions can be added with extra_dims.

cempty(extra_dims=())[source]

Returns new uninitialized 1D complex numpy.ndarray.

tofftmesh(mesh, arr_on_sphere)[source]

Insert the array arr_on_sphere given on the sphere inside the FFT mesh.

Parameters
  • mesh

  • arr_on_sphere

fromfftmesh(mesh, arr_on_mesh)[source]

Transfer arr_on_mesh given on the FFT mesh to the G-sphere.

kpoints Module

This module defines objects describing the sampling of the Brillouin Zone.

abipy.core.kpoints.issamek(k1, k2, atol=None)[source]

True if k1 and k2 are equal modulo a lattice vector. Use _ATOL_KDIFF is atol is None.

>>> assert issamek([1, 1, 1], [0, 0, 0])
>>> assert issamek([1.1, 1, 1], [0, 0, 0], atol=0.1)
>>> assert not issamek(0.00003, 1)
abipy.core.kpoints.wrap_to_ws(x)[source]

Transforms x in its corresponding reduced number in the interval ]-1/2,1/2].

abipy.core.kpoints.wrap_to_bz(x)[source]

Transforms x in its corresponding reduced number in the interval [0,1[.”

abipy.core.kpoints.as_kpoints(obj, lattice, weights=None, names=None)[source]

Convert obj into a list of k-points.

Parameters
  • objKpoint or list of Kpoint objects or array-like object.

  • lattice – Reciprocal lattice.

  • weights – k-point weights. Ignored if obj is already a Kpoint instance or a list of Kpoint items.

  • name – string with the name of the k-point. Ignored if obj is already a Kpoint instance or a list of Kpoint items.

class abipy.core.kpoints.Kpoint(frac_coords, lattice, weight=None, name=None)[source]

Bases: pymatgen.util.serialization.SlotPickleMixin

Class defining one k-point. This object is immutable and can be used as key in dictionaries

Note that we usually construct the object by passing pymatgen.reciprocal_lattice that is the standard reciprocal lattice used for solid state physics with a factor of 2 * pi i.e. a_i . b_j = 2pi delta_ij. Abinit, on the contrary, uses the crystallographic reciprocal lattice i.e. no 2pi factor. so pay attention when converting Abinit routines to AbiPy.

classmethod from_name_and_structure(name, structure)[source]

Build Kpoint object from string with name and structure.

property frac_coords

Fractional coordinates of the k-points.

property lattice

pymatgen.core.lattice.Lattice object describing the Reciprocal lattice.

property weight

Weight of the k-point. 0.0 if the weight is not defined.

set_weight(weight)[source]

Set the weight of the k-point.

cart_coords()[source]

Cartesian coordinates of the k-point.

property name

Name of the k-point. None if not available.

set_name(name)[source]

Set the name of the k-point.

on_border()[source]

True if the k-point is on the border of the BZ (lattice translations are taken into account).

tos(m='fract')[source]

Return string with fractional or cartesian coords depending on mode m in (“fract”, “cart”, “fracart”)

to_string(verbose=0)[source]

String representation.

classmethod as_kpoint(obj, lattice)[source]

Convert obj into a Kpoint instance.

Parameters
classmethod gamma(lattice, weight=None)[source]

Constructor for the Gamma point.

copy()[source]

Deep copy.

is_gamma(allow_umklapp=False, atol=None)[source]

Return True if this the gamma point.

Parameters
  • allow_umklapp – True if umklapp G-vectors are allowed.

  • atol – Absolute tolerance for k-point comparison (used only if umklapp).

norm()[source]

Norm of the kpoint.

versor()[source]

Returns the versor i.e. math:||k|| = 1

wrap_to_ws()[source]

Returns a new abipy.core.kpoints.Kpoint in the Wigner-Seitz zone.

wrap_to_bz()[source]

Returns a new abipy.core.kpoints.Kpoint in the first unit cell.

compute_star(symmops, wrap_tows=True)[source]

Return the star of the kpoint (tuple of abipy.core.kpoints.Kpoint objects).

class abipy.core.kpoints.KpointList(reciprocal_lattice, frac_coords, weights=None, names=None, ksampling=None)[source]

Bases: collections.abc.Sequence

Base class defining a sequence of abipy.core.kpoints.Kpoint objects. Essentially consists of base methods implementing the sequence protocol and helper functions. The subclasses abipy.core.kpoints.Kpath and abipy.core.kpoints.IrredZone provide specialized methods to operate on k-points representing a path or list of points in the IBZ, respectively. This object is immutable.

Inheritance Diagram

Inheritance diagram of KpointList
Error

alias of abipy.core.kpoints.KpointsError

classmethod subclass_from_name(name)[source]

Return the class with the given name.

classmethod from_dict(d)[source]

Makes Kpoints obey the general json interface used in pymatgen for easier serialization.

as_dict()[source]

Makes Kpoints obey the general json interface used in pymatgen for easier serialization.

property reciprocal_lattice

pymatgen.core.lattice.Lattice object defining the reciprocal lattice.

to_string(func=<class 'str'>, title=None, verbose=0)[source]

String representation.

index(kpoint)[source]

Returns: the first index of kpoint in self.

Raises: ValueError if not found.

get_all_kindices(kpoint)[source]

Return numpy array with indexes of all the k-point Accepts: abipy.core.kpoints.Kpoint instance or integer.

find(kpoint)[source]

Returns: first index of kpoint. -1 if not found

count(kpoint)[source]

Return number of occurrences of kpoint

find_closest(obj)[source]

Find the closest k-point in the list (not necessarily equal).

Parameters

obj – Fractional coordinates or abipy.core.kpoints.Kpoint instance.

Returns

(ind, kpoint, dist)

where ind is the index in self of the closest k-point. kpoint is the abipy.core.kpoints.Kpoint instance of index ind. dist is the distance between obj and kpoint.

property is_path

True if self represents a path in the BZ.

property is_ibz

True if self represents a list of points in the IBZ.

mpdivs_shifts()[source]

The Monkhorst-Pack (MP) divisions and shifts. Both quantities are set to None if self is not a MP mesh. Use is_mpmesh to check whether self is a MP mesh.

property is_mpmesh

True if self represents a Monkhorst-Pack mesh. i.e if the sampling has been specified in terms of divisions along the reciprocal lattice vectors (ngkpt)

property frac_coords

Fractional coordinates of the k-point as numpy.ndarray of shape (len(self), 3)

get_cart_coords()[source]

Cartesian coordinates of the k-point as numpy.ndarray of shape (len(self), 3)

property names

List with the name of the k-points.

property weights

numpy.ndarray with the weights of the k-points.

sum_weights()[source]

Returns the sum of the weights.

check_weights()[source]

Check if weights are normalized to one. Raises: ValueError if Weights are not normalized.

get_highsym_datataframe(with_cart_coords=False)[source]

Return pandas Dataframe with the names of the high-symmetry k-points and the reduced coordinates.

Parameters

with_cart_coords – True to add extra column with the Cartesian coordinates.

Return: pandas.DataFrame

remove_duplicated()[source]

Remove duplicated k-points from self. Returns new KpointList instance.

to_array()[source]

Returns a numpy.ndarray [nkpy, 3] with the fractional coordinates.

to_json()[source]

Returns a JSON string representation of the MSONable object.

plot(ax=None, **kwargs)[source]

Plot k-points with matplotlib.

plotly(fig=None, **kwargs)[source]

Plot k-points with plotly.

get_k2kqg_map(qpt, atol_kdiff=None)[source]

Compute mapping k_index –> (k + q)_index, g0

Parameters
  • qpt – q-point in fractional coordinate or Kpoint instance.

  • atol_kdiff – Tolerance used to compare k-points. Use _ATOL_KDIFF is atol is None.

class abipy.core.kpoints.KpointStar(reciprocal_lattice, frac_coords, weights=None, names=None, ksampling=None)[source]

Bases: abipy.core.kpoints.KpointList

Star of the kpoint. Note that the first k-point is assumed to be the base of the star namely the point that is used to generate the Star.

Inheritance diagram of KpointStar
property base_point

The point used to generate the star.

property name

The name of the star (inherited from the name of the base point).

class abipy.core.kpoints.Kpath(reciprocal_lattice, frac_coords, weights=None, names=None, ksampling=None)[source]

Bases: abipy.core.kpoints.KpointList

This object describes a k-path in reciprocal space. It provides methods to compute (line) derivatives along the path. The k-points do not have weights so Kpath should not be used to compute integral in the BZ.

Inheritance diagram of Kpath
classmethod from_names(structure, knames, line_density=20)[source]

Generate normalized K-path from list of k-point labels.

Parameters
  • structureabipy.core.structure.Structure object.

  • knames – List of strings with the k-point labels.

  • line_density – Number of points used to sample the smallest segment of the path

classmethod from_vertices_and_names(structure, vertices_names, line_density=20)[source]

Generate normalized k-path from a list of vertices and the corresponding labels.

Parameters
  • structureabipy.core.structure.Structure object.

  • vertices_names – List of tuple, each tuple is of the form (kfrac_coords, kname) where kfrac_coords are the reduced coordinates of the k-point and kname is a string with the name of the k-point. Each point represents a vertex of the k-path.

  • line_density – Number of points used to sample the smallest segment of the path. If 0, use list of k-points given in vertices_names

to_string(verbose=0, title=None, **kwargs)[source]

String representation.

Parameters

verbose – Verbosity level. Default: 0

ds()[source]

numpy.ndarray of len(self)-1 elements giving the distance between two consecutive k-points, i.e. ds[i] = ||k[i+1] - k[i]|| for i=0,1,…,n-1

versors()[source]

Tuple of len(self) - 1 elements with the versors connecting k[i] to k[i+1].

lines()[source]

Nested list containing the indices of the points belonging to the same line. Used for extracting the eigenvalues while looping over the lines.

Example

for line in self.lines:

vals_on_line = eigens[spin, line, band]

frac_bounds()[source]

Numpy array of shape [M, 3] with the vertexes of the path in frac coords.

cart_bounds()[source]

Numpy array of shape [M, 3] with the vertexes of the path in frac coords.

find_points_along_path(cart_coords, dist_tol=1e-12)[source]

Find points in cart_coords lying on the path with distance less than dist_tol. See find_points_along_path function for API.

finite_diff(values, order=1, acc=4)[source]

Compute the derivatives of values by finite differences.

Parameters
  • values – array-like object with shape=(nkpt) containing the values of the path.

  • order – Order of the derivative.

  • acc – Accuracy: 4 corresponds to a central difference with 5 points.

Returns

ragged numpy array. The i-th entry is a numpy array with the derivatives on the i-th line.

class abipy.core.kpoints.IrredZone(reciprocal_lattice, frac_coords, weights=None, names=None, ksampling=None)[source]

Bases: abipy.core.kpoints.KpointList

An IrredZone is a (immutable) sequence of points in the irreducible wedge of the BZ. Each point has a weight whose sum must equal 1 so that we can integrate quantities in the full Brillouin zone.

Note

Abinit supports different options for the specification of the BZ sampling:

  • kptrlatt(3,3) or ngkpt(3) for the definition grid.

  • shiftk(3, nshiftk) for the definition of multiple shifts.

  • kptopt for the treatment of symmetry operations.

All these possibilities complicate the internal implementation in particular when we need to recostruct the full BZ and take into account the presence of multiple shifts since kptrlatt may have non-zero off-diagonal components. Client code that needs to know how the mesh was generated can rely on the following checks:

if not self.ibz: raise(“Need an IBZ sampling”)

mpdivs, shifts = self.mpdivs_shifts if mpdivs is None: raise ValueError(“Cannot handle kptrlatt with non-zero off-diagonal elements”) if len(shifts) > 1: raise ValueError(“Multiple shifts are not supported”) # Code for mesh defined in terms of mpdivs and one shift.

Inheritance diagram of IrredZone
classmethod from_ngkpt(structure, ngkpt, shiftk, kptopt=1, spin_mode='unpolarized', verbose=0)[source]

Build an IrredZone object from (ngkpt, shift) by calling Abinit to get the list of irreducible k-points.

classmethod from_kppa(structure, kppa, shiftk, kptopt=1, verbose=0)[source]

Build an IrredZone object from (kppa, shift) by calling Abinit to get the list of irreducible k-points.

to_string(func=<class 'str'>, verbose=0, title=None)[source]

String representation.

abipy.core.kpoints.rc_list(mp, sh, pbc=False, order='bz')[source]

Returns a numpy.ndarray with the linear mesh used to sample one dimension of the reciprocal space. Note that the coordinates are always ordered so that rc[i+1] > rc[i]. so that we can easily plot quantities defined on the 3D multidimensional mesh.

Parameters
  • mp – Number of Monkhorst-Pack divisions along this direction.

  • sh – Shift

  • pbc – if pbc is True, periodic boundary conditions are enforced.

  • order – Possible values [“bz”, “unit_cell”]. if “bz”, the coordinates are forced to be in [-1/2, 1/2) if “unit_cell”, the coordinates are forced to be in [0, 1).

abipy.core.kpoints.kmesh_from_mpdivs(mpdivs, shifts, pbc=False, order='bz')[source]

Returns a numpy.ndarray with the reduced coordinates of the k-points from the MP divisions and the shifts.

Parameters
  • mpdivs – The three MP divisions.

  • shifts – Array-like object with the MP shift.

  • pbc – If True, periodic images of the k-points will be included i.e. closed mesh.

  • order – “unit_cell” if the kpoint coordinates must be in [0,1) “bz” if the kpoint coordinates must be in [-1/2, +1/2)

class abipy.core.kpoints.Ktables(structure, mesh, is_shift, has_timrev)[source]

Bases: object

Call spglib to compute the k-points in the IBZ with the corresponding weights as well as the mapping BZ –> IBZ.

Parameters
  • mesh

  • is_shift

mesh
is_shift
ibz
nibz
weights
bz
nbz
grid
to_string(verbose=0, title=None, **kwargs)[source]

String representation

print_bz2ibz(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Print BZ –> IBZ mapping.

abipy.core.kpoints.find_points_along_path(cart_bounds, cart_coords, dist_tol)[source]

Find points in cart_coords lying on the path defined by cart_bounds. Result are ordered according to distance along the path.

Parameters
  • cart_bounds – [N, 3] array with the boundaries of the path in Cartesian coordinates.

  • cart_coords – [M, 3] array with the points in Cartesian coordinate

  • dist_tol – A point is considered to be on the path if its distance from the line is less than dist_tol.

Return: namedtuple with the following attributes:

(ikfound, dist_list, path_ticks)

ikfound is a numpy array with the indices of the points lying on the path. Empty if no point is found. dist_list: numpy array with the distance of the points along the line. path_ticks: numpy array with the ticks associated to the input k-path.

mesh3d Module

This module contains the class defining Uniform 3D meshes.

class abipy.core.mesh3d.Mesh3D(shape, vectors)[source]

Bases: object

Descriptor-class for uniform 3D meshes.

A Mesh3D object holds information on how functions, such as wave functions and electron densities, are discretized in a certain domain in space. The main information here is how many grid points are used in each direction of the unit cell.

There are methods for tasks such as allocating arrays, performing symmetry operations and integrating functions over space.

This is how a 2x2x2 3D array arr[x,y,z] is stored in memory:

3-----7
|\    |
| \   |
|  1-----5      z
2--|--6  |   y  |
 \ |   \ |    \ |
  \|    \|     \|
   0-----4      +-----x
iter_ixyz_r()[source]

Iterator returning (ixyz, rr) where ixyz gives the index of the point and r is the point on the grid.

rpoint(ix, iy, iz)[source]

The vector corresponding to the (ix, iy, iz) indices

to_string(verbose=0)[source]

String representation.

property nx

Number of points along x.

property ny

Number of points along y.

property nz

Number of points along z.

inv_vectors()[source]
zeros(dtype=<class 'float'>, extra_dims=())[source]

Returns new zeroed 3D array for this domain.

The type can be set with the dtype keyword. Extra dimensions can be added with extra_dims.

czeros(extra_dims=())[source]

Returns new zeroed 3D complex array for this domain.

empty(dtype=<class 'float'>, extra_dims=())[source]

Returns new uninitialized 3D numpy.ndarray for this domain.

The type can be set with the dtype keyword. Extra dimensions can be added with extra_dims.

cempty(extra_dims=())[source]

Returns new uninitialized 3D complex numpy.ndarray for this domain.

random(dtype=<class 'float'>, extra_dims=())[source]

Returns random real numpy.ndarray for this domain with val in [0.0, 1.0).

crandom(extra_dims=())[source]

Returns random complex numpy.ndarray for this domain with val in [0.0, 1.0).

reshape(arr)[source]

Reshape the array arr defined on the FFT box.

Returns numpy.ndarray with 4 dimensions (?, nx, ny, nz) where ?*nx*ny*nz == arr.size

fft_r2g(fr, shift_fg=False)[source]

FFT of array fr given in real space.

fft_g2r(fg, fg_ishifted=False)[source]

FFT of array fg given in G-space.

integrate(fr)[source]

Integrate array(s) fr.

gvecs()[source]

Array with the reduced coordinates of the G-vectors.

Note

These are the G-vectors of the FFT box and should be used when we compute quantities on the FFT mesh. These vectors differ from the gvecs stored in abipy.core.gsphere.GSphere that are k-centered and enclosed by a sphere whose radius is defined by ecut.

gmods()[source]

[ng] numpy.ndarray with \(|G|\)

rpoints()[source]

numpy.ndarray with the points in real space in reduced coordinates.

i_closest_gridpoints(points)[source]

Given a list of points, this function return a numpy.ndarray with the indices of the closest gridpoint.

dist_gridpoints_in_spheres(points, radius)[source]

mixins Module

This module provides mixin classes

class abipy.core.mixins.AbinitNcFile(filepath)[source]

Bases: abipy.core.mixins.BaseFile

Abstract class representing a Netcdf file with data saved according to the ETSF-IO specifications (when available). An AbinitNcFile has a netcdf reader to read data from file and build objects.

classmethod from_binary_string(bstring)[source]

Build object from a binary string with the netcdf data. Useful for implementing GUIs in which widgets returns binary data.

ncdump(*nc_args, **nc_kwargs)[source]

Returns a string with the output of ncdump.

abinit_version()[source]

String with the abinit version: three digits separated by comma.

abstract property params

OrderedDict with the convergence parameters Used to construct pandas.DataFrame.

get_dims_dataframe(path='/')[source]

Return: pandas.DataFrame with the dimensions defined in the path group.

class abipy.core.mixins.Has_Structure[source]

Bases: object

Mixin class for abipy.core.mixins.AbinitNcFile containing crystallographic data.

abstract property structure

Returns the abipy.core.structure.Structure object.

plot_bz(**kwargs)[source]

Gives the plot (as a matplotlib object) of the symmetry line path in the Brillouin Zone.

show_bz(**kwargs)

Gives the plot (as a matplotlib object) of the symmetry line path in the Brillouin Zone.

export_structure(filepath)[source]

Export the structure on file.

returns: abipy.iotools.visualizer.Visualizer instance.

visualize_structure_with(appname)[source]

Visualize the crystalline structure with the specified visualizer.

See abipy.iotools.visualizer.Visualizer for the list of applications and formats supported.

yield_structure_figs(**kwargs)[source]

Generates a predefined list of matplotlib figures with minimal input from the user.

yield_structure_plotly_figs(**kwargs)[source]

Generates a predefined list of plotly figures with minimal input from the user.

class abipy.core.mixins.Has_ElectronBands[source]

Bases: object

Mixin class for abipy.core.mixins.AbinitNcFile containing electron data.

abstract property ebands

Returns the abipy.electrons.ebands.ElectronBands object.

property nsppol

Number of spin polarizations

property nspinor

Number of spinors

property nspden

Number of indepedendent spin-density components.

property mband

Maximum number of bands.

property nband

Maximum number of bands.

property nelect

Number of electrons per unit cell

property nkpt

Number of k-points.

property kpoints

Iterable with the Kpoints.

tsmear()[source]
get_ebands_params()[source]

OrderedDict with the convergence parameters.

plot_ebands(**kwargs)[source]

Plot the electron energy bands. See the ElectronBands.plot() for the signature.

plot_ebands_with_edos(edos, **kwargs)[source]

Plot the electron energy bands with DOS. See the ElectronBands.plot_with_edos() for the signature.

get_edos(**kwargs)[source]

Compute the electronic DOS on a linear mesh. Wraps ebands.get_edos.

yield_ebands_figs(**kwargs)[source]

Generates a predefined list of matplotlib figures with minimal input from the user.

yield_ebands_plotly_figs(**kwargs)[source]

Generates a predefined list of plotly figures with minimal input from the user.

expose_ebands(slide_mode=False, slide_timeout=None, expose_web=False, **kwargs)[source]

Shows a predefined list of matplotlib figures for electron bands with minimal input from the user.

class abipy.core.mixins.Has_PhononBands[source]

Bases: object

Mixin class for abipy.core.mixins.AbinitNcFile containing phonon data.

abstract property phbands

Returns the abipy.dfpt.phonons.PhononBands object.

get_phbands_params()[source]

OrderedDict with the convergence parameters.

plot_phbands(**kwargs)[source]

Plot the electron energy bands. See the PhononBands.plot() for the signature.””

yield_phbands_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

yield_phbands_plotly_figs(**kwargs)[source]

This function generates a predefined list of plotly figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

expose_phbands(slide_mode=False, slide_timeout=None, **kwargs)[source]

Shows a predefined list of matplotlib figures for phonon bands with minimal input from the user.

class abipy.core.mixins.NotebookWriter[source]

Bases: abipy.core.mixins.HasNotebookTools

Mixin class for objects that are able to generate jupyter notebooks. Subclasses must provide a concrete implementation of write_notebook.

abstract write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file is created. Return path to the notebook. A typical template:

# Preable.
nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None)

#####################
# Put your code here
nb.cells.extend([
    nbv.new_markdown_cell("# This is a markdown cell"),
    nbv.new_code_cell("a = 1"),
])
#####################

# Call _write_nb_nbpath
return self._write_nb_nbpath(nb, nbpath)
classmethod pickle_load(filepath)[source]

Loads the object from a pickle file.

pickle_dump(filepath=None)[source]

Save the status of the object in pickle format. If filepath is None, a temporary file is created.

Return: The name of the pickle file.

abstract yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

expose(slide_mode=False, slide_timeout=None, use_web=False, **kwargs)[source]

Shows a predefined list of matplotlib figures with minimal input from the user. Relies on the ``yield_fig``s methods implemented by the subclass to generate matplotlib figures.

Parameters

use_web – True to show all figures inside a panel template executed in the local browser. False to show figures in different GUIs

plotly_expose(**kwargs)[source]

This function generates a predefined list of plotly figures with minimal input from the user. Relies on the yield_plotly_figs method implemented by the subclass in order to generate the figures.

class abipy.core.mixins.Has_Header[source]

Bases: object

Mixin class for netcdf files containing the Abinit header.

hdr()[source]

monty.collections.AttrDict with the Abinit header e.g. hdr.ecut.

restapi Module

This module provides interfaces with the Materials Project REST API v2 to enable the creation of data structures and pymatgen objects using Materials Project data.

abipy.core.restapi.get_mprester(api_key=None, endpoint=None)[source]
Parameters
  • api_key (str) – A String API key for accessing the MaterialsProject REST interface. Please apply on the Materials Project website for one. If this is None, the code will check if there is a PMG_MAPI_KEY in your .pmgrc.yaml. If so, it will use that environment This makes easier for heavy users to simply add this environment variable to their setups and MPRester can then be called without any arguments.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface. Defaults to the standard Materials Project REST address, but can be changed to other urls implementing a similar interface.

class abipy.core.restapi.MyMPRester(api_key=None, endpoint=None, notify_db_version=True, include_user_agent=True)[source]

Bases: pymatgen.ext.matproj.MPRester

Subclass Materials project Rester. See [Jain2013][Ong2015].

Inheritance Diagram

Inheritance diagram of MyMPRester
Error

alias of pymatgen.ext.matproj.MPRestError

get_phasediagram_results(elements)[source]

Contact the materials project database, fetch entries and build :class:PhaseDiagramResults instance.

Parameters

elements – List of chemical elements.

class abipy.core.restapi.PhaseDiagramResults(entries)[source]

Bases: object

Simplified interface to phase-diagram pymatgen API.

Inspired to:

See also: [Ong2008][Ong2010]

plot(show_unstable=True, show=True)[source]

Plot phase diagram.

Parameters
  • show_unstable (float) – Whether unstable phases will be plotted as well as red crosses. If a number > 0 is entered, all phases with ehull < show_unstable will be shown.

  • show – True to show plot.

Return: plotter object.

dataframe()[source]

Pandas dataframe with the most important results.

print_dataframes(with_spglib=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, verbose=0)[source]

Print pandas dataframe to file file.

Parameters
  • with_spglib – True to compute spacegroup with spglib.

  • file – Output stream.

  • verbose – Verbosity level.

class abipy.core.restapi.DatabaseStructures(structures, ids, data=None)[source]

Bases: abipy.core.mixins.NotebookWriter

Store the results of a query to the MP database. This object is immutable, use add_entry to create a new instance.

filter_by_spgnum(spgnum)[source]

Filter structures by space group number. Return new MpStructures object.

add_entry(structure, entry_id, data_dict=None)[source]

Add new entry, return new object.

Parameters
  • structure – New structure object.

  • entry_id – ID associated to new structure.

  • data_dict – Option dictionary with metadata.

property lattice_dataframe

pandas DataFrame with lattice parameters.

property coords_dataframe

pandas DataFrame with atomic positions.

structure_dataframes()[source]

Pandas dataframes constructed from self.structures.

print_results(fmt='abivars', verbose=0, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Print pandas dataframe, structures using format fmt, and data to file file. fmt is automaticall set to cif if structure is disordered. Set fmt to None or empty string to disable structure output.

yield_figs(**kwargs)[source]

NOP required by NotebookWriter protocol.

write_notebook(nbpath=None, title=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.core.restapi.MpStructures(structures, ids, data=None)[source]

Bases: abipy.core.restapi.DatabaseStructures

Store the results of a query to the Materials Project database.

Inheritance diagram of MpStructures
dbname = 'Materials Project'
dataframe()[source]

Pandas dataframe constructed from self.data. None if data is not available.

open_browser(browser=None, limit=10)[source]
Parameters
  • browser – Open webpage in browser. Use default if $BROWSER if None.

  • limit – Max number of tabs opened in browser. None for no limit.

class abipy.core.restapi.CodStructures(structures, ids, data=None)[source]

Bases: abipy.core.restapi.DatabaseStructures

Store the results of a query to the COD database [Grazulis2011].

Inheritance diagram of CodStructures
dbname = 'COD'
dataframe()[source]

pandas.DataFrame constructed. Essentially geometrical info and space groups found by spglib as COD API is rather limited.

class abipy.core.restapi.Dotdict[source]

Bases: dict

dotget(key, default=None)[source]

d.dotget[“foo.bar”] –> d[“foo”][“bar”] if “foo.bar” not in self

skw Module

Shankland-Koelling-Wood Fourier interpolation scheme. For the theoretical background see [Euwema1969][Koelling1986][Pickett1988][Madsen2006].

class abipy.core.skw.ElectronInterpolator[source]

Bases: object

symprec = 1e-05
angle_tolerance = -1.0
occtype = 'insulator'
use_cache = True
classmethod pickle_load(filepath)[source]

Loads the object from a pickle file.

pickle_dump(filepath)[source]

Save the status of the object in pickle format.

get_sampling(mesh, is_shift)[source]

Use spglib to compute the k-points in the IBZ with the corresponding weights as well as the k-points in the full BZ.

Parameters
  • mesh

  • is_shift

Return: named tuple with the following attributes:

ibz: nibz weights: bz: nbz grid:

property val_ib

The index of the valence band.

get_edos(kmesh, is_shift=None, method='gaussian', step=0.1, width=0.2, wmesh=None)[source]

Compute the electron DOS on a linear mesh.

Parameters
  • kmesh – Three integers with the number of divisions along the reciprocal primitive axes.

  • is_shift – three integers (spglib API). When is_shift is not None, the kmesh is shifted along the axis in half of adjacent mesh points irrespective of the mesh numbers. None means unshited mesh.

  • method – String defining the method for the computation of the DOS.

  • step – Energy step (eV) of the linear mesh.

  • width – Standard deviation (eV) of the gaussian.

  • mesh – Frequency mesh to use. If None, the mesh is computed automatically from the eigenvalues.

Returns

(mesh, values, integral)

plot_dos_vs_kmeshes(kmeshes, is_shift=None, method='gaussian', step=0.1, width=0.2, fontsize=12, ax=None, **kwargs)[source]

Plot (interpolated) DOSes computed with different meshes.

Parameters
  • kmeshes – List of kmeshes. Each item is given by three integers with the number of divisions along the reciprocal primitive axes.

  • is_shift – three integers (spglib API). When is_shift is not None, the kmesh is shifted along the axis in half of adjacent mesh points irrespective of the mesh numbers. None means unshited mesh.

  • method – String defining the method for the computation of the DOS.

  • step – Energy step (eV) of the linear mesh.

  • width – Standard deviation (eV) of the gaussian.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

abstract eval_sk(spin, kpt, der1=None, der2=None)[source]

Interpolate eigenvalues for all bands at a given (spin, k-point). Optionally compute gradients and Hessian matrices.

Parameters
  • spin – Spin index.

  • kpt – K-point in reduced coordinates.

  • der1 – If not None, ouput gradient is stored in der1[nband, 3].

  • der2 – If not None, output Hessian is der2[nband, 3, 3].

Returns

oeigs[nband]

interp_kpts(kfrac_coords, dk1=False, dk2=False)[source]

Interpolate energies on an arbitrary set of k-points. Optionally, compute gradients and Hessian matrices.

Parameters
  • kfrac_coords – K-points in reduced coordinates.

  • dk1 (bool) – True if gradient is wanted.

  • dk2 (bool) – True to compute 2nd order derivatives.

Returns

interpolated energies in eigens[nsppol, len(kfrac_coords), nband] gradient in dedk[self.nsppol, len(kfrac_coords), self.nband, 3)) hessian in dedk2[self.nsppol, len(kfrac_coords), self.nband, 3, 3))

gradient and hessian are set to None if not computed.

Return type

namedtuple with

interp_kpts_and_enforce_degs(kfrac_coords, ref_eigens, atol=0.0001)[source]

Interpolate energies on an arbitrary set of k-points. Use ref_eigens to detect degeneracies and average the interpolated values in the degenerate subspace.

class abipy.core.skw.SkwInterpolator(lpratio, kpts, eigens, fermie, nelect, cell, symrel, has_timrev, filter_params=None, verbose=1)[source]

Bases: abipy.core.skw.ElectronInterpolator

This object implements the Shankland-Koelling-Wood Fourier interpolation scheme. It can be used to interpolate functions in k-space with the periodicity of the reciprocal lattice and satisfying F(k) = F(Sk) for each rotation S belonging to the point group of the crystal. For readability reason, the names of the variables are chosen assuming we are interpolating electronic eigenvalues but the same object can be used to interpolate other quantities. Just set the first dimension to 1.

to_string(verbose=0)[source]

String representation.

eval_sk(spin, kpt, der1=None, der2=None)[source]

Interpolate eigenvalues for all bands at a given (spin, k-point). Optionally compute gradients and Hessian matrices.

Parameters
  • spin – Spin index.

  • kpt – K-point in reduced coordinates.

  • der1 – If not None, ouput gradient is stored in der1[nband, 3].

  • der2 – If not None, output Hessian is der2[nband, 3, 3].

Returns

oeigs[nband]

get_stark(kpt)[source]

Return the star function for k-point kpt.

Parameters

kpt – K-point in reduced coordinates.

Returns

complex array of shape [self.nr]

get_stark_dk1(kpt)[source]

Compute the 1st-order derivative of the star function wrt k

Parameters

kpt – K-point in reduced coordinates.

Returns

complex array [3, self.nr] with the derivative of the star function wrt k in reduced coordinates.

get_stark_dk2(kpt)[source]

Compute the 2nd-order derivatives of the star function wrt k.

Parameters

kpt – K-point in reduced coordinates.

Returns

Complex numpy array of shape [3, 3, self.nr] with the 2nd-order derivatives of the star function wrt k in reduced coordinates.

abipy.core.skw.extract_point_group(symrel, has_timrev)[source]

Extract the point group rotations from the spacegroup. Add time-reversal if spatial inversion is not present and has_timrev.

Returns

(ptg_symrel, ptg_symrec) with rotations in real- and reciprocal-space.

structure Module

This module defines basic objects representing the crystalline structure.

abipy.core.structure.mp_match_structure(obj, api_key=None, endpoint=None, final=True)[source]

Finds matching structures on the Materials Project database.

Parameters
  • obj – filename or abipy.core.structure.Structure object.

  • api_key (str) – A String API key for accessing the MaterialsProject REST interface.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface.

  • final (bool) – Whether to get the final structure, or the initial (pre-relaxation) structure. Defaults to True.

Returns

MpStructures object with

structures: List of matching structures and list of Materials Project identifier.

Connect to the materials project database. Get a list of structures corresponding to a chemical system, formula, or materials_id.

Parameters
  • chemsys_formula_id (str) – A chemical system (e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234).

  • api_key (str) – A String API key for accessing the MaterialsProject REST interface. If this is None, the code will check if there is a PMG_MAPI_KEY in your .pmgrc.yaml.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface.

Returns

MpStructures object with

List of Structure objects, Materials project ids associated to structures. and List of dictionaries with MP data (same order as structures).

Note that the attributes evalute to False if no match is found

Connect to the COD database. Get list of structures corresponding to a chemical formula

Parameters
  • formula (str) – Chemical formula (e.g., Fe2O3)

  • primitive (bool) – True if primitive structures are wanted. Note that many COD structures are not primitive.

Returns

CodStructures object with

List of Structure objects, COD ids associated to structures. and List of dictionaries with COD data (same order as structures).

Note that the attributes evalute to False if no match is found

class abipy.core.structure.Structure(lattice: Union[Sequence[Sequence[Sequence[Sequence[Sequence[Any]]]]], numpy.typing._array_like._SupportsArray[dtype[Any]], Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]], Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]], Sequence[Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]]], Sequence[Sequence[Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]]]], bool, int, float, complex, str, bytes, Sequence[Union[bool, int, float, complex, str, bytes]], Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]], Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]], Sequence[Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]]], pymatgen.core.lattice.Lattice], species: Sequence[Union[str, pymatgen.core.periodic_table.Element, pymatgen.core.periodic_table.Species, pymatgen.core.periodic_table.DummySpecies, dict, pymatgen.core.composition.Composition]], coords: Sequence[Union[Sequence[Sequence[Sequence[Sequence[Sequence[Any]]]]], numpy.typing._array_like._SupportsArray[dtype[Any]], Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]], Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]], Sequence[Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]]], Sequence[Sequence[Sequence[Sequence[numpy.typing._array_like._SupportsArray[dtype[Any]]]]]], bool, int, float, complex, str, bytes, Sequence[Union[bool, int, float, complex, str, bytes]], Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]], Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]], Sequence[Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]]]]], charge: float = None, validate_proximity: bool = False, to_unit_cell: bool = False, coords_are_cartesian: bool = False, site_properties: dict = None)[source]

Bases: pymatgen.core.structure.Structure, abipy.core.mixins.NotebookWriter

Extends pymatgen.core.structure.Structure with Abinit-specific methods.

A jupyter notebook documenting the usage of this object is available at <https://nbviewer.jupyter.org/github/abinit/abitutorials/blob/master/abitutorials/structure.ipynb>

For the pymatgen project see [Ong2013].

Inheritance Diagram

Inheritance diagram of Structure
classmethod as_structure(obj)[source]

Convert obj into a abipy.core.structure.Structure. Accepts:

  • Structure object.

  • Filename

  • Dictionaries (JSON format or dictionaries with abinit variables).

  • Objects with a structure attribute.

classmethod from_file(filepath, primitive=False, sort=False)[source]

Reads a structure from a file. For example, anything ending in a “cif” is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR, Netcdf and pymatgen’s JSON serialized structures.

Netcdf files supported:

All files produced by ABINIT with info of the crystalline geometry HIST.nc, in this case the last structure of the history is returned.

Parameters
  • filename (str) – The filename to read from.

  • primitive (bool) – Whether to convert to a primitive cell Only available for cifs, POSCAR, CSSR, JSON, YAML Defaults to True.

  • sort (bool) – Whether to sort sites. Default to False.

Returns: abipy.core.structure.Structure object

classmethod from_mpid(material_id, final=True, api_key=None, endpoint=None)[source]

Get a Structure corresponding to a material_id.

Parameters
  • material_id (str) – Materials Project material_id (a string, e.g., mp-1234).

  • final (bool) – Whether to get the final structure, or the initial (pre-relaxation) structure. Defaults to True.

  • api_key (str) – A String API key for accessing the MaterialsProject REST interface. Please apply on the Materials Project website for one. If this is None, the code will check if there is a PMG_MAPI_KEY in your .pmgrc.yaml. If so, it will use that environment This makes easier for heavy users to simply add this environment variable to their setups and MPRester can then be called without any arguments.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface. Defaults to the standard Materials Project REST address, but can be changed to other urls implementing a similar interface.

Returns: abipy.core.structure.Structure object.

classmethod from_cod_id(cod_id, primitive=False, **kwargs)[source]

Queries the COD for a structure by id. Returns abipy.core.structure.Structure object.

Parameters
  • cod_id (int) – COD id.

  • primitive (bool) – True if primitive structures are wanted. Note that many COD structures are not primitive.

  • kwargs – Arguments passed to get_structure_by_id

Returns: abipy.core.structure.Structure object.

classmethod from_ase_atoms(atoms)[source]

Returns structure from ASE Atoms.

Parameters

atoms – ASE Atoms object

Returns

Equivalent Structure

to_ase_atoms()[source]

Returns ASE Atoms object from structure.

classmethod boxed_molecule(pseudos, cart_coords, acell=(10, 10, 10))[source]

Creates a molecule in a periodic box of lengths acell [Bohr]

Parameters
  • pseudos – List of pseudopotentials

  • cart_coords – Cartesian coordinates

  • acell – Lengths of the box in Bohr

classmethod boxed_atom(pseudo, cart_coords=(0, 0, 0), acell=(10, 10, 10))[source]

Creates an atom in a periodic box of lengths acell [Bohr]

Parameters
  • pseudo – Pseudopotential object.

  • cart_coords – Cartesian coordinates in Angstrom

  • acell – Lengths of the box in Bohr (Abinit input variable)

classmethod bcc(a, species, primitive=True, units='ang', **kwargs)[source]

Build a primitive or a conventional bcc crystal structure.

Parameters
  • a – Lattice parameter (Angstrom if units is not given)

  • species – Chemical species. See __init__ method of pymatgen.core.structure.Structure

  • primitive – if True a primitive cell will be produced, otherwise a conventional one

  • units – Units of input lattice parameters e.g. “bohr”, “pm”

  • kwargs – All keyword arguments accepted by pymatgen.core.structure.Structure.

classmethod fcc(a, species, primitive=True, units='ang', **kwargs)[source]

Build a primitive or a conventional fcc crystal structure.

Parameters
  • a – Lattice parameter (Angstrom if units is not given)

  • species – Chemical species. See __init__ method of pymatgen.Structure

  • primitive – if True a primitive cell will be produced, otherwise a conventional one

  • units – Units of input lattice parameters e.g. “bohr”, “pm”

  • kwargs – All keyword arguments accepted by pymatgen.Structure

classmethod zincblende(a, species, units='ang', **kwargs)[source]

Build a primitive zincblende crystal structure.

Parameters
  • a – Lattice parameter (Angstrom if units is not given)

  • species – Chemical species. See __init__ method of pymatgen.Structure

  • units – Units of input lattice parameters e.g. “bohr”, “pm”

  • kwargs – All keyword arguments accepted by pymatgen.Structure

Example:

Structure.zincblende(a, ["Zn", "S"])
classmethod rocksalt(a, species, units='ang', **kwargs)[source]

Build a primitive fcc crystal structure.

Parameters
  • a – Lattice parameter (Angstrom if units is not given)

  • units – Units of input lattice parameters e.g. “bohr”, “pm”

  • species – Chemical species. See __init__ method of pymatgen.Structure

  • kwargs – All keyword arguments accepted by pymatgen.Structure

Example:

Structure.rocksalt(a, ["Na", "Cl"])
classmethod ABO3(a, species, units='ang', **kwargs)[source]

Peroviskite structures.

Parameters
  • a – Lattice parameter (Angstrom if units is not given)

  • species – Chemical species. See __init__ method of pymatgen.Structure

  • units – Units of input lattice parameters e.g. “bohr”, “pm”

  • kwargs – All keyword arguments accepted by pymatgen.Structure

classmethod from_abistring(string)[source]

Initialize Structure from string with Abinit input variables.

classmethod from_abivars(*args, **kwargs)[source]

Build a abipy.core.structure.Structure object from a dictionary with ABINIT variables.

Example:

al_structure = Structure.from_abivars(
    acell=3*[7.5],
    rprim=[0.0, 0.5, 0.5,
           0.5, 0.0, 0.5,
           0.5, 0.5, 0.0],
    typat=1,
    xred=[0.0, 0.0, 0.0],
    ntypat=1,
    znucl=13,
)

xred can be replaced with xcart or xangst.

property species_by_znucl

Return list of unique specie found in the structure ordered according to sites.

Example

Site0: 0.5 0 0 O Site1: 0 0 0 Si

produces [Specie_O, Specie_Si] and not set([Specie_O, Specie_Si]) as in types_of_specie.

Important:: We call this method species_by_znucl but this does not mean that the list can automagically reproduce the value of znucl(ntypat) specified in an arbitrary ABINIT input file created by the user. This array is ordered as the znucl list produced by AbiPy when writing the structure to the input file.

to_string(title=None, verbose=0)[source]

String representation.

to(fmt=None, filename=None, **kwargs)[source]

Outputs the structure to a file or string.

Parameters
  • fmt (str) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”. Non-case sensitive.

  • filename (str) – If provided, output will be written to a file. If fmt is not specified, the format is determined from the filename. Defaults is None, i.e. string output.

  • **kwargs – Kwargs passthru to relevant methods. E.g., This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric cifs.

Returns

(str) if filename is None. None otherwise.

mp_match(**kwargs)[source]

Finds matching structures on the Materials Project database. Just a wrapper around mp_match_structure.

write_cif_with_spglib_symms(filename, symprec=0.001, angle_tolerance=5.0, significant_figures=8, ret_string=False)[source]
Parameters
  • symprec (float) – If not none, finds the symmetry of the structure and writes the cif with symmetry information. Passes symprec to the SpacegroupAnalyzer.

  • significant_figures (int) – Specifies precision for formatting of floats. Defaults to 8.

  • angle_tolerance (float) – Angle tolerance for symmetry finding. Passes angle_tolerance to the SpacegroupAnalyzer. Used only if symprec is not None.

to_abivars(enforce_znucl=None, enforce_typat=None, **kwargs)[source]

Returns a dictionary with the ABINIT variables.

enforce_znucl[ntypat] = Enforce this value for znucl. enforce_typat[natom] = Fortran conventions. Start to count from 1.

property latex_formula

LaTeX formatted formula. E.g., Fe2O3 is transformed to Fe$_{2}$O$_{3}$.

property abi_string

Return a string with the ABINIT input associated to this structure.

get_panel(**kwargs)[source]

Build panel with widgets to interact with the structure either in a notebook or in a bokeh app

get_conventional_standard_structure(international_monoclinic=True, symprec=0.001, angle_tolerance=5)[source]

Gives a structure with a conventional cell according to certain standards. The standards are defined in [Setyawan2010] They basically enforce as much as possible norm(a1) < norm(a2) < norm(a3)

Returns: The structure in a conventional standardized cell

abi_primitive(symprec=0.001, angle_tolerance=5, no_idealize=0)[source]
refine(symprec=0.001, angle_tolerance=5)[source]

Get the refined structure based on detected symmetry. The refined structure is a conventional cell setting with atoms moved to the expected symmetry positions.

Returns: Refined structure.

abi_sanitize(symprec=0.001, angle_tolerance=5, primitive=True, primitive_standard=False)[source]

Returns a new structure in which:

  • Structure is refined.

  • Reduced to primitive settings.

  • Lattice vectors are exchanged if the triple product is negative

Parameters
  • symprec (float) – Symmetry precision used to refine the structure.

  • angle_tolerance (float) – Tolerance on angles. if symprec is None and angle_tolerance is None, no structure refinement is peformed.

  • primitive (bool) – Returns most primitive structure found.

  • primitive_standard (bool) – Whether to convert to a primitive cell using the standards defined in Setyawan, W., & Curtarolo, S. (2010). High-throughput electronic band structure calculations: Challenges and tools. Computational Materials Science, 49(2), 299-312. doi:10.1016/j.commatsci.2010.05.010

get_oxi_state_decorated(**kwargs)[source]

Use pymatgen.analysis.bond_valence.BVAnalyzer to estimate oxidation states Return oxidation state decorated structure. This currently works only for ordered structures only.

Parameters

kwargs – Arguments passed to BVAnalyzer

Returns

A modified structure that is oxidation state decorated.

property reciprocal_lattice

Reciprocal lattice of the structure. Note that this is the standard reciprocal lattice used for solid state physics with a factor of 2 * pi i.e. a_j . b_j = 2pi delta_ij

If you are looking for the crystallographic reciprocal lattice, use the reciprocal_lattice_crystallographic property.

lattice_vectors(space='r')[source]

Returns the vectors of the unit cell in Angstrom.

Parameters

space – “r” for real space vectors, “g” for reciprocal space basis vectors.

spget_lattice_type(symprec=0.001, angle_tolerance=5)[source]

Call spglib to get the lattice for the structure, e.g., (triclinic, orthorhombic, cubic, etc.).This is the same than the crystal system with the exception of the hexagonal/rhombohedral lattice

Parameters
  • symprec (float) – Symmetry precision for distance

  • angle_tolerance (float) – Tolerance on angles.

Returns

Lattice type for structure or None if type cannot be detected.

Return type

(str)

spget_equivalent_atoms(symprec=0.001, angle_tolerance=5, printout=False)[source]

Call spglib to find the inequivalent atoms and build symmetry tables.

Parameters
  • symprec (float) – Symmetry precision for distance.

  • angle_tolerance (float) – Tolerance on angles.

  • printout (bool) – True to print symmetry tables.

Returns

namedtuple (irred_pos, eqmap, spgdata) with the following attributes:

* irred_pos: array giving the position of the i-th irred atom in the structure.
    The number of irred atoms is len(irred_pos).
*   eqmap: Mapping irred atom position --> list with positions of symmetrical atoms.
*   wyckoffs: Wyckoff letters.
*   wyck_mult: Array with Wyckoff multiplicity.
*   wyck_labels: List of labels with Wyckoff multiplicity and letter e.g. 3a
*   site_labels: Labels for each site in computed from element symbol and wyckoff positions e.g Si2a
*   spgdata: spglib dataset with additional data reported by spglib_.
Example
for irr_pos in irred_pos:

eqmap[irr_pos] # List of symmetrical positions associated to the irr_pos atom.

spget_summary(symprec=0.001, angle_tolerance=5, site_symmetry=False, verbose=0)[source]

Return string with full information about crystalline structure i.e. space group, point group, wyckoff positions, equivalent sites.

Parameters
  • symprec (float) – Symmetry precision for distance.

  • angle_tolerance (float) – Tolerance on angles.

  • site_symmetry – True to show site symmetries i.e. the point group operations that leave the site invariant.

  • verbose (int) – Verbosity level.

property abi_spacegroup

AbinitSpaceGroup instance with Abinit symmetries read from the netcd file. None if abinit symmetries are not available e.g. if the structure has been created from a CIF file.

set_abi_spacegroup(spacegroup)[source]

AbinitSpaceGroup setter.

property has_abi_spacegroup

True is the structure contains info on the spacegroup.

spgset_abi_spacegroup(has_timerev, overwrite=False)[source]

Call spglib to find the spacegroup of the crystal, create new AbinitSpaceGroup object and store it in self.abi_spacegroup.

Parameters
  • has_timerev (bool) – True if time-reversal can be used.

  • overwrite (bool) – By default, the method raises ValueError if the object already has the list of symmetries found by Abinit.

Returns: AbinitSpaceGroup

property indsym

Compute indsym (natom, nsym, 4) array.

For each isym,iatom, the fourth element is label of atom into which iatom is sent by INVERSE of symmetry operation isym; first three elements are the primitive translations which must be subtracted after the transformation to get back to the original unit cell (see symatm.F90).

site_symmetries()[source]

Object with SiteSymmetries.

spget_site_symmetries()[source]
abiget_spginfo(tolsym=None, pre=None)[source]

Call Abinit to get spacegroup information. Return dictionary with e.g. {‘bravais’: ‘Bravais cF (face-center cubic)’, ‘spg_number’: 227, ‘spg_symbol’: ‘Fd-3m’}.

Parameters
  • tolsym – Abinit tolsym input variable. None correspondes to the default value.

  • pre – Keywords in dictionary are prepended with this string

print_neighbors(radius=2.0)[source]

Get neighbors for each atom in the unit cell, out to a distance radius in Angstrom Print results.

hsym_kpath()[source]

Returns an instance of pymatgen.symmetry.bandstructure.HighSymmKpath. (Database of high symmetry k-points and high symmetry lines).

hsym_kpoints()[source]

abipy.core.kpoints.KpointList object with the high-symmetry K-points.

get_kcoords_from_names(knames, cart_coords=False)[source]

Return numpy array with the fractional coordinates of the high-symmetry k-points listed in knames.

Parameters
  • knames – List of strings with the k-point labels.

  • cart_coords – True if the coords dataframe should contain Cartesian cordinates instead of Reduced coordinates.

hsym_stars()[source]

List of abipy.core.kpoints.KpointStar objects. Each star is associated to one of the special k-points present in the pymatgen database.

get_sorted_structure_z()[source]

Order the structure according to increasing Z of the elements

findname_in_hsym_stars(kpoint)[source]

Returns the name of the special k-point, None if kpoint is unknown.

get_symbol2indices()[source]

Return a dictionary mapping chemical symbols to numpy array with the position of the atoms.

Example

MgB2 –> {Mg: [0], B: [1, 2]}

get_symbol2coords()[source]

Return a dictionary mapping chemical symbols to a [ntype_symbol, 3] numpy array with the fractional coordinates.

dot(coords_a, coords_b, space='r', frac_coords=False)[source]

Compute the scalar product of vector(s) either in real space or reciprocal space.

Parameters
  • coords (3x1 array) – Array-like object with the coordinates.

  • space (str) – “r” for real space, “g” for reciprocal space.

  • frac_coords (bool) – Whether the vector corresponds to fractional or cartesian coordinates.

Returns

one-dimensional numpy array.

norm(coords, space='r', frac_coords=True)[source]

Compute the norm of vector(s) either in real space or reciprocal space.

Parameters
  • coords (3x1 array) – Array-like object with the coordinates.

  • space (str) – “r” for real space, “g” for reciprocal space.

  • frac_coords (bool) – Whether the vector corresponds to fractional or cartesian coordinates.

Returns

one-dimensional numpy array.

scale_lattice(new_volume)[source]

Return a new abipy.core.structure.Structure with volume new_volume by performing a scaling of the lattice vectors so that length proportions and angles are preserved.

get_dict4pandas(symprec=0.01, angle_tolerance=5.0, with_spglib=True)[source]

Return a OrderedDict with the most important structural parameters:

  • Chemical formula and number of atoms.

  • Lattice lengths, angles and volume.

  • The spacegroup number computed by Abinit (set to None if not available).

  • The spacegroup number and symbol computed by spglib (if with_spglib).

Useful to construct pandas DataFrames

Parameters
  • with_spglib (bool) – If True, spglib is invoked to get the spacegroup symbol and number

  • symprec (float) – Symmetry precision used to refine the structure.

  • angle_tolerance (float) – Tolerance on angles.

get_symb2coords_dataframe(with_cart_coords=False)[source]

Return dictionary mapping element symbol to DataFrame with atomic positions in cartesian coordinates.

Parameters

with_cart_coords – True if Cartesian coordinates should be added as well.

plot(**kwargs)[source]

Plot structure in 3D with matplotlib. Return matplotlib Figure. See plot_structure for kwargs.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plotly(**kwargs)[source]

Plot structure in 3D with plotly. Return plotly Figure. See plot_structure for kwargs

Keyword arguments controlling the display of the figure: ================ ==================================================================== kwargs Meaning ================ ==================================================================== title Title of the plot (Default: None). show True to show the figure (default: True). hovormode True to show the hover info (default: False) savefig “abc.png” , “abc.jpeg” or “abc.webp” to save the figure to a file. write_json Write plotly figure to write_json JSON file.

Inside jupyter-lab, one can right-click the write_json file from the file menu and open with “Plotly Editor”. Make some changes to the figure, then use the file menu to save the customized plotly plot. Requires jupyter labextension install jupyterlab-chart-editor. See https://github.com/plotly/jupyterlab-chart-editor

renderer (str or None (default None)) –

A string containing the names of one or more registered renderers (separated by ‘+’ characters) or None. If None, then the default renderers specified in plotly.io.renderers.default are used. See https://plotly.com/python-api-reference/generated/plotly.graph_objects.Figure.html

config (dict) A dict of parameters to configure the figure. The defaults are set in plotly.js. chart_studio True to push figure to chart_studio server. Requires authenticatios.

Default: False.

plot_bz(ax=None, pmg_path=True, with_labels=True, **kwargs)[source]

Use matplotlib to plot the symmetry line path in the Brillouin Zone.

Parameters
  • ax – matplotlib Axes or None if a new figure should be created.

  • pmg_path (bool) – True if the default path used in pymatgen should be show.

  • with_labels (bool) – True to plot k-point labels.

Returns: matplotlib.figure.Figure.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plotly_bz(fig=None, pmg_path=True, with_labels=True, **kwargs)[source]

Use matplotlib to plot the symmetry line path in the Brillouin Zone.

Parameters
  • ax – matplotlib Axes or None if a new figure should be created.

  • pmg_path (bool) – True if the default path used in pymatgen should be show.

  • with_labels (bool) – True to plot k-point labels.

Returns: matplotlib.figure.Figure.

Keyword arguments controlling the display of the figure: ================ ==================================================================== kwargs Meaning ================ ==================================================================== title Title of the plot (Default: None). show True to show the figure (default: True). hovormode True to show the hover info (default: False) savefig “abc.png” , “abc.jpeg” or “abc.webp” to save the figure to a file. write_json Write plotly figure to write_json JSON file.

Inside jupyter-lab, one can right-click the write_json file from the file menu and open with “Plotly Editor”. Make some changes to the figure, then use the file menu to save the customized plotly plot. Requires jupyter labextension install jupyterlab-chart-editor. See https://github.com/plotly/jupyterlab-chart-editor

renderer (str or None (default None)) –

A string containing the names of one or more registered renderers (separated by ‘+’ characters) or None. If None, then the default renderers specified in plotly.io.renderers.default are used. See https://plotly.com/python-api-reference/generated/plotly.graph_objects.Figure.html

config (dict) A dict of parameters to configure the figure. The defaults are set in plotly.js. chart_studio True to push figure to chart_studio server. Requires authenticatios.

Default: False.

plot_xrd(wavelength='CuKa', symprec=0, debye_waller_factors=None, two_theta_range=(0, 90), annotate_peaks=True, ax=None, **kwargs)[source]

Use pymatgen XRDCalculator to show the XRD plot.

Parameters
  • wavelength (str/float) – The wavelength can be specified as either a float or a string. If it is a string, it must be one of the supported definitions in the AVAILABLE_RADIATION class variable, which provides useful commonly used wavelengths. If it is a float, it is interpreted as a wavelength in angstroms. Defaults to “CuKa”, i.e, Cu K_alpha radiation.

  • symprec (float) – Symmetry precision for structure refinement. If set to 0, no refinement is done. Otherwise, refinement is performed using spglib with provided precision.

  • ({element symbol (debye_waller_factors) – float}): Allows the specification of Debye-Waller factors. Note that these factors are temperature dependent.

  • two_theta_range ([float of length 2]) – Tuple for range of two_thetas to calculate in degrees. Defaults to (0, 90). Set to None if you want all diffracted beams within the limiting sphere of radius 2 / wavelength.

  • annotate_peaks (bool) – Whether to annotate the peaks with plane information.

  • ax – matplotlib Axes or None if a new figure should be created.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

export(filename, visu=None, verbose=1)[source]

Export the crystalline structure to file filename.

Parameters
  • filename (str) – String specifying the file path and the file format. The format is defined by the file extension. filename=”prefix.xsf”, for example, will produce a file in XSF format. An empty prefix, e.g. “.xsf” makes the code use a temporary file.

  • visuabipy.iotools.visualizer.Visualizer subclass. By default, this method returns the first available visualizer that supports the given file format. If visu is not None, an instance of visu is returned. See abipy.iotools.visualizer.Visualizer for the list of applications and formats supported.

  • verbose – Verbosity level

Returns: Visulizer instance.

get_chemview(**kwargs)[source]

Visualize structure inside the jupyter notebook using chemview package.

plot_vtk(show=True, **kwargs)[source]

Visualize structure with VTK. Requires vVTK python bindings.

Parameters
  • show – True to show structure immediately.

  • kwargs – keyword arguments passed to StructureVis.

Return: StructureVis object.

plot_mayaview(figure=None, show=True, **kwargs)[source]

Visualize structure with mayavi.

plot_atoms(rotations='default', **kwargs)[source]

Plot 2d representation with matplotlib using ASE plot_atoms function.

Parameters
  • rotations – String or List of strings. Each string defines a rotation (in degrees) in the form ‘10x,20y,30z’ Note that the order of rotation matters, i.e. ‘50x,40z’ is different from ‘40z,50x’.

  • kwargs – extra kwargs passed to plot_atoms ASE function.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_ngl_view()[source]

Visualize the structure with nglview inside the jupyter notebook.

get_crystaltk_view()[source]

Visualize the structure with crystal_toolkit inside the jupyter notebook.

get_jsmol_view(symprec=None, verbose=0, **kwargs)[source]

Visualize the structure with jsmol inside the jupyter notebook.

Parameters
  • symprec (float) – If not none, finds the symmetry of the structure and writes the CIF with symmetry information. Passes symprec to the spglib SpacegroupAnalyzer.

  • verbose – Verbosity level.

visualize(appname='vesta')[source]

Visualize the crystalline structure with visualizer. See abipy.iotools.visualizer.Visualizer for the list of applications and formats supported.

convert(fmt='cif', **kwargs)[source]

Return string with the structure in the given format fmt Options include “abivars”, “cif”, “xsf”, “poscar”, “siesta”, “wannier90”, “cssr”, “json”.

displace(displ, eta, frac_coords=True, normalize=True)[source]

Displace the sites of the structure along the displacement vector displ.

The displacement vector is first rescaled so that the maxium atomic displacement is one Angstrom, and then multiplied by eta. Hence passing eta=0.001, will move all the atoms so that the maximum atomic displacement is 0.001 Angstrom.

Parameters
  • displ – Displacement vector with 3*len(self) entries (fractional coordinates).

  • eta – Scaling factor.

  • frac_coords – Boolean stating whether the vector corresponds to fractional or cartesian coordinates.

get_smallest_supercell(qpoint, max_supercell)[source]
Parameters
  • qpoint – q vector in reduced coordinates in reciprocal space

  • max_supercell – vector with the maximum supercell size

Returns: the scaling matrix of the supercell

get_trans_vect(scale_matrix)[source]

Returns the translation vectors for a given scale matrix.

Parameters

scale_matrix – Scale matrix defining the new lattice vectors in term of the old ones

Return: the translation vectors

write_vib_file(xyz_file, qpoint, displ, do_real=True, frac_coords=True, scale_matrix=None, max_supercell=None)[source]

Write into the file descriptor xyz_file the positions and displacements of the atoms

Parameters
  • xyz_file – file_descriptor

  • qpoint – qpoint to be analyzed

  • displ – eigendisplacements to be analyzed

  • do_real – True if you want to get only real part, False means imaginary part

  • frac_coords – True if the eigendisplacements are given in fractional coordinates

  • scale_matrix – Scale matrix for supercell

  • max_supercell – Maximum size of supercell vectors with respect to primitive cell

frozen_2phonon(qpoint, displ1, displ2, eta=1, frac_coords=False, scale_matrix=None, max_supercell=None)[source]

Creates the supercell needed for a given qpoint and adds the displacements. The displacements are normalized so that the largest atomic displacement will correspond to the value of eta in Angstrom.

Parameters
  • qpoint – q vector in reduced coordinate in reciprocal space.

  • displ1 – first displacement in real space of the atoms.

  • displ2 – second displacement in real space of the atoms.

  • eta – pre-factor multiplying the displacement. Gives the value in Angstrom of the largest displacement.

  • frac_coords – whether the displacements are given in fractional or cartesian coordinates

  • scale_matrix – the scaling matrix of the supercell. If None a scaling matrix suitable for the qpoint will be determined.

  • max_supercell – mandatory if scale_matrix is None, ignored otherwise. Defines the largest supercell in the search for a scaling matrix suitable for the q point.

Returns

A namedtuple with a Structure with the displaced atoms, a numpy array containing the displacements applied to each atom and the scale matrix used to generate the supercell.

frozen_phonon(qpoint, displ, eta=1, frac_coords=False, scale_matrix=None, max_supercell=None)[source]

Creates a supercell with displaced atoms for the specified q-point. The displacements are normalized so that the largest atomic displacement will correspond to the value of eta in Angstrom.

Parameters
  • qpoint – q vector in reduced coordinate in reciprocal space.

  • displ – displacement in real space of the atoms.

  • eta – pre-factor multiplying the displacement. Gives the value in Angstrom of the largest displacement.

  • frac_coords – whether the displacements are given in fractional or cartesian coordinates

  • scale_matrix – the scaling matrix of the supercell. If None a scaling matrix suitable for the qpoint will be determined.

  • max_supercell – mandatory if scale_matrix is None, ignored otherwise. Defines the largest supercell in the search for a scaling matrix suitable for the q point.

Returns

A namedtuple with a Structure with the displaced atoms, a numpy array containing the displacements applied to each atom and the scale matrix used to generate the supercell.

calc_kptbounds()[source]

Returns the suggested value for the ABINIT variable kptbounds.

get_kpath_input_string(fmt='abinit', line_density=10)[source]

Return string with input variables for band-structure calculations in the format used by code fmt. Use line_density points for the smallest segment (if supported by code).

calc_ksampling(nksmall, symprec=0.01, angle_tolerance=5)[source]

Return the k-point sampling from the number of divisions nksmall to be used for the smallest reciprocal lattice vector.

calc_ngkpt(nksmall)[source]

Compute the ABINIT variable ngkpt from the number of divisions used for the smallest lattice vector.

Parameters

nksmall (int) – Number of division for the smallest lattice vector.

calc_shiftk(symprec=0.01, angle_tolerance=5)[source]

Find the values of shiftk and nshiftk appropriated for the sampling of the Brillouin zone.

When the primitive vectors of the lattice do NOT form a FCC or a BCC lattice, the usual (shifted) Monkhorst-Pack grids are formed by using nshiftk=1 and shiftk 0.5 0.5 0.5 . This is often the preferred k point sampling. For a non-shifted Monkhorst-Pack grid, use nshiftk=1 and shiftk 0.0 0.0 0.0, but there is little reason to do that.

When the primitive vectors of the lattice form a FCC lattice, with rprim:

0.0 0.5 0.5
0.5 0.0 0.5
0.5 0.5 0.0

the (very efficient) usual Monkhorst-Pack sampling will be generated by using nshiftk= 4 and shiftk:

0.5 0.5 0.5
0.5 0.0 0.0
0.0 0.5 0.0
0.0 0.0 0.5

When the primitive vectors of the lattice form a BCC lattice, with rprim:

-0.5  0.5  0.5
 0.5 -0.5  0.5
 0.5  0.5 -0.5

the usual Monkhorst-Pack sampling will be generated by using nshiftk= 2 and shiftk:

 0.25  0.25  0.25
-0.25 -0.25 -0.25

However, the simple sampling nshiftk=1 and shiftk 0.5 0.5 0.5 is excellent.

For hexagonal lattices with hexagonal axes, e.g. rprim:

 1.0  0.0       0.0
-0.5  sqrt(3)/2 0.0
 0.0  0.0       1.0

one can use nshiftk= 1 and shiftk 0.0 0.0 0.5 In rhombohedral axes, e.g. using angdeg 3*60., this corresponds to shiftk 0.5 0.5 0.5, to keep the shift along the symmetry axis.

Returns

Suggested value of shiftk.

num_valence_electrons(pseudos)[source]

Returns the number of valence electrons.

Parameters

pseudos – List of pymatgen.io.abinit.pseudos.Pseudo objects or list of filenames.

valence_electrons_per_atom(pseudos)[source]

Returns the number of valence electrons for each atom in the structure.

Parameters

pseudos – List of pymatgen.io.abinit.pseudos.Pseudo objects or list of filenames.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

abipy.core.structure.dataframes_from_structures(struct_objects, index=None, symprec=0.01, angle_tolerance=5, with_spglib=True, cart_coords=False)[source]

Build two pandas Dataframes with the most important geometrical parameters associated to a list of structures or a list of objects that can be converted into structures.

Parameters
  • struct_objects – List of objects that can be converted to structure. Support filenames, structure objects, Abinit input files, dicts and many more types. See Structure.as_structure for the complete list.

  • index – Index of the pandas.DataFrame.

  • symprec (float) – Symmetry precision used to refine the structure.

  • angle_tolerance (float) – Tolerance on angles.

  • with_spglib (bool) – If True, spglib is invoked to get the spacegroup symbol and number.

  • cart_coords – True if the coords dataframe should contain Cartesian cordinates instead of Reduced coordinates.

Returns

namedtuple with two pandas.DataFrame named lattice and coords lattice contains the lattice parameters. coords the atomic positions.. The list of structures is available in the structures entry.

dfs = dataframes_from_structures(files)
dfs.lattice
dfs.coords
for structure in dfs.structures:
    print(structure)

symmetries Module

Objects used to deal with symmetry operations in crystals.

class abipy.core.symmetries.LatticeRotation(mat)[source]

Bases: abipy.core.symmetries.Operation

This object defines a pure rotation of the lattice (proper, improper, mirror symmetry) that is a rotation which is compatible with a lattice. The rotation matrix is expressed in reduced coordinates, therefore its elements are integers.

See:

http://xrayweb2.chem.ou.edu/notes/symmetry.html#rotation

Note

This object is immutable and therefore we do not inherit from numpy.ndarray.

inverse()[source]

Invert an orthogonal 3x3 matrix of INTEGER elements. Note use of integer arithmetic. Raise ValueError if not invertible.

isE()[source]

True if it is the identity

property order

Order of the rotation.

property root_inv
det()[source]

Return the determinant of a symmetry matrix mat[3,3]. It must be +-1

trace()[source]

The trace of the rotation matrix

is_proper()[source]

True if proper rotation

isI()[source]

True if self is the inversion operation.

name()[source]
class abipy.core.symmetries.AbinitSpaceGroup(spgid, symrel, tnons, symafm, has_timerev, inord='C')[source]

Bases: abipy.core.symmetries.OpSequence

Container storing the space group symmetries.

classmethod from_ncreader(r, inord='F')[source]

Builds the object from a netcdf reader

classmethod from_structure(structure, has_timerev=True, symprec=1e-05, angle_tolerance=5)[source]

Takes a abipy.core.structure.Structure object. Uses spglib to perform various symmetry finding operations.

Parameters
  • structureabipy.core.structure.Structure object.

  • has_timerev – True is time-reversal symmetry is included.

  • symprec – Tolerance for symmetry finding.

  • angle_tolerance – Angle tolerance for symmetry finding.

Warning

AFM symmetries are not supported.

to_string(verbose=0)[source]

String representation.

is_symmorphic()[source]

True if there’s at least one operation with non-zero fractional translation.

property has_timerev

True if time-reversal symmetry is present.

property symrel

[nsym, 3, 3] int array with symmetries in reduced coordinates of the direct lattice.

property tnons

[nsym, 3] float array with fractional translations in reduced coordinates of the direct lattice.

property symrec

[nsym, 3, 3] int array with symmetries in reduced coordinates of the reciprocal lattice.

property symafm

[nsym] int array with +1 if FM or -1 if AFM symmetry.

property num_spatial_symmetries
property afm_symmops

Tuple with antiferromagnetic symmetries.

property fm_symmops

Tuple of ferromagnetic symmetries.

symmops(time_sign=None, afm_sign=None)[source]
Parameters
  • time_sign – If specified, only symmetries with time-reversal sign time_sign are returned.

  • afm_sign – If specified, only symmetries with anti-ferromagnetic part afm_sign are returned.

Returns

tuple of SymmOp instances.

symeq(k1_frac_coords, k2_frac_coords, atol=None)[source]

Test whether two k-points in fractional coordinates are symmetry equivalent i.e. if there’s a symmetry operations TO (including time-reversal T, if present) such that:

TO(k1) = k2 + G0

Return: namedtuple with:

isym: The index of the symmetry operation such that TS(k1) = k2 + G0
    Set to -1 if k1 and k2 are not related by symmetry.
op: Symmetry operation.
g0: numpy vector.
find_little_group(kpoint)[source]

Find the little group of the kpoint.

Parameters

kpoint – Accept vector with the reduced coordinates or Kpoint object.

Returns

LittleGroup object.

get_spglib_hall_number(symprec=1e-05)[source]

Uses spglib.get_hall_number_from_symmetry to determine the hall number based on the symmetry operations. Useful when the space group number is not available, but the symmetries are (e.g. the DDB file)

Parameters

symprec – distance tolerance in fractional coordinates (not the standard in cartesian coordinates). See spglib docs for more details.

Returns

the hall number.

Return type

int

testing Module

Common test support for all AbiPy test scripts.

This single module should provide all the common functionality for abipy tests in a single location, so that test scripts can just import it and work right away.

class abipy.core.testing.AbipyTest(methodName='runTest')[source]

Bases: pymatgen.util.testing.PymatgenTest

Extends PymatgenTest with Abinit-specific methods. Several helper functions are implemented as static methods so that we can easily reuse the code in the pytest integration tests.

exception SkipTest

Bases: Exception

Raise this exception in a test to skip it.

Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly.

static which(program)[source]

Returns full path to a executable. None if not found or not executable.

static has_abinit(version=None, op='>=')[source]

Return True if abinit is in $PATH and version is op min_version.

skip_if_abinit_not_ge(version)[source]

Skip test if Abinit version is not >= version

static has_matplotlib(version=None, op='>=')[source]
static has_plotly(version=None, op='>=')[source]
static has_seaborn()[source]
static has_ase(version=None, op='>=')[source]

True if ASE package is available.

static has_skimage()[source]

True if skimage package is available.

static has_python_graphviz(need_dotexec=True)[source]

True if python-graphviz package is installed and dot executable in path.

static has_mayavi()[source]

True if mayavi is available. Set also offscreen to True

has_panel()[source]

False if Panel library is not installed.

has_networkx()[source]

False if networkx library is not installed.

has_graphviz()[source]

True if graphviz library is installed and dot in $PATH

has_phonopy(version=None, op='>=')[source]

True if phonopy is installed. If version is None, the result of phonopy.__version__ op version is returned.

static get_abistructure_from_abiref(basename)[source]

Return an Abipy abipy.core.structure.Structure from the basename of one of the reference files.

static mkdtemp(**kwargs)[source]

Invoke mkdtep with kwargs, return the name of a temporary directory.

static tmpfileindir(basename, **kwargs)[source]

Return the absolute path of a temporary file with basename basename created in a temporary directory.

static get_tmpname(**kwargs)[source]

Invoke mkstep with kwargs, return the name of a temporary file.

tmpfile_write(string)[source]

Write string to a temporary file. Returns the name of the temporary file.

static has_nbformat()[source]

Return True if nbformat is available and we can test the generation of jupyter notebooks.

run_nbpath(nbpath)[source]

Test that the notebook in question runs all cells correctly.

static has_ipywidgets()[source]

Return True if ipywidgets package is available.

static assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True)[source]

Alternative naming for assertArrayAlmostEqual.

static assert_equal(actual, desired, err_msg='', verbose=True)[source]

Alternative naming for assertArrayEqual.

static json_read_abinit_input(json_basename)[source]

Return an abipy.abio.inputs.AbinitInput from the basename of the file in abipy/data/test_files.

static assert_input_equality(ref_basename, input_to_test, rtol=1e-05, atol=1e-08, equal_nan=False)[source]

Check equality between an input and a reference in test_files. only input variables and structure are compared.

Parameters
  • ref_basename – base name of the reference file to test against in test_files

  • input_to_testabipy.abio.inputs.AbinitInput object to test

  • rtol – passed to numpy.isclose for float comparison

  • atol – passed to numpy.isclose for float comparison

  • equal_nan – passed to numpy.isclose for float comparison

Returns

raises an assertion error if the two inputs are not the same

static straceback()[source]

Returns a string with the traceback.

static skip_if_not_phonopy(version=None, op='>=')[source]

Raise SkipTest if phonopy is not installed. Use version and op to ask for a specific version

static skip_if_not_bolztrap2(version=None, op='>=')[source]

Raise SkipTest if bolztrap2 is not installed. Use version and op to ask for a specific version

skip_if_not_executable(executable)[source]

Raise SkipTest if executable is not installed.

static skip_if_not_pseudodojo()[source]

Raise SkipTest if pseudodojo package is not installed.

static get_mock_module()[source]

Return mock module for testing. Raises ImportError if not found.

decode_with_MSON(obj)[source]

Convert obj into JSON assuming MSONable protocolo. Return new object decoded with MontyDecoder

static abivalidate_input(abinput, must_fail=False)[source]

Invoke Abinit to test validity of an abipy.abio.inputs.AbinitInput object Print info to stdout if failure before raising AssertionError.

static abivalidate_multi(multi)[source]

Invoke Abinit to test validity of a abipy.abio.inputs.MultiDataset or a list of abipy.abio.inputs.AbinitInput objects.

abivalidate_work(work)[source]

Invoke Abinit to test validity of the inputs of a abipy.flowtk.works.Work

static abivalidate_flow(flow)[source]

Invoke Abinit to test validity of the inputs of a abipy.flowtk.flows.Flow

static get_gsinput_si(usepaw=0, as_task=False)[source]

Build and return a GS input file for silicon or a Task if as_task

static get_gsinput_alas_ngkpt(ngkpt, usepaw=0, as_task=False)[source]

Build and return a GS input file for AlAs or a Task if as_task

site_symmetries Module

This module provides objects related to site symmetries

class abipy.core.site_symmetries.SiteSymmetries(structure)[source]

Bases: abipy.core.mixins.Has_Structure

property structure

abipy.core.structure.Structure object.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

get_wyckoff_dataframe(view='all', select_symbols=None, decimals=5, verbose=0)[source]

Find Wyckoff positions.

Parameters
  • view

  • select_symbols

  • decimals – Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • verbose – Verbosity level.

Return pandas.DataFrame with cartesian tensor components as columns and (inequivalent) sites along the rows.

get_tensor_rank2_dataframe(view='all', select_symbols=None, decimals=5, verbose=0)[source]

Use site symmetries to detect indipendent elements of rank 2 tensor.

Parameters
  • view

  • select_symbols

  • decimals – Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • verbose – Verbosity level

Return pandas.DataFrame with cartesian tensor components as columns and (inequivalent) sites along the rows.

check_site_symmetries(tcart, verbose=0)[source]

Test whether a set of tensors associated to the crystalline sites are compatible with the space group symmetries.

Parameters
  • tcart – (natom, 3, 3) array

  • verbose – Verbosity level.

Return: max_err