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: str) float[source]

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

abipy.core.abinit_units.phunit_tag(units: str, unicode=False) str[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: str, unicode=False) str[source]

Return latex string for phonon frequencies in units.

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

Return latex string for phonon DOS values in units.

abipy.core.abinit_units.s2itup(comp: str) tuple[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: tuple) str[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"

atom Module

This module provides objects and helper functions for atomic calculations.

class abipy.core.atom.NlkState(n: int, l: int, k: int | None = None)[source]

Bases: NlkState

Named tuple storing (n, l) or (n, l, k) if relativistic pseudos. k is set to None if we are in non-relativistic mode.

classmethod from_nlkap(n: int, l: int, kap: int | None) NlkState[source]
latex()[source]
latex_l()[source]
ksign()[source]
j()[source]

Total angular momentum

as_dict() dict[source]

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

get_dict4pandas() dict[source]

Dictionary used to build pandas DataFrames.

from_dict(d: dict) NlkState[source]

Reconstruct object from the dictionary in MSONable format produced by as_dict.

class abipy.core.atom.QState(n: int, l: int, occ: float, eig: float | None = None, j: int | None = None, s: int | None = None)[source]

Bases: QState

This object collects the set of quantum numbers and the physical properties associated to a single electron in a spherically symmetric atom.

property has_j: bool
property has_s: bool
class abipy.core.atom.AtomicConfiguration(Z: int, states: list[QState])[source]

Bases: object

Atomic configuration of an all-electron atom.

classmethod from_string(Z: int, string: str, has_s: bool = False, has_j: bool = False) AtomicConfiguration[source]
classmethod neutral_from_symbol(symbol: str | int) AtomicConfiguration[source]
symbol: str or int

Can be a chemical symbol (str) or an atomic number (int).

copy() AtomicConfiguration[source]

Shallow copy of self.

property symbol: str

Chemical symbol

property spin_mode: str

Spin-unpolarized calculation. polarized: Spin-polarized calculation.

Type:

unpolarized

property echarge: float

Electronic charge (float < 0 ).

property isneutral: bool

True if self is a neutral configuration.

add_state(**qnumbers) None[source]

Add a list of QState instances to self.

remove_state(**qnumbers) None[source]

Remove a quantum state from self.

class abipy.core.atom.RadialFunction(name: str, rmesh, values)[source]

Bases: object

A RadialFunction has a name, a radial mesh and values defined on this mesh.

classmethod from_filename(filename: str, rfunc_name=None, cols=(0, 1)) RadialFunction[source]

Initialize the object reading data from filename (txt format).

Parameters:
  • filename – Path to the file containing data.

  • rfunc_name – Optional name for the RadialFunction (defaults to filename)

  • cols – List with the index of the columns containing the radial mesh and the values.

property to_dict: dict
pprint(what: str = 'rmesh+values', stream=None) None[source]

pprint method (useful for debugging)

property rmax: float

Outermost point of the radial mesh.

property rsize: float

Size of the radial mesh.

property minmax_ridx: tuple[int, int]

Returns the indices of the values in a list with the maximum and minimum value.

property inodes: list[int]

” List with the index of the nodes of the radial function.

spline()[source]

Cubic spline.

roots()[source]

Return the zeros of the spline.

get_peaks(**kwargs)[source]
derivatives(r)[source]

Return all derivatives of the spline at the point r.

integral() RadialFunction[source]

Cumulatively integrate y(x) using the composite trapezoidal rule.

Returns:

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

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

Return definite integral of the spline of (r**2 values**2) between two given points a and b

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

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

ifromr(rpoint) int[source]

The index of the point in the radial mesh.

ir_small(abs_tol: float = 0.01) int[source]

Returns the rightmost index where the abs value of the wf becomes greater than abs_tol

Parameters:

abs_tol – Absolute tolerance.

Warning

Assumes that self.values are tending to zero for r –> infinity.

r2f2_integral()[source]

Cumulatively integrate r**2 f**2(r) using the composite trapezoidal rule.

r2f_integral()[source]

Cumulatively integrate r**2 f(r) using the composite trapezoidal rule.

get_intr2j0(ecut: float, numq: float = 3001)[source]

Compute 4piint[(frac{sin(2pi q r)}{2pi q r})(r^2 n(r))dr].

class abipy.core.atom.RadialWaveFunction(nlk: NlkState, name: str, rmesh, values)[source]

Bases: RadialFunction

Extends RadialFunction adding info on the set of quantum numbers. and methods specialized for electronic wavefunctions.

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: _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') None[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) Chgcar[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: _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: _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: _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: _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) Function1D[source]

Build a constant function from the mesh and the scalar const

property mesh: ndarray

numpy.ndarray with the mesh points

property values: ndarray

Values of the functions.

property real: Function1D

Return new Function1D with the real part of self.

property imag: Function1D

Return new Function1D with the imaginary part of self.

conjugate() Function1D[source]

Return new Function1D with the complex conjugate.

abs() Function1D[source]

Return Function1D with the absolute value.

classmethod from_func(func, mesh) Function1D[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)) Function1D[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='') None[source]

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

has_same_mesh(other: Function1D) bool[source]

True if self and other have the same mesh.

property bma: float

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

property max: float

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

property min: float

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

property iscomplexobj: bool

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) int[source]

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

finite_diff(order: int = 1, acc: int = 4) Function1D[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) Function1D[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) Function1D[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() Function1D[source]

Compute the FFT transform (negative sign).

ifft(x0=None) Function1D[source]

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

plot_ax(ax, exchange_xy=False, normalize=False, xfactor=1, yfactor=1, *args, **kwargs) list[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

  • normalize – Normalize the ydata to 1.

  • 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.

plot(ax=None, **kwargs) Any[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.

plotly

Try to convert mpl figure to plotly.

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

Helper function to plot the function with plotly.

Parameters:
  • fig – plotly.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 “-”

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

Plot the function with plotly.

Parameters:
  • exchange_xy – True to exchange x- and y-axis (default: False)

  • fig – plotly figure or None if a new figure should be created.

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

Returns: plotly-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). hovermode 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.

template Plotly template. See https://plotly.com/python/templates/
[“plotly”, “plotly_white”, “plotly_dark”, “ggplot2”,

“seaborn”, “simple_white”, “none”]

Default is None that is the default template is used.

globals Module

Global variables used to initialize AbiPy environment in notebooks.

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

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

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

Set in_notebook flag to False.

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

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

abipy.core.globals.get_abinb_workdir() str[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) tuple[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: str) str[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: Sequence

Descriptor-class for the G-sphere.

property gvecs: ndarray

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

index(gvec) int[source]

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

count(gvec) int[source]

Return number of occurrences of gvec.

copy() GSphere[source]

shallow copy.

to_string(verbose=0) str[source]

String representation.

zeros(dtype=<class 'float'>, extra_dims=()) ndarray[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=()) ndarray[source]

New zeroed 1D complex numpy.ndarray.

empty(dtype=<class 'float'>, extra_dims=()) ndarray[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=()) ndarray[source]

Returns new uninitialized 1D complex numpy.ndarray.

tofftmesh(mesh, arr_on_sphere) ndarray[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) ndarray[source]

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

irrepsdb Module

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: 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', scale=False)[source]

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

to_string(verbose: int = 0) str[source]

String representation.

classmethod as_kpoint(obj, lattice)[source]

Convert obj into a Kpoint instance.

Parameters:
  • objKpoint instance or array-like with the reduced coordinates.

  • latticepymatgen.core.lattice.Lattice object defining the reciprocal lattice.

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

Constructor for the Gamma point.

copy()[source]

Deep copy.

is_gamma(allow_umklapp=False, atol=None) bool[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) KpointStar[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: 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 KpointsError

classmethod subclass_from_name(name: str)[source]

Return the class with the given name.

classmethod from_dict(d: dict)[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(title=None, verbose=0, pre_string='') str[source]

String representation.

index(kpoint) int[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) int[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: bool

True if self represents a path in the BZ.

property is_ibz: bool

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: bool

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[str]

List with the name of the k-points.

property weights: ndarray

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

sum_weights()[source]

Returns the sum of the weights.

check_weights() None[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() str[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: 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: 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) str[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: KpointList

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) IrredZone[source]

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

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

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

to_string(verbose: int = 0, title=None) str[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) str[source]

String representation

print_bz2ibz(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[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) str[source]

String representation.

property nx: int

Number of points along x.

property ny: int

Number of points along y.

property nz: int

Number of points along z.

inv_vectors()[source]
zeros(dtype=<class 'float'>, extra_dims=()) ndarray[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=()) ndarray[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=()) ndarray[source]

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

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

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

crandom(extra_dims=()) ndarray[source]

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

reshape(arr) ndarray[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) ndarray[source]

FFT of array fr given in real space.

fft_g2r(fg, fg_ishifted=False) ndarray[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) ndarray[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

Mixin classes

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

Bases: 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) AbinitNcFile[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) str[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: dict

dict with the convergence parameters used to construct pandas.DataFrame.

get_dims_dataframe(as_dict=False, path='/') DataFrame[source]
Return: pandas.DataFrame with the dimensions defined in the path group.

or dict if as_dict is True.

get_input_string() str[source]

Read and return input string stored in the netcdf. Only nc files generared by Abinit9 have this variable.

get_ncfile_view(**kwargs)[source]

Return panel Parameterized object with widgets to visualize netcdf dimensions and variables.

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) Any[source]

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

show_bz(**kwargs) Any

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

export_structure(filepath: str)[source]

Export the structure on file.

returns: abipy.iotools.visualizer.Visualizer instance.

visualize_structure_with(appname: str)[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: int

Number of spin polarizations

property nspinor: int

Number of spinors

property nspden: int

Number of indepedendent spin-density components.

property mband: int

Maximum number of bands.

property nband: int

Maximum number of bands.

property nelect: float

Number of electrons per unit cell

property nkpt: int

Number of k-points.

property kpoints

Iterable with the Kpoints.

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

OrderedDict with the convergence parameters.

plot_ebands(**kwargs) Any[source]

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

plot_ebands_with_edos(edos, **kwargs) Any[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() dict[source]

OrderedDict with the convergence parameters.

plot_phbands(**kwargs) Any[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: 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) str[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: str)[source]

Loads the object from a pickle file.

pickle_dump(filepath=None) str[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 figures with minimal input from the user. Relies on the ``yield_fig``s methods implemented by the subclass to generate such 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.

class abipy.core.mixins.SlotPickleMixin[source]

Bases: object

This mixin makes it possible to pickle/unpickle objects with __slots__

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()[source]

Args:

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

Bases: 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: int) MpStructures[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: DataFrame

pandas DataFrame with lattice parameters.

property coords_dataframe: 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'>) None[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) str[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: 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: 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, Madsen2006, Pickett1988].

class abipy.core.skw.ElectronInterpolator[source]

Bases: object

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

Loads the object from a pickle file.

pickle_dump(filepath: str) None[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: int

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.

plotly

Try to convert mpl figure to plotly.

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: 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: int = 0) str[source]

String representation.

eval_sk(spin, kpt, der1=None, der2=None) ndarray[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) ndarray[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) ndarray[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) ndarray[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) tuple[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)[source]

Finds matching structures on the Materials Project database.

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

  • 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).

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: ArrayLike | Lattice, species: Sequence[CompositionLike], coords: Sequence[ArrayLike] | np.ndarray, charge: float | None = None, validate_proximity: bool = False, to_unit_cell: bool = False, coords_are_cartesian: bool = False, site_properties: dict | None = None, labels: Sequence[str | None] | None = None, properties: dict | None = None)[source]

Bases: Structure, NotebookWriter

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

Inheritance Diagram

Inheritance diagram of Structure
classmethod as_structure(obj: Any) Structure[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.

  • ASE atoms.

classmethod from_file(filepath: str, primitive: bool = False, sort: bool = False) Structure[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: str) Structure[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.

Returns: abipy.core.structure.Structure object.

classmethod from_cod_id(cod_id: int, primitive: bool = False, **kwargs) Structure[source]

Queries the COD database 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) Structure[source]

Returns structure from ASE Atoms.

Parameters:

atoms – ASE Atoms object

property n_elems: int

Number of types of atoms.

to_ase_atoms(calc=None)[source]

Returns ASE Atoms object from structure and attach calculator calc.

get_phonopy_atoms()[source]

Convert a pymatgen Structure object to a PhonopyAtoms object.

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

Creates a molecule in a periodic box of lengths acell in 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)) Structure[source]

Creates an atom in a periodic box of lengths acell in 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) Structure[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: float, species, primitive=True, units='ang', **kwargs) Structure[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) Structure[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) Structure[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) Structure[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: str) Structure[source]

Initialize Structure from a string with Abinit input variables.

classmethod from_abivars(*args, **kwargs) Structure[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 species 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) str[source]

String representation. Extends the implementation of the superclass.

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

Output the structure to a file or string.

Parameters:
  • filename (PathLike) – 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.

  • 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”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”. Non-case sensitive.

  • **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:

String representation of molecule in given format. If a filename

is provided, the same string is written to the file.

Return type:

str

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]

Write CIF file with symmetries as detected by spglib.

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.

  • ret_string – True to return string.

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

Returns a dictionary with the ABINIT variables.

Parameters:
  • znucl. (enforce_znucl[ntypat] = Enforce this value for)

  • 1. (enforce_typat[natom] = Fortran conventions. Start to count from)

property latex_formula: str

e.g., Fe2O3 is transformed to Fe$_{2}$O$_{3}$.

Type:

LaTeX formatted formula

property poscar_string: str

String with the structure in POSCAR format.

property abi_string: str

String with the ABINIT input associated to this structure.

get_abi_string(fmt: str = 'abinit_input') str[source]

Return a string with the ABINIT input associated to this structure. Two formats are available. fmt=”abinit_input” corresponds to the standard format with typat, znucl. fmt=”abicell” is the lightweight format that uses xred_symbols This format can be used to include the structure in the input via the structure “abivars:FILE” syntax.

get_panel(with_inputs=True, **kwargs)[source]

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

Parameters:

with_inputs – True if tabs for generating input files should be shown.

get_conventional_standard_structure(international_monoclinic=True, symprec=0.001, angle_tolerance=5) Structure[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) Structure[source]
new_with_uptri_lattice(mode='uptri') Structure[source]

Build and return new structure with cell matrix in upper triangle form. In the cell matrix, lattice vectors are along rows.

Parameters:

wanted. (mode="lowtri" if lower triangle cell matrix is)

refine(symprec=0.001, angle_tolerance=5) Structure[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) Structure[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) Structure[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.

spget_lattice_type(symprec=0.001, angle_tolerance=5) str[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) str[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) None[source]

AbinitSpaceGroup setter.

property has_abi_spacegroup: bool

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) dict[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) None[source]

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

has_zero_dynamical_quadrupoles()[source]

Dynamical quadrupoles are nonzero in all noncentrosymmetric crystals, but also in centrosymmetric ones if one or more atoms are placed at noncentrosymmetric sites.

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) ndarray[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() Structure[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() dict[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() dict[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) Structure[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) dict[source]

Return a dict 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) dict[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

Try to convert mpl figure to plotly.

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). hovermode 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.

template Plotly template. See https://plotly.com/python/templates/
[“plotly”, “plotly_white”, “plotly_dark”, “ggplot2”,

“seaborn”, “simple_white”, “none”]

Default is None that is the default template is used.

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

Try to convert mpl figure to plotly.

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

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

Parameters:
  • fig – plotly figure 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: plotly.graph_objects.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). hovermode 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.

template Plotly template. See https://plotly.com/python/templates/
[“plotly”, “plotly_white”, “plotly_dark”, “ggplot2”,

“seaborn”, “simple_white”, “none”]

Default is None that is the default template is used.

plot_xrd(wavelength='CuKa', symprec=0, debye_waller_factors=None, two_theta_range=(0, 90), annotate_peaks=True, ax=None, **kwargs) Any[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.

  • symbol (debye_waller_factors ({element) – 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.

plotly

Try to convert mpl figure to plotly.

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.

plotly

Try to convert mpl figure to plotly.

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: str = 'cif', **kwargs) str[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 in fractional coordinates.

  • eta – Scaling factor in Ang

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

displace_one_site(index, displ, eta, frac_coords: bool = True, to_unit_cell: bool = False) Structure[source]

Displace one site 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 the site so that the maximum atomic displacement is 0.001 Angstrom.

Parameters:
  • index – Index of the site (starts at 0).

  • displ – Displacement vector in fractional coordinates.

  • eta – Scaling factor in Ang

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

  • to_unit_cell (bool) – Whether new sites are transformed to unit cell

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

make_doped_supercells(scaling_matrix, replaced_atom, dopant_atom)[source]

Returns a list doped supercell structures, one for each non-equivalent site of the replaced atom.

Parameters:
  • scaling_matrix

    A scaling matrix for transforming the lattice vectors. Has to be all integers. Several options are possible: a. A full 3x3 scaling matrix defining the linear combination of the old lattice vectors.

    E.g., [[2,1,0],[0,3,0],[0,0,1]] generates a new structure with lattice vectors a’ = 2a + b, b’ = 3b, c’ = c where a, b, and c are the lattice vectors of the original structure.

    1. A sequence of three scaling factors. e.g., [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c.

    2. A number, which simply scales all lattice vectors by the same factor.

  • atom (replaced) – Symbol of the atom to be replaced (ex: ‘Sr’)

  • dopant_atom – Symbol of the dopant_atom (ex: ‘Eu’)

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) 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 input 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() array[source]

Returns the suggested value for the ABINIT variable kptbounds.

get_kpath_input_string(fmt: str = 'abinit', line_density: int = 10) str[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) AttrDict[source]

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

calc_ngkpt(nksmall) ndarray[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.

as_ngkpt(ngkpt) ndarray[source]

Flexible API to compute the ABINIT variable ngkpt using different approaches.

The following cases are supported:
  • If ngkpt is a 1D vector with 3 items, return ngkpt as-is.

  • If ngkpt is a positive float, interpret it as nksmall (a scaling factor for the k-point grid).

  • If ngkpt is a negative float, interpret it as the desired number of k-points per atom.

This method allows users to flexibly specify the k-point grid based on their preferred input format.

calc_shiftk(symprec=0.01, angle_tolerance=5) ndarray[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) float[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) list[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) str[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: 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: 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) str[source]

String representation.

is_symmorphic()[source]

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

property has_timerev: bool

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: int
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

site_symmetries Module

This module provides objects related to site symmetries

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

Bases: Has_Structure

property structure: Structure

abipy.core.structure.Structure object.

to_string(verbose=0) str[source]

String representation with verbosity level verbose.

get_wyckoff_dataframe(view='all', select_symbols=None, decimals=5, verbose=0) DataFrame[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) DataFrame[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) float[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