Index 
  Example 
  StaticPlots 
  InteractivePlots 
  SpinProjectedSurfaces 
  StructureIO 
  Widgets 
  MainAPI● 

Download POSACR

download_structure[source]

download_structure(formula, mp_id=None, max_sites=None, min_sites=None, api_key=None, save_key=False)

Download structure data from Materials project website.

  • Parameters
    • formula: chemical formula of the material.
    • mp_id: Materials project id of material.
    • max_sites: maximum number of sites in structure to download.
    • min_sites: minimum number of sites in structure to download.

      max_sites and min_sites are used to filter the number of sites in structure, or use mp_id to download a specific structure.

  • One Time API Key
    • api_key: API key from Materials project websit, if you use save_key=True, never required again.
    • save_key: Save API key to file. You can save any time of key or device changed.
  • Return List of Structure data containing attribute/method cif/export_poscar, write_cif etc.

Useful Functions

set_dir[source]

set_dir(path)

work in some directory and come back

get_child_items[source]

get_child_items(path='E:\\Research\\pivotpy', depth=None, recursive=True, include=None, exclude=None, filesOnly=False, dirsOnly=False)

  • Returns selected directories/files recursively from a parent directory.
  • Parameters
    • path : path to a parent directory, default is "."
    • depth : int, subdirectories depth to get recursively, default is None to list all down.
    • recursive : If False, only list current directory items, if True,list all items recursively down the file system.
    • include: Default is None and includes everything. String of patterns separated by | to keep, could be a regular expression.
    • exclude: Default is None and removes nothing. String of patterns separated by | to drop,could be a regular expression.
    • filesOnly : Boolean, if True, returns only files.
    • dirsOnly : Boolean, if True, returns only directories.
  • Returns
    • GLOB : Tuple (children,parent), children is list of selected directories/files and parent is given path. Access by index of by get_child_items().{children,path}.

transform_color[source]

transform_color(arr, s=1, c=1, b=0, mixing_matrix=None)

  • Color transformation such as brightness, contrast, saturation and mixing of an input color array. c = -1 would invert color,keeping everything else same.
  • Parameters
    • arr: input array, a single RGB/RGBA color or an array with inner most dimension equal to 3 or 4. e.g. [[[0,1,0,1],[0,0,1,1]]].
    • c : contrast, default is 1. Can be a float in [-1,1].
    • s : saturation, default is 1. Can be a float in [-1,1]. If s = 0, you get a gray scale image.
    • b : brightness, default is 0. Can be a float in [-1,1] or list of three brightnesses for RGB components.
    • mixing_matrix: A 3x3 matrix to mix RGB values, such as pp.color_matrix.

Recoloring Rainmeter

interpolate_data[source]

interpolate_data(x, y, n=10, k=3)

  • Returns interpolated xnew,ynew. If two points are same, it will add 0.1*min(dx>0) to compensate it.
  • Parameters

    • x: 1D array of size p,
    • y: ndarray of size pqr,....
    • n: Number of points to add between two given points.
    • k: Polynomial order to interpolate.
  • Only axis 0 will be interpolated. If you want general interploation, use from scipy.interpolate import make_interp_spline, BSpline

  • General Usage: K(p),E(p,q) input from bandstructure.

    • Knew,Enew= interpolate_data(K,E,n=10,k=3). cubic interploation

get_kpath[source]

get_kpath(*patches, n=5, weight=None, ibzkpt=None, outfile=None, rec_basis=None)

Generate list of kpoints along high symmetry path. Options are write to file or return KPOINTS list. It generates uniformly spaced point with input n as just a scale factor of number of points per unit length. You can also specify custom number of kpoints in an interval by putting number of kpoints as 4th entry in left kpoint.

  • Parameters
    • *ptaches : Any number of disconnected patches where a single patch is a dictionary like {'label': (x,y,z,[N]), ...} where x,y,z is high symmetry point and
            N (optional) is number of points in current inteval, points in a connected path patch are at least two i.e. `{'p1':[x1,y1,z1],'p2':[x2,y2,z2]}`.
            A key of a patch should be string reperenting the label of the high symmetry point. A key that starts with '_' is ignored, so you can add points without high symmetry points as well.
    • n : int, number per length of body diagonal of rec_basis, this makes uniform steps based on distance between points.
    • weight : Float, if None, auto generates weights.
    • ibzkpt : Path to ibzkpt file, required for HSE calculations.
    • outfile: Path/to/file to write kpoints.
    • rec_basis: Reciprocal basis 3x3 array to use for calculating uniform points.

If outfile = None, KPONITS file content is printed.

str2kpath[source]

str2kpath(kpath_str, n=5, weight=None, ibzkpt=None, outfile=None, rec_basis=None)

Get Kpath from a string of kpoints (Line-Mode like). Useful in Terminal.

  • Parameters

    • kpath_str: str, a multiline string similiar to line mode of KPOINTS, initial 4 lines are not required.
      • If you do not want to label a point, label it as 'skip' and it will be removed.
      • You can add an interger at end of a line to customize number of points in a given patch.
      • Each empty line breaks the path, so similar points before and after empty line are useless here.
    • n : int, number per length of body diagonal of rec_basis, this makes uniform steps based on distance between points.
    • weight : Float, if None, auto generates weights.
    • ibzkpt : Path to ibzkpt file, required for HSE calculations.
    • outfile: Path/to/file to write kpoints.
    • rec_basis: Reciprocal basis 3x3 array to use for calculating uniform points.
  • Example

    str2kpath('''0 0 0 !$\Gamma$ 3 0.25 0.25 0.25 !L''') Automatically generated using PivotPy with HSK-INDS = [0, -1], LABELS = ['$\Gamma$', 'L'], SEG-INDS = [] 3 Reciprocal Lattice 0.0000000000 0.0000000000 0.0000000000 0.333333 0.1250000000 0.1250000000 0.1250000000 0.333333 0.2500000000 0.2500000000 0.2500000000 0.333333

fancy_quiver3d[source]

fancy_quiver3d(X, Y, Z, U, V, W, ax=None, C='r', L=0.7, mutation_scale=10, **kwargs)

Plots 3D arrows on a given ax. See FancyArrowPatch.

  • Parameters
    • X, Y, Z : 1D arrays of coordinates of arrows' tail point.
    • U, V, W : 1D arrays of dx,dy,dz of arrows.
    • ax: 3D axes, if not given, auto created.
    • C : 1D colors array mapping for arrows. Could be one color.
    • L : 1D linwidths array mapping for arrows. Could be one linewidth.
    • mutation_scale: Arrow head width/size scale. Default is 10.
    • kwargs: FancyArrowPatch's keyword arguments excluding positions,color, lw and mutation_scale, shrinkA, shrinkB which are already used. An important keyword argument is arrowstyle which could be '->','-|>', their inverted forms and many more. See on matplotlib.

rotation[source]

rotation(angle_deg, axis_vec)

Get a scipy Rotation object at given angle_deg around axis_vec. Usage: rot = rotation(60,[0,0,1]) rot.apply([1,1,1]) [-0.3660254 1.3660254 1.] #give this

to_basis[source]

to_basis(basis, coords)

Transforms coordinates of points (relative to othogonal basis) into basis space.

  • Parameters
    • basis : Non-orthogonal basis of real or reciprocal space.
    • points: 3D points relative to cartesian axes, such as KPOINTS and Lattice Points.

to_R3[source]

to_R3(basis, points)

Transforms coordinates of points (relative to non-othogonal basis) into orthogonal space.

  • Parameters
    • basis : Non-orthogonal basis of real or reciprocal space.
    • points: 3D points relative to basis, such as KPOINTS and Lattice Points.

Note: Do not use this function if points are Cartesian or provide identity basis.

periodic_table[source]

periodic_table()

Display colorerd elements in periodic table.

generate_summary[source]

generate_summary(paths_list=None)

split_vasprun[source]

split_vasprun(path=None)

  • Splits a given vasprun.xml file into a smaller _vasprun.xml file plus _set[1,2,3,4].txt files which contain projected data for each spin set.
  • Parameters
    • path: path/to/vasprun.xml file.
  • Output
    • _vasprun.xml file with projected data.
    • _set1.txt for projected data of colinear calculation.
    • _set1.txt for spin up data and _set2.txt for spin-polarized case.
    • _set[1,2,3,4].txt for each spin set of non-colinear calculations.

xml2dict[source]

xml2dict(xmlnode_or_filepath)

Convert xml node or xml file content to dictionary. All output text is in string format, so further processing is required to convert into data types/split etc.

  • The only paramenter xmlnode_or_filepath is either a path to an xml file or an xml.etree.ElementTree.Element object.
  • Each node has tag,text,attr,nodes attributes. Every text element can be accessed via xml2dict()['nodes'][index]['nodes'][index]... tree which makes it simple.

iplot2html[source]

iplot2html(fig, filename=None, out_string=False, modebar=True)

  • Writes plotly's figure as HTML file or display in IPython which is accessible when online. It is different than plotly's fig.to_html as it is minimal in memory. If you need to have offline working file, just use fig.write_html('file.html') which will be larger in size.
  • Parameters
    • fig : A plotly's figure object.
    • filename : Name of file to save fig. Defualt is None and show plot in Colab/Online or return hrml string.
    • out_string: If True, returns HTML string, if False displays graph if possible.

plt2html[source]

plt2html(plt_fig=None, transparent=True, dash_html=None)

  • Returns base64 encoded Image to display in notebook or HTML or plotly's dash_html_components.Img object.
  • Parameters
    • plt_fig : Matplotlib's figure instance, auto picks as well.
    • transparent: True of False for fig background.
    • dash_html : Default is None which results in an image display in jupyter notebook.
      • If True, returns html.Img object for plotly's dash.
      • If False, returns object to embed in HTML DOM.

plt2text[source]

plt2text(plt_fig=None, width=144, vscale=0.96, colorful=True, invert=False, crop=False, outfile=None)

Displays matplotlib figure in terminal as text. You should use a monospcae font like Cascadia Code PL to display image correctly. Use before plt.show().

  • Parameters
    • plt_fig: Matplotlib's figure instance. Auto picks if not given.
    • width : Character width in terminal, default is 144. Decrease font size when width increased.
    • vscale : Useful to tweek aspect ratio. Default is 0.96 and prints actual aspect in Cascadia Code PL. It is approximately 2*width/height when you select a single space in terminal.
    • colorful: Default is False, prints colored picture if terminal supports it, e.g Windows Terminal.
    • invert : Defult is False, could be useful for grayscale image.
    • crop : Default is False. Crops extra background, can change image color if top left pixel is not in background, in that case set this to False.
    • outfile: If None, prints to screen. Writes on a file.

show[source]

show(transparent=False)

Displays all available figures in browser without blocking terminal

savefig[source]

savefig(filename, dpi=600, **kwargs)

Save matplotlib's figure while handling existing files. kwargs are passed to plt.savefig

append_axes[source]

append_axes(ax, position='right', size=0.2, pad=0.1, sharex=False, sharey=False, **kwargs)

Append an axes to the given ax at given position |top|right|left|bottom|. Useful for adding custom colorbar. kwargs are passed to mpl_toolkits.axes_grid1.make_axes_locatable.append_axes. Returns appended axes.

join_axes[source]

join_axes(ax1, ax2, **kwargs)

Join two axes together. Useful for adding custom colorbar on a long left axes of whole figure. Apply tight_layout() before calling this function. kwargs are passed to fig.add_axes.

add_colorbar[source]

add_colorbar(ax, cmap_or_clist=None, N=256, ticks=None, ticklabels=None, vmin=None, vmax=None, cax=None, tickloc='right', vertical=True, digits=2, fontsize=8)

  • Plots colorbar on a given axes. This axes should be only for colorbar. Returns None or throws ValueError for given colors.
  • Parameters

    • ax : Matplotlib axes for which colorbar will be added.
    • cmap_or_clist: List/array of colors in or colormap's name. If None (default), matplotlib's default colormap is plotted.
    • N : int, number of color points Default 256.
    • ticks : List of tick values to show on colorbar. To turn off, give [].
    • ticklabels : List of labels for ticks.
    • vmin,vmax : Minimum and maximum values. Only work if ticks are given.
    • cax : Matplotlib axes for colorbar. If not given, one is created.
    • tickloc : Default 'right'. Any of ['right','left','top','bottom'].
    • digits : Number of digits to show in tick if ticklabels are not given.
    • vertical : Boolean, default is Fasle.
    • fontsize : Default 8. Adjustable according to plot space.
  • Returns

    • cax : Matplotlib axes for colorbar, you can customize further.

color_cube[source]

color_cube(ax, colormap='brg', loc=(1, 0.4), size=0.2, N=7, labels=['s', 'p', 'd'], color='k', fontsize=10)

Color-mapped hexagon that serves as a legend for splot_rgb_lines

color_wheel[source]

color_wheel(ax=None, xy=(1, 1), scale=0.12, rlim=(0.2, 1), N=256, colormap=None, ticks=[0.16666666666666666, 0.5, 0.8333333333333334], labels=['s', 'p', 'd'], showlegend=True)

  • Returns cax i.e. color wheel axes.
  • Parameters
    • ax : Axes on which color wheel will be drawn. Auto created if not given.
    • xy : (x,y) of center of wheel.
    • scale : Scale of the cax internally generated by color wheel.
    • rlim : Values in [0,1] interval, to make donut like shape.
    • N : Number of segments in color wheel.
    • colormap : Matplotlib's color map name. fallbacks to hsv.
    • ticks : Ticks in fractions in interval [0,1].
    • labels : Ticks labels.
    • showlegend: True or False.

add_legend[source]

add_legend(ax=None, colors=[], labels=[], styles='solid', widths=0.7, anchor=(0, 1), ncol=3, loc='lower left', fontsize='small', frameon=False, **kwargs)

  • Adds custom legeneds on a given axes,returns None.
  • Parameters
    • ax : Matplotlib axes.
    • colors : List of colors.
    • labels : List of labels.
    • styles : str or list of line styles.
    • widths : str or list of line widths.

kwargs are passed to plt.legend. Given arguments like anchor,ncol etc are preferred.

add_text[source]

add_text(ax=None, xs=0.25, ys=0.9, txts='[List]', colors='r', transform=True, **kwargs)

  • Adds text entries on axes, given single string or list.
  • Parameters
    • xs : List of x coordinates relative to axes or single coordinate.
    • ys : List of y coordinates relative to axes or single coordinate.
    • txts : List of strings or one string.
    • colors: List of x colors of txts or one color.
    • transform: Dafault is True and positions are relative to axes, If False, positions are in data coordinates.

kwargs are passed to plt.text.

class VasprunApp[source]

VasprunApp(height=610)

Display a GUI for vasp output analysis. self.theme_colors can be used to edit custom theme.

Usage Example

import pivotpy as pp
va = pp.VasprunApp()
va.set_options(
    cache_data = False, #Turn off cache globally.
    mode = 'bands', #Change graph mode from 'markers' to 'bands'. Setting it to 'lines' is not recommended in live graph, it could hang all UI.
    interp_nk = dict(n = 2, k = 2), #Add 2 points between data points with quadratic interpolation.
)
va.show() #Displays App and do work!
va.theme_colors = pp.dark_colors #Set theme to dark externally and edit dictionary values to make your own theme
va.splot(**kwargs) #Get matplotlib plot of current data.
va.df #After you do some analysis and hit `Project Summary` button, get DataFrame or directly by.df
va.fig #Get current fig in Notebook cell.

VasprunApp.show[source]

VasprunApp.show()

VasprunApp.splot[source]

VasprunApp.splot(**kwargs)

Returns matplotlib Axes.kwargs are passed to splot_rgb_lines or splot_dos_lines based on current figure. kwargs should exclude whatever inside self._input and path_evr

VasprunApp.iplot[source]

VasprunApp.iplot(**kwargs)

Returns a detached interactive Figure. kwargs are passed to iplot_rgb_lines or iplot_dos_lines based on current figure. kwargs should exclude whatever inside self._input and path_evr

VasprunApp.set_theme_colors[source]

VasprunApp.set_theme_colors(theme_colors)

Get self.theme_colors and after edit set back

class KPathApp[source]

KPathApp(path='POSCAR')

View and trace path on BZ.

  • Usage

    ka = KPathApp() ka.show() #Display app ka.splot() #get matplotlib figure

KPathApp.show[source]

KPathApp.show()

KPathApp.splot[source]

KPathApp.splot(text_kws={}, plot_kws={}, **kwargs)

Same as pp.splot_bz except it also plots path on BZ.

  • text_kws: dict of keyword arguments for plt.text
  • plot_kws: dict of keyword arguments for plt.plot kwargs are passed to pp.splot_bz

KPathApp.iplot[source]

KPathApp.iplot()

Returns disconnected current plotly figure

KPathApp.get_kpath[source]

KPathApp.get_kpath(n=5, weight=None, ibzkpt=None, outfile=None)

See Docs of pp.str2kpath for details.

class SpinDataFrame[source]

SpinDataFrame(*args, path=None, bands=[0], elements=[[0]], orbs=[[0]], scale_data=False, elim=None, skipk=None, data=None, **kwargs) :: DataFrame

Spin data from vasprun.xml is converted to a dataframe.

  • Parameters:

    • path: path to vasprun.xml or auto picks in current directory.
    • bands: list of band indices [zero based here], In output data frame you will see corresponding band number based on full data.
    • elements: list of elements to plot. inner list contains ions indices. Can leave empty to discard projection data.
    • orbs: list of orbitals to plot. inner list contains orbitals indices. Can leave empty to discard projection data
    • scale_data: if True, spin data is scaled to -1 to 1.
    • skipk: if not None, auto skipped unnecessary k-points.
    • elim: if not None, filtered out unnecessary bands.
    • data: if not None, data is loaded from given data/pickle/json/dict and validated. Many other parameters are ignored when data is given.
  • Returns:

    • SpinDataFrame: dataframe with colums as k-points, eigenvalues[with fermi energy subtracted], spin components projected over selected ions and orbtials.
  • Methods:

    • sliced: Slice data in a plane orthogonal to given column at given value.
    • masked: Mask data over a constant value in a given column. Useful for plotting fermi level/surface.
    • splot: plot data in a 2D plot.
    • splot3d: plot data in a 3D plot.
    • join/append/concat/+/+=: Append another SpinDataFrame to this one with same columns and copy metadata.
    • send_metadata: Copy metadata from this to another SpinDataFrame, some methods may not carry over metadata, useful in that case.
    • get_data: Return data as collection of numpy arrays with kpoints already sent to BZ. Use .to_json() to export to json for plotting in other libraries/languages like Mathematica.

      All other methods are inherited from pd.DataFrame. If you apply some method that do not pass metadat, then use send_metadata to copy metadata to traget SpinDataFrame.

SpinDataFrame.splot[source]

SpinDataFrame.splot(*args, arrows=[], every=1, norm=1, marker='H', ax=None, quiver_kws={}, shift=0, **kwargs)

Plot energy in 2D with/without arrows.

  • Parameters:
    • *args: 3 or 4 names of columns, representing [X,Y,Energy,[Anything]], from given args, last one is colormapped. If kwargs has color, that takes precedence.
    • arrows: 2 or 3 names of columns, representing [U,V,[color]]. If quiver_kws has color, that takes precedence.
    • every: every nth point is plotted as arrow.
    • norm: normalization factor for size of arrows.
    • marker: marker to use for scatter, use s as another argument to change size.
    • ax: matplotlib axes to plot on (defaults to auto create one).
    • quiver_kws: these are passed to matplotlib.pyplot.quiver.
    • shift: A number or a list of three numbers that will be added to kpoints before any other operation.

**kwargs are passed to matplotlib.pyplot.scatter.

  • Returns:
    • ax: matplotlib axes. It has additinal method colorbar to plot colorbar from most recent plot.

See examples at https://massgh.github.io/pivotpy/

SpinDataFrame.splot3d[source]

SpinDataFrame.splot3d(*args, arrows=[], every=1, norm=1, marker='H', ax=None, quiver_kws={'arrowstyle': '-|>', 'size': 1}, shift=0, **kwargs)

Plot energy in 3D with/without arrows.

  • Parameters:
    • *args: 3, 4 or 5 names of columns, representing [X,Y,[Z or Energy],Energy, [Anything]], out of given args, last one is color mapped. if kwargs has color, that takes precedence.
    • arrows: 3 or 4 names of columns, representing [U,V,W,[color]]. If color is not given, magnitude of arrows is color mapped. If quiver_kws has color, that takes precedence.
    • every: every nth point is plotted as arrow.
    • norm: normalization factor for size of arrows.
    • marker: marker to use for scatter, use s as another argument to change size.
    • ax: matplotlib 3d axes to plot on (defaults to auto create one).
    • quiver_kws: these are passed to pivotpy.fancy_quiver3d.
    • shift: A number or a list of three numbers that will be added to kpoints before any other operation.

**kwargs are passed to matplotlib.pyplot.scatter.

  • Returns:
    • ax: matplotlib 3d axes. It has additinal method colorbar to plot colorbar from most recent plot.

See examples at https://massgh.github.io/pivotpy/

SpinDataFrame.masked[source]

SpinDataFrame.masked(column, value, tol=0.01, n=None, band=None, method='linear')

Mask dataframe with a given value, using a tolerance. If n is given, (band should also be given to avoid multivalued interpolation error) data values are interpolated to grid of size (l,m,n) where n is longest side. n could be arbirarily large as mask will filter out data outside the tolerance.

SpinDataFrame.sliced[source]

SpinDataFrame.sliced(column='kz', value=0)

Slice data in a plane orthogonal to given column at given value

Paser Text Files

parse_text[source]

parse_text(path, dtype=float, delimiter='\\s+', include=None, exclude='#', raw=False, fix_format=True, start=0, nlines=None, count=-1, new_shape=None, cols=None, old_shape=None, slice_rows=None)

  • Reads a sliced array from txt,csv type files and return to array. Also manages if columns lengths are not equal and return 1D array. It is faster than loading whole file into memory. This single function could be used to parse EIGENVAL, PROCAR, DOCAR and similar files with just a combination of exclude, include,start,stop,step arguments.
  • Parameters
    • path: Path/to/file to be parsed.
    • dtype: float by default. Data type of output array, it is must have argument.
    • start,nlines: The indices of lines to start reading from and number of lines after start respectively. Both could be None or int, while start could be a list to read slices from file provided that nlines is int. The spacing between adjacent indices in start should be equal to or greater than nlines as pointer in file do not go back on its own. These parameters are not required if slice_rows and old_shape are given.

      Note: start should count comments if exclude is None.

    • count: np.size(output_array) = nrows x ncols, if it is known before execution, performance is increased.
    • delimiter: Default is \s+. Could be any kind of delimiter valid in numpy and in the file.
    • cols: List of indices of columns to pick. Useful when reading a file like PROCAR which e.g. has text and numbers inline. This parameter is in output of slice_data.
    • include: Default is None and includes everything. String of patterns separated by | to keep, could be a regular expression.
    • exclude: Default is '#' to remove comments. String of patterns separated by | to drop,could be a regular expression.
    • raw : Default is False, if True, returns list of raw strings. Useful to select cols.
    • fix_format: Default is True, it sepearates numbers with poor formatting like 1.000-2.000 to 1.000 2.000 which is useful in PROCAR. Keep it False if want to read string literally.
    • new_shape : Tuple of shape Default is None. Will try to reshape in this shape, if fails fallbacks to 2D or 1D. Not required if slice_rows and old_shape are given.
    • old_shape: It is required when you need to pick blocks of data from rows.
        columns should be last entry, like (2,2,3) means 3 columns and two different indexed blocks are there.
        Only works if `slice_rows` is given too.
    • slice_rows: It is required when you need to pick blocks of data from rows.
        [(0,1),(0,1)] will pick lines at index 0,1,3,4 if first dimension has size 3. It is like N1*i+j for N1=3.
        General formula to pick rows is `inner_block_index + inner_block_size*second_block_index + inner_most_size*second_block_size*third_block_index + ...`
        `i_1 + N_1*i_2 + N_1*N_2*i_3 + ...` where i_1 is inner most index.
        Only works if `old_shape` is given too.
  • Examples

    parse_text('path/to/PROCAR',start=3,include='k-point',cols=[3,4,5])[:2] array([[ 0.125, 0.125, 0.125], [ 0.375, 0.125, 0.125]]) parse_text('path/to/EIGENVAL',start=7,exclude='E',cols=[1,2])[:2] array([[-11.476913, 1. ], [ 0.283532, 1. ]]) Note: Slicing a dimension to 100% of its data is faster than let say 80% for inner dimensions, so if you have to slice more than 50% of an inner dimension, then just load full data and slice after it.

print(parse_text('POSCAR',raw=True))
parse_text('POSCAR',start=8,cols=[0,1,2])
2.46803100000000
1.0000000000000000    0.0000000000000000    0.0000000000000000
-0.4999997974093519    0.8660251836382931    0.0000000000000000
0.0000000000000000    0.0000000000000000    8.1029342824300024
C
2
Selective Dynamics
Direct
0.3333330000000000   0.6666670000000000   0.0000000000000000   T T T
0.6666670000000000   0.3333330000000000   0.0000000000000000   F F F
array([[0.333333, 0.666667, 0.      ],
       [0.666667, 0.333333, 0.      ]])

class POSCAR[source]

POSCAR(path=None, content=None, data=None)

POSACR class to contain data and related methods, data is PoscarData, json/tuple file/string.

POSCAR.to_clipboard[source]

POSCAR.to_clipboard()

Writes POSCAR to clipboard (as implemented by pandas library) for copy in other programs such as vim.

POSCAR.copy[source]

POSCAR.copy()

Copy POSCAR object. It avoids accidental changes to numpy arrays in original object.

POSCAR.get_bz[source]

POSCAR.get_bz(loop=True, digits=8, primitive=False)

  • Return required information to construct first Brillouin zone in form of tuple (basis, normals, vertices, faces).
  • Parameters

    • loop : If True, joins the last vertex of a BZ plane to starting vertex in order to complete loop.
    • digits : int, rounding off decimal places, no effect on intermediate calculations, just for pretty final results.
    • primitive: Defualt is False and returns Wigner-Seitz cell, If True returns parallelipiped in rec_basis.
  • Attributes

    • basis : get_bz().basis, recprocal lattice basis.
    • normals : get_bz().normals, all vertors that are perpendicular BZ faces/planes.
    • vertices: get_bz().vertices, all vertices of BZ, could be input into ConvexHull for constructing 3D BZ.
    • faces : get_bz().faces, vertices arranged into faces, could be input to Poly3DCollection of matplotlib for creating BZ from faces' patches.
    • specials : get_bz().specials, Data with attributes coords,kpoints and near in on-one correspondence for high symmetry KPOINTS in recirprocal coordinates space. near gives indices of nearest special points around a vertex. All vertices with z > 0 are included.

POSCAR.set_bz[source]

POSCAR.set_bz(primitive=False, loop=True, digits=8)

Set BZ in primitive or regular shape. returns None, just set self.bz

POSCAR.get_cell[source]

POSCAR.get_cell(loop=True, digits=8)

See docs of get_bz, same except space is inverted and no factor of 2pi.

POSCAR.splot_bz[source]

POSCAR.splot_bz(ax=None, plane=None, color='blue', fill=True, vectors=True, v3=False, vname='b', colormap='plasma', light_from=(1, 1, 1), alpha=0.4)

  • Plots matplotlib's static figure.
  • Parameters
    • fill : True by defult, determines whether to fill surface of BZ or not.
    • color : color to fill surface and stroke color.
    • vectors : Plots basis vectors, default is True.
    • v3 : Plots 3rd vector as well. Only works in 2D and when vectors=True.
    • plane : Default is None and plots 3D surface. Can take 'xy','yz','zx' to plot in 2D.
    • ax : Auto generated by default, 2D/3D axes, auto converts in 3D on demand as well.
    • vname : Default is b for reciprocal space, can set a for plotting cell as after get_bz(get_bz().basis) you get real space lattice back if primitive=True both times.
    • colormap : If None, single color is applied, only works in 3D and fill=True. Colormap is applied along z.
    • light_from: Point from where light is thrown on BZ planes, default is (1,1,1). Only works on plane in 3D.
    • alpha : Opacity of filling in range [0,1]. Increase for clear viewpoint.
  • Returns
    • ax : Matplotlib's 2D axes if plane=None.
    • ax3d : Matplotlib's 2D axes if plane is given.

Tip: splot_bz(rec_basis,primitive=True) will plot cell in real space.

POSCAR.splot_kpath[source]

POSCAR.splot_kpath(vertex=0, knn_inds=None, labels=None, color='k', line_width=0.8, marker_size=10, marker_style='.', **labels_kwargs)

Plot k-path over existing BZ.

  • Parameters
    • vertex: vertex index nearby which to plot path. There are as many vertices as there are in BZ's shape.
    • knn_inds: list of indices of k nearest points e.g. [2,3,1] will trace path linking as 2-3-1. 0 is Gamma point and 1 is the selected vertex itself. Points are taken internally from BZ, you can see from self.bz.specials.
    • labels: list of labels for each k-point in same order as knn_inds.
    • color, line_width, marker_size, marker_style are passed to plt.plot.

labels_kwargs are passed to plt.text.

Tip: You can use this function multiple times to plot multiple/broken paths over same BZ.

POSCAR.splot_cell[source]

POSCAR.splot_cell(ax=None, plane=None, color='blue', fill=True, vectors=True, v3=False, vname='a', colormap='plasma', light_from=(1, 1, 1), alpha=0.4)

See docs of splot_bz, everything is same except space is inverted.

POSCAR.iplot_bz[source]

POSCAR.iplot_bz(fill=True, color='rgba(168,204,216,0.4)', background='rgb(255,255,255)', vname='b', special_kpoints=True, alpha=0.4, ortho3d=True, fig=None)

  • Plots interactive figure showing axes,BZ surface, special points and basis, each of which could be hidden or shown.
  • Parameters
    • fill : True by defult, determines whether to fill surface of BZ or not.
    • color : color to fill surface 'rgba(168,204,216,0.4)` by default.
    • background : Plot background color, default is 'rgb(255,255,255)'.
    • vname : Default is b for reciprocal space, can set a for plotting cell as after get_bz(get_bz().basis) you get real space lattice back if primitive=True both times.
    • special_kpoints : True by default, determines whether to plot special points or not.
    • alpha : Opacity of BZ planes.
    • ortho3d : Default is True, decides whether x,y,z are orthogonal or perspective.
    • fig : (Optional) Plotly's go.Figure. If you want to plot on another plotly's figure, provide that.
  • Returns
    • fig : plotly.graph_object's Figure instance.

Tip: iplot_bz(rec_basis,primitive=True) will plot cell in real space.

POSCAR.iplot_cell[source]

POSCAR.iplot_cell(fill=True, color='rgba(168,204,216,0.4)', background='rgb(255,255,255)', vname='a', alpha=0.4, ortho3d=True, fig=None)

See docs of iplot_bz, everything is same except space is iverted.

POSCAR.splot_lat[source]

POSCAR.splot_lat(plane=None, sizes=50, colors=None, colormap=None, bond_length=None, tol=0.01, bond_tol=0.001, eqv_sites=True, translate=None, line_width=1, edge_color=(1, 0.5, 0, 0.4), vectors=True, v3=False, light_from=(1, 1, 1), fill=False, alpha=0.4, ax=None, alpha_points=0.7)

Static plot of lattice.

  • Main Parameters
    • plane : Plane to plot. Either 'xy','xz','yz' or None for 3D plot.
    • sizes : Size of sites. Either one int/float or list equal to type of ions.
    • bond_length: Length of bond in fractional unit [0,1]. It is scaled to V^1/3 and auto calculated if not provides.
    • colors: Sequence of colors for each ion type. If None, automatically generated.
    • colormap: This is passed to splot_bz.
    • alpha_points: Opacity of points and bonds. Other parameters just mean what they seem to be.

Tip: Use plt.style.use('ggplot') for better 3D perception.

POSCAR.iplot_lat[source]

POSCAR.iplot_lat(sizes=10, colors=None, bond_length=None, tol=0.01, bond_tol=0.001, eqv_sites=True, translate=None, line_width=4, edge_color='black', fill=False, alpha=0.4, ortho3d=True, fig=None)

Interactive plot of lattice.

  • Main Parameters
    • sizes : Size of sites. Either one int/float or list equal to type of ions.
    • colors : Sequence of colors for each type. Automatically generated if not provided.
    • bond_length: Length of bond in fractional unit [0,1]. It is scaled to V^1/3 and auto calculated if not provides. Other parameters just mean what they seem to be.

POSCAR.write[source]

POSCAR.write(outfile=None, overwrite=False)

Write POSCAR data to file.

POSCAR.join[source]

POSCAR.join(other, direction='c', tol=0.01, system=None)

Joins two POSCARs in a given direction. In-plane lattice parameters are kept from poscar1 and basis of other parallel to direction is modified while volume is kept same.

  • Parameters
    • direction: The joining direction. It is general and can join in any direction along basis. Expect one of ['a','b','c'].
    • tol: Default is 0.01. It is used to bring sites near 1 to near zero in order to complete sites in plane. Vasp relaxation could move a point, say at 0.00100 to 0.99800 which is not useful while merging sites.
    • system: If system is given, it is written on top of file. Otherwise, it is infered from atomic species.

POSCAR.scale[source]

POSCAR.scale(scale=(1, 1, 1), tol=0.01)

Create larger/smaller cell from a given POSCAR. Can be used to repeat a POSCAR with integer scale values.

  • Parameters
    • scale: Tuple of three values along (a,b,c) vectors. int or float values. If number of sites are not as expected in output, tweak tol instead of scale. You can put a minus sign with tol to get more sites and plus sign to reduce sites.
    • tol: It is used such that site positions are blow 1 - tol, as 1 belongs to next cell, not previous one. Tip: scale = (2,2,2) enlarges a cell and next operation of (1/2,1/2,1/2) should bring original cell back. Caveat: A POSACR scaled with Non-integer values should only be used for visualization purposes, Not for any other opration such as making supercells, joining POSCARs.

POSCAR.rotate[source]

POSCAR.rotate(angle_deg, axis_vec)

Rotate a given POSCAR.

  • Parameters
    • path_poscar: Path/to/POSCAR or poscar data object.
    • angle_deg: Rotation angle in degrees.
    • axis_vec : (x,y,z) of axis about which rotation takes place. Axis passes through origin.

POSCAR.fix_sites[source]

POSCAR.fix_sites(tol=0.01, eqv_sites=False, translate=None)

Add equivalent sites to make a full data shape of lattice. Returns same data after fixing.

  • Parameters
    • tol : Tolerance value. Default is 0.01.
    • eqv_sites: If True, add sites on edges and faces. If False, just fix coordinates, i.e. pos > 1 - tol -> pos - 1, useful for merging poscars to make slabs.
    • translate: A number(+/-) or list of three numbers to translate in a,b,c directions.

POSCAR.translate[source]

POSCAR.translate(offset)

Translate sites of a PPSCAR. Usully a farction of integarers like 1/2,1/4 etc.

  • Parameters
    • offset: A number(+/-) or list of three numbers to translate in a,b,c directions.

POSCAR.repeat[source]

POSCAR.repeat(n, direction)

Repeat a given POSCAR.

  • Parameters
    • path_poscar: Path/to/POSCAR or poscar data object.
    • n: Number of repetitions.
    • direction: Direction of repetition. Can be 'a', 'b' or 'c'.

POSCAR.mirror[source]

POSCAR.mirror(direction)

Mirror a POSCAR in a given direction. Sometime you need it before joining two POSCARs

POSCAR.get_transform_matrix[source]

POSCAR.get_transform_matrix(target_basis)

Returns a transformation matrix that gives target_bsis when applied on basis of current lattice. Useful in transforming crystal structure.

POSCAR.transform[source]

POSCAR.transform(transform_matrix, repeat_given=[2, 2, 2], tol=0.01)

Transform a POSCAR with a given transformation matrix. Use get_transform_matrix to get transformation matrix from one basis to another. repeat_given is used to repeat the POSCAR before applying transformation matrix to include all possible sites in resultant cell.

POSCAR.transpose[source]

POSCAR.transpose(axes=[1, 0, 2])

Transpose a POSCAR by switching basis from [0,1,2] -> axes. By Default, x and y are transposed.

POSCAR.add_vaccum[source]

POSCAR.add_vaccum(thickness, direction, left=False)

Add vacuum to a POSCAR.

  • Parameters
    • thickness: Thickness of vacuum in Angstrom.
    • direction: Direction of vacuum. Can be 'a', 'b' or 'c'.
    • left: If True, vacuum is added to left of sites. By default, vacuum is added to right of sites.

POSCAR.add_atoms[source]

POSCAR.add_atoms(name, positions)

Add atoms with a name to a POSCAR at given positions in fractional coordinates.

POSCAR.convert[source]

POSCAR.convert(atoms_mapping, basis_factor)

Convert a POSCAR to a similar structure of other atomic types or same type with strained basis. atoms_mapping is a dictionary of {old_atom: new_atom} like {'Ga':'Al'} will convert GaAs to AlAs structure. basis_factor is a scaling factor multiplied with basis vectors, single value (useful for conversion to another type) or list of three values to scale along (a,b,c) vectors (useful for strained structures).

POSCAR.add_selective_dynamics[source]

POSCAR.add_selective_dynamics(a=None, b=None, c=None, show_plot=True)

Returns selective dynamics included POSCAR if input is given. By default, if a direction is not given, it turns ON with others.

  • Parameters

    • a, b, c: Arrays of shape (N,2) that contain ranges in fractional coordinates to turn selective dynamics on.
    • show_plot: Plots the selective dynamics included sites in fractional orthogonal space to have an idea quickly.
  • Usage

    • add_selective_dynamics(a = [(0,0.1),(0.9,1)]) will turn selective dynamics on for the first and last 10% of the unit cell in a-direction as T T T.
    • add_selective_dynamics(a = [(0,0.1),(0.9,1)], b = [(0,0.1),(0.9,1)]) will turn selective dynamics on for the first and last 10% of the unit cell in ab-plane in form of T T T, F T T and T F T whichever applies.

Returns POSCAR with selective dynamics included. You can write it to file or send to clipboard, but any other transformation will result in loss of selective dynamics information.

POSCAR.get_kmesh[source]

POSCAR.get_kmesh(*args, shift=0, weight=None, cartesian=False, ibzkpt=None, outfile=None, endpoint=True)

Note: Use pivotpy.POSCAR.get_kmesh to get k-mesh based on current POSCAR.

  • Generates uniform mesh of kpoints. Options are write to file, or return KPOINTS list.
  • Parameters
    • *args: 1 or 3 integers which decide shape of mesh. If 1, mesh points equally spaced based on data from POSCAR.
    • shift : Only works if cartesian = False. Defualt is 0. Could be a number or list of three numbers to add to interval [0,1].
    • weight : Float, if None, auto generates weights.
    • cartesian: If True, generates cartesian mesh.
    • ibzkpt : Path to ibzkpt file, required for HSE calculations.
    • outfile: Path/to/file to write kpoints.
    • endpoint: Default True, include endpoints in mesh at edges away from origin.

If outfile = None, KPOINTS file content is printed.

POSCAR.get_kpath[source]

POSCAR.get_kpath(*patches, n=5, weight=None, ibzkpt=None, outfile=None)

Generate list of kpoints along high symmetry path. Options are write to file or return KPOINTS list. It generates uniformly spaced point with input n as just a scale factor of number of points per unit length. You can also specify custom number of kpoints in an interval by putting number of kpoints as 4th entry in left kpoint.

  • Parameters
    • *ptaches : Any number of disconnected patches where a single patch is a dictionary like {'label': (x,y,z,[N]), ...} where x,y,z is high symmetry point and
            N (optional) is number of points in current inteval, points in a connected path patch are at least two i.e. `{'p1':[x1,y1,z1],'p2':[x2,y2,z2]}`.
            A key of a patch should be string reperenting the label of the high symmetry point. A key that starts with '_' is ignored, so you can add points without high symmetry points as well.
    • n : int, number per length of body diagonal of rec_basis, this makes uniform steps based on distance between points.
    • weight : Float, if None, auto generates weights.
    • ibzkpt : Path to ibzkpt file, required for HSE calculations.
    • outfile: Path/to/file to write kpoints.

If outfile = None, KPONITS file content is printed.

POSCAR.str2kpath[source]

POSCAR.str2kpath(kpath_str, n=5, weight=None, ibzkpt=None, outfile=None)

Get Kpath from a string of kpoints (Line-Mode like). Useful in Terminal.

  • Parameters

    • kpath_str: str, a multiline string similiar to line mode of KPOINTS, initial 4 lines are not required.
      • If you do not want to label a point, label it as 'skip' and it will be removed.
      • You can add an interger at end of a line to customize number of points in a given patch.
      • Each empty line breaks the path, so similar points before and after empty line are useless here.
    • n : int, number per length of body diagonal of rec_basis, this makes uniform steps based on distance between points.
    • weight : Float, if None, auto generates weights.
    • ibzkpt : Path to ibzkpt file, required for HSE calculations.
    • outfile: Path/to/file to write kpoints.
  • Example

    str2kpath('''0 0 0 !$\Gamma$ 3 0.25 0.25 0.25 !L''') Automatically generated using PivotPy with HSK-INDS = [0, -1], LABELS = ['$\Gamma$', 'L'], SEG-INDS = [] 3 Reciprocal Lattice 0.0000000000 0.0000000000 0.0000000000 0.333333 0.1250000000 0.1250000000 0.1250000000 0.333333 0.2500000000 0.2500000000 0.2500000000 0.333333

POSCAR.bring_in_cell[source]

POSCAR.bring_in_cell(points)

Brings atoms's positions inside Cell and returns their R3 coordinates.

POSCAR.bring_in_bz[source]

POSCAR.bring_in_bz(kpoints, sys_info=None, shift=0)

Brings KPOINTS inside BZ. Applies to_R3 only if primitive=True.

  • Parameters
    • kpoints : List or array of KPOINTS to transorm into BZ or R3.
    • sys_info : If given, returns kpoints using that information. Useful If kpoints are cartesian and you need to scale those.
    • primitive: Default is False and brings kpoints into regular BZ. If True, returns to_R3().
    • shift : This value is added to kpoints before any other operation, single number of list of 3 numbers for each direction.

Note: If kpoints are Cartesian, provide sys_info, otherwise it will go wrong.

import matplotlib.pyplot as plt, pivotpy as pp

poscar = pp.POSCAR('POSCAR')
axs = pp.get_axes(ncols=4,figsize=(8,2))
poscar.splot_cell(ax=axs[0],colormap='hot',color='white').set_axis_off()
poscar.splot_cell(ax=axs[1],plane='xy').set_axis_off()
poscar.splot_bz(ax=axs[2],color='white').set_axis_off()
poscar.splot_bz(ax=axs[3],plane='xy').set_axis_off()
# Next commnad plot path on most recent BZ from line above
poscar.splot_kpath(4,[0,2,4],['$\Gamma$','K','M'],color='r',ha='right',va='bottom')
pos = poscar.bring_in_cell(poscar.data.positions)
axs[1].scatter(pos[:,0],pos[:,1],c='c',s=200)
axs[1].add_text(xs=pos[:,0],ys=pos[:,1],txts=poscar.data.labels,transform=False)
_ = plt.gcf().suptitle('Cell, Cell on XY, BZ, BZ on XY')
2022-09-02T11:41:04.882896 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

If you do not provide colors in iplot_lat or splot_lat functions, colors are picked from the table below:

sio.periodic_table()
2022-09-02T11:41:07.080659 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

class LOCPOT[source]

LOCPOT(path=None, data_set=0)

  • Returns Data from LOCPOT and similar structure files. Loads only single set out of 2/4 magnetization data to avoid performance/memory cost while can load electrostatic and one set of magnetization together.
  • Parameters
    • path: path/to/LOCPOT. LOCPOT is auto picked in CWD.
    • data_set: 0 for electrostatic data, 1 for magnetization data if ISPIN = 2. If non-colinear calculations, 1,2,3 will pick Mx,My,Mz data sets respectively. Only one data set is loaded, so you should know what you are loading.
  • Exceptions
    • Would raise index error if magnetization density set is not present in LOCPOT/CHG in case m is not False.

Note: To avoid memory issues while loading multiple LOCPOT files, use this class as a context manager which cleans up the memory after use.

with LOCPOT('path/to/LOCPOT') as tmp:
    tmp.splot()
# The object tmp is destroyed here and memory is freed.

class CHG[source]

CHG(path=None, data_set=0) :: LOCPOT

  • Returns Data from CHG and similar structure files. Loads only single set out of 2/4 magnetization data to avoid performance/memory cost while can load electrostatic and one set of magnetization together.
  • Parameters
    • path: path/to/CHG. CHG is auto picked in CWD.
    • data_set: 0 for electrostatic data, 1 for magnetization data if ISPIN = 2. If non-colinear calculations, 1,2,3 will pick Mx,My,Mz data sets respectively. Only one data set is loaded, so you should know what you are loading.
  • Exceptions
    • Would raise index error if magnetization density set is not present in CHG/CHG in case m is not False.

Note: To avoid memory issues while loading multiple CHG files, use this class as a context manager which cleans up the memory after use.

with CHG('path/to/CHG') as tmp:
    tmp.splot()
# The object tmp is destroyed here and memory is freed.

class ELFCAR[source]

ELFCAR(path=None, data_set=0) :: LOCPOT

  • Returns Data from ELFCAR and similar structure files. Loads only single set out of 2/4 magnetization data to avoid performance/memory cost while can load electrostatic and one set of magnetization together.
  • Parameters
    • path: path/to/ELFCAR. ELFCAR is auto picked in CWD.
    • data_set: 0 for electrostatic data, 1 for magnetization data if ISPIN = 2. If non-colinear calculations, 1,2,3 will pick Mx,My,Mz data sets respectively. Only one data set is loaded, so you should know what you are loading.
  • Exceptions
    • Would raise index error if magnetization density set is not present in ELFCAR/CHG in case m is not False.

Note: To avoid memory issues while loading multiple ELFCAR files, use this class as a context manager which cleans up the memory after use.

with ELFCAR('path/to/ELFCAR') as tmp:
    tmp.splot()
# The object tmp is destroyed here and memory is freed.

class PARCHG[source]

PARCHG(path=None, data_set=0) :: LOCPOT

  • Returns Data from PARCHG and similar structure files. Loads only single set out of 2/4 magnetization data to avoid performance/memory cost while can load electrostatic and one set of magnetization together.
  • Parameters
    • path: path/to/PARCHG. PARCHG is auto picked in CWD.
    • data_set: 0 for electrostatic data, 1 for magnetization data if ISPIN = 2. If non-colinear calculations, 1,2,3 will pick Mx,My,Mz data sets respectively. Only one data set is loaded, so you should know what you are loading.
  • Exceptions
    • Would raise index error if magnetization density set is not present in PARCHG/CHG in case m is not False.

Note: To avoid memory issues while loading multiple PARCHG files, use this class as a context manager which cleans up the memory after use.

with PARCHG('path/to/PARCHG') as tmp:
    tmp.splot()
# The object tmp is destroyed here and memory is freed.

class OUTCAR[source]

OUTCAR(path=None)

Parse some required data from OUTCAR file.

LOCPOT.splot[source]

LOCPOT.splot(operation='mean_c', ax=None, period=None, period_right=None, lr_pos=(0.25, 0.75), interface=None, smoothness=2, labels=('$V(z)$', '$\\langle V \\rangle _{roll}(z)$', '$\\langle V \\rangle $'), colors=((0, 0.2, 0.7), 'b', 'r'), annotate=True)

  • Returns tuple(ax,Data) where Data contains resultatnt parameters of averaged potential of LOCPOT.
  • Parameters
    • operation: Default is 'mean_c'. What to do with provided volumetric potential data. Anyone of these 'mean_a','min_a','max_a','mean_b','min_b','max_b','mean_c','min_c','max_c'.
    • ax: Matplotlib axes, if not given auto picks.
    • period: Periodicity of potential in fraction between 0 and 1. For example if a slab is made of 4 super cells in z-direction, period=0.25.
    • period_right: Periodicity of potential in fraction between 0 and 1 if right half of slab has different periodicity.
    • lr_pos: Locations around which averages are taken.Default (0.25,0.75). Provide in fraction between 0 and 1. Center of period is located at these given fractions. Work only if period is given.
    • interface: Default is 0.5 if not given, you may have slabs which have different lengths on left and right side. Provide in fraction between 0 and 1 where slab is divided in left and right halves.
    • smoothness: Default is 3. Large value will smooth the curve of potential. Only works if period is given.
    • labels: List of three labels for legend. Use plt.legend() or pp.add_legend() for labels to appear. First entry is data plot, second is its convolution and third is complete average.
    • colors: List of three colors for lines.
    • annotate: True by default, writes difference of right and left averages on plot.

LOCPOT.check_period[source]

LOCPOT.check_period(operation:str='mean_c', interface=0.5, lr_pos=(0.25, 0.75), smoothness=2, figsize=(5, 3), **kwargs)

Check periodicity using ipywidgets interactive plot.

  • operation: What to do, such as 'mean_c' or 'mean_a' etc.
  • interface: Interface in range [0,1] to divide left and right halves.
  • lr_pos: Tuple of (left,right) positions in range [0,1] to get ΔV of right relative to left.
  • smoothness: int. Default is 2. Smoothing parameter for rolling mean. Larger is better.
  • figsize: Tuple of (width,height) of figure. Since each time a figure is created, we can't reuse it, so we need to specify the size. kwargs are passed to the plt.Axes.set(kwargs) method to handle the plot styling.

Matplotlib Axes Utility

get_axes[source]

get_axes(figsize=(3.4, 2.6), nrows=1, ncols=1, widths=[], heights=[], axes_off=[], axes_3d=[], sharex=False, sharey=False, azim=45, elev=15, ortho3d=True, **subplots_adjust_kwargs)

- Returns flatten axes of initialized figure, based on plt.subplots(). If you want to access parent figure, use ax.get_figure() or current figure as plt.gcf().
- **Parameters**
    - figsize   : Tuple (width, height). Default is (3.4,2.6).
    - nrows     : Default 1.
    - ncols     : Default 1.
    - widths    : List with len(widths)==nrows, to set width ratios of subplots.
    - heights   : List with len(heights)==ncols, to set height ratios of subplots.
    - share(x,y): Share axes between plots, this removes shared ticks automatically.
    - axes_off  : Turn off axes visibility, If `nrows = ncols = 1, set True/False`, If anyone of `nrows or ncols > 1`, provide list of axes indices to turn off. If both `nrows and ncols > 1`, provide list of tuples (x_index,y_index) of axes.
    - axes_3d   : Change axes to 3D. If `nrows = ncols = 1, set True/False`, If anyone of `nrows or ncols > 1`, provide list of axes indices to turn off. If both `nrows and ncols > 1`, provide list of tuples (x_index,y_index) of axes.
    - azim,elev   : Matplotlib's 3D angles, defualt are 45,15.
    - ortho3d     : Only works for 3D axes. If True, x,y,z are orthogonal, otherwise perspective.
    - **subplots_adjust_kwargs : These are same as `plt.subplots_adjust()`'s arguements.

There are extra methods added to each axes (only 2D) object.

  • add_text
  • add_legend
  • add_colorbar
  • color_wheel
  • break_spines
  • modify_axes
  • append_axes
  • join_axes
axs = get_axes(nrows=2,ncols=2,widths=[1,2],heights=[1,2],axes_3d=[(1,1)])
axs[0,0].add_text(0.5,0.5,'ax[0,0]')
axs[0,1].add_text(0.5,0.5,'ax[0,1]',colors='blue')
axs[1,0].add_text(0.5,0.5,'ax[1,0]',colors='olive')
axs[1,0].break_spines(['top'])
axs[0,0].break_spines(['bottom'])
axs[0,1].color_wheel(colormap='RGB')
poscar.splot_bz(axs[1,1],colormap='RGB').set_axis_off()
2022-09-02T11:41:08.427496 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

class Vasprun[source]

Vasprun(path=None, skipk=None, elim=[], dos_only=False, data=None)

  • All plotting functions that depend on export_vasprun are joined under this class and renamed.

  • Main Parameter

    • path: str: path/to/vasprun.xml. Auto picks in CWD.
  • Optional Parameters (only useful if path is vasprun.xml file)

    • skipk : int: Skip initial kpoints.
    • elim : list: Energy range e.g. [-5,5].
    • dos_only : bool: False by default, If True, load mimimal bands data to save memeory.
    • data : json/pickle file/str or VasprunData or a valid dictionary. Takes precedence over path parameter.
  • Attributes and Methods

    • data : Exported data from given file. This has it's own attributes as well to save as json/pickle etc.
    • to_json : Saves data in .json file. Useful for transport to other langauges.
    • to_pickle : Saves data in .pickle file. Useful for fast reload in python.
    • splot[...] : Plots data using `sp.splot[...]` functions.
    • iplot[...] : Plots data using `sp.iplot[...]` functions.

Tip: If KPOINTS file is generated by this module, ticks on kpath are auto-picked.

Note: To avoid memory issues while loading multiple vasprun.xml files, use this class as a context manager which cleans up the memory after use.

with Vasprun('path/to/vasprun.xml') as vr:
    vr.splot_bands()
# The object `vr` is destroyed here and memory is freed.

Vasprun.to_json[source]

Vasprun.to_json(outfile=None, indent=1)

Vasprun.to_pickle[source]

Vasprun.to_pickle(outfile=None)

Vasprun.get_fermi[source]

Vasprun.get_fermi(tol=0.001)

Fermi energy based on occupancy. Returns self.Fermi if occupancies cannot be resolved. tol is the value of occupnacy to ignore as filled.

Vasprun.select[source]

Vasprun.select(kpoints_inds=None, bands_inds=None)

Seletc data based on kpoints and bands indices. This is useful to select only a subset of data and even reorder kpoints after calculations. Both kpoints_inds and bands_inds are based on current data and should be based on zero indexing.

Returns Vasprun object with selected data that can be plotted using splot_[...] or iplot_[...] functions.

New in version 1.1.4

Vasprun.splot_bands[source]

Vasprun.splot_bands(ax=None, **kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • txt,xytxt and ctxt are extra arguments for text on figure.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.

Additional kwargs are passed to matplotlib.lines.Lin2D. For passing a keyword to spindown channel, append an underscore, e.g 'lw' goes to SpinUp and 'lw_' goes to SpinDown.

  • Returns
    • ax : matplotlib axes object with plotted bands.

Vasprun.splot_dos_lines[source]

Vasprun.splot_dos_lines(query_data={}, ax=None, **kwargs)

  • Returns ax object (if ax!=False) and plot on which all matplotlib allowed actions could be performed, returns lists of energy,tdos and pdos and labels. If given,elements,orbs colors, and labels must have same length. If not given, zeroth ions is plotted with s-orbital.
  • Parameters)
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • ax : Matplotlib axes object, if None, one is created. If False, data lists are returned.
    • include_dos: One of {'both','tdos','pdos'}.
    • elim : [min,max] of energy range.
    • Fermi : If not given, automatically picked from export_vasprun.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • fill_area : Default is True and plots filled area for dos. If False, plots lines only.
    • vertical : False, If True, plots along y-axis.
    • showlegend : True by defualt.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • legend_kwargs: Dictionary to contain legend arguments to fix.
    • query_data : Dictionary with keys as label and values as list of length 2. If given, used in place of elements, orbs and labels arguments.
            Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
  • Returns
    • ax : Matplotlib axes.

Vasprun.splot_rgb_lines[source]

Vasprun.splot_rgb_lines(query_data={}, ax=None, **kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. In this function,orbs,labels,elements all have list of length 3. Inside list, sublists or strings could be any length but should be there even if empty.
  • Parameters
    • elements : List [[],[],[]] by default and plots s,p,d orbital of system.
    • orbs : List [[r],[g],[b]] of indices of orbitals, could be empty, but shape should be same.
    • labels : List [str,str,str] of projection labels. empty string should exist to maintain shape. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in colorbar ticks or legend.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • max_width : Default is None and linewidth at any point = 2.5*sum(ions+orbitals projection of all three input at that point). Linewidth is scaled to max_width if an int or float is given.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • scale_data : Default is False. If True, normalizes projection data to 1.
    • colorbar : Default is True. Displays a vertical RGB colorbar. Forfine control, set it False and use plot_handle.add_colorbar and plot_handle.color_cube just afer plotting.
    • colormap : 1.2.7+, Default is None and picks suitable for each case. For all three projections given, only first, middle and last colors are used to interpolate between them.
    • N : Number of distinct colors in colormap. For given three non-zero projections, even number will be rounded up to greater odd number, so 4 and 5 are same in that case.
    • query_data : Dictionary with keys as label and values as list of length 2. Should be <= 3 for RGB plots. If given, used in place of elements, orbs and labels arguments.
                Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
  • Returns
    • ax : matplotlib axes object with plotted projected bands.

Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None as these parameters act internally on data.

Vasprun.splot_color_lines[source]

Vasprun.splot_color_lines(query_data={}, axes=None, **kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. If given, elements, orbs, and labels must have same length. If not given, zeroth ion is plotted with s-orbital.
  • Parameters
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in legend.
    • axes : Matplotlib axes object with one or many axes, if not given, auto created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • showlegend : True by defualt and displays legend relative to axes[0]. If False, it writes text on individual ax.
    • scale_data : Default is False, If True, normalize projection data to 1.
    • max_width : Width to scale whole projections. Default is None and linewidth at any point on a line = 2.5*sum(ions+orbitals projection of the input for that line at that point). Linewidth is scaled to max_width if an int or float is given.
    • xytxt : [x_coord,y_coord] of labels relative to axes. Works if showlegend = False.
    • ctxt : color of text of labels
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • legend_kwargs: Dictionary containing legend arguments.
    • query_data : Dictionary with keys as label and values as list of length 2. If given, used in place of elements, orbs and labels arguments.
                Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
    • **subplots_adjust_kwargs : plt.subplots_adjust parameters.
  • Returns
    • axes : matplotlib axes object [one or list of axes] with plotted projected bands.

      Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None as these parameters act internally on data.

Vasprun.iplot_dos_lines[source]

Vasprun.iplot_dos_lines(query_data={}, **kwargs)

  • Returns plotly's figure. If given,elements,orbs colors, and labels must have same length. If not given, zeroth ions is plotted with s-orbital.
  • Parameters)
    • elements : List [[0,],] of ions indices, by defualt plot first ion's projections.
    • orbs : List [[0,],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels) == len(orbs) must hold.
    • elim : [min,max] of energy range.
    • Fermi : If not given, automatically picked from export_vasprun.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'. Use 'RGB' if want to compare with iplot_rgb_lines with 3 projection inputs (len(orbs)==3).
    • fill_area : Default is True and plots filled area for dos. If False, plots lines only.
    • vertical : False, If True, plots along y-axis.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • figsize : Tuple(width,height) in pixels, e.g. (700,400).
    • query_data : Dictionary with keys as label and values as list of length 2. If given, used in place of elements, orbs and labels arguments.
            Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
  • Returns
    • fig : Plotly's figure object.

Vasprun.iplot_rgb_lines[source]

Vasprun.iplot_rgb_lines(query_data={}, **kwargs)

  • Returns plotly's figure object, takes care of spin-polarized calculations automatically. elements,orbs and labels are required to be one-to-one lists of size 3 where each item in list could be another list or integer.
  • Parameters

    • elements : List of size 3 of list of indices of ions. If not given, picks all ions for each orbital.
    • orbs : List of size 3 of list of orbital indices, if not gievn, s,p,d plotted.
    • labels : List of labels for projection.
    • mode : Three plotting modes are available:

      • 'markers' : Plot whole data as a single scatter object. Its too fast.
      • 'bands' : Plot data such that each band is accessible via legend.
      • 'lines' : A replica of matplotlib LineCollection object. It plots at each point separately, slower than other two modes.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.

    • figsize : Tuple(width,height) in pixels, e.g. (700,400).
    • query_data : Dictionary with keys as label and values as list of length 2. len(query_data) <=3 should hold for RGB plots. If given, used in place of elements, orbs and labels arguments.
                Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
    • Other Parameters
      • ktick_inds, ktick_vals,elim,kseg_inds,max_width,title etc.

Vasprun.get_band_info[source]

Vasprun.get_band_info(b_i, k_i=None)

Get band information for given band index b_i. If k_i is given, returns info at that point Fermi energy is subtracted from all energies. When a plot commnad is called, the Fermi energy is updated if provided.

Vasprun.get_en_diff[source]

Vasprun.get_en_diff(b1_i, b2_i, k1_i=None, k2_i=None)

Get energy difference between two bands at given two kpoints indices. Index 2 is considered at higher energy.

  • b1_i, b2_i : band indices of the two bands, minimum energy difference is calculated.
  • k1_i, k2_i : k-point indices of the two bands.

If k1_i and k2_i are not provided, min(b2_i) - max(b1_i) is calculated which is equivalent to band gap.

Returns: Data with follwoing attributes which can be used to annotate the difference on plot. de : energy difference coords : np.array([[k1,e1],[k2,e2]]) #Fermi is subtracted either from system or when user provides in a plot command. eqv_coords: list(coords) at equivalent k-points if exit. Do not appear if k1_i and k2_i are provided.

For spin-polarized case, 4 blocks of above data are returned which are accessible by u1u2, u1d2, d1u2, d1d2 and they collects energy difference between 2 given bands at 2 different spin.

Vasprun.splot_en_diff[source]

Vasprun.splot_en_diff(coords, ax, **kwargs)

Plot energy difference at given ax. Provide coords from output of get_en_diff().coords or get_en_diff().eqv_coords[i] if exist. Provide ax on which bandstructure is plotted. Fermi is already subtracted in coords from system or by user input when bandstructure plot commands are run. kwargs are passed to ax.step. Returns ax.

Examples

Use Vasprun class to plot all related figures.

from pivotpy import Vasprun, iplot2html
vr = Vasprun(path='../graphene_example/ISPIN_1/bands/vasprun.xml')
ax = vr.splot_bands(Fermi=0)
delta = vr.get_en_diff(4,6,30,60)
#ax.annotate('',xy=delta.coords[0],xytext=delta.coords[1], arrowprops=dict(arrowstyle='<->',color='g'))
vr.splot_en_diff(delta.coords, ax, color='k',lw=0.5)
ax.add_text(delta.coords[:,0].mean() + 0.2, delta.coords[:,1].mean(), f'$ΔE = {np.round(delta.de,2)}$ eV', colors = 'k',transform=False)
2022-09-02T11:41:09.837281 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
vr.splot_rgb_lines()
<AxesSubplot:>
2022-09-02T11:41:10.376578 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
iplot2html(vr.iplot_rgb_lines(),modebar=False) #iplot2html is required to show in docs properly
ax1 = vr.splot_dos_lines()
# You can annotate special points using `ax.annotate`
ax1.annotate('Peak to talk about',xy=(9,4),xytext=(-10,3), color='r',arrowprops=dict(arrowstyle='-|>',color='m'))
Text(-10, 3, 'Peak to talk about')
2022-09-02T11:41:11.360708 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

A Mininmal Example of SpinDataFrame

First see an example of SpinDataFrame.splot, later you can manipulate and plot data yourself as given after that.

import pivotpy as pp
df = pp.SpinDataFrame(path = r'E:\Research\graphene_example\ISPIN_2\dos\sigm0_01\vasprun.xml',
                   bands=[3],elements=[[0],[1]], orbs= [(0,1),(1,2,3)],scale_data=True)
df.describe()
 Found ISPIN = 2, output data got attributes spins.<u,d> instead of spins.<s,x,y,z>
kx ky kz band eu ed su_0 sd_0 su_1 sd_1
count 840.000000 840.000000 840.0 840.0 840.000000 840.000000 840.000000 840.000000 840.000000 840.000000
mean 0.006098 0.250000 0.0 4.0 -3.332142 -3.332141 0.133251 0.133251 0.686662 0.686661
std 0.288783 0.144424 0.0 0.0 1.295273 1.295274 0.272950 0.272950 0.167976 0.167977
min -0.487805 0.000000 0.0 4.0 -5.535500 -5.535500 0.000000 0.000000 0.541748 0.541748
25% -0.243902 0.121951 0.0 4.0 -4.420925 -4.420925 0.000000 0.000000 0.568689 0.568689
50% 0.012195 0.243902 0.0 4.0 -3.436100 -3.436100 0.000000 0.000000 0.603641 0.603641
75% 0.250000 0.365854 0.0 4.0 -2.287600 -2.287600 0.008495 0.008495 0.912318 0.912318
max 0.487805 0.487805 0.0 4.0 0.000000 0.000000 0.990049 0.990049 1.000000 1.000000
df_m = df.copy()
df_m[['kx','ky','kz']] = -df[['kx','ky','kz']]
df1 = df.append(df_m)
df.send_metadata(df1)
df2 = df1.masked('eu',-3.4,0.05,n=100,band=4,method='linear')
df2
kx ky kz band eu ed su_0 sd_0 su_1 sd_1
468 -0.448386 0.182311 0.0 4.0 -3.354734 -3.354734 0.0 0.0 0.571188 0.571188
469 -0.448386 0.192166 0.0 4.0 -3.371419 -3.371419 0.0 0.0 0.570570 0.570570
470 -0.448386 0.202020 0.0 4.0 -3.382942 -3.382942 0.0 0.0 0.570089 0.570089
471 -0.448386 0.211875 0.0 4.0 -3.389084 -3.389084 0.0 0.0 0.569844 0.569844
472 -0.448386 0.221729 0.0 4.0 -3.391950 -3.391950 0.0 0.0 0.569736 0.569736
... ... ... ... ... ... ... ... ... ... ...
9527 0.448386 -0.221729 0.0 4.0 -3.393123 -3.393123 0.0 0.0 0.569692 0.569692
9528 0.448386 -0.211875 0.0 4.0 -3.386203 -3.386203 0.0 0.0 0.569996 0.569996
9529 0.448386 -0.202020 0.0 4.0 -3.380340 -3.380340 0.0 0.0 0.570227 0.570227
9530 0.448386 -0.192166 0.0 4.0 -3.371419 -3.371419 0.0 0.0 0.570570 0.570570
9531 0.448386 -0.182311 0.0 4.0 -3.354734 -3.354734 0.0 0.0 0.571188 0.571188

244 rows × 10 columns

(ax1,_),(ax2,ax3) = pp.get_axes((3,3),ncols=2,nrows=2,widths=[20,1],heights=[1,18],axes_off=[(0,1)],hspace=0.1,wspace=0.0)
df1.splot('kx','ky','eu',s=5,ax=ax2,cmap='viridis')
df1.colorbar(ax1,vertical=False)
df2.splot('kx','ky','eu','su_1',arrows=['','su_1','su_1'],every=4,quiver_kws = dict(cmap='inferno'),ax=ax2)
df2.colorbar(ax3)
df2.poscar.splot_bz(plane='xy',ax=ax2)
ax1.xaxis.set_label_position("top")
ax1.set_xlabel('$E_\\uparrow $')
ax3.yaxis.set_label_position("right")
ax3.set_ylabel('$S_\\uparrow(C_1-p)$')
Text(0, 0.5, '$S_\\uparrow(C_1-p)$')
2022-09-02T11:41:15.123969 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
df['kz'] = 0
ax = df1.splot3d('kx','ky','kz','eu',s=3)
df1.splot3d('kx','ky','kz','eu',arrows=['','','su_1'],norm=0.2,every=15,quiver_kws= dict(arrowstyle='wedge',cmap='inferno',zorder=3),ax=ax)
df1.poscar.splot_bz(ax=ax,fill=False)
ax.view_init(elev=50,azim=90)
df1.colorbar()
ax.set_axis_off()
ax.set_title('$E_\\uparrow$ with $S_\\uparrow(C_1-p)$ in 3D')
Text(0.5, 0.92, '$E_\\uparrow$ with $S_\\uparrow(C_1-p)$ in 3D')
2022-09-02T11:41:18.729964 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

You can plot with methods/libraries of your own choice, see two examples below which do not use splot or splot3d.

import numpy as np 
data = df2.get_data().band_4
KPTS = np.array([data.kx,data.ky,data.kz]).T
KPTS[:,2] = 0
UVW = np.array([data.su_0, data.sd_1, data.su_1]).T

ax3d = pp.get_axes(axes_3d=True)
ax3d.scatter(*KPTS.T,c = df2['eu'],s=2,cmap='inferno')
df2.poscar.splot_bz(ax=ax3d,fill=False)

pp.fancy_quiver3d(*KPTS[::8].T,*UVW[::8].T/5,C = np.abs(UVW)[::8]/UVW.max(),arrowstyle='-|>',ax=ax3d)
ax3d.set_axis_off()
ax3d.view_init(elev=60,azim=90)
2022-09-02T11:41:19.325802 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
import plotly.graph_objects as go
fig = go.Figure()
fig.add_scatter3d(x = KPTS[:,0],y = KPTS[:,1], z = KPTS[:,2],marker =dict(color= np.abs(UVW)/UVW.max(),size=2),mode='markers')
df2.poscar.iplot_bz(fig=fig)
fig.add_cone(x = KPTS[::8,0],y = KPTS[::8,1], z = KPTS[::8,2],u = UVW[::8,0],v = UVW[::8,1], w = UVW[::8,2],sizemode='absolute',sizeref=50,colorscale='magma',showscale=False)
pp.iplot2html(fig,modebar=False)

  Index 
  Example 
  StaticPlots 
  InteractivePlots 
  SpinProjectedSurfaces 
  StructureIO 
  Widgets 
  MainAPI●