abipy.core package
Core objects.
Submodules
abipy.core.abinit_units module
This module defines constants and conversion factors matching those present in abinit that can be used when it is important to preserve consistency with the results produced by abinit.
- abipy.core.abinit_units.phfactor_ev2units(units)[source]
- Return conversion factor eV –> units for phonons (case-insensitive) - Return type:
 
- abipy.core.abinit_units.phunit_tag(units, unicode=False)[source]
- Mainly used for phonons. Return latex string from - units. If unicode is True, replace Latex superscript with unitcode.- Return type:
 
- abipy.core.abinit_units.wlabel_from_units(units, unicode=False)[source]
- Return latex string for phonon frequencies in - units.- Return type:
 
- abipy.core.abinit_units.phdos_label_from_units(units, unicode=False)[source]
- Return latex string for phonon DOS values in - units.- Return type:
 
abipy.core.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. 
- 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. 
- class abipy.core.atom.AtomicConfiguration(Z, states)[source]
- Bases: - object- Atomic configuration of an all-electron atom. - classmethod neutral_from_symbol(symbol)[source]
- Return type:
 - symbol: str or int
- Can be a chemical symbol (str) or an atomic number (int). 
 
 
- class abipy.core.atom.RadialFunction(name, rmesh, values)[source]
- Bases: - object- A RadialFunction has a name, a radial mesh and values defined on this mesh. - classmethod from_filename(filename, rfunc_name=None, cols=(0, 1))[source]
- Initialize the object reading data from filename (txt format). - Parameters:
- filename ( - str) – 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. 
 
- Return type:
 
 - property minmax_ridx: tuple[int, int]
- Returns the indices of the values in a list with the maximum and minimum value. 
 - property spline
- Cubic spline. 
 - property roots
- Return the zeros of the spline. 
 - integral()[source]
- Cumulatively integrate y(x) using the composite trapezoidal rule. - Return type:
- 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 
 
 
 
- class abipy.core.atom.RadialWaveFunction(nlk, name, rmesh, values)[source]
- Bases: - RadialFunction- Extends - RadialFunctionadding info on the set of quantum numbers. and methods specialized for electronic wavefunctions.
abipy.core.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  - 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 
- rhoc – rhoc 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 performed 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.
 
- mesh3d_dist_gridpoints: based on 
- 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. 
 - property total_rhor: ndarray
- numpy.ndarraywith the total density in real space on the FFT mesh.
 - property total_rhog: ndarray
- numpy.ndarraywith the total density in G-space.
 - property magnetization_field: ndarray
- numpy.ndarraywith 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 
 
 - property magnetization
- Magnetization field integrated over the unit cell. Scalar if collinear, vector with (mx, my, mz) components if non-collinear. 
 - property nelect_updown: tuple
- Tuple with the number of electrons in the up/down channel. Return (None, None) if non-collinear. 
 - property zeta: ndarray
- numpy.ndarraywith Magnetization(r) / total_density(r)
 - export_to_cube(filename, spin='total')[source]
- Export real space density to CUBE file - filename.- Return type:
 
 - classmethod from_cube(filename, spin='total')[source]
- Read real space density to CUBE file - filename. Return new- Densityinstance.
 - to_chgcar(filename=None)[source]
- Convert a - Densityobject into a- Chgarobject. If- filenameis not None, density is written to this file in Chgar format- Return type:
- Chgcar
- Returns:
- Chgcarinstance.
 - 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. 
 
- class abipy.core.fields.VxcPotential(nspinor, nsppol, nspden, datar, structure, iorder='c')[source]
- Bases: - _PotentialField- XC Potential. - Inheritance Diagram  - 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  - netcdf_name = 'vhartree'
 - latex_label = 'vh $[eV/A^3]$'
 
abipy.core.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, etc.
- class abipy.core.func1d.Function1D(mesh, values)[source]
- Bases: - object- Immutable object representing a real|complex function of real variable. - classmethod from_constant(mesh, const)[source]
- Build a constant function from the mesh and the scalar - const- Return type:
 
 - classmethod from_func(func, mesh)[source]
- Initialize the object from a callable. - Example:
- Function1D.from_func(np.sin, mesh=np.arange(1,10)) 
- Return type:
 
 - as_dict()[source]
- Makes Function1D obey the general json interface used in pymatgen for easier serialization. - Return type:
 
 - classmethod from_dict(d)[source]
- Reconstruct object from the dictionary in MSONable format produced by as_dict. - Return type:
 
 - classmethod from_file(path, comments='#', delimiter=None, usecols=(0, 1))[source]
- Initialize an instance by reading data from path (txt format) see also - np.loadtxt()- Parameters:
- path – Path to the file containing data. 
- comments – The character used to indicate the start of a comment; default: ‘#’. 
- delimiter – str, optional The string used to separate values. By default, this is any whitespace. 
- usecols – sequence, optional. Which columns to read, with 0 being the first. For example, usecols = (1,4) will extract data from the 2nd, and 5th columns. 
 
- Return type:
 
 - property mesh: ndarray
- numpy.ndarraywith the mesh points
 - property real: Function1D
- Return new - Function1Dwith the real part of self.
 - property imag: Function1D
- Return new - Function1Dwith the imaginary part of self.
 - conjugate()[source]
- Return new - Function1Dwith the complex conjugate.- Return type:
 
 - abs()[source]
- Return - Function1Dwith the absolute value.- Return type:
 
 - to_file(path, fmt='%.18e', header='')[source]
- Save data in a text file. Use format fmr. A header is added at the beginning. - Return type:
 
 - 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. 
 - property dx: ndarray
- numpy.ndarrayof len(self) - 1 elements giving the distance between two consecutive points of the mesh, i.e. dx[i] = ||x[i+1] - x[i]||.
 - find_mesh_index(value)[source]
- Return the index of the first point in the mesh whose value is >= value -1 if not found - Return type:
 
 - finite_diff(order=1, acc=4)[source]
- Compute the derivatives by finite differences. - Parameters:
- Return type:
- Returns:
- Function1Dinstance with the derivative.
 
 - integral(start=0, stop=None)[source]
- Cumulatively integrate y(x) from start to stop using the composite trapezoidal rule. - Return type:
- Returns:
- Function1Dwith \(\int y(x) dx\)
 
 - property spline
- Cubic spline with s=0 
 - property spline_roots
- Zeros of the spline. 
 - spline_on_mesh(mesh)[source]
- Spline the function on the given mesh, returns - Function1Dobject.- Return type:
 
 - 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 
 
 
 - property integral_value
- Compute \(\int f(x) dx\). 
 - plot_ax(ax, exchange_xy=False, normalize=False, xfactor=1, yfactor=1, *args, **kwargs)[source]
- Helper function to plot self on axis ax. - Parameters:
- ax – - matplotlib.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 “-” - Return type:
- Returns:
- List of lines added. 
 
 - plot(ax=None, **kwargs)[source]
- Plot the function with matplotlib. - Parameters:
- ax – - matplotlib.axes.Axesor 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.svg” 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: Default: False - Return type:
 
 - 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 authentication. 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. 
 
abipy.core.globals module
Global variables used to initialize AbiPy environment in notebooks.
- abipy.core.globals.in_notebook()[source]
- True if we are running inside a jupyter notebook (and enable_notebook has been called). - Return type:
 
- abipy.core.globals.enable_notebook(with_seaborn=True)[source]
- Set - in_notebookflag to True and activate seaborn settings for notebooks if- with_seaborn.- Return type:
 
- abipy.core.globals.get_abinb_workdir()[source]
- Return the absolute path of the scratch directory used to produce and save temporary files when we are runnning inside a jupyter notebook. - Note - Due to web-browser policy, files used in the notebook must be within the current working directory. - Return type:
 
- abipy.core.globals.abinb_mkstemp(force_abinb_workdir=False, use_relpath=False, **kwargs)[source]
- Invoke mkstep with kwargs, return the (fd, name) of the temporary file. kwargs are passed to - mkstempexcept for- dirif 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. 
 
- Return type:
 - _, filename = abinb_mkstep(suffix="." + ext, text=True) 
abipy.core.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.ndarraywith the G-vectors in reduced coordinates.
 - index(gvec)[source]
- return the index of the G-vector - gvecin self. Raises: ValueError if the value is not present.- Return type:
 
 - zeros(dtype=<class 'float'>, extra_dims=())[source]
- Returns new zeroed 1D - numpy.ndarray.- The type can be set with the - dtypekeyword. Extra dimensions can be added with- extra_dims.- Return type:
 
 - czeros(extra_dims=())[source]
- New zeroed 1D complex - numpy.ndarray.- Return type:
 
 - empty(dtype=<class 'float'>, extra_dims=())[source]
- Returns new uninitialized 1D - numpy.ndarray.- The type can be set with the - dtypekeyword. Extra dimensions can be added with- extra_dims.- Return type:
 
 - cempty(extra_dims=())[source]
- Returns new uninitialized 1D complex - numpy.ndarray.- Return type:
 
 
abipy.core.irrepsdb module
abipy.core.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:
- obj – - Kpointor 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.Latticeobject describing the Reciprocal lattice.
 - property weight
- Weight of the k-point. 0.0 if the weight is not defined. 
 - property cart_coords
- Cartesian coordinates of the k-point. 
 - property name
- Name of the k-point. None if not available. 
 - property on_border
- 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”) 
 - classmethod as_kpoint(obj, lattice)[source]
- Convert obj into a - Kpointinstance.- Parameters:
- obj – - Kpointinstance or array-like with the reduced coordinates.
- lattice – - pymatgen.core.lattice.Latticeobject defining the reciprocal lattice.
 
 
 - is_gamma(allow_umklapp=False, atol=None)[source]
- Return True if this the gamma point. - Parameters:
- allow_umklapp – True if umklapp G-vectors are allowed. 
- atol – Absolute tolerance for k-point comparison (used only if umklapp). 
 
- Return type:
 
 - property norm
- Norm of the kpoint. 
 - wrap_to_ws()[source]
- Returns a new - abipy.core.kpoints.Kpointin the Wigner-Seitz zone.
 - wrap_to_bz()[source]
- Returns a new - abipy.core.kpoints.Kpointin the first unit cell.
 - compute_star(symmops, wrap_tows=True)[source]
- Return the star of the kpoint (tuple of - abipy.core.kpoints.Kpointobjects).- Return type:
 
 
- 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.Kpointobjects. Essentially consists of base methods implementing the sequence protocol and helper functions. The subclasses- abipy.core.kpoints.Kpathand- abipy.core.kpoints.IrredZoneprovide specialized methods to operate on k-points representing a path or list of points in the IBZ, respectively. This object is immutable.- Inheritance Diagram  - Error
- alias of - KpointsError
 - classmethod from_dict(d)[source]
- Makes Kpoints obey the general json interface used in pymatgen for easier serialization. 
 - as_dict()[source]
- Makes Kpoints obey the general json interface used in pymatgen for easier serialization. 
 - property reciprocal_lattice
- pymatgen.core.lattice.Latticeobject defining the reciprocal lattice.
 - index(kpoint)[source]
- Returns: the first index of kpoint in self. - Raises: ValueError if not found. - Return type:
 
 - get_all_kindices(kpoint)[source]
- Return numpy array with indexes of all the k-point Accepts: - abipy.core.kpoints.Kpointinstance or integer.
 - find_closest(obj)[source]
- Find the closest k-point in the list (not necessarily equal). - Parameters:
- obj – Fractional coordinates or - abipy.core.kpoints.Kpointinstance.
- Returns:
- (ind, kpoint, dist) - where - indis the index in self of the closest k-point.- kpointis the- abipy.core.kpoints.Kpointinstance of index- ind. dist is the distance between- objand- kpoint.
 
 - property mpdivs_shifts
- 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.ndarrayof shape (len(self), 3)
 - get_cart_coords()[source]
- Cartesian coordinates of the k-point as - numpy.ndarrayof shape (len(self), 3)
 - property weights: ndarray
- numpy.ndarraywith the weights of the k-points.
 - check_weights()[source]
- Check if weights are normalized to one. Raises: ValueError if Weights are not normalized. - Return type:
 
 - 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 - KpointListinstance.
 - to_array()[source]
- Returns a - numpy.ndarray[nkpy, 3] with the fractional coordinates.
 
- 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  - 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  - classmethod from_names(structure, knames, line_density=20)[source]
- Generate normalized K-path from list of k-point labels. - Parameters:
- structure – - abipy.core.structure.Structureobject.
- knames – List of strings with the k-point labels. 
- line_density ( - int) – Number of points used to sample the smallest segment of the path
 
- Return type:
 
 - 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:
- structure – - abipy.core.structure.Structureobject.
- 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 ( - int) – Number of points used to sample the smallest segment of the path. If 0, use list of k-points given in vertices_names
 
- Return type:
 
 - to_string(verbose=0, title=None, **kwargs)[source]
- String representation. - Parameters:
- verbose – Verbosity level. Default: 0 
- Return type:
 
 - property ds: ndarray
- numpy.ndarrayof 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
 - property versors: tuple
- Tuple of len(self) - 1 elements with the versors connecting k[i] to k[i+1]. 
 - property lines: list
- 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 kpath.lines:
- vals_on_line = eigens[spin, line, band] 
 
 - property frac_bounds: ndarray
- Numpy array of shape [M, 3] with the vertices of the path in frac coords. 
 - property cart_bounds: ndarray
- Numpy array of shape [M, 3] with the vertices of the path in frac coords. 
 - find_points_along_path(cart_coords, dist_tol=1e-12)[source]
- Find points in - cart_coordslying on the path with distance less than dist_tol. See find_points_along_path function for API.
 
- 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  - classmethod from_ngkpt(structure, ngkpt, shiftk, kptopt=1, spin_mode='unpolarized', verbose=0)[source]
- Build an IrredZone instance from (ngkpt, shift) by calling Abinit to get the list of IBZ k-points. - Return type:
 
 
- abipy.core.kpoints.rc_list(mp, sh, pbc=False, order='bz')[source]
- Returns a - numpy.ndarraywith 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.ndarraywith 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
 
- abipy.core.kpoints.find_points_along_path(cart_bounds, cart_coords, dist_tol)[source]
- Find points in - cart_coordslying 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. 
abipy.core.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. 
 - property inv_vectors
 - zeros(dtype=<class 'float'>, extra_dims=())[source]
- Returns new zeroed 3D array for this domain. - The type can be set with the - dtypekeyword. Extra dimensions can be added with- extra_dims.- Return type:
 
 - empty(dtype=<class 'float'>, extra_dims=())[source]
- Returns new uninitialized 3D - numpy.ndarrayfor this domain.- The type can be set with the - dtypekeyword. Extra dimensions can be added with- extra_dims.
 - cempty(extra_dims=())[source]
- Returns new uninitialized 3D complex - numpy.ndarrayfor this domain.- Return type:
 
 - random(dtype=<class 'float'>, extra_dims=())[source]
- Returns random real - numpy.ndarrayfor this domain with val in [0.0, 1.0).- Return type:
 
 - crandom(extra_dims=())[source]
- Returns random complex - numpy.ndarrayfor this domain with val in [0.0, 1.0).- Return type:
 
 - reshape(arr)[source]
- Reshape the array arr defined on the FFT box. - Returns - numpy.ndarraywith 4 dimensions (?, nx, ny, nz) where ?*nx*ny*nz == arr.size- Return type:
 
 - property gvecs: ndarray
- 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.GSpherethat are k-centered and enclosed by a sphere whose radius is defined by ecut.
 - property gmods: ndarray
- [ng] - numpy.ndarraywith \(|G|\)
 - property rpoints: ndarray
- numpy.ndarraywith the points in real space in reduced coordinates.
 - i_closest_gridpoints(points)[source]
- Given a list of points, this function return a - numpy.ndarraywith the indices of the closest gridpoint.- Return type:
 
 
abipy.core.mixins module
Mixin classes
- class abipy.core.mixins.AbinitNcFile(filepath)[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)[source]
- Build object from a binary string with the netcdf data. Useful for implementing GUIs in which widgets returns binary data. - Return type:
 
 - abstract property params: dict
- dictionary with the convergence parameters used to construct - pandas.DataFrame.
 - get_dims_dataframe(as_dict=False, path='/')[source]
- Return type:
 - Return: pandas.DataFramewith the dimensions defined in the path group.
- or dict if as_dict is True. 
 
 
- class abipy.core.mixins.Has_Structure[source]
- Bases: - object- Mixin class for - abipy.core.mixins.AbinitNcFilecontaining crystallographic data.- abstract property structure
- Returns the - abipy.core.structure.Structureobject.
 - plot_bz(**kwargs)[source]
- Gives the plot (as a matplotlib object) of the symmetry line path in the Brillouin Zone. - Return type:
 
 - show_bz(**kwargs)
- Gives the plot (as a matplotlib object) of the symmetry line path in the Brillouin Zone. - Return type:
 
 - export_structure(filepath)[source]
- Export the structure on file. - returns: - abipy.iotools.visualizer.Visualizerinstance.
 - visualize_structure_with(appname)[source]
- Visualize the crystalline structure with the specified visualizer. - See - abipy.iotools.visualizer.Visualizerfor the list of applications and formats supported.
 
- class abipy.core.mixins.Has_ElectronBands[source]
- Bases: - object- Mixin class for - abipy.core.mixins.AbinitNcFilecontaining electron data.- abstract property ebands
- Returns the - abipy.electrons.ebands.ElectronBandsobject.
 - property kpoints
- Iterable with the Kpoints. 
 - property tsmear
 - plot_ebands(**kwargs)[source]
- Plot the electron energy bands. See the - ElectronBands.plot()for the signature.- Return type:
 
 - plot_ebands_with_edos(edos, **kwargs)[source]
- Plot the electron energy bands with DOS. See the - ElectronBands.plot_with_edos()for the signature.- Return type:
 
 - yield_ebands_figs(**kwargs)[source]
- Generates a predefined list of matplotlib figures with minimal input from the user. 
 
- class abipy.core.mixins.Has_PhononBands[source]
- Bases: - object- Mixin class for - abipy.core.mixins.AbinitNcFilecontaining phonon data.- abstract property phbands
- Returns the - abipy.dfpt.phonons.PhononBandsobject.
 - plot_phbands(**kwargs)[source]
- Plot the electron energy bands. See the - PhononBands.plot()for the signature.””- Return type:
 
 - 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. 
 
- 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. - abstractmethod write_notebook(nbpath=None)[source]
- Write a jupyter notebook to nbpath. If nbpath is None, a temporaty 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) - Return type:
 
 - pickle_dump(filepath=None)[source]
- Save the status of the object in pickle format. If filepath is None, a temporary file is created. - Return: The name of the pickle file. - Return type:
 
 - abstractmethod yield_figs(**kwargs)[source]
- This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiopen.py or 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_figmethods 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. 
 
 
abipy.core.pauli module
Pauli matrices and operations associated to them.
- class abipy.core.pauli.Pauli[source]
- Bases: - object- Pauli matrices - project_mats(mats)[source]
- Project a batch of 2x2 Hermitian matrices onto the Pauli basis. - This method computes the coefficients of the given matrices in the Pauli basis (identity, sigma_x, sigma_y, sigma_z) for each 2x2 matrix in the input array. The input array must have shape […, 2, 2], where the trailing dimensions represent individual 2x2 matrices. - Parameters:
- mats (np.ndarray) – An array of shape […, 2, 2], where each trailing 2x2 subarray is a matrix to be projected onto the Pauli basis. 
- Returns:
- An array of shape […, 4], where the last dimension contains the coefficients (a_0, a_x, a_y, a_z) for the identity matrix, sigma_x, sigma_y, and sigma_z, respectively. 
- Return type:
- np.ndarray 
 - Examples - >>> import numpy as np >>> mats = np.array([[[1, 0], [0, 1]], [[0, 1], [1, 0]]]) # Shape (2, 2, 2) >>> result = project_mats(mats) >>> print(result) # Shape (2, 4) [[ 0.5 0. 0. 0.5] [ 0. 0.5 0. 0. ]] 
 - mats_from_projections(coefficients)[source]
- Reconstruct 2x2 matrices from their Pauli basis coefficients. - This method takes an array of coefficients (a_0, a_x, a_y, a_z) and reconstructs the corresponding 2x2 matrices using the Pauli basis (identity, sigma_x, sigma_y, sigma_z). - Parameters:
- coefficients (np.ndarray) – An array of shape […, 4], where the last dimension contains the coefficients (a_0, a_x, a_y, a_z) for the identity matrix, sigma_x, sigma_y, and sigma_z, respectively. 
- Returns:
- An array of shape […, 2, 2], where each trailing 2x2 matrix is reconstructed from the input coefficients. 
- Return type:
- np.ndarray 
 - Examples - >>> coefficients = np.array([[0.5, 0, 0, 0.5], [0, 0.5, 0, 0]]) # Shape (2, 4) >>> result = reconstruct_mats(coefficients) >>> print(result) # Shape (2, 2, 2) [[[1. 0.] [0. 1.]] [[0. 1.] [1. 0.]]] 
 
abipy.core.perl module
abipy.core.release module
Release data for the AbiPy project.
abipy.core.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.
- 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)[source]
- Filter structures by space group number. Return new MpStructures object. - Return type:
 
 - 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 structure_dataframes
- Pandas dataframes constructed from self.structures. 
 - print_results(fmt='abivars', verbose=0, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]
- Print pandas dataframe, structures using format fmt, and data to file file. fmt is automaticall set to cif if structure is disordered. Set fmt to None or empty string to disable structure output. - Return type:
 
 
- class abipy.core.restapi.MpStructures(structures, ids, data=None)[source]
- Bases: - DatabaseStructures- Store the results of a query to the Materials Project database.  - dbname = 'Materials Project'
 
- class abipy.core.restapi.CodStructures(structures, ids, data=None)[source]
- Bases: - DatabaseStructures- Store the results of a query to the COD database [Grazulis2011].  - dbname = 'COD'
 - property dataframe: DataFrame
- pandas.DataFrameconstructed. Essentially geometrical info and space groups found by spglib as COD API is rather limited.
 
abipy.core.site_symmetries module
This module provides objects related to site symmetries
- class abipy.core.site_symmetries.SiteSymmetries(structure)[source]
- Bases: - Has_Structure- property structure: Structure
- abipy.core.structure.Structureobject.
 - get_wyckoff_dataframe(view='all', select_symbols=None, decimals=5, verbose=0)[source]
- Find Wyckoff positions. - Parameters:
- view 
- select_symbols 
- decimals – Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point. 
- verbose – Verbosity level. 
 
- Return type:
 - Return - pandas.DataFramewith cartesian tensor components as columns and (inequivalent) sites along the rows.
 - get_tensor_rank2_dataframe(view='all', select_symbols=None, decimals=5, verbose=0)[source]
- Use site symmetries to detect independent 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 type:
 - Return - pandas.DataFramewith cartesian tensor components as columns and (inequivalent) sites along the rows.
 
abipy.core.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- Abstract class for band structure interpolator. - symprec = 1e-05
 - angle_tolerance = -1.0
 - occtype = 'insulator'
 - use_cache = True
 - 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: 
 - 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. 
- ax – - matplotlib.axes.Axesor None if a new figure should be created.
- fontsize – Legend and title fontsize. 
 
- Return type:
 - 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.svg” 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: Default: False 
 - abstractmethod 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, output 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:
- 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 
 
 
- 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. - 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, output gradient is stored in der1[nband, 3]. 
- der2 – If not None, output Hessian is der2[nband, 3, 3]. 
 
- Return type:
- Returns:
- oeigs[nband] 
 
 - get_stark(kpt)[source]
- Return the star function for k-point kpt. - Parameters:
- kpt – K-point in reduced coordinates. 
- Return type:
- Returns:
- complex array of shape [self.nr] 
 
 
abipy.core.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.Structureobject.
- Returns:
- MpStructuresobject with
- structures: List of matching structures and list of Materials Project identifier. 
 
 
- abipy.core.structure.mp_search(chemsys_formula_id)[source]
- 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:
- MpStructuresobject 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 evaluate to False if no match is found. 
 
- abipy.core.structure.cod_search(formula, primitive=False)[source]
- Connect to the COD database. Get list of structures corresponding to a chemical formula - Parameters:
- Returns:
- CodStructuresobject 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 evaluate to False if no match is found 
 
- class abipy.core.structure.Structure(lattice, species, coords, charge=None, validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None, labels=None, properties=None)[source]
- Bases: - Structure,- NotebookWriter- Extends - pymatgen.core.structure.Structurewith Abinit-specific methods.- Inheritance Diagram  - classmethod as_structure(obj)[source]
- Convert obj into a - abipy.core.structure.Structure. Accepts:- Structure object. 
- Filename 
- Dictionaries (JSON format or dictionaries with abinit variables). 
- Objects with a - structureattribute.
- ASE atoms. 
 - Return type:
 
 - classmethod from_file(filepath, primitive=False, sort=False)[source]
- Reads a structure from a file. For example, anything ending in a “cif” is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR, Netcdf and pymatgen’s JSON serialized structures. - Netcdf files supported:
- All files produced by ABINIT with info of the crystalline geometry HIST.nc, in this case the last structure of the history is returned. 
 - Parameters:
- Return type:
 - Returns: - abipy.core.structure.Structureobject
 - classmethod from_mpid(material_id)[source]
- Get a Structure corresponding to a material_id. - Parameters:
- Return type:
 - Returns: - abipy.core.structure.Structureobject.
 - classmethod from_cod_id(cod_id, primitive=False, **kwargs)[source]
- Queries the COD database for a structure by id. Returns - abipy.core.structure.Structureobject.- Parameters:
- Return type:
 - Returns: - abipy.core.structure.Structureobject.
 - classmethod from_ase_atoms(atoms)[source]
- Returns structure from ASE Atoms. - Parameters:
- atoms – ASE Atoms object 
- Return type:
 
 - to_ase_atoms(calc=None)[source]
- Returns ASE Atoms object from structure and attach calculator calc. 
 - classmethod boxed_molecule(pseudos, cart_coords, acell=(10, 10, 10))[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 
 
- Return type:
 
 - classmethod boxed_atom(pseudo, cart_coords=(0, 0, 0), acell=(10, 10, 10))[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) 
 
- Return type:
 
 - classmethod bcc(a, species, primitive=True, units='ang', **kwargs)[source]
- Build a primitive or a conventional bcc crystal structure. - Parameters:
- a – Lattice parameter (Angstrom if units is not given) 
- species – Chemical species. See __init__ method of - pymatgen.core.structure.Structure
- primitive – if True a primitive cell will be produced, otherwise a conventional one 
- units – Units of input lattice parameters e.g. “bohr”, “pm” 
- kwargs – All keyword arguments accepted by - pymatgen.core.structure.Structure.
 
- Return type:
 
 - classmethod fcc(a, species, primitive=True, units='ang', **kwargs)[source]
- Build a primitive or a conventional fcc crystal structure. - Parameters:
- a ( - float) – 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
 
- Return type:
 
 - classmethod zincblende(a, species, units='ang', **kwargs)[source]
- Build a primitive zincblende crystal structure. - Parameters:
- a – Lattice parameter (Angstrom if units is not given) 
- species – Chemical species. See __init__ method of - pymatgen.Structure
- units – Units of input lattice parameters e.g. “bohr”, “pm” 
- kwargs – All keyword arguments accepted by - pymatgen.Structure
 
- Return type:
 - structure = Structure.zincblende(a, ["Zn", "S"]) 
 - classmethod rocksalt(a, species, units='ang', **kwargs)[source]
- Build a primitive fcc crystal structure. - Parameters:
- a – Lattice parameter (Angstrom if units is not given) 
- units – Units of input lattice parameters e.g. “bohr”, “pm” 
- species – Chemical species. See __init__ method of - pymatgen.Structure
- kwargs – All keyword arguments accepted by - pymatgen.Structure
 
- Return type:
 - structure = Structure.rocksalt(a, ["Na", "Cl"]) 
 - classmethod ABO3(a, species, units='ang', **kwargs)[source]
- Peroviskite structures. - Parameters:
- a – Lattice parameter (Angstrom if units is not given) 
- species – Chemical species. See __init__ method of - pymatgen.Structure
- units – Units of input lattice parameters e.g. “bohr”, “pm” 
- kwargs – All keyword arguments accepted by - pymatgen.Structure
 
- Return type:
 
 - classmethod from_abistring(string)[source]
- Initialize Structure from a string with Abinit input variables. - Return type:
 
 - classmethod from_abivars(*args, **kwargs)[source]
- Build a - abipy.core.structure.Structureobject from a dictionary with ABINIT variables.- 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, ) - xredcan be replaced with- xcartor- xangst.- Return type:
 
 - 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)[source]
- String representation. Extends the implementation of the superclass. - Return type:
 
 - to(fmt=None, filename=None, **kwargs)[source]
- Output the structure to a string (and to a file when filename is given). - 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 specified, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”. Case insensitive. 
- **kwargs – Kwargs pass thru to relevant methods. This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric CIFs. 
 
- Returns:
- String representation of structure in given format. If a filename
- is provided, the same string is written to the file. 
 
- Return type:
 
 - compare(other, atol=1e-06)[source]
- Compare two structures with absolute tolerance atol. Return: bool indicating if structures are equal and string with error message, if any. 
 - 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)[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) 
 
- Return type:
 
 - property latex_formula: str
- e.g., Fe2O3 is transformed to Fe$_{2}$O$_{3}$. - Type:
- LaTeX formatted formula 
 
 - get_abi_string(fmt='abinit_input')[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. - Return type:
 
 - 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)[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 - Return type:
 
 - new_with_uptri_lattice(mode='uptri')[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) 
- Return type:
 
 - refine(symprec=0.001, angle_tolerance=5)[source]
- Get the refined structure based on detected symmetry. The refined structure is a conventional cell setting with atoms moved to the expected symmetry positions. - Returns: Refined structure. - Return type:
 
 - abi_sanitize(symprec=0.001, angle_tolerance=5, primitive=True, primitive_standard=False, atol=1e-12)[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 - symprecis None and angle_tolerance is None, no structure refinement is performed.
- 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 
- atol – Components whose absolute value are less than atol are set to zero. Use None or zero to disable this step. 
 
- Return type:
 
 - get_oxi_state_decorated(**kwargs)[source]
- Use - pymatgen.analysis.bond_valence.BVAnalyzerto estimate oxidation states Return oxidation state decorated structure. This currently works only for ordered structures only.- Parameters:
- kwargs – Arguments passed to BVAnalyzer 
- Return type:
- 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)[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 
 - spget_equivalent_atoms(symprec=0.001, angle_tolerance=5, printout=False)[source]
- Call spglib to find the inequivalent atoms and build symmetry tables. - Parameters:
- Returns:
- namedtuple(irred_pos, eqmap, spgdata) with the following attributes:- * irred_pos: array giving the position of the i-th irred atom in the structure. The number of irred atoms is len(irred_pos). * eqmap: Mapping irred atom position --> list with positions of symmetrical atoms. * wyckoffs: Wyckoff letters. * wyck_mult: Array with Wyckoff multiplicity. * wyck_labels: List of labels with Wyckoff multiplicity and letter e.g. 3a * site_labels: Labels for each site in computed from element symbol and wyckoff positions e.g Si2a * spgdata: spglib dataset with additional data reported by spglib_. - Example:
- for irr_pos in irred_pos:
- eqmap[irr_pos] # List of symmetrical positions associated to the irr_pos atom. 
 
 
 
 - spget_summary(symprec=0.001, angle_tolerance=5, site_symmetry=False, verbose=0)[source]
- Return string with full information about crystalline structure i.e. space group, point group, wyckoff positions, equivalent sites. 
 - property abi_spacegroup
- AbinitSpaceGroupinstance 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.
 - spgset_abi_spacegroup(has_timerev, overwrite=False)[source]
- Call spglib to find the spacegroup of the crystal, create new - AbinitSpaceGroupobject and store it in- self.abi_spacegroup.- Parameters:
 - 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). 
 - property site_symmetries
- Object with SiteSymmetries. 
 - abiget_spginfo(tolsym=None, pre=None)[source]
- Call Abinit to get spacegroup information. Return dictionary with e.g. {‘bravais’: ‘Bravais cF (face-center cubic)’, ‘spg_number’: 227, ‘spg_symbol’: ‘Fd-3m’}. - Parameters:
- tolsym – Abinit tolsym input variable. None corresponds to the default value. 
- pre – Keywords in dictionary are prepended with this string 
 
- Return type:
 
 - print_neighbors(radius=2.0)[source]
- Get neighbors for each atom in the unit cell, out to a distance - radiusin Angstrom Print results.- Return type:
 
 - property has_zero_dynamical_quadrupoles
- Dynamical quadrupoles are nonzero in all noncentrosymmetric crystals, but also in centrosymmetric ones if one or more atoms are placed at noncentrosymmetric sites. 
 - property hsym_kpath
- Returns an instance of - pymatgen.symmetry.bandstructure.HighSymmKpath. (Database of high symmetry k-points and high symmetry lines).
 - property hsym_kpoints
- abipy.core.kpoints.KpointListobject with the high-symmetry K-points.
 - get_kcoords_from_names(knames, cart_coords=False)[source]
- Return numpy array with the fractional coordinates of the high-symmetry k-points listed in knames. - Parameters:
- knames – List of strings with the k-point labels. 
- cart_coords – True if the - coordsdataframe should contain Cartesian coordinates instead of Reduced coordinates.
 
- Return type:
 
 - property hsym_stars: list
- List of - abipy.core.kpoints.KpointStarobjects. Each star is associated to one of the special k-points present in the pymatgen database.
 - get_sorted_structure_z()[source]
- Order the structure according to increasing Z of the elements - Return type:
 
 - findname_in_hsym_stars(kpoint)[source]
- Returns the name of the special k-point, None if kpoint is unknown. 
 - get_symbol2indices()[source]
- Return a dictionary mapping chemical symbols to numpy array with the position of the atoms. - Return type:
 - Example - MgB2 –> {Mg: [0], B: [1, 2]} 
 - get_symbol2coords()[source]
- Return a dictionary mapping chemical symbols to a [ntype_symbol, 3] numpy array with the fractional coordinates. - Return type:
 
 - 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. 
 - norm(coords, space='r', frac_coords=True)[source]
- Compute the norm of vector(s) either in real space or reciprocal space. 
 - scale_lattice(new_volume)[source]
- Return a new - abipy.core.structure.Structurewith volume new_volume by performing a scaling of the lattice vectors so that length proportions and angles are preserved.- Return type:
 
 - magnetic_supercell(scaling_matrix, magmom=None)[source]
- Make a supercell. Allow sites outside the unit cell. - Parameters:
- scaling_matrix ( - int|- Sequence[- int]) –- A scaling matrix for transforming the lattice vectors. Has to be all integers. Several options are possible: - A sequence of three scaling factors. e.g. [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c. 
- A number, which simply scales all lattice vectors by the same factor. 
 
- Return type:
- Returns:
- Supercell structure. Note that a Structure is always returned, even if the input structure is a subclass of Structure. This is to avoid different arguments signatures from causing problems. If you prefer a subclass to return its own type, you need to override this method in the subclass. 
 
 - get_dict4pandas(symprec=0.01, angle_tolerance=5.0, with_spglib=True)[source]
- Return a dict with the most important structural parameters useful to construct pandas DataFrames. - 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). 
 
 - get_symb2coords_dataframe(with_cart_coords=False)[source]
- Return dictionary mapping element symbol to DataFrame with atomic positions in cartesian coordinates. - Parameters:
- with_cart_coords – True if Cartesian coordinates should be added as well. 
- Return type:
 
 - 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.svg” 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: Default: False 
 - plotly(**kwargs)[source]
- Plot structure in 3D with plotly. Return plotly Figure. See plot_structure for kwargs - Keyword arguments controlling the display of the figure: - kwargs - Meaning - title - Title of the plot (Default: None). - show - True to show the figure (default: True). - 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 authentication. 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:
 - 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.svg” 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: Default: False 
 - 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:
 - 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 authentication. 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)[source]
- Use pymatgen - XRDCalculatorto 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 - Axesor None if a new figure should be created.
 
- Return type:
 - 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.svg” 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: Default: False 
 - yield_figs(**kwargs)[source]
- This function generates a predefined list of matplotlib figures with minimal input from the user. 
 - export(filename, visu=None, verbose=1)[source]
- Export the crystalline structure to file - filename.- Parameters:
- filename (str) – String specifying the file path and the file format. The format is defined by the file extension. filename=”prefix.xsf”, for example, will produce a file in XSF format. An empty prefix, e.g. “.xsf” makes the code use a temporary file. 
- visu – - abipy.iotools.visualizer.Visualizersubclass. 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.Visualizerfor the list of applications and formats supported.
- verbose – Verbosity level 
 
 - Returns: - Visualizerinstance.
 - 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_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.svg” 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: Default: False 
 - 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.Visualizerfor the list of applications and formats supported.
 - convert(fmt='cif', **kwargs)[source]
- Return string with the structure in the given format fmt Options include: “abivars”, “cif”, “xsf”, “poscar”, “siesta”, “wannier90”, “cssr”, “json”. - Return type:
 
 - 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 maximum 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=True, to_unit_cell=False)[source]
- Displace one site of the structure along the displacement vector displ. - The displacement vector is first rescaled so that the maximum 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:
- Return type:
 
 - 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 of 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_new = 2a + b, b_new = 3b, c_new = c where a, b, and c are the lattice vectors of the original structure. b) A sequence of three scaling factors. e.g., [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c. c) 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 ( - str) – Symbol of the dopant_atom (ex: ‘Eu’)
 
- Return type:
 
 - get_trans_vect(scale_matrix)[source]
- Returns the translation vectors for a given scale matrix. - Parameters:
- scale_matrix – Scale matrix defining the new lattice vectors in term of the old ones 
 - Return: the translation vectors 
 - write_vib_file(xyz_file, qpoint, displ, do_real=True, frac_coords=True, scale_matrix=None, max_supercell=None)[source]
- Write into the file descriptor xyz_file the positions and displacements of the atoms - Parameters:
- xyz_file – file_descriptor 
- qpoint – qpoint to be analyzed 
- displ – eigendisplacements to be analyzed 
- do_real – True if you want to get only real part, False means imaginary part 
- frac_coords – True if the eigendisplacements are given in fractional coordinates 
- scale_matrix – Scale matrix for supercell 
- max_supercell – Maximum size of supercell vectors with respect to primitive cell 
 
- Return type:
 
 - 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()[source]
- Returns the suggested value for the ABINIT variable - kptbounds.- Return type:
- array
 
 - get_kpath_input_string(fmt='abinit', line_density=10)[source]
- Return string with input variables for band-structure calculations in the format used by code fmt. Use line_density points for the smallest segment (if supported by code). - Return type:
 
 - calc_ksampling(nksmall, symprec=0.01, angle_tolerance=5)[source]
- Return the k-point sampling from the number of divisions - nksmallto be used for the smallest reciprocal lattice vector.- Return type:
- AttrDict
 
 - calc_ngkpt(nksmall)[source]
- Compute the ABINIT variable - ngkptfrom the number of divisions used for the smallest lattice vector.
 - as_ngkpt(ngkpt)[source]
- Flexible API to compute the ABINIT variable - ngkptusing different approaches.- Return type:
 - 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)[source]
- Find the values of - shiftkand- nshiftkappropriated 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. - Return type:
- Returns:
- Suggested value of shiftk. 
 
 - num_valence_electrons(pseudos)[source]
- Returns the number of valence electrons. - Parameters:
- pseudos – List of - pymatgen.io.abinit.pseudos.Pseudoobjects or list of filenames.
- Return type:
 
 
- 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_structurefor 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 - coordsdataframe should contain Cartesian coordinates instead of Reduced coordinates.
 
- Returns:
- namedtuple with two - pandas.DataFramenamed- latticeand- coords- latticecontains the lattice parameters.- coordsthe atomic positions.. The list of structures is available in the- structuresentry.
 - dfs = dataframes_from_structures(files) dfs.lattice dfs.coords for structure in dfs.structures: print(structure) 
abipy.core.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. - 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. 
 - property isE
- True if it is the identity 
 - property order
- Order of the rotation. 
 - property root_inv
 - property det
- Return the determinant of a symmetry matrix mat[3,3]. It must be +-1 
 - property trace
- The trace of the rotation matrix 
 - property is_proper
- True if proper rotation 
 - property isI
- True if self is the inversion operation. 
 - property name
 
- 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 - Return type:
 
 - classmethod from_structure(structure, has_timerev=True, symprec=1e-05, angle_tolerance=5)[source]
- Takes a - abipy.core.structure.Structureobject. Uses spglib to perform various symmetry finding operations.- Parameters:
- structure – - abipy.core.structure.Structureobject.
- 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. 
 - property is_symmorphic: bool
- True if there’s at least one operation with non-zero fractional translation. 
 - 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 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 - SymmOpinstances.
 
 - 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 - Kpointobject.
- Returns:
- LittleGroupobject.
 
 - 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:
 
 

