IPyVASP¶
Tip
Some most commonly functions are documented specially at top level. Other functions/classes are also available at top level but documented in their respective modules.
ipyvasp is a processing tool for VASP DFT input/output processing.
It is designed to primarily be used in Jupyter Notebook because it offers widgets for interactive visualization and bulk analysis.
- class ipyvasp.Files(self, path_or_files='.', glob='*', exclude=None, files_only=False, dirs_only=False)[source]¶
Bases:
object
Creates a Batch of files in a directory recursively based on glob pattern or given list of files. This is a boilerplate abstraction to do analysis in multiple calculations simultaneously.
- Parameters:
path_or_files (str, current directory by default or list of files or an instance of Files.) –
glob (str, glob pattern, '*' by default. '**' is used for recursive glob. Not used if files supplied above.) –
exclude (str, regular expression pattern to exclude files.) –
files_only (bool, if True, returns only files.) –
dirs_only (bool, if True, returns only directories.) –
summarize (Use methods on return such as) –
with_name –
filtered –
others. (interact and) –
Files(root_1 (>>>) –
glob_1 –
...).add(root_2 –
glob_2 –
chain (...) # Fully flexible to) –
WARNING (Don't use write operations on paths in files in batch mode, it can cause unrecoverable data loss.) –
- filtered(include=None, exclude=None, files_only=False, dirs_only=False)[source]¶
Filter all files. Only keeps existing file.
- load_results(exclude_keys=None)[source]¶
Load result.json files from these paths into a dataframe, with optionally excluding keys.
- input_info(*tags)[source]¶
Grab input information into a dataframe from POSCAR and INCAR. Provide INCAR tags (case-insinsitive) to select only few of them.
- update(path_or_files, glob='*', cleanup=True, exclude=None, **kwargs)[source]¶
Update files inplace with similar parameters as initialization. If cleanup=False, older files are kept too. Useful for widgets such as BandsWidget to preserve their state while using widget.files.update.
- to_dropdown(description='File')[source]¶
Convert this instance to Dropdown. If there is only one file, adds an empty option to make that file switchable. Options of this dropdown are update on calling Files.update method.
- add(path_or_files, glob='*', exclude=None, **kwargs)[source]¶
Add more files or with a diffrent glob on top of exitsing files. Returns same instance. Useful to add multiple globbed files into a single chained call.
>>> Files(root_1, glob_1,...).add(root_2, glob_2,...) # Fully flexible
- interactive(*funcs, auto_update=True, app_layout=None, grid_css={}, **kwargs)[source]¶
Enhanced interactive widget with multiple callbacks, grid layout and fullscreen support.
This function is used for quick dashboards. Subclass InteractBase for complex applications.
Features:
Multiple function support with selective updates
CSS Grid layout system
Extended widget trait observation
Dynamic widget property updates
Built-in fullscreen support
Basic Usage:
from ipyslides.interaction import interactive, callback, monitor import ipywidgets as ipw import plotly.graph_objects as go fig = go.FigureWidget() @callback('out-plot', timeit=True) # check execution time def update_plot(x, y, fig): fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) def resize_fig(fig, fs): fig.layout.autosize = False # double trigger fig.layout.autosize = True # plotly's figurewidget always make trouble with sizing # Above two functions can be merged since we can use changed detection @monitor # check execution time def respond(x, y, fig , fs, changed): if 'fs' in changed: # or changed('fs') fig.layout.autosize = False # double trigger fig.layout.autosize = True else: fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) dashboard = interactive( update_plot, resize_fig, # responds to fullscreen change # respond, instead of two functions x = ipw.IntSlider(0, 0, 100), y = ipw.FloatSlider(0, 1), fig = ipw.fixed(fig), changed = '.changed', # detect a change in parameter fs = '.isfullscreen', # detect fullscreen change on instance itself )
Parameters:
*funcs: One or more callback functions
auto_update: Update automatically on widget changes
app_layout: Initial layout configuration, see relayout() method for details
- grid_css: CSS Grid properties for layout
Use :fullscreen at root level of dict to apply styles in fullscreen mode
Use [Button, ToggleButton, ToggleButtons].add_class(‘content-width-button’) to fix button widths easily.
See [CSS Grid Layout Guide](https://css-tricks.com/snippets/css/complete-guide-grid/).
**kwargs: Widget parameters
Widget Parameters:
Regular ipywidgets
Fixed widgets via ipw.fixed()
String pattern ‘widget.trait’ for trait observation, ‘widget’ must be in kwargs or ‘.trait’ to observe traits on this instance.
You can use ‘.fullscreen’ to detect fullscreen change and do actions based on that.
You can use changed = ‘.changed’ to detect which parameters of a callback changed by checking changed(‘param’) -> Bool in a callback.
Any DOM widget that needs display (inside fixed too). A widget and its observed trait in a single function are not allowed, such as f(fig, v) where v=’fig.selected’.
Plotly FigureWidgets (use patched_plotly)
- ipywidgets.Button for manual updates on callbacks besides global auto_update. Add tooltip for info on button when not synced.
You can have multiple buttons in a single callback and check btn.clicked attribute to run code based on which button was clicked.
Widget Updates:
Functions can modify widget traits (e.g. options, min/max)
Order matters for dependent updates
Parameter-less functions run with any interaction
Animation widgets work even with manual updates
- Output Widget Behavior:
Output widgets are created only if a CSS class is provided via @callback.
If no CSS class is provided, the callback will use the main output widget labeled as ‘out-main’.
CSS Classes:
Parameter names from kwargs
Custom ‘out-*’ classes from @callback, and ‘out-main’ class.
‘btn-main’ for manual update button
Notes:
Avoid modifying global slide state
Use widget descriptions to prevent name clashes
See set_css() method for styling options
interactive(no_args_func_which_may_fetch_data_on_click,) is perfectly valid and run on button click.
Python dictionary to CSS
CSS is formatted using a props nested dictionary to simplify the process. There are few special rules in props:
All nested selectors are joined with space, so hl`’.A’: {‘.B’: … }` becomes hl[‘css’]`.A .B {…}` in CSS.
A ‘^’ in start of a selector joins to parent selector without space, so hl`’.A’: {‘^:hover’: …}` becomes hl[‘css’]`.A:hover {…}` in CSS. You can also use hl`’.A:hover’` directly but it will restrict other nested keys to hover only.
A list/tuple of values for a key in dict generates CSS fallback, so hl`’.A’: {‘font-size’: (‘20px’,’2em’)}` becomes hl[‘css’]`.A {font-size: 20px; font-size: 2em;}` in CSS.
Read about specificity of CSS selectors [here](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity).
- interact(*funcs, auto_update=True, app_layout=None, grid_css={}, **kwargs)[source]¶
Enhanced interactive widget with multiple callbacks, grid layout and fullscreen support.
This function is used for quick dashboards. Subclass InteractBase for complex applications.
Features:
Multiple function support with selective updates
CSS Grid layout system
Extended widget trait observation
Dynamic widget property updates
Built-in fullscreen support
Basic Usage:
from ipyslides.interaction import interactive, callback, monitor import ipywidgets as ipw import plotly.graph_objects as go fig = go.FigureWidget() @callback('out-plot', timeit=True) # check execution time def update_plot(x, y, fig): fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) def resize_fig(fig, fs): fig.layout.autosize = False # double trigger fig.layout.autosize = True # plotly's figurewidget always make trouble with sizing # Above two functions can be merged since we can use changed detection @monitor # check execution time def respond(x, y, fig , fs, changed): if 'fs' in changed: # or changed('fs') fig.layout.autosize = False # double trigger fig.layout.autosize = True else: fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) dashboard = interactive( update_plot, resize_fig, # responds to fullscreen change # respond, instead of two functions x = ipw.IntSlider(0, 0, 100), y = ipw.FloatSlider(0, 1), fig = ipw.fixed(fig), changed = '.changed', # detect a change in parameter fs = '.isfullscreen', # detect fullscreen change on instance itself )
Parameters:
*funcs: One or more callback functions
auto_update: Update automatically on widget changes
app_layout: Initial layout configuration, see relayout() method for details
- grid_css: CSS Grid properties for layout
Use :fullscreen at root level of dict to apply styles in fullscreen mode
Use [Button, ToggleButton, ToggleButtons].add_class(‘content-width-button’) to fix button widths easily.
See [CSS Grid Layout Guide](https://css-tricks.com/snippets/css/complete-guide-grid/).
**kwargs: Widget parameters
Widget Parameters:
Regular ipywidgets
Fixed widgets via ipw.fixed()
String pattern ‘widget.trait’ for trait observation, ‘widget’ must be in kwargs or ‘.trait’ to observe traits on this instance.
You can use ‘.fullscreen’ to detect fullscreen change and do actions based on that.
You can use changed = ‘.changed’ to detect which parameters of a callback changed by checking changed(‘param’) -> Bool in a callback.
Any DOM widget that needs display (inside fixed too). A widget and its observed trait in a single function are not allowed, such as f(fig, v) where v=’fig.selected’.
Plotly FigureWidgets (use patched_plotly)
- ipywidgets.Button for manual updates on callbacks besides global auto_update. Add tooltip for info on button when not synced.
You can have multiple buttons in a single callback and check btn.clicked attribute to run code based on which button was clicked.
Widget Updates:
Functions can modify widget traits (e.g. options, min/max)
Order matters for dependent updates
Parameter-less functions run with any interaction
Animation widgets work even with manual updates
- Output Widget Behavior:
Output widgets are created only if a CSS class is provided via @callback.
If no CSS class is provided, the callback will use the main output widget labeled as ‘out-main’.
CSS Classes:
Parameter names from kwargs
Custom ‘out-*’ classes from @callback, and ‘out-main’ class.
‘btn-main’ for manual update button
Notes:
Avoid modifying global slide state
Use widget descriptions to prevent name clashes
See set_css() method for styling options
interactive(no_args_func_which_may_fetch_data_on_click,) is perfectly valid and run on button click.
Python dictionary to CSS
CSS is formatted using a props nested dictionary to simplify the process. There are few special rules in props:
All nested selectors are joined with space, so hl`’.A’: {‘.B’: … }` becomes hl[‘css’]`.A .B {…}` in CSS.
A ‘^’ in start of a selector joins to parent selector without space, so hl`’.A’: {‘^:hover’: …}` becomes hl[‘css’]`.A:hover {…}` in CSS. You can also use hl`’.A:hover’` directly but it will restrict other nested keys to hover only.
A list/tuple of values for a key in dict generates CSS fallback, so hl`’.A’: {‘font-size’: (‘20px’,’2em’)}` becomes hl[‘css’]`.A {font-size: 20px; font-size: 2em;}` in CSS.
Read about specificity of CSS selectors [here](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity).
Tips:
You can use this inside columns using delayed display trick, like hl`write(‘First column’, C2)` where hl`C2 = Slides.hold(Slides.ei.interact, f, x = 5) or Slides.ei.interactive(f, x = 5)`.
You can also use this under Slides.capture_content to display later in a specific place.
- map(func, to_df=False)[source]¶
Map files to a function that takes path as argument. If to_df=True, func may return a dict to create named columns, or just two columns will be created. Otherwise returns generator of elemnets (path, func(path)). If you need to operate on opened file pointer, use .mapf instead.
>>> import ipyvasp as ipv >>> files = ipv.Files(...) >>> files.map(lambda path: ipv.read(path, '<pattern>',apply = lambda line: float(line.split()[0]))) >>> files.map(lambda path: ipv.load(path), to_df=True)
- mapf(func, to_df=False, mode='r', encoding=None)[source]¶
Map files to a function that takes opened file pointer as argument. Opened files are automatically closed and should be in readonly mode. Load files content into a generator sequence of tuples like (path, func(open(path))) or DataFrame if to_df=True. If to_df=True, func may return a dict to create named columns, or just two columns will be created. If you need to operate on just path, use .map instead.
>>> import json >>> import ipyvasp as ipv >>> files = ipv.Files(...) >>> files.mapf(lambda fp: json.load(fp,cls=ipv.DecodeToNumpy),to_df=True) # or use ipv.load(path) in map >>> files.mapf(lambda fp: ipv.take(fp, range(5)) # read first five lines >>> files.mapf(lambda fp: ipv.take(fp, range(-5,0)) # read last five lines >>> files.mapf(lambda fp: ipv.take(fp, -1, 1, float) # read last line, second column as float
- class ipyvasp.OUTCAR(path=None)[source]¶
Bases:
object
Parse some required data from OUTCAR file.
- property data¶
- property path¶
- read(start_match, stop_match='\\n', nth_match=1, skip_last=False, apply=None)[source]¶
Reads a part of the file between start_match and stop_match and returns a generator. It is lazy and fast. start_match and stop_match`(default is end of same line) are regular expressions. `nth_match is the number of occurence of start_match to start reading. skip_last is used to determine whether to keep or skip last line. apply should be None or func to transform each captured line.
- ipyvasp.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)[source]¶
Returns 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) – Tuple (width, height). Default is (3.4,2.6).
nrows (int) – Default 1.
ncols (int) – Default 1.
widths (list) – List with len(widths)==nrows, to set width ratios of subplots.
heights (list) – List with len(heights)==ncols, to set height ratios of subplots.
sharex (bool) – Share x-axis between plots, this removes shared ticks automatically.
sharey (bool) – Share y-axis between plots, this removes shared ticks automatically.
axes_off (bool or list) – 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 (bool or list) – 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.
ortho3d (bool) – Only works for 3D axes. If True, x,y,z are orthogonal, otherwise perspective.
azim, elev are passed to ax.view_init. Defualt values are 45,15 respectively.
subplots_adjust_kwargs are passed to plt.subplots_adjust.
Note
There are extra methods added to each axes (only 2D) object.
add_text
,add_legend
,add_colorbar
,color_wheel
,break_spines
,adjust_axes
,append_axes
,join_axes
.
- ipyvasp.plt2text(plt_fig=None, width=144, vscale=0.96, colorful=True, invert=False, crop=False, outfile=None)[source]¶
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.) –
- ipyvasp.plt2html(plt_fig=None, transparent=True)[source]¶
Returns
ipython.display.HTML(<svg of figure>)
. It clears figure after use. Soplt.show()
will not work after this.- Parameters:
plt_fig (Matplotlib's figure instance, auto picks as well.) –
transparent (True of False for fig background.) –
- ipyvasp.iplot2html(fig, outfile=None, modebar=True)[source]¶
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.) –
outfile (Name of file to save fig. Defualt is None and show plot in Notebook.) –
modebar (If True, shows modebar in graph. Default is True. Not used if saving to file.) –
- ipyvasp.iplot2widget(fig, fig_widget=None, template=None)[source]¶
Converts plotly’s figure to FigureWidget by copying attributes and data. If fig_widget is provided, it will update it. Adds template if provided. If fig is FigureWidget, it is just returned
- ipyvasp.image2plt(image_or_fname, ax=None, crop=None, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)[source]¶
Plot PIL image, numpy array or image file on given matploltib axes. crop is list or tuple of [x0,y0,x1,y1] in [0,1] interval. kwargs are passed to plt.imshow.
- ipyvasp.webshow(transparent=False)[source]¶
Displays all available figures in browser without blocking terminal
- ipyvasp.load_results(paths_list, exclude_keys=None)[source]¶
Loads result.json from paths_list and returns a dataframe. Use exclude_keys to get subset of data.
- ipyvasp.parse_text(path, shape, slice, slices, raw: bool = False, dtype=<class 'float'>, delimiter='\\s+', include: str = None, exclude: str = '#', fix_format: bool = True)[source]¶
Convert a generator of text lines to numpy array while excluding comments, given matches and empty lines. Data is sliced and reshaped as per given shape and slices. It is very efficient for large data files to fetch only required data.
- Parameters:
path (Path to file containing data.) –
shape (tuple) – Tuple or list of integers. Given shape of data to be read. Last item is considered to be columns. User should keep track of empty lines and excluded lines.
slices (tuple) – Tuple or list of integers or range or -1. Given slices of data to be read along each dimension. Last item is considered to be columns.
raw (bool) – Returns raw data for quick visualizing and determining shape such as columns, if True.
dtype (object) – Data type of numpy array to be returned. Default is float.
delimiter (str) – Delimiter of data in text file.
include (str) – Match to include in each line to be read. If None, all lines are included.
exclude (str) – Match to exclude in each line to be read. If None, no lines are excluded.
fix_format (bool) – If True, it will fix the format of data in each line. It is useful when data is not properly formatted. like 0.500-0.700 -> 0.500 -0.700
- Returns:
numpy array of given shape and dtype.
- Return type:
ndarray
- ipyvasp.take(f, rows, cols=None, dtype=None, exclude=None, sep=None)[source]¶
Read data from an opened file pointer f by indexing. rows=None picks all lines. Negative indexing is supported to read lines from end. Negative indexing is not supported in cols because of variable length of each line. If cols=None, returns a single str of line if one integer given, otherwise a list of lines. If cols is int ot sequence of int, each line is splitted by sep (default all whitespaces) and dtype is applied over resulting fields. exclude should be regex. It removes matching lines after selection by rows. Empty lines are also discarded if cols is given.
Returns list (nested or plain) or single value or None based on rows and cols selection.
take(f, -1, 1, float) == float(f.readlines()[-1].split()[1]) with advantage for consuming almost no memory as compared to f.readlines() on a huge file.
Note
For more robust reading of structured files like PROCAR use ipyvasp.parse_text function.
Tip
If your output is matrix-like, you can cast it to numpy array like take(…)*np.array(1).
>>> with open('some_file','r') as f: >>> take(f, -1, 1, float) # read last line, second column as float >>> take(f, range(5)) # first 5 lines >>> take(f, range(-5,0)) # last 5 lines
- ipyvasp.summarize(files, func, **kwargs)[source]¶
Apply given func to each file in files and return a dataframe of the results.
- Parameters:
files (Iterable, must be an iterable of PathLike objects, a dictionary of {name: PathLike} pairs also works and name appears in the dataframe.) –
func (callable with a single arguemnt path. Must return a dictionary.) –
kwargs (passed to func itself.) –
Data Parsers¶
- class ipyvasp.core.parser.Vasprun(path='./vasprun.xml', skipk=None)[source]¶
Bases:
DataSource
Reads vasprun.xml file lazily. It reads only the required data from the file when a plot or data access is requested.
- get_evals_dataframe(spins=[0], bands=[0], atoms=None, orbs=None)¶
Initialize and return an EvalsDataFrame instance, with the given parameters.
- property poscar¶
- property dos¶
- property bands¶
- read(start_match, stop_match='\\n', nth_match=1, skip_last=False, apply=None)[source]¶
Reads a part of the file between start_match and stop_match and returns a generator. It is lazy and fast. start_match and stop_match`(default is end of same line) are regular expressions. `nth_match is the number of occurence of start_match to start reading. skip_last is used to determine whether to keep or skip last line. apply should be None or func to transform each captured line.
- get_structure()[source]¶
Returns a structure object including types, basis, rec_basis and positions.
- get_kpoints()[source]¶
Returns k-points data including kpoints, coords, weights and rec_basis in which coords are calculated.
- get_dos(elim=None, ezero=None, atoms=None, orbs=None, spins=None)[source]¶
Returns energy, total and integrated dos of the calculation. If atoms and orbs are specified, then partial dos are included too.
- Parameters:
elim (tuple, energy range to be returned. Default is None, which returns full range. elim is applied around ezero if specified, otherwise around VBM.) –
ezero (float, energy reference to be used. Default is None, which uses VBM as reference. ezero is ignored if elim is not specified. In output data, ezero would be VBM or ezero itself if specified.) –
atoms (list/tuple/range, indices of atoms to be returned. Default is None, which does not return ionic projections.) –
orbs (list/tuple/range, indices of orbitals to be returned. Default is None, which does not return orbitals.) –
spins (list/tuple/range of spin sets indices to pick. If None, spin set will be picked 0 or [0,1] if spin-polarized. Default is None.) –
- Returns:
Dict2Data
- Return type:
object which includes energy,’tdos` and idos as attributes, and includes pdos if atoms and orbs specified. Shape of arrays a is (spins, [atoms, orbs], energy).
- get_evals(elim=None, ezero=None, atoms=None, orbs=None, spins=None, bands=None)[source]¶
Returns eigenvalues and occupations of the calculation. If atoms and orbs are specified, then orbitals are included too.
- Parameters:
elim (tuple, energy range to be returned. Default is None, which returns all eigenvalues. elim is applied around ezero if specified, otherwise around VBM.) –
ezero (float, energy reference to be used. Default is None, which uses VBM as reference. ezero is ignored if elim is not specified. In output data, ezero would be VBM or ezero itself if specified.) –
atoms (list/tuple/range, indices of atoms to be returned. Default is None, which does not return ionic projections.) –
orbs (list/tuple/range, indices of orbitals to be returned. Default is None, which does not return orbitals.) –
spins (list/tuple/range of spin sets indices to pick. If None, spin set will be picked 0 or [0,1] if spin-polarized. Default is None.) –
bands (list/tuple/range, indices of bands to pick. overrides elim. Useful to load same bands range for spin up and down channels. Plotting classes automatically handle this for spin up and down channels.) –
- Return type:
Dict2Data object which includes evals and occs as attributes, and pros if atoms and orbs specified. Shape arrays is (spin, [atoms, orbitals], kpts, bands)
- class ipyvasp.core.parser.Vaspout(path, skipk=None)[source]¶
Bases:
DataSource
Read data from vaspout.h5 file on demand.
- get_evals_dataframe(spins=[0], bands=[0], atoms=None, orbs=None)¶
Initialize and return an EvalsDataFrame instance, with the given parameters.
- property poscar¶
- property dos¶
- property bands¶
- ipyvasp.core.parser.minify_vasprun(path: str)[source]¶
Minify vasprun.xml file by removing projected data.
- ipyvasp.core.parser.xml2dict(xmlnode_or_filepath)[source]¶
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.
Each node has
tag,text,attr,nodes
attributes. Every text element can be accessed viaxml2dict()['nodes'][index]['nodes'][index]...
tree which makes it simple.
- ipyvasp.core.parser.read(file, start_match, stop_match='\\n', nth_match=1, skip_last=False, apply=None)[source]¶
Reads a part of the file between start_match and stop_match and returns a generator. It is lazy and fast. start_match and stop_match`(default is end of same line) are regular expressions. `nth_match is the number of occurence of start_match to start reading. skip_last is used to determine whether to keep or skip last line. apply should be None or func to transform each captured line.
Data Serializer¶
- ipyvasp.core.serializer.dump(data, format: str = 'pickle', outfile: str | None = None, indent: int = 1) None [source]¶
Dump
Dict2Data
or subclass object or any dictionary to json or pickle string/file.- Parameters:
data (dict or instance of Dict2Data) – Any dictionary/Dict2Data(or subclass Data) object can be saved.
format (str,) – Defualt is
pickle
. Should bepickle
orjson
.outfile (str) – Defualt is None and return string. File name does not require extension as it is added from
format
.indent (int) – Defualt is 1. Only works for json.
- ipyvasp.core.serializer.load(file_or_str: str)[source]¶
Loads a json/pickle dumped file or string by auto detecting it.
- Parameters:
file_or_str (str, Filename of pickl/json or their string.) –
- ipyvasp.core.serializer.dict2tuple(name: str, d: dict)[source]¶
Converts a dictionary (nested as well) to namedtuple, accessible via index and dot notation as well as by unpacking.
- Parameters:
name (str, Name of the tuple.) –
d (dict, Dictionary, nested works as well.) –
- class ipyvasp.core.serializer.Dict2Data(d)[source]¶
Bases:
object
Creates a
Data
object with dictionary keys as attributes of Data accessible by dot notation or by key. Once an attribute is created, it can not be changed from outside.- Parameters:
d (dict) – Python dictionary (nested as well) containing any python data types.
>>> x = Dict2Data({'A':1,'B':{'C':2}}) >>> x Data( A = 1 B = Data( C = 2 ) ) >>> x.B.to_dict() {'C': 2}
- to_json(outfile: str | None = None, indent: int = 1)[source]¶
Dumps a Dict2Data object (root or nested level) to json.
- Parameters:
outfile (str, Default is None and returns string. If given, writes to file.) –
indent (int, JSON indent. Default is 1.) –
- class ipyvasp.core.serializer.PoscarData(d)[source]¶
Bases:
Dict2Data
- property coords¶
Returns the lattice coordinates in cartesian space of the atoms in the poscar data.
- property rec_basis¶
Returns the reciprocal lattice basis of the atoms in the poscar data. Gets automatically updated when the lattice is changed.
- property norms¶
Returns the norm of the lattice basis of the atoms in the poscar data. Gets automatically updated when the lattice is changed.
- property rec_norms¶
Returns the norm of the reciprocal lattice basis of the atoms in the poscar data. Gets automatically updated when the lattice is changed.
- property angles¶
Returns the angles of the lattice basis of the atoms in the poscar data. Gets automatically updated when the lattice is changed.
- property rec_angles¶
Returns the angles of reciprocal lattice basis of the atoms in the poscar data. Gets automatically updated when the lattice is changed.
- property volume¶
Returns the volume of the lattice.
- property rec_volume¶
Returns the volume of the reciprocal lattice.
- property labels¶
Returns the numbered labels of the atoms in the poscar data
- property symbols¶
Returns the symbols of the atoms in the poscar data without numbers
- property sites¶
Returns data with types mapped to their positions.
- property G¶
Return metric tensor to be used with fractional coordinates.
>>> D2 = points @ self.G @ points.T # assuming points is Nx3 numpy array, D2 is NxN matrix whose elements are dot product of coordinates in 3D space. >>> assert (self.metric(points) == np.sqrt(np.diag(D2))).all()
Note: You can use self.metric(points) instead of doing a long operation like np.sqrt(np.diag(points @ self.G @ points.T)).
- metric(points)[source]¶
Shortcut for np.linalg.norm(self.to_cartesian(points),axis=<1 or 0>). points are assumed as fractional coordinates in self.basis. You can compute metric from any point other than origin by just subtracting that point, e.g. points - 0.5 will get metric from center of cell (1/2,1/2,1/2).
- get_sites(type_or_indices, as_coords=False)[source]¶
Shortcut method for POSCAR.data.positions[POSCAR.data.types[‘name’]] or with regular indexing.
- get_neighbors(k=5, as_symbols=False)[source]¶
Get the k nearest neighbors of each atom (including itself) in the lattice. Returns array (N, k) of indices of atoms. The first index is the atom itself.
>>> import ipyvasp as ipv >>> data = ipv.POSCAR('POSCAR').data # Assume 8 atoms >>> knn = data.get_neighbors(5) # or .get_knn, Array of shape (8, 5) with indices of neighbors >>> data.labels[knn] # Array of shape (8, 5) with labels of neighbors >>> data.positions[knn] # Array of shape (8, 5, 3) with positions of neighbors >>> data.labels[knn[0]] # Array of shape (5,) with labels of neighbors of first atom including itself
- get_knn(k=5, as_symbols=False)¶
Get the k nearest neighbors of each atom (including itself) in the lattice. Returns array (N, k) of indices of atoms. The first index is the atom itself.
>>> import ipyvasp as ipv >>> data = ipv.POSCAR('POSCAR').data # Assume 8 atoms >>> knn = data.get_neighbors(5) # or .get_knn, Array of shape (8, 5) with indices of neighbors >>> data.labels[knn] # Array of shape (8, 5) with labels of neighbors >>> data.positions[knn] # Array of shape (8, 5, 3) with positions of neighbors >>> data.labels[knn[0]] # Array of shape (5,) with labels of neighbors of first atom including itself
- get_distance(atom1, atom2)[source]¶
Returns the mimimum distance between two atoms taking translations into account. Provide atom1 and atom2 as strings such as get_distance(‘Ga’, ‘As’) to get a mimimal distance between two types or as a dict with a single key as get_distance({‘Ga’:0}, {‘As’:0}) to get distance between specific atoms, or mixed as get_distance(‘Ga’, {‘As’:0}) to get minimum distance between a type and a specific atom.
- get_distances(type1, type2, min=-inf, max=inf)[source]¶
Get an array of all distnaces in a range set by min and max between type 1 and type2. For example get_distances(‘Ga’,’As’,2,3)[:,-1].mean() can be used to get average bond length between Ga and As in GaAs. Returned array is of shape (N,3) where first two entries in columns are indices of pairs between which distance was calculated.
- get_bond_data(site_indices, k=5)[source]¶
Returns a DataFrame with bonds angle, bond length, vector positions etc. that can be used for plotting. t_a and t_b are translation vectors to get them near selected sites. You can use POSCAR.translate if somehow need nearest coordinates.
- to_fractional(coords)[source]¶
Converts cartesian coordinates to fractional coordinates in the basis of cell.
- to_cartesian(points)[source]¶
Converts fractional coordinates in the basis of cell to cartesian coordinates.
- get_selective_dynamics(func)[source]¶
Returns a dictionary of {‘Ga 1’: ‘T T T’, ‘As 1’: ‘T F F’,…} for each atom in the poscar data.
func should be a callable like func(atom) -> (bool, bool, bool) which turns on/off selective dynamics for each atom based in each dimension. atom passed to function is a namedtuple like Atom(symbol,number,index,x,y,z) which has extra attribute p = array([x,y,z]).
You can visualize selective dynamics sites by their labels as follows:
>>> poscar = POSCAR.from_file('POSCAR') >>> sd = poscar.data.get_selective_dynamics(lambda a: (True, False, True) if a.index % 2 == 0 else (False, True, False)) # Just an example >>> poscar.splot_lattice(..., fmt_label = lambda lab: sd[lab]) # This will label sites as T T T, F F F, ... and so so on
- class ipyvasp.core.serializer.BrZoneData(d)[source]¶
Bases:
Dict2Data
- splot(plane=None, ax=None, color='blue', fill=False, fill_zorder=0, vectors=(0, 1, 2), colormap=None, shade=True, alpha=0.4, zoffset=0, **kwargs)¶
Plots matplotlib’s static figure of BZ/Cell. You can also plot in 2D on a 3D axes.
- Parameters:
plane (str) – Default is None and plots 3D surface. Can take ‘xy’,’yz’,’zx’ to plot in 2D.
fill (bool) – True by defult, determines whether to fill surface of BZ or not.
fill_zorder (int) – Default is 0, determines zorder of filled surface in 2D plots if fill=True.
color (Any) – Color to fill surface and stroke color. Default is ‘blue’. Can be any valid matplotlib color.
vectors (tuple) – Tuple of indices of basis vectors to plot. Default is (0,1,2). All three are plotted in 3D (you can turn of by None or empty tuple), whhile you can specify any two/three in 2D. Vectors do not appear if given data is subzone data.
ax (matplotlib.pyplot.Axes) – Auto generated by default, 2D/3D axes, auto converts in 3D on demand as well.
colormap (str) – If None, single color is applied, only works in 3D and fill=True. Colormap is applied along z.
shade (bool) – Shade polygons or not. Only works in 3D and fill=True.
alpha (float) – Opacity of filling in range [0,1]. Increase for clear viewpoint.
zoffset (float) – Only used if plotting in 2D over a 3D axis. Default is 0. Any plane ‘xy’,’yz’ etc.
kwargs are passed to plt.plot or Poly3DCollection if fill=True.
- Returns:
Matplotlib’s 2D axes if plane=None otherswise 3D axes.
- Return type:
matplotlib.pyplot.Axes
- iplot(fill=False, color='rgba(84,102,108,0.8)', special_kpoints=True, alpha=0.4, ortho3d=True, fig=None, **kwargs)¶
Plots interactive figure showing axes,BZ surface, special points and basis, each of which could be hidden or shown.
- Parameters:
fill (bool) – False by defult, determines whether to fill surface of BZ or not.
color (str) – Color to fill surface ‘rgba(84,102,108,0.8)` by default. This sholud be a valid Plotly color.
special_kpoints (bool or callable) – True by default, determines whether to plot special points or not. You can also proivide a mask function f(x,y,z) -> bool which will be used to filter special points based on their fractional coordinates. This is ignored if BZ is primitive.
alpha (float) – Opacity of BZ planes.
ortho3d (bool) – Default is True, decides whether x,y,z are orthogonal or perspective.
fig (plotly.graph_objects.Figure) – Plotly’s go.Figure. If you want to plot on another plotly’s figure, provide that.
kwargs are passed to plotly.graph_objects.Scatter3d for BZ lines.
- Return type:
plotly.graph_objects.Figure
- splot_kpath(kpoints, labels=None, fmt_label=<function <lambda>>, **kwargs)¶
Plot k-path over existing BZ. It will take
ax
,plane
andzoffset
internally from most recent call tosplot_bz
/bz.splot
.- Parameters:
kpoints (array_like) – List of k-points in fractional coordinates. e.g. [(0,0,0),(0.5,0.5,0.5),(1,1,1)] in order of path.
labels (list) – List of labels for each k-point in same order as kpoints.
fmt_label (callable) – Function that takes a label from labels and should return a string or (str, dict) of which dict is passed to
plt.text
.
kwargs are passed to
plt.plot
with some defaults.You can get
kpoints = POSCAR.get_bz().specials.masked(lambda x,y,z : (-0.1 < z 0.1) & (x >= 0) & (y >= 0))
to get k-points in positive xy plane. Then you can reorder them by an indexer likekpoints = kpoints[[0,1,2,0,7,6]]
, note double brackets, and also that point at zero index is taken twice.Tip
You can use this function multiple times to plot multiple/broken paths over same BZ.
- get_special_points(orderby=(1, 1, 1))[source]¶
Returns the special points in the brillouin zone in the order relative to a given point in cartesian coordinates. Gamma is always first.
- property specials¶
Returns the special points in the brillouin zone ordered by point (1,1,1) in cartesian coordinates. Gamma is always first.
- property faces_coords¶
Returns the coordinates of the faces of the brillouin zone in list of N faces of shape (M,3) where M is the number of vertices of the face.
- property normals¶
Get normal vectors to the faces of BZ. Returns a tuple of 6 arrays as (X,Y,Z,U,V,W) where (X,Y,Z) is the center of the faces and (U,V,W) is the normal direction.
- to_fractional(coords)[source]¶
Converts cartesian coordinates to fractional coordinates in the basis of the brillouin zone.
- to_cartesian(points)[source]¶
Converts fractional coordinates in the basis of the brillouin zone to cartesian coordinates.
- map_kpoints(other, kpoints, fold=True)[source]¶
Map kpoints (fractional) from this to other Brillouin zone. In simple words, how other BZ sees the kpoints of this BZ into their basis. This operation is useful when you do POSCAR.transform() and want to map kpoints between given and transformed BZ.
Note
Points outside the first BZ of other BZ will be mapped to the first BZ of other if fold is True (defualt).
- translate_inside(kpoints, shift=0, keep_geometry=False)[source]¶
Brings KPOINTS inside BZ. Applies to_R3 only if BZ is primitive.
- Parameters:
kpoints (array_like) – List or array of KPOINTS to transform into BZ or R3.
shift (float) – This value is added to kpoints before any other operation, single number of list of 3 numbers for each direction.
keep_geomerty (bool) – If True, returns kpoints in R3 with shift applied, keeping the neighbors in order, else kpoints adopt the shape of BZ. This is useful when you already created cartesian kpoints mesh and want to collect their fractional coordinates back to cartesian.
- subzone(func, loop=True)[source]¶
Returns a subzone of the brillouin zone by applying a function on the fractional special points of the zone.
Tip
You can get a 2D subzone by using
lambda x,y,z: -0.1 < z < 0.1
where 0.1 is taken as a tolerance.Tip
func = lambda x,y,z: all([z >= 0, z - x <= 0, z - y <= 0])
gives the irreducible BZ of cubic cell.Warning
We do not check if output is an irreducible zone or not. It is just a subzone based on the function.
- class ipyvasp.core.serializer.CellData(d)[source]¶
Bases:
Dict2Data
- splot(plane=None, ax=None, color='blue', fill=False, fill_zorder=0, vectors=(0, 1, 2), colormap=None, shade=True, alpha=0.4, zoffset=0, **kwargs)¶
Plots matplotlib’s static figure of BZ/Cell. You can also plot in 2D on a 3D axes.
- Parameters:
plane (str) – Default is None and plots 3D surface. Can take ‘xy’,’yz’,’zx’ to plot in 2D.
fill (bool) – True by defult, determines whether to fill surface of BZ or not.
fill_zorder (int) – Default is 0, determines zorder of filled surface in 2D plots if fill=True.
color (Any) – Color to fill surface and stroke color. Default is ‘blue’. Can be any valid matplotlib color.
vectors (tuple) – Tuple of indices of basis vectors to plot. Default is (0,1,2). All three are plotted in 3D (you can turn of by None or empty tuple), whhile you can specify any two/three in 2D. Vectors do not appear if given data is subzone data.
ax (matplotlib.pyplot.Axes) – Auto generated by default, 2D/3D axes, auto converts in 3D on demand as well.
colormap (str) – If None, single color is applied, only works in 3D and fill=True. Colormap is applied along z.
shade (bool) – Shade polygons or not. Only works in 3D and fill=True.
alpha (float) – Opacity of filling in range [0,1]. Increase for clear viewpoint.
zoffset (float) – Only used if plotting in 2D over a 3D axis. Default is 0. Any plane ‘xy’,’yz’ etc.
kwargs are passed to plt.plot or Poly3DCollection if fill=True.
- Returns:
Matplotlib’s 2D axes if plane=None otherswise 3D axes.
- Return type:
matplotlib.pyplot.Axes
- iplot(fill=False, color='rgba(84,102,108,0.8)', special_kpoints=True, alpha=0.4, ortho3d=True, fig=None, **kwargs)¶
Plots interactive figure showing axes,BZ surface, special points and basis, each of which could be hidden or shown.
- Parameters:
fill (bool) – False by defult, determines whether to fill surface of BZ or not.
color (str) – Color to fill surface ‘rgba(84,102,108,0.8)` by default. This sholud be a valid Plotly color.
special_kpoints (bool or callable) – True by default, determines whether to plot special points or not. You can also proivide a mask function f(x,y,z) -> bool which will be used to filter special points based on their fractional coordinates. This is ignored if BZ is primitive.
alpha (float) – Opacity of BZ planes.
ortho3d (bool) – Default is True, decides whether x,y,z are orthogonal or perspective.
fig (plotly.graph_objects.Figure) – Plotly’s go.Figure. If you want to plot on another plotly’s figure, provide that.
kwargs are passed to plotly.graph_objects.Scatter3d for BZ lines.
- Return type:
plotly.graph_objects.Figure
- property faces_coords¶
Returns the coordinates of the faces of the cell in list of N faces of shape (M,3) where M is the number of vertices of the face.
- property normals¶
Get normal vectors to the faces of Cell. Returns a tuple of 6 arrays as (X,Y,Z,U,V,W) where (X,Y,Z) is the center of the faces and (U,V,W) is the normal direction.
Spatial Toolkit¶
- ipyvasp.core.spatial_toolkit.tan_inv(vy, vx)[source]¶
Returns full angle from x-axis counter clockwise.
- Parameters:
vy (Perpendicular componet of vector including sign.) –
vx (Base compoent of vector including sign.) –
- ipyvasp.core.spatial_toolkit.order(points, loop=True)[source]¶
Returns indices of counterclockwise ordered vertices of a plane in 3D.
- Parameters:
points (numpy array of shape (N,3) or List[List(len=3)].) –
loop (Default is True and appends start point at end to make a loop.) –
Example
>>> pts = np.array([[1,0,3],[0,0,0],[0,1,2]]) >>> inds = order(pts) >>> pts[inds] # Ordered points array([[1, 2, 3], [0, 0, 0], [1, 0, 3] [0, 1, 2]])
- ipyvasp.core.spatial_toolkit.angle_rad(v1, v2)[source]¶
Returns interier angle between two vectors in radians.
- ipyvasp.core.spatial_toolkit.angle_deg(v1, v2)[source]¶
Returns interier angle between two vectors in degrees.
- ipyvasp.core.spatial_toolkit.outer_side(test_point, plane)[source]¶
Returns True if test_point is between plane and origin. Could be used to sample BZ mesh in place of ConvexHull.
- Parameters:
test_point (array_like 3D point.) –
plane (List of at least three coplanar 3D points.) –
- ipyvasp.core.spatial_toolkit.to_plane(normal, points)[source]¶
Project points to a plane defined by normal. shape of normal should be (3,) and of points (N,3).
- ipyvasp.core.spatial_toolkit.rotation(angle_deg, axis_vec)[source]¶
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.]
- ipyvasp.core.spatial_toolkit.coplanar(points, tol=1e-05)[source]¶
Returns true if points are coplanar within tol tolerance.
- ipyvasp.core.spatial_toolkit.to_R3(basis, points)[source]¶
Transforms coordinates of points (relative to non-othogonal basis) into orthogonal space.
- Parameters:
basis (array_like) – 3x3 matrix with basis vectors as rows like [[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]].
points (array_like) – Nx3 points relative to basis, such as KPOINTS and Lattice Points.
Conversion formula: [x,y,z] = n1*b1 + n2*b2 +n3*b3 = [n1, n2, n3] @ [[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]]
Note
Do not use this function if points are Cartesian or provide identity basis.
- ipyvasp.core.spatial_toolkit.to_basis(basis, coords)[source]¶
Transforms coordinates of points (relative to othogonal basis) into basis space.
- Parameters:
basis (array_like) – 3x3 matrix with basis vectors as rows like [[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]].
coords (array_like) – Nx3 points relative to cartesian axes.
Conversion formula: [n1, n2, n3] = [x,y,z] @ inv([[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]])
- ipyvasp.core.spatial_toolkit.get_TM(basis1, basis2)[source]¶
Returns a transformation matrix that gives basis2 when applied on basis1. basis are 3x3 matrices with basis vectors as rows like [[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]].
>>> from ipyvasp.core.spatial_toolkit import get_TM >>> TM = get_TM(basis1, basis2) # Can be ipyvasp.POSCAR.get_TM(basis2) while basis1 is POSCAR.data.basis >>> assert np.allclose(basis2, TM @ basis1) >>> Q = P @ TM.T # Transform points from P in basis1 to Q in basis2 >>> # Both P and Q are N x D matrices where N is number of points and D is dimension of space ```
- ipyvasp.core.spatial_toolkit.get_bz(basis, loop=True, primitive=False)[source]¶
Return required data to construct first Brillouin zone.
- Parameters:
basis (array_like, shape (3, 3) in reciprocal space.) –
loop (If True, joins the last vertex of a BZ plane to starting vertex in order to complete loop.) –
primitive (Defualt is False and returns Wigner-Seitz cell, If True returns parallelipiped of basis in reciprocal space.) –
- Returns:
BrZoneData(basis, vertices, faces).
You can access special points with .get_special_points method or by default from .specials property.
You can access coordinates of faces with .faces_coords property.
You can access normals vectors of faces with .normals property.
- ipyvasp.core.spatial_toolkit.kpoints2bz(bz_data, kpoints, shift=0, keep_geomerty=False)[source]¶
Brings KPOINTS inside BZ. Applies to_R3 only if BZ is primitive.
- Parameters:
bz_data (Output of get_bz().) –
kpoints (array_like) – List or array of KPOINTS to transform into BZ or R3.
shift (float) – This value is added to kpoints before any other operation, single number of list of 3 numbers for each direction.
keep_geomerty (bool) – If True, returns kpoints in R3 with shift applied, keeping the neighbors in order, else kpoints adopt the shape of BZ. This is useful when you already created cartesian kpoints mesh and want to collect their fractional coordinates back to cartesian.
- ipyvasp.core.spatial_toolkit.simplify_faces(vertices, faces, loop=True)[source]¶
Simplifies faces by merging adjacent coplanar faces.
- Parameters:
vertices (array_like) – List of vertices of faces. Should be cartesian coordinates.
faces (array_like) – List of faces, each face is a list of indices of vertices.
loop (bool) – If True, joins the last vertex of a face to starting vertex in order to complete loop.
- Return type:
faces
Plot Toolkit¶
- ipyvasp.core.plot_toolkit.global_matplotlib_settings(rcParams={}, display_format='svg')[source]¶
Set global matplotlib settings for notebook.
- ipyvasp.core.plot_toolkit.quiver3d(X, Y, Z, U, V, W, ax=None, C='r', L=0.7, mutation_scale=10, **kwargs)[source]¶
Plots 3D arrows on a given ax. See FancyArrowPatch for more details.
X, Y, Z
should be 1D arrays of coordinates of arrows tail point.U, V, W
should be 1D arrays of dx,dy,dz of arrows.- Parameters:
ax (matplotlib.pyplot.Axes) – 3D axes, if not given, auto created.
C (array_like) – 1D colors array mapping for arrows. Could be one color.
L (array_like) – 1D linwidths array mapping for arrows. Could be one linewidth.
mutation_scale (float) – Arrow head width/size scale. Default is 10.
kwargs are passed to
FancyArrowPatch
excluding positions, color, lw, mutation_scale, shrinkA, shrinkB which are already used. An important keyword argument is arrowstyle which could be any style valid in matplotlib.
- ipyvasp.core.plot_toolkit.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)[source]¶
Returns 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) – Tuple (width, height). Default is (3.4,2.6).
nrows (int) – Default 1.
ncols (int) – Default 1.
widths (list) – List with len(widths)==nrows, to set width ratios of subplots.
heights (list) – List with len(heights)==ncols, to set height ratios of subplots.
sharex (bool) – Share x-axis between plots, this removes shared ticks automatically.
sharey (bool) – Share y-axis between plots, this removes shared ticks automatically.
axes_off (bool or list) – 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 (bool or list) – 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.
ortho3d (bool) – Only works for 3D axes. If True, x,y,z are orthogonal, otherwise perspective.
azim, elev are passed to ax.view_init. Defualt values are 45,15 respectively.
subplots_adjust_kwargs are passed to plt.subplots_adjust.
Note
There are extra methods added to each axes (only 2D) object.
add_text
,add_legend
,add_colorbar
,color_wheel
,break_spines
,adjust_axes
,append_axes
,join_axes
.
- ipyvasp.core.plot_toolkit.adjust_axes(ax=None, xticks=[], xticklabels=[], xlim=[], yticks=[], yticklabels=[], ylim=[], xlabel=None, ylabel=None, vlines=False, **kwargs)[source]¶
Applies given settings on axes obect and returns None.
- Parameters:
ax (matplotlib.pyplot.Axes) – Matplotlib axes object on which settings are applied.
vlines (bool) – If True, draw vertical lines at points of xticks.
Other parameters are well known matplotlib parameters.
kwargs are passed to ax.tick_params
- ipyvasp.core.plot_toolkit.append_axes(ax, position='right', size=0.2, pad=0.1, sharex=False, sharey=False, **kwargs)[source]¶
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.
- ipyvasp.core.plot_toolkit.join_axes(ax1, ax2, **kwargs)[source]¶
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.
- ipyvasp.core.plot_toolkit.break_spines(ax, spines, symbol='╱', **kwargs)[source]¶
Simulates broken axes using subplots. Need to fix heights according to given data for real aspect. Also plot the same data on each axes and set axes limits.
- Parameters:
ax (matplotlib.pyplot.Axes) – Axes who’s spine(s) to edit.
spines (str or list) – str/list of any of [‘top’,’bottom’,’left’,’right’].
symbol (str) – Defult is u’╱’. Its at 60 degrees. so you can apply rotation to make it any angle.
kwargs are passed to plt.text.
- ipyvasp.core.plot_toolkit.add_text(ax=None, xs=0.25, ys=0.9, txts='[List]', colors='r', transform=True, **kwargs)[source]¶
Adds text entries on axes, given single string or list.
- Parameters:
xs (float or array_like) – List of x coordinates relative to axes or single coordinate.
ys (float or array_like) – List of y coordinates relative to axes or single coordinate.
txts (str or array_like) – List of strings or one string.
colors (array_like or Any) – List of colors of txts or one color.
transform (bool) – Dafault is True and positions are relative to axes, If False, positions are in data coordinates.
kwargs are passed to plt.text.
- ipyvasp.core.plot_toolkit.add_legend(ax=None, colors=[], labels=[], styles='solid', widths=0.7, anchor=(0, 1), ncol=3, loc='lower left', fontsize='small', frameon=False, **kwargs)[source]¶
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.) –
anchor (kwargs are passed to plt.legend. Given arguments like) –
preferred. (ncol etc are) –
- ipyvasp.core.plot_toolkit.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)[source]¶
Plots colorbar on a given axes. This axes should be only for colorbar.
- 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 (Minimum and maximum values. Only work if ticks are given.) –
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
- Return type:
Matplotlib axes for colorbar, you can customize further.
- ipyvasp.core.plot_toolkit.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)[source]¶
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 (bool, default is True.) –
- ipyvasp.core.plot_toolkit.color_cube(ax, colormap='brg', loc=(1, 0.4), size=0.2, N=7, labels=['s', 'p', 'd'], color='k', fontsize=10)[source]¶
Color-mapped hexagon that serves as a legend for splot_rgb_lines
- ipyvasp.core.plot_toolkit.webshow(transparent=False)[source]¶
Displays all available figures in browser without blocking terminal
- ipyvasp.core.plot_toolkit.plt2text(plt_fig=None, width=144, vscale=0.96, colorful=True, invert=False, crop=False, outfile=None)[source]¶
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.) –
- ipyvasp.core.plot_toolkit.plt2html(plt_fig=None, transparent=True)[source]¶
Returns
ipython.display.HTML(<svg of figure>)
. It clears figure after use. Soplt.show()
will not work after this.- Parameters:
plt_fig (Matplotlib's figure instance, auto picks as well.) –
transparent (True of False for fig background.) –
- ipyvasp.core.plot_toolkit.iplot2html(fig, outfile=None, modebar=True)[source]¶
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.) –
outfile (Name of file to save fig. Defualt is None and show plot in Notebook.) –
modebar (If True, shows modebar in graph. Default is True. Not used if saving to file.) –
- ipyvasp.core.plot_toolkit.iplot2widget(fig, fig_widget=None, template=None)[source]¶
Converts plotly’s figure to FigureWidget by copying attributes and data. If fig_widget is provided, it will update it. Adds template if provided. If fig is FigureWidget, it is just returned
- ipyvasp.core.plot_toolkit.image2plt(image_or_fname, ax=None, crop=None, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)[source]¶
Plot PIL image, numpy array or image file on given matploltib axes. crop is list or tuple of [x0,y0,x1,y1] in [0,1] interval. kwargs are passed to plt.imshow.
Additional Utilities¶
- ipyvasp.utils.take(f, rows, cols=None, dtype=None, exclude=None, sep=None)[source]¶
Read data from an opened file pointer f by indexing. rows=None picks all lines. Negative indexing is supported to read lines from end. Negative indexing is not supported in cols because of variable length of each line. If cols=None, returns a single str of line if one integer given, otherwise a list of lines. If cols is int ot sequence of int, each line is splitted by sep (default all whitespaces) and dtype is applied over resulting fields. exclude should be regex. It removes matching lines after selection by rows. Empty lines are also discarded if cols is given.
Returns list (nested or plain) or single value or None based on rows and cols selection.
take(f, -1, 1, float) == float(f.readlines()[-1].split()[1]) with advantage for consuming almost no memory as compared to f.readlines() on a huge file.
Note
For more robust reading of structured files like PROCAR use ipyvasp.parse_text function.
Tip
If your output is matrix-like, you can cast it to numpy array like take(…)*np.array(1).
>>> with open('some_file','r') as f: >>> take(f, -1, 1, float) # read last line, second column as float >>> take(f, range(5)) # first 5 lines >>> take(f, range(-5,0)) # last 5 lines
- ipyvasp.utils.set_dir(path: str)[source]¶
Context manager to work in some directory and come back.
>>> with set_dir('some_folder'): >>> do_something() >>> # Now you are back in starting directory
- ipyvasp.utils.interpolate_data(x: ndarray, y: ndarray, n: int = 10, k: int = 3) tuple [source]¶
Returns interpolated xnew,ynew. If two points are same, it will add 0.1*min(dx>0) to compensate it.
- Parameters:
x (ndarry, 1D array of size p,) –
y (ndarray, ndarray of size p*q*r,....) –
n (int, Number of points to add between two given points.) –
k (int, Polynomial order to interpolate.) –
Example
For
K(p),E(p,q)
input from bandstructure, doKnew, Enew = interpolate_data(K,E,n=10,k=3)
for cubic interploation.- Returns:
tuple
- Return type:
(xnew, ynew) after interpolation.
Note
Only axis 0 will be interpolated. If you want general interploation, use
from scipy.interpolate import make_interp_spline, BSpline
.
- ipyvasp.utils.rolling_mean(X: ndarray, period: float, period_right: float | None = None, interface: float | None = None, mode: str = 'wrap', smoothness: int = 2) ndarray [source]¶
Caluate rolling mean of array X using scipy.ndimage.filters.convolve1d.
- Parameters:
X (ndarray, 1D numpy array.) –
period (float, In range [0,1]. Period of rolling mean. Applies left side of X from center if period_right is given.) –
period_right (float, In range [0,1]. Period of rolling mean on right side of X from center.) –
interface (float, In range [0,1]. The point that divides X into left and right, like in a slab calculation.) –
mode (string, Mode of convolution. Default is wrap to keep periodcity of crystal in slab caluation. Read scipy.ndimage.filters.convolve1d for more info.) –
smoothness (int, Default is 2. Order of making the output smoother. Larger is better but can't be too large as there will be points lost at each convolution.) –
- Returns:
ndarray
- Return type:
convolved array of same size as X if mode is ‘wrap’. May be smaller if mode is something else.
- class ipyvasp.utils.color[source]¶
Bases:
object
- r()¶
- rb()¶
- g()¶
- gb()¶
- b()¶
- bb()¶
- y()¶
- yb()¶
- m()¶
- mb()¶
- c()¶
- cb()¶
- ipyvasp.utils.transform_color(arr: ndarray, s: float = 1, c: float = 1, b: float = 0, mixing_matrix: ndarray | None = None) ndarray [source]¶
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 (ndarray, 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 (float, contrast, default is 1. Can be a float in [-1,1].) –
s (float, saturation, default is 1. Can be a float in [-1,1]. If s = 0, you get a gray scale image.) –
b (float, brightness, default is 0. Can be a float in [-1,1] or list of three brightnesses for RGB components.) –
mixing_matrix (ndarray, A 3x3 matrix to mix RGB values, such as ipyvas.utils.color_matrix.) –
- Returns:
ndarray (Transformed color array of same shape as input array.)
See `Recoloring <https (//docs.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-recoloring-use?redirectedfrom=MSDN>`_)
and `Rainmeter <https (//docs.rainmeter.net/tips/colormatrix-guide/>`_ for useful information on color transformation.)
- ipyvasp.utils.create_colormap(name='RB', colors=[(0.9, 0, 0), (0, 0, 0.9)])[source]¶
Create and register a custom colormap from a list of RGB colors. and then use it’s name in plottoing functions to get required colors.
- Parameters:
name (str, name of the colormap) –
colors (list of RGB colors, e.g. [(0.9,0,0),(0,0,0.9)] or named colors, e.g. ['red','blue'], add as many colors as you want.) –
- Return type:
Colormap object which you can use to get colors from. like cm = create_colormap(); cm(0.5) which will return a color at center of map
Bandstructure and Density of States¶
- ipyvasp.bsdos.splot_bands(K, E, ax=None, elim=None, kticks=None, interp=None, **kwargs)[source]¶
Plot band structure for a single spin channel and return the matplotlib axes which can be used to add other channel if spin polarized.
- Parameters:
K (array-like) – Array of kpoints with shape (nkpts,)
E (array-like) – Array of eigenvalues with shape (nkpts, nbands)
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
kwargs are passed to matplotlib’s command plt.plot.
- Return type:
matplotlib.pyplot.Axes
- ipyvasp.bsdos.iplot_bands(K, E, occs=None, fig=None, elim=None, kticks=None, interp=None, title=None, **kwargs)[source]¶
Plot band structure using plotly.
- Parameters:
K (array-like) – Array of kpoints with shape (nkpts,)
E (array-like) – Array of eigenvalues with shape (nkpts, nbands)
fig (plotly.graph_objects.Figure) – If not given, create a new figure.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
title (str, title of plot) –
kwargs are passed to plotly.graph_objects.Scatter
- Return type:
plotly.graph_objects.Figure
- ipyvasp.bsdos.splot_rgb_lines(K, E, pros, labels, ax=None, elim=None, kticks=None, interp=None, maxwidth=3, uniwidth=False, colormap=None, colorbar=True, N=9, shadow=False)[source]¶
Plot projected band structure for a given projections.
- Parameters:
K (array-like) – Array of kpoints with shape (nkpts,)
E (array-like) – Array of eigenvalues with shape (nkpts, nbands)
pros (array-like) – Projections of shape (m,nk,nb), m is the number of projections. m <= 3 in rgb case.
labels (list) – As many labels for as projections.
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
maxwidth (float) – Maximum linewidth to which the projections line width will be scaled. Default is 3.
uniwidth (bool) – If True, use same linewidth for all patches to maxwidth/2. Otherwise, use linewidth proportional to projection value.
colormap (str) – A valid matplotlib colormap name.
colorbar (bool) – If True, add colorbar, otherwise add attribute to ax to add colorbar or color cube later
N (int) – Number of colors in colormap
shadow (bool) – If True, add shadow to lines
- Returns:
Returned ax has additional attributes: .add_colorbar() : Add colorbar that represents most recent plot .color_cube() : Add color cube that represents most recent plot if pros is 3 components
- Return type:
matplotlib.pyplot.Axes
- ipyvasp.bsdos.iplot_rgb_lines(K, E, pros, labels, occs, kpoints, fig=None, elim=None, kticks=None, interp=None, maxwidth=10, mode='markers + lines', title=None, **kwargs)[source]¶
Interactive plot of band structure with rgb data points using plotly.
- Parameters:
K (array-like) – Array of kpoints with shape (nkpts,)
E (array-like) – Array of eigenvalues with shape (nkpts, nbands)
pros (array-like) – Projections of shape (m,nk,nb), m is the number of projections. m <= 3 in rgb case.
labels (list) – As many labels for as projections.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
occs (array-like, shape (nk,nb)) –
kpoints (array-like, shape (nk,3)) –
fig (plotly.graph_objects.Figure, if not provided, a new figure will be created) –
maxwidth (float, maximum linewidth, 10 by default) –
mode (str, plotly mode, ‘markers + lines’ by default, see modes in plotly.graph_objects.Scatter.) –
title (str, title of the figure, labels are added to the end of the title.) –
plotly.graph_objects.Scatter. (kwargs are passed to) –
- Return type:
plotly.graph_objects.Figure
- ipyvasp.bsdos.splot_color_lines(K, E, pros, labels, axes=None, elim=None, kticks=None, interp=None, maxwidth=3, colormap=None, shadow=False, showlegend=True, xyc_label=[0.2, 0.85, 'black'], **kwargs)[source]¶
Plot projected band structure for a given projections.
- Parameters:
K (array-like) – Array of kpoints with shape (nkpts,)
E (array-like) – Array of eigenvalues with shape (nkpts, nbands)
pros (array-like) – Projections of shape (m,nk,nb), m is the number of projections. m <= 3 in rgb case.
labels (list) – As many labels for as projections.
axes (matplotlib.axes.Axes or list of Axes) – Number of axes should be 1 or equal to the number of projections to plot separately. If None, creates new axes.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
maxwidth (float) – Maximum linewidth to which the projections line width will be scaled. Default is 3.
colormap (str) – A valid matplotlib colormap name.
shadow (bool) – If True, add shadow to lines
showlegend (bool) – If True, add legend, otherwise adds a label to the plot.
xyc_label (list or tuple) – List of (x, y, color) for the label. Used only if showlegend = False
kwargs are passed to matplotlib’s command ax.legend.
- Return type:
One or as many matplotlib.axes.Axes as given by axes parameter.
- ipyvasp.bsdos.splot_dos_lines(energy, dos_arrays, labels, ax=None, elim=None, colormap='tab10', colors=None, fill=True, vertical=False, stack=False, interp=None, showlegend=True, legend_kws={'anchor': (0, 1.0), 'ncol': 4}, **kwargs)[source]¶
Plot density of states (DOS) lines.
- Parameters:
energy (array-like, shape (n,)) –
dos_arrays (list of array_like, each of shape (n,) or array-like (m,n)) –
labels (list of str, length = len(dos_arrays) should hold.) –
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
colormap (str) – A valid matplotlib colormap name.
colors (list of str, length = len(dos_arrays) should hold if given, and will override colormap.) –
fill (bool, default True, if True, fill the area under the DOS lines.) –
vertical (bool, default False, if True, plot DOS lines vertically.) –
stack (bool, default False, if True, stack the DOS lines. Only works for horizontal plots.) –
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
showlegend (bool, default True, if True, show legend.) –
legend_kws (dict, default is just hint, anything that ipyvasp.add_legend accepts can be passed, only used if showlegend is True.) –
matplotlib.axes.Axes.fill_betweenx. (keyword arguments are passed to matplotlib.axes.Axes.plot or matplotlib.axes.Axes.fill_between or) –
- Return type:
matplotlib.pyplot.Axes
- ipyvasp.bsdos.iplot_dos_lines(energy, dos_arrays, labels, fig=None, elim=None, colormap='tab10', colors=None, fill=True, vertical=False, stack=False, mode='lines', interp=None, **kwargs)[source]¶
Plot density of states (DOS) lines.
- Parameters:
energy (array-like, shape (n,)) –
dos_arrays (list of array_like, each of shape (n,) or array-like (m,n)) –
labels (list of str, length = len(dos_arrays) should hold.) –
fig (plotly.graph_objects.Figure, if not provided, a new figure will be created) –
{elim} –
{colormap} –
colors (list of str, length = len(dos_arrays) should hold if given, and will override colormap. Should be valid CSS colors.) –
fill (bool, default True, if True, fill the area under the DOS lines.) –
vertical (bool, default False, if True, plot DOS lines vertically.) –
mode (str, default ‘lines’, plotly mode, see modes in plotly.graph_objects.Scatter.) –
stack (bool, default False, if True, stack the DOS lines. Only works for horizontal plots.) –
{interp} –
keyword arguments are passed to plotly.graph_objects.Scatter. {return_fig}
- class ipyvasp.bsdos.Bands(source)[source]¶
Bases:
_BandsDosBase
Class to handle and plot bandstructure data.
- Parameters:
source (instance of ipyvasp.DataSource such as ipyvasp.Vasprun or ipyvasp.Vaspout.) –
ipyvasp.DataSource. (You can define your own class to parse data with same attributes and methods by subclassing) –
- get_kticks(rel_path='KPOINTS')[source]¶
Reads associated KPOINTS file form a relative path of calculations and returns kticks. If KPOINTS file does not exist or was not created by this module, returns empty dict.
- get_plot_coords(kindices, eindices)[source]¶
Returns coordinates of shape (len(zip(kindices, eindices)), 2) from most recent bandstructure plot. Use in a plot command as plt.plot(*get_plot_coords(kindices, eindices).T). Enegy values are shifted by ezero from a plot command or data. Use coords + [0, ezero] to get data values.
- property gap¶
Retruns band gap data with following attributes:
coords : array of shape (2, 2) -> (K,E) band gap in coordinates of most recent plot if exists, otherwise in data coordinates. X,Y = coords.T for plotting purpose. value : band gap value in eV given by E_gap = cbm - vbm. vbm, cbm : valence and conduction band energies in data coordinates. No shift is applied. kvbm, kcbm : kpoints of vbm and cbm in fractional coordinates. Useful to know which kpoint is at the band gap.
These attributes will be None if band gap cannot be found. coords will be empty array of size (0,2) in that case.
- get_data(elim=None, ezero=None, projections: dict | None = None, kpairs=None, bands=None)[source]¶
Selects bands and projections to use in plotting functions. If input arguments are same as previous call, returns cached data.
- Parameters:
elim (list, tuple of two floats to pick bands in this energy range. If None, picks all bands.) –
ezero (float, None by default. If not None, elim is applied around this energy.) –
projections (dict, str -> [atoms, orbs]. Use dict to select specific projections, e.g. {'Ga-s': (0,[0]), 'Ga1-p': ([0],[1,2,3])} in case of GaAs. If values of the dict are callable, they must accept two arguments evals, occs of shape (spin,kpoints, bands) and return array of shape (kpoints, bands).) –
kpairs (list, tuple of integers, None by default to select all kpoints in given order. Use this to select specific kpoints intervals in specific order.) –
bands (list,tuple of integers, this ovverides elim if given.) –
- Returns:
data
- Return type:
Selected bands and projections data to be used in bandstructure plotting functions under this class as data argument.
- splot_bands(spin=0, kpairs=None, ezero=None, bands=None, ax=None, elim=None, kticks=None, interp=None, **kwargs)[source]¶
Plot band structure for a single spin channel and return the matplotlib axes which can be used to add other channel if spin polarized.
- Parameters:
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
kpairs (list/tuple) – List of pair of indices to rearrange a computed path. For example, if you computed 0:L, 15:G, 25:X, 34:M path and want to plot it as X-G|M-X, use [(25,15), (34,25)] as kpairs.
bands (list/tuple) – List of indices of bands. If given, this ovverides elim.
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
kwargs are passed to matplotlib’s command plt.plot.
- Return type:
matplotlib.pyplot.Axes
- splot_rgb_lines(projections, spin=0, kpairs=None, ezero=None, bands=None, ax=None, elim=None, kticks=None, interp=None, maxwidth=3, uniwidth=False, colormap=None, colorbar=True, N=9, shadow=False)[source]¶
Plot projected band structure for a given projections.
- Parameters:
projections (dict) – Mapping from str -> [atoms, orbs]. Use dict to select specific projections, e.g. {‘Ga-s’:(0,[0]),’Ga-px+py’:(0,[2,3]),’Ga-all’:(0,’all’)} or {‘Ga-s’:(‘Ga’,’s’),’Ga-px+py’:(0,’px+py’),’all-d’:(‘all’,’d’)}. If values of the dict are callable, they must accept two arguments evals/tdos, occs/idos of from data and should return array of shape[1:] (all but spin dimension).
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
kpairs (list/tuple) – List of pair of indices to rearrange a computed path. For example, if you computed 0:L, 15:G, 25:X, 34:M path and want to plot it as X-G|M-X, use [(25,15), (34,25)] as kpairs.
bands (list/tuple) – List of indices of bands. If given, this ovverides elim.
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
maxwidth (float) – Maximum linewidth to which the projections line width will be scaled. Default is 3.
uniwidth (bool) – If True, use same linewidth for all patches to maxwidth/2. Otherwise, use linewidth proportional to projection value.
colormap (str) – A valid matplotlib colormap name.
colorbar (bool) – If True, add colorbar, otherwise add attribute to ax to add colorbar or color cube later
N (int) – Number of colors in colormap
shadow (bool) – If True, add shadow to lines
- Returns:
Returned ax has additional attributes: .add_colorbar() : Add colorbar that represents most recent plot .color_cube() : Add color cube that represents most recent plot if pros is 3 components
- Return type:
matplotlib.pyplot.Axes
- splot_color_lines(projections, spin=0, kpairs=None, ezero=None, bands=None, axes=None, elim=None, kticks=None, interp=None, maxwidth=3, colormap=None, shadow=False, showlegend=True, xyc_label=[0.2, 0.85, 'black'], **kwargs)[source]¶
Plot projected band structure for a given projections.
- Parameters:
projections (dict) – Mapping from str -> [atoms, orbs]. Use dict to select specific projections, e.g. {‘Ga-s’:(0,[0]),’Ga-px+py’:(0,[2,3]),’Ga-all’:(0,’all’)} or {‘Ga-s’:(‘Ga’,’s’),’Ga-px+py’:(0,’px+py’),’all-d’:(‘all’,’d’)}. If values of the dict are callable, they must accept two arguments evals/tdos, occs/idos of from data and should return array of shape[1:] (all but spin dimension).
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
kpairs (list/tuple) – List of pair of indices to rearrange a computed path. For example, if you computed 0:L, 15:G, 25:X, 34:M path and want to plot it as X-G|M-X, use [(25,15), (34,25)] as kpairs.
bands (list/tuple) – List of indices of bands. If given, this ovverides elim.
axes (matplotlib.axes.Axes or list of Axes) – Number of axes should be 1 or equal to the number of projections to plot separately. If None, creates new axes.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
maxwidth (float) – Maximum linewidth to which the projections line width will be scaled. Default is 3.
colormap (str) – A valid matplotlib colormap name.
shadow (bool) – If True, add shadow to lines
showlegend (bool) – If True, add legend, otherwise adds a label to the plot.
xyc_label (list or tuple) – List of (x, y, color) for the label. Used only if showlegend = False
kwargs are passed to matplotlib’s command ax.legend.
- Return type:
One or as many matplotlib.axes.Axes as given by axes parameter.
- iplot_rgb_lines(projections, spin=0, kpairs=None, ezero=None, bands=None, fig=None, elim=None, kticks=None, interp=None, maxwidth=10, mode='markers + lines', title=None, **kwargs)[source]¶
Interactive plot of band structure with rgb data points using plotly.
- Parameters:
projections (dict) – Mapping from str -> [atoms, orbs]. Use dict to select specific projections, e.g. {‘Ga-s’:(0,[0]),’Ga-px+py’:(0,[2,3]),’Ga-all’:(0,’all’)} or {‘Ga-s’:(‘Ga’,’s’),’Ga-px+py’:(0,’px+py’),’all-d’:(‘all’,’d’)}. If values of the dict are callable, they must accept two arguments evals/tdos, occs/idos of from data and should return array of shape[1:] (all but spin dimension).
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
kpairs (list/tuple) – List of pair of indices to rearrange a computed path. For example, if you computed 0:L, 15:G, 25:X, 34:M path and want to plot it as X-G|M-X, use [(25,15), (34,25)] as kpairs.
bands (list/tuple) – List of indices of bands. If given, this ovverides elim.
fig (plotly.graph_objects.Figure, if not provided, a new figure will be created) –
maxwidth (float, maximum linewidth, 10 by default) –
mode (str, plotly mode, ‘markers + lines’ by default, see modes in plotly.graph_objects.Scatter.) –
title (str, title of the figure, labels are added to the end of the title.) –
plotly.graph_objects.Scatter. (kwargs are passed to) –
- Return type:
plotly.graph_objects.Figure
- iplot_bands(spin=0, kpairs=None, ezero=None, bands=None, occs=None, fig=None, elim=None, kticks=None, interp=None, title=None, **kwargs)[source]¶
Plot band structure using plotly.
- Parameters:
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
kpairs (list/tuple) – List of pair of indices to rearrange a computed path. For example, if you computed 0:L, 15:G, 25:X, 34:M path and want to plot it as X-G|M-X, use [(25,15), (34,25)] as kpairs.
bands (list/tuple) – List of indices of bands. If given, this ovverides elim.
fig (plotly.graph_objects.Figure) – If not given, create a new figure.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
kticks (list) – List of pairs [(int, str),…] for indices of high symmetry k-points. To join a broken path, use ‘<=’ before symbol, e.g. [(0, ‘G’),(40, ‘<=K|M’), …] will join 40 back to 39. You can also use shortcut like zip([0,10,20],’GMK’).
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
title (str, title of plot) –
kwargs are passed to plotly.graph_objects.Scatter
- Return type:
plotly.graph_objects.Figure
- class ipyvasp.bsdos.DOS(source)[source]¶
Bases:
_BandsDosBase
Class to handle and plot density of states data.
- Parameters:
source (instance of ipyvasp.DataSource such as ipyvasp.Vasprun or ipyvasp.Vaspout.) –
ipyvasp.DataSource. (You can define your own class to parse data with same attributes and methods by subclassing) –
- splot_dos_lines(projections=None, spin=0, multiply=1, total=True, ezero=None, ax=None, elim=None, colormap='tab10', colors=None, fill=True, vertical=False, stack=False, interp=None, showlegend=True, legend_kws={'anchor': (0, 1.0), 'ncol': 4}, **kwargs)[source]¶
Plot density of states (DOS) lines.
- Parameters:
projections (dict) – Mapping from str -> [atoms, orbs]. Use dict to select specific projections, e.g. {‘Ga-s’:(0,[0]),’Ga-px+py’:(0,[2,3]),’Ga-all’:(0,’all’)} or {‘Ga-s’:(‘Ga’,’s’),’Ga-px+py’:(0,’px+py’),’all-d’:(‘all’,’d’)}. If values of the dict are callable, they must accept two arguments evals/tdos, occs/idos of from data and should return array of shape[1:] (all but spin dimension).
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
multiply (float) – A float number to be multiplied by total dos and its sign is multiplied by partial dos to flip plot in case of spin down.
total (bool) – True by default. If False, total dos is not plotted, but sign of multiply parameter is still used for partial dos
ax (matplotlib.pyplot.Axes) – Matplotlib axes to plot on. If None, a new figure and axes will be created.
elim (list or tuple) – A list or tuple of length 2 for energy limits.
colormap (str) – A valid matplotlib colormap name.
colors (list of str, length = len(dos_arrays) should hold if given, and will override colormap.) –
fill (bool, default True, if True, fill the area under the DOS lines.) –
vertical (bool, default False, if True, plot DOS lines vertically.) –
stack (bool, default False, if True, stack the DOS lines. Only works for horizontal plots.) –
interp (int or list/tuple) – If int, n is number of points to interpolate. If list/tuple, n is number of points and k is the order of spline.
showlegend (bool, default True, if True, show legend.) –
legend_kws (dict, default is just hint, anything that ipyvasp.add_legend accepts can be passed, only used if showlegend is True.) –
matplotlib.axes.Axes.fill_betweenx. (keyword arguments are passed to matplotlib.axes.Axes.plot or matplotlib.axes.Axes.fill_between or) –
- Return type:
matplotlib.pyplot.Axes
- iplot_dos_lines(projections=None, spin=0, multiply=1, total=True, ezero=None, fig=None, elim=None, colormap='tab10', colors=None, fill=True, vertical=False, stack=False, mode='lines', interp=None, **kwargs)[source]¶
Plot density of states (DOS) lines.
- Parameters:
projections (dict) – Mapping from str -> [atoms, orbs]. Use dict to select specific projections, e.g. {‘Ga-s’:(0,[0]),’Ga-px+py’:(0,[2,3]),’Ga-all’:(0,’all’)} or {‘Ga-s’:(‘Ga’,’s’),’Ga-px+py’:(0,’px+py’),’all-d’:(‘all’,’d’)}. If values of the dict are callable, they must accept two arguments evals/tdos, occs/idos of from data and should return array of shape[1:] (all but spin dimension).
spin (int) – 0 by default. Use 0 for spin up and 1 for spin down for spin polarized calculations. Data for both channel is loaded by default, so when you plot one spin channel, plotting other with same parameters will use the same data.
multiply (float) – A float number to be multiplied by total dos and its sign is multiplied by partial dos to flip plot in case of spin down.
total (bool) – True by default. If False, total dos is not plotted, but sign of multiply parameter is still used for partial dos
fig (plotly.graph_objects.Figure, if not provided, a new figure will be created) –
{elim} –
{colormap} –
colors (list of str, length = len(dos_arrays) should hold if given, and will override colormap. Should be valid CSS colors.) –
fill (bool, default True, if True, fill the area under the DOS lines.) –
vertical (bool, default False, if True, plot DOS lines vertically.) –
mode (str, default ‘lines’, plotly mode, see modes in plotly.graph_objects.Scatter.) –
stack (bool, default False, if True, stack the DOS lines. Only works for horizontal plots.) –
{interp} –
keyword arguments are passed to plotly.graph_objects.Scatter. {return_fig}
Lattice Structure¶
- class ipyvasp.lattice.POSCAR(path=None, content=None, data=None)[source]¶
Bases:
object
- property path¶
- property last¶
Points to last created POSCAR instance during chained operations! You don’t need to store results.
`python pc = POSCAR() pc.filter_atoms(lambda a: a.index in pc.data.types.Ga) # FINE, can use a.symbol == 'Ga' too, but we need to show a point below pc.set_boundary([-2,2]).filter_atoms(lambda a: a.index in pc.data.types.Ga) # INCORRECT sites picked pc.set_boundary([-2,2]).filter_atoms(lambda a: a.index in pc.last.data.types.Ga) # PERFECT, pc.last is output of set_boundary `
- property auto_renderer¶
A renderer for auto viewing POSCAR when at last line of cell.
Use auto_renderer.on() to enable it. Use auto_renderer.off() to disable it. Use auto_renderer.[params, update_params()] to view and update parameters.
In Jupyterlab, you can use Create New View for Output to drag a view on side. In VS Code, you can open another view of Notebook to see it on side while doing operations.
- to_ase()[source]¶
Convert to ase.Atoms format. You need to have ase installed. You can apply all ase methods on this object after conversion.
Example
>>> from ase.visualize import view >>> structure = poscar.to_ase() >>> view(structure) # POSCAR.view() also uses this method if viewer is given. >>> reciprocal_lattice = structure.cell.get_bravais_lattice() >>> reciprocal_lattice.plt_bz() # Plot BZ usinn ase, it also plots suggested band path.
- view(viewer=None, **kwargs)[source]¶
View POSCAR in notebook. If viewer is given it will be passed ase.visualize.view. You need to have ase installed.
kwargs are passed to self.splot_lattice if viewer is None, otherwise a single keyword argument data is passed to ase viewer. data should be volumetric data for ase.visualize.view, such as charge density, spin density, etc.
Tip
Use
self.view_ngl()
if you don’t want to passviewer = 'nglview'
to ASE viewer or not showing volumetric data.
- view_ngl(colors=None, sizes=0.5, plot_cell=True, linewidth=0.05, color=[0, 0, 0.2], bond_color='whitesmoke', width='400px', height='400px', plot_vectors=True, dashboard=False, origin=(0, 0, 0), eqv_sites=True)[source]¶
Display structure in Jupyter notebook using nglview.
- Parameters:
colors (color or sheme name or dict of type -> color) – Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types. If colors = ‘element’, then element colors from nglview will be used. You can use nglview.color.COLOR_SCHEME to see available color schemes to use.
plot_cell (bool) – Plot unit cell. Default True.
linewidth (float) – Linewidth of cell edges.
color (list or str) – Color of cell edges. Must be a valid color to support conversion to RGB via matplotlib.
bond_color (str) – Color of bonds. Default “whitesmoke”. Can be “element” or any other scheme from nglview.
width (str) – Width of viewer. Default “400px”.
height (str) – Height of viewer. Default “400px”.
plot_vectors (bool) – Plot vectors. Default True. Only works if plot_cell = True.
dashboard (bool) – Show dashboard. Default False. It just sets view.gui_style = ‘NGL’.
- Returns:
NGLWidget – An instance of nglview.NGLWidget object. You can use .render_image(), .download_image() etc. on it or can add more representations.
.. note:: – nglview sometimes does not work in Jupyter lab. You can switch to classic notebook in that case.
.. tip:: – See Advanced NGLView usage.
- view_weas(sizes=1, colors=None, bond_length=None, model_style=1, plot_cell=True, origin=(0, 0, 0), eqv_sites=True)[source]¶
- sizesfloat or dict of type -> float
Size of sites. Either one int/float or a mapping like {‘Ga’: 2, …}.
- colorscolor, color scheme or dict of type -> color
Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types. You can use color schemes as ‘VESTA’,’JMOL’,’CPK’.
- sizeslist
List of sizes for each atom type.
- model_type: int
whether to show Balls (0), Ball + Stick (1), Polyheda (2) or Sticks (3).
- plot_cellbool
Plot unit cell. Default True.
- bond_lengthfloat or dict
Length of bond in Angstrom. Auto calculated if not provides. Can be a dict like {‘Fe-O’:3.2,…} to specify bond length between specific types.
Returns a WeasWidget instance. You can use .export_image, save_image and other operations on it. Read what you can do more with WeasWidget [here](https://weas-widget.readthedocs.io/en/latest/index.html).
- view_kpath(height='400px')[source]¶
Initialize a KPathWidget instance to view kpath for current POSCAR, and you can select others too.
- view_plotly(sizes=10, colors=None, bond_length=None, tol=0.01, eqv_sites=True, translate=None, origin=(0, 0, 0), fig=None, ortho3d=True, bond_kws={'line_width': 4}, site_kws={'line_color': 'rgba(1,1,1,0)', 'line_width': 0.001, 'opacity': 1}, plot_cell=True, label_sites=False, **kwargs)[source]¶
Plotly’s interactive plot of lattice.
- Parameters:
sizes (float or dict of type -> float) – Size of sites. Either one int/float or a mapping like {‘Ga’: 2, …}.
colors (color or dict of type -> color) – Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types.
bond_length (float or dict) – Length of bond in Angstrom. Auto calculated if not provides. Can be a dict like {‘Fe-O’:3.2,…} to specify bond length between specific types.
bond_kws (dict) – Keyword arguments passed to plotly.graph_objects.Scatter3d for bonds. Default is jus hint, you can use any keyword argument that is accepted by plotly.graph_objects.Scatter3d.
site_kws (dict) – Keyword arguments passed to plotly.graph_objects.Scatter3d for sites. Default is jus hint, you can use any keyword argument that is accepted by plotly.graph_objects.Scatter3d.
plot_cell (bool) – Defult is True. Plot unit cell with default settings. If you want to customize, use POSCAR.iplot_cell(fig = <return of iplot_lattice>) function.
kwargs are passed to iplot_bz.
- classmethod download(formula, mp_id, api_key=None, save_key=False)[source]¶
Downloads POSCAR from materials project. mp_id should be string associated with a material on their website. api_key is optional if not saved. Get your API key from https://legacy.materialsproject.org/open and save it using save_key to avoid entering it everytime.
- to_dict()[source]¶
Returns a dictionary that can be modified generally and passed to POSCAR.new method.
- classmethod new(basis, sites, scale=1, system=None)[source]¶
Crate a new POSCAR instance from basis and sites.
- Parameters:
basis (array_like of shape (3, 3)) –
sites (dict, key is element and value is array_like of shape (n, 3)) – For example, {‘Mg’: [[0, 0, 0]], ‘Cl’: [[1/3, 2/3,0.214],[2/3,1/3,0.786]]} for MgCl2.
scale (int or float used to scale basis and kept in metadata to use when writing to file.) –
system (str, name of the structure, if None, will be inferred from sites.) –
- classmethod from_clipborad()[source]¶
Read POSCAR from clipboard (based on clipboard reader impelemented by pandas library) It picks the latest from clipboard.
- to_clipboard()[source]¶
Writes POSCAR to clipboard (as implemented by pandas library) for copy in other programs such as vim.
- property data¶
Data object in POSCAR.
- property metadata¶
Metadata associated with this POSCAR.
- copy()[source]¶
Copy POSCAR object. It avoids accidental changes to numpy arrays in original object.
- property content¶
POSCAR content.
- property bz¶
Regular BZ data. Shortcut for get_bz(primitive = False).
- property pbz¶
Primitive BZ data. Shortcut for get_bz(primitive = True).
- property cell¶
- get_plane(hkl, d=0.5, tol=0.01)[source]¶
Returns tuple Plane(point, normal, vertices) of a plane bound inside cell. . hkl should be list of three miller indices. d is fractional distance in range 0,1 in direction of hkl. e.g. if there are 8 planes of atoms in a cubic cell, d = 0, 1/8,…7/8, 1 match position of those planes.
- splot_plane(hkl, d=0.5, tol=0.01, ax=None, **kwargs)[source]¶
Provide hkl and a 3D axes to plot plane. kwargs are passed to mpl_toolkits.mplot3d.art3d.Poly3DCollection Note: You may get wrong plane if your basis are not aligned to axes. So you can use transpose or set_zdir methods before plottling cell.
- iplot_plane(hkl, d=0.5, tol=0.001, fig=None, **kwargs)[source]¶
Plot plane on a plotly Figure. kwargs are passed to plotly.graph_objects.Mesh3d.
- get_bz(loop=True, primitive=False)[source]¶
Return required data to construct first Brillouin zone.
- Parameters:
loop (If True, joins the last vertex of a BZ plane to starting vertex in order to complete loop.) –
primitive (Defualt is False and returns Wigner-Seitz cell, If True returns parallelipiped of basis in reciprocal space.) –
- Returns:
BrZoneData(basis, vertices, faces).
You can access special points with .get_special_points method or by default from .specials property.
You can access coordinates of faces with .faces_coords property.
You can access normals vectors of faces with .normals property.
- get_cell(loop=True)[source]¶
See docs of get_bz, same except space is inverted and no factor of 2pi.
- splot_bz(plane=None, ax=None, color='blue', fill=False, fill_zorder=0, vectors=(0, 1, 2), colormap=None, shade=True, alpha=0.4, zoffset=0, **kwargs)[source]¶
Plots matplotlib’s static figure of BZ/Cell. You can also plot in 2D on a 3D axes.
- Parameters:
plane (str) – Default is None and plots 3D surface. Can take ‘xy’,’yz’,’zx’ to plot in 2D.
fill (bool) – True by defult, determines whether to fill surface of BZ or not.
fill_zorder (int) – Default is 0, determines zorder of filled surface in 2D plots if fill=True.
color (Any) – Color to fill surface and stroke color. Default is ‘blue’. Can be any valid matplotlib color.
vectors (tuple) – Tuple of indices of basis vectors to plot. Default is (0,1,2). All three are plotted in 3D (you can turn of by None or empty tuple), whhile you can specify any two/three in 2D. Vectors do not appear if given data is subzone data.
ax (matplotlib.pyplot.Axes) – Auto generated by default, 2D/3D axes, auto converts in 3D on demand as well.
colormap (str) – If None, single color is applied, only works in 3D and fill=True. Colormap is applied along z.
shade (bool) – Shade polygons or not. Only works in 3D and fill=True.
alpha (float) – Opacity of filling in range [0,1]. Increase for clear viewpoint.
zoffset (float) – Only used if plotting in 2D over a 3D axis. Default is 0. Any plane ‘xy’,’yz’ etc.
kwargs are passed to plt.plot or Poly3DCollection if fill=True.
- Returns:
Matplotlib’s 2D axes if plane=None otherswise 3D axes.
- Return type:
matplotlib.pyplot.Axes
- splot_kpath(kpoints, labels=None, fmt_label=<function <lambda>>, **kwargs)[source]¶
Plot k-path over existing BZ. It will take
ax
,plane
andzoffset
internally from most recent call tosplot_bz
/bz.splot
.- Parameters:
kpoints (array_like) – List of k-points in fractional coordinates. e.g. [(0,0,0),(0.5,0.5,0.5),(1,1,1)] in order of path.
labels (list) – List of labels for each k-point in same order as kpoints.
fmt_label (callable) – Function that takes a label from labels and should return a string or (str, dict) of which dict is passed to
plt.text
.
kwargs are passed to
plt.plot
with some defaults.You can get
kpoints = POSCAR.get_bz().specials.masked(lambda x,y,z : (-0.1 < z 0.1) & (x >= 0) & (y >= 0))
to get k-points in positive xy plane. Then you can reorder them by an indexer likekpoints = kpoints[[0,1,2,0,7,6]]
, note double brackets, and also that point at zero index is taken twice.Tip
You can use this function multiple times to plot multiple/broken paths over same BZ.
- splot_cell(plane=None, ax=None, color='blue', fill=False, fill_zorder=0, vectors=(0, 1, 2), colormap=None, shade=True, alpha=0.4, zoffset=0, **kwargs)[source]¶
See docs of splot_bz, everything is same except space is inverted.
- iplot_bz(fill=False, color='rgba(84,102,108,0.8)', special_kpoints=True, alpha=0.4, ortho3d=True, fig=None, **kwargs)[source]¶
Plots interactive figure showing axes,BZ surface, special points and basis, each of which could be hidden or shown.
- Parameters:
fill (bool) – False by defult, determines whether to fill surface of BZ or not.
color (str) – Color to fill surface ‘rgba(84,102,108,0.8)` by default. This sholud be a valid Plotly color.
special_kpoints (bool or callable) – True by default, determines whether to plot special points or not. You can also proivide a mask function f(x,y,z) -> bool which will be used to filter special points based on their fractional coordinates. This is ignored if BZ is primitive.
alpha (float) – Opacity of BZ planes.
ortho3d (bool) – Default is True, decides whether x,y,z are orthogonal or perspective.
fig (plotly.graph_objects.Figure) – Plotly’s go.Figure. If you want to plot on another plotly’s figure, provide that.
kwargs are passed to plotly.graph_objects.Scatter3d for BZ lines.
- Return type:
plotly.graph_objects.Figure
- iplot_cell(fill=False, color='rgba(84,102,108,0.8)', alpha=0.4, ortho3d=True, fig=None, **kwargs)[source]¶
See docs of iplot_bz, everything is same except space is iverted.
- splot_lattice(plane=None, sizes=50, colors=None, bond_length=None, tol=0.01, eqv_sites=True, translate=None, origin=(0, 0, 0), ax=None, showlegend=True, fmt_label=None, site_kws={'alpha': 0.7}, bond_kws={'alpha': 0.7, 'lw': 1}, plot_cell=True, **kwargs)[source]¶
Matplotlib Static plot of lattice.
- Parameters:
plane (str) – Plane to plot. Either ‘xy’,’xz’,’yz’ or None for 3D plot.
sizes (float or dict of type -> float) – Size of sites. Either one int/float or a mapping like {‘Ga’: 2, …}.
colors (color or dict of type -> color) – Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types.
bond_length (float or dict) – Length of bond in Angstrom. Auto calculated if not provides. Can be a dict like {‘Fe-O’:3.2,…} to specify bond length between specific types.
alpha (float) – Opacity of points and bonds.
showlegend (bool) – Default is True, show legend for each ion type.
site_kws (dict) – Keyword arguments to pass to plt.scatter for plotting sites. Default is just hint, you can pass any keyword argument that plt.scatter accepts.
bond_kws (dict) – Keyword arguments to pass to LineCollection/Line3DCollection for plotting bonds.
fmt_label (callable) – If given, each site label is passed to it as a subclass of str ‘Ga 1’ with extra attributes symbol and number and a method to_latex. You can show specific labels based on condition, e.g. lambda lab: lab.to_latex() if lab.number in [1,5] else ‘’ will show 1st and 5th atom of each types. It must return a string or a list/tuple of length 2 with first item as label and second item as dictionary of keywords to pass to plt.text.
plot_cell (bool) – Default is True, plot unit cell with default settings. To customize options, use plot_cell = False and do POSCAR.splot_cell(ax = <return of splot_lattice>).
kwargs are passed to splot_bz.
Tip
Use plt.style.use(‘ggplot’) for better 3D perception.
- iplot_lattice(sizes=10, colors=None, bond_length=None, tol=0.01, eqv_sites=True, translate=None, origin=(0, 0, 0), fig=None, ortho3d=True, bond_kws={'line_width': 4}, site_kws={'line_color': 'rgba(1,1,1,0)', 'line_width': 0.001, 'opacity': 1}, plot_cell=True, label_sites=False, **kwargs)[source]¶
Plotly’s interactive plot of lattice.
- Parameters:
sizes (float or dict of type -> float) – Size of sites. Either one int/float or a mapping like {‘Ga’: 2, …}.
colors (color or dict of type -> color) – Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types.
bond_length (float or dict) – Length of bond in Angstrom. Auto calculated if not provides. Can be a dict like {‘Fe-O’:3.2,…} to specify bond length between specific types.
bond_kws (dict) – Keyword arguments passed to plotly.graph_objects.Scatter3d for bonds. Default is jus hint, you can use any keyword argument that is accepted by plotly.graph_objects.Scatter3d.
site_kws (dict) – Keyword arguments passed to plotly.graph_objects.Scatter3d for sites. Default is jus hint, you can use any keyword argument that is accepted by plotly.graph_objects.Scatter3d.
plot_cell (bool) – Defult is True. Plot unit cell with default settings. If you want to customize, use POSCAR.iplot_cell(fig = <return of iplot_lattice>) function.
kwargs are passed to iplot_bz.
- write(outfile=None, selective_dynamics=None, overwrite=False, comment='', scale=None)[source]¶
Writes POSCAR data to a file or returns string
- Parameters:
outfile (PathLike) –
selective_dynamics (callable) – If given, should be a function like f(a) -> (a.p < 1/4) or f(a) -> (a.x < 1/4, a.y < 1/4, a.z < 1/4) which turns on/off selective dynamics for each atom based in each dimension. See ipyvasp.POSCAR.data.get_selective_dynamics for more info.
overwrite (bool) – If file already exists, overwrite=True changes it.
comment (str) – Add comment, previous comment will be there too.
scale (float) – Scale factor for the basis vectors. Default is provided by loaded data.
Note
POSCAR is only written in direct format even if it was loaded from cartesian format.
- join(other, direction='c', tol=0.01, system=None)[source]¶
Joins two POSCARs in a given direction. In-plane lattice parameters are kept from first poscar and out of plane basis vector of other is modified while volume is kept same.
- Parameters:
other (type(self)) – Other POSCAR to be joined with this POSCAR.
direction (str) – The joining direction. It is general and can join in any direction along basis. Expect one of [‘a’,’b’,’c’].
tol (float) – 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 (str) – If system is given, it is written on top of file. Otherwise, it is infered from atomic species.
- scale(scale=(1, 1, 1), tol=0.01)[source]¶
Create larger/smaller cell from a given POSCAR. Can be used to repeat a POSCAR with integer scale values.
- Parameters:
scale (tuple) – 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 (float) – It is used such that site positions are blow 1 - tol, as 1 belongs to next cell, not previous one.
note:: (..) –
scale = (2,2,2)
enlarges a cell and next operation of(1/2,1/2,1/2)
should bring original cell back.warning:: (..) – A POSCAR scaled with Non-integer values should only be used for visualization purposes, Not for any other opration such as making supercells, joining POSCARs etc.
- set_boundary(a=[0, 1], b=[0, 1], c=[0, 1])[source]¶
View atoms in a given boundary along a,b,c directions.
- filter_atoms(func, tol=0.01)[source]¶
Filter atomic sites based on a function that acts on an atom such as lambda a: (a.p < 1/2).all(). atom passed to function is a namedtuple like Atom(symbol,number,index,x,y,z) which has extra attribute p = array([x,y,z]). This may include equivalent sites, so it should be used for plotting purpose only, e.g. showing atoms on a plane. An attribute source_indices is added to metadata which is useful to pick other things such as OUTCAR.ion_pot[POSCAR.filter(…).data.metadata.source_indices].
>>> filter_atoms(..., lambda a: a.symbol=='Ga' or a.number in range(2)) # picks all Ga atoms and first two atoms of every other types.
Note: If you are filtering a plane with more than one non-zero hkl like 110, you may first need to translate or set boundary on POSCAR to bring desired plane in full view to include all atoms.
- rotate(angle_deg, axis_vec)[source]¶
Rotate a given POSCAR.
- Parameters:
angle_deg (float) – Rotation angle in degrees.
axis_vec (array_like) – Vector (x,y,z) of axis about which rotation takes place. Axis passes through origin.
- set_zdir(hkl, phi=0)[source]¶
Set z-direction of POSCAR along a given hkl direction and returns new data.
- Parameters:
hkl (tuple) – (h,k,l) of the direction along which z-direction is to be set. Vector is constructed as h*a + k*b + l*c in cartesian coordinates.
phi (float) – Rotation angle in degrees about z-axis to set a desired rotated view.
- Return type:
New instance of poscar with z-direction set along hkl.
- translate(offset)[source]¶
Translate sites of a POSCAR with a given offset as a number or list of three number. Usully a farction of integarers like 1/2,1/4 etc.
- repeat(n, direction)[source]¶
Repeat a given POSCAR.
- Parameters:
n (int) – Number of repetitions.
direction (str) – Direction of repetition. Can be ‘a’, ‘b’ or ‘c’.
- mirror(direction)[source]¶
Mirror a POSCAR in a given direction. Sometime you need it before joining two POSCARs
- get_TM(target_basis)[source]¶
Returns a transformation matrix that gives basis2 when applied on self.basis. basis are 3x3 matrices with basis vectors as rows like [[b1x, b1y, b1z],[b2x, b2y, b2z],[b3x, b3y, b3z]].
>>> from ipyvasp.core.spatial_toolkit import get_TM >>> TM = get_TM(basis1, basis2) # Can be ipyvasp.POSCAR.get_TM(basis2) while basis1 is POSCAR.data.basis >>> assert np.allclose(basis2, TM @ basis1) >>> Q = P @ TM.T # Transform points from P in basis1 to Q in basis2 >>> # Both P and Q are N x D matrices where N is number of points and D is dimension of space ```
- transform(transformation, fill_factor=2, tol=0.01)[source]¶
Transform a POSCAR with a given transformation matrix or function that takes old basis and return target basis. Use get_TM(basis1, basis2) to get transformation matrix from one basis to another or function to return new basis of your choice. An example of transformation function is lambda a,b,c: a + b, a-b, c which will give a new basis with a+b, a-b, c as basis vectors.
You may find errors due to missing atoms in the new basis, use fill_factor and tol to include any possible site in new cell.
Examples
FCC primitive → 111 hexagonal cell:
lambda a,b,c: (a-c,b-c,a+b+c) ~ [[1,0,-1],[0,1,-1],[1,1,1]]
FCC primitive → FCC unit cell:
lambda a,b,c: (b+c -a,a+c-b,a+b-c) ~ [[-1,1,1],[1,-1,1],[1,1,-1]]
FCC unit cell → 110 tetragonal cell:
lambda a,b,c: (a-b,a+b,c) ~ [[1,-1,0],[1,1,0],[0,0,1]]
Note
This function keeps underlying lattice same.
- transpose(axes=[1, 0, 2])[source]¶
Transpose a POSCAR by switching basis from [0,1,2] -> axes. By Default, x and y are transposed.
- add_vaccum(thickness, direction, left=False)[source]¶
Add vacuum to a POSCAR.
- Parameters:
thickness (float) – Thickness of vacuum in Angstrom.
direction (str) – Direction of vacuum. Can be ‘a’, ‘b’ or ‘c’.
left (bool) – If True, vacuum is added to left of sites. By default, vacuum is added to right of sites.
- add_atoms(name, positions)[source]¶
Add atoms with a name to a POSCAR at given positions in fractional coordinates.
- remove_atoms(func, fillby=None)[source]¶
Remove atoms that satisfy func(atom) -> bool on their fractional coordinates like lambda a: all(a.p < 1/2). atom passed to function is a namedtuple like Atom(symbol,number,index,x,y,z) which has extra attribute p = array([x,y,z]). If fillby is given, it will fill the removed atoms with atoms from fillby POSCAR.
>>> remove_atoms(..., lambda a: sum((a.p - 0.5)**2) <= 0.25**2) # remove atoms in center of cell inside radius of 0.25
Note
The coordinates of fillby POSCAR are transformed to basis of given POSCAR, before filling. So a good filling is only guaranteed if both POSCARs have smaller lattice mismatch.
- replace_atoms(func, name)[source]¶
Replace atoms satisfying a func(atom) -> bool with a new name. Like lambda a: a.symbol == ‘Ga’
- convert(atoms_mapping, basis_factor)[source]¶
Convert a POSCAR to a similar structure of other atomic types or same type with strained basis.
- Parameters:
atoms_mapping (dict) – A dictionary of {old_atom: new_atom} like {‘Ga’:’Al’} will convert GaAs to AlAs structure.
basis_factor (float) – 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).
Note
This can be used to strain basis vectors uniformly only. For non-uniform strain, use
ipyvasp.POSCAR.strain()
.
- deform(deformation)[source]¶
Deform a POSCAR by a deformation as 3x3 ArrayLike, or a function that takee basis and returns a 3x3 ArrayLike, to be multiplied with basis (elementwise) and return a new POSCAR.
Note
This function can change underlying crystal structure if cell shape changes, to just change cell shape, use transform function instead.
- get_kmesh(*args, shift=0, weight=None, cartesian=False, ibzkpt=None, outfile=None, endpoint=True)[source]¶
Generates uniform mesh of kpoints. Options are write to file, or return KPOINTS list.
- Parameters:
*args (tuple) – 1 or 3 integers which decide shape of mesh. If 1, mesh points equally spaced based on data from POSCAR.
shift (float) – 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 (bool) – If True, generates cartesian mesh.
ibzkpt (PathLike) – Path to ibzkpt file, required for HSE calculations.
outfile (PathLike) – Path/to/file to write kpoints.
endpoint (bool) – Default True, include endpoints in mesh at edges away from origin.
If outfile = None, KPOINTS file content is printed.
- get_kpath(kpoints, n: int = 5, weight: float = None, ibzkpt: str = None, outfile: str = None)[source]¶
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 average length of rec_basis.
- Parameters:
kpoints (list or str) – Any number points as [(x,y,z,[label],[N]), …]. N adds as many points in current interval. To disconnect path at a point, provide it as (x,y,z,[label], 0), next point will be start of other patch. If kpoints is a multiline string, it is converted to list of points. Each line should be in format “x y z [label] [N]”. A file path can be provided to read kpoints from file with same format as multiline string.
n (int) – Number of point per averge length of rec_basis, this makes uniform steps based on distance between points. If (x,y,z,[label], N) is provided, this is ignored for that specific interval. If rec_basis is not provided, each interval has exactly n points. Number of points in each interval is at least 2 even if n is less than 2 to keep end points anyway.
weight (float) – None by default to auto generates weights.
ibzkpt (PathLike) – Path to ibzkpt file, required for HSE calculations.
outfile (PathLike) – Path/to/file to write kpoints.
If outfile = None, KPONITS file content is printed.
- ipyvasp.lattice.download_structure(formula, mp_id=None, max_sites=None, min_sites=None, api_key=None, save_key=False)[source]¶
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.) –
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.) –
- Returns:
list
- Return type:
List of Structure data containing attribute/method cif/export_poscar, write_cif etc.
Note
max_sites and min_sites are used to filter the number of sites in structure, or use mp_id to download a specific structure.
- ipyvasp.lattice.periodic_table(selection=None)[source]¶
Display colorerd elements in periodic table. Use a list of atoms to only color a selection.
- ipyvasp.lattice.get_kpath(kpoints, n: int = 5, weight: float | None = None, ibzkpt: str | None = None, outfile: str | None = None, rec_basis=None)[source]¶
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 average length of rec_basis.
- Parameters:
kpoints (list or str) – Any number points as [(x,y,z,[label],[N]), …]. N adds as many points in current interval. To disconnect path at a point, provide it as (x,y,z,[label], 0), next point will be start of other patch. If kpoints is a multiline string, it is converted to list of points. Each line should be in format “x y z [label] [N]”. A file path can be provided to read kpoints from file with same format as multiline string.
n (int) – Number of point per averge length of rec_basis, this makes uniform steps based on distance between points. If (x,y,z,[label], N) is provided, this is ignored for that specific interval. If rec_basis is not provided, each interval has exactly n points. Number of points in each interval is at least 2 even if n is less than 2 to keep end points anyway.
weight (float) – None by default to auto generates weights.
ibzkpt (PathLike) – Path to ibzkpt file, required for HSE calculations.
outfile (PathLike) – Path/to/file to write kpoints.
rec_basis (array_like) – Reciprocal basis 3x3 array to use for calculating uniform points.
If outfile = None, KPONITS file content is printed.
- ipyvasp.lattice.get_kmesh(poscar_data, *args, shift=0, weight=None, cartesian=False, ibzkpt=None, outfile=None, endpoint=True)[source]¶
Generates uniform mesh of kpoints. Options are write to file, or return KPOINTS list.
- Parameters:
poscar_data (ipyvasp.POSCAR.data) –
*args (tuple) – 1 or 3 integers which decide shape of mesh. If 1, mesh points equally spaced based on data from POSCAR.
shift (float) – 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 (bool) – If True, generates cartesian mesh.
ibzkpt (PathLike) – Path to ibzkpt file, required for HSE calculations.
outfile (PathLike) – Path/to/file to write kpoints.
endpoint (bool) – Default True, include endpoints in mesh at edges away from origin.
If outfile = None, KPOINTS file content is printed.
- ipyvasp.lattice.splot_bz(bz_data, plane=None, ax=None, color='blue', fill=False, fill_zorder=0, vectors=(0, 1, 2), colormap=None, shade=True, alpha=0.4, zoffset=0, **kwargs)[source]¶
Plots matplotlib’s static figure of BZ/Cell. You can also plot in 2D on a 3D axes.
- Parameters:
plane (str) – Default is None and plots 3D surface. Can take ‘xy’,’yz’,’zx’ to plot in 2D.
fill (bool) – True by defult, determines whether to fill surface of BZ or not.
fill_zorder (int) – Default is 0, determines zorder of filled surface in 2D plots if fill=True.
color (Any) – Color to fill surface and stroke color. Default is ‘blue’. Can be any valid matplotlib color.
vectors (tuple) – Tuple of indices of basis vectors to plot. Default is (0,1,2). All three are plotted in 3D (you can turn of by None or empty tuple), whhile you can specify any two/three in 2D. Vectors do not appear if given data is subzone data.
ax (matplotlib.pyplot.Axes) – Auto generated by default, 2D/3D axes, auto converts in 3D on demand as well.
colormap (str) – If None, single color is applied, only works in 3D and fill=True. Colormap is applied along z.
shade (bool) – Shade polygons or not. Only works in 3D and fill=True.
alpha (float) – Opacity of filling in range [0,1]. Increase for clear viewpoint.
zoffset (float) – Only used if plotting in 2D over a 3D axis. Default is 0. Any plane ‘xy’,’yz’ etc.
kwargs are passed to plt.plot or Poly3DCollection if fill=True.
- Returns:
Matplotlib’s 2D axes if plane=None otherswise 3D axes.
- Return type:
matplotlib.pyplot.Axes
- ipyvasp.lattice.iplot_bz(bz_data, fill=False, color='rgba(84,102,108,0.8)', special_kpoints=True, alpha=0.4, ortho3d=True, fig=None, **kwargs)[source]¶
Plots interactive figure showing axes,BZ surface, special points and basis, each of which could be hidden or shown.
- Parameters:
fill (bool) – False by defult, determines whether to fill surface of BZ or not.
color (str) – Color to fill surface ‘rgba(84,102,108,0.8)` by default. This sholud be a valid Plotly color.
special_kpoints (bool or callable) – True by default, determines whether to plot special points or not. You can also proivide a mask function f(x,y,z) -> bool which will be used to filter special points based on their fractional coordinates. This is ignored if BZ is primitive.
alpha (float) – Opacity of BZ planes.
ortho3d (bool) – Default is True, decides whether x,y,z are orthogonal or perspective.
fig (plotly.graph_objects.Figure) – Plotly’s go.Figure. If you want to plot on another plotly’s figure, provide that.
kwargs are passed to plotly.graph_objects.Scatter3d for BZ lines.
- Return type:
plotly.graph_objects.Figure
- ipyvasp.lattice.ngl_viewer(poscar, colors=None, sizes=0.5, plot_cell=True, linewidth=0.05, color=[0, 0, 0.2], bond_color='whitesmoke', width='400px', height='400px', plot_vectors=True, dashboard=False, origin=(0, 0, 0), eqv_sites=True)[source]¶
Display structure in Jupyter notebook using nglview.
- Parameters:
poscar (ipyvasp.POSCAR) –
sizes (float or dict of type -> float) – Size of sites. Either one int/float or a mapping like {‘Ga’: 2, …}.
colors (color or sheme name or dict of type -> color) – Mapping of colors like {‘Ga’: ‘red, …} or a single color. Automatically generated color for missing types. If colors = ‘element’, then element colors from nglview will be used. You can use nglview.color.COLOR_SCHEME to see available color schemes to use.
plot_cell (bool) – Plot unit cell. Default True.
linewidth (float) – Linewidth of cell edges.
color (list or str) – Color of cell edges. Must be a valid color to support conversion to RGB via matplotlib.
bond_color (str) – Color of bonds. Default “whitesmoke”. Can be “element” or any other scheme from nglview.
width (str) – Width of viewer. Default “400px”.
height (str) – Height of viewer. Default “400px”.
plot_vectors (bool) – Plot vectors. Default True. Only works if plot_cell = True.
dashboard (bool) – Show dashboard. Default False. It just sets view.gui_style = ‘NGL’.
- Returns:
NGLWidget – An instance of nglview.NGLWidget object. You can use .render_image(), .download_image() etc. on it or can add more representations.
.. note:: – nglview sometimes does not work in Jupyter lab. You can switch to classic notebook in that case.
.. tip:: – See Advanced NGLView usage.
Widgets¶
- ipyvasp.widgets.load_results(paths_list, exclude_keys=None)[source]¶
Loads result.json from paths_list and returns a dataframe. Use exclude_keys to get subset of data.
- ipyvasp.widgets.summarize(files, func, **kwargs)[source]¶
Apply given func to each file in files and return a dataframe of the results.
- Parameters:
files (Iterable, must be an iterable of PathLike objects, a dictionary of {name: PathLike} pairs also works and name appears in the dataframe.) –
func (callable with a single arguemnt path. Must return a dictionary.) –
kwargs (passed to func itself.) –
- class ipyvasp.widgets.Files(self, path_or_files='.', glob='*', exclude=None, files_only=False, dirs_only=False)[source]¶
Bases:
object
Creates a Batch of files in a directory recursively based on glob pattern or given list of files. This is a boilerplate abstraction to do analysis in multiple calculations simultaneously.
- Parameters:
path_or_files (str, current directory by default or list of files or an instance of Files.) –
glob (str, glob pattern, '*' by default. '**' is used for recursive glob. Not used if files supplied above.) –
exclude (str, regular expression pattern to exclude files.) –
files_only (bool, if True, returns only files.) –
dirs_only (bool, if True, returns only directories.) –
summarize (Use methods on return such as) –
with_name –
filtered –
others. (interact and) –
Files(root_1 (>>>) –
glob_1 –
...).add(root_2 –
glob_2 –
chain (...) # Fully flexible to) –
WARNING (Don't use write operations on paths in files in batch mode, it can cause unrecoverable data loss.) –
- filtered(include=None, exclude=None, files_only=False, dirs_only=False)[source]¶
Filter all files. Only keeps existing file.
- load_results(exclude_keys=None)[source]¶
Load result.json files from these paths into a dataframe, with optionally excluding keys.
- input_info(*tags)[source]¶
Grab input information into a dataframe from POSCAR and INCAR. Provide INCAR tags (case-insinsitive) to select only few of them.
- update(path_or_files, glob='*', cleanup=True, exclude=None, **kwargs)[source]¶
Update files inplace with similar parameters as initialization. If cleanup=False, older files are kept too. Useful for widgets such as BandsWidget to preserve their state while using widget.files.update.
- to_dropdown(description='File')[source]¶
Convert this instance to Dropdown. If there is only one file, adds an empty option to make that file switchable. Options of this dropdown are update on calling Files.update method.
- add(path_or_files, glob='*', exclude=None, **kwargs)[source]¶
Add more files or with a diffrent glob on top of exitsing files. Returns same instance. Useful to add multiple globbed files into a single chained call.
>>> Files(root_1, glob_1,...).add(root_2, glob_2,...) # Fully flexible
- interactive(*funcs, auto_update=True, app_layout=None, grid_css={}, **kwargs)[source]¶
Enhanced interactive widget with multiple callbacks, grid layout and fullscreen support.
This function is used for quick dashboards. Subclass InteractBase for complex applications.
Features:
Multiple function support with selective updates
CSS Grid layout system
Extended widget trait observation
Dynamic widget property updates
Built-in fullscreen support
Basic Usage:
from ipyslides.interaction import interactive, callback, monitor import ipywidgets as ipw import plotly.graph_objects as go fig = go.FigureWidget() @callback('out-plot', timeit=True) # check execution time def update_plot(x, y, fig): fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) def resize_fig(fig, fs): fig.layout.autosize = False # double trigger fig.layout.autosize = True # plotly's figurewidget always make trouble with sizing # Above two functions can be merged since we can use changed detection @monitor # check execution time def respond(x, y, fig , fs, changed): if 'fs' in changed: # or changed('fs') fig.layout.autosize = False # double trigger fig.layout.autosize = True else: fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) dashboard = interactive( update_plot, resize_fig, # responds to fullscreen change # respond, instead of two functions x = ipw.IntSlider(0, 0, 100), y = ipw.FloatSlider(0, 1), fig = ipw.fixed(fig), changed = '.changed', # detect a change in parameter fs = '.isfullscreen', # detect fullscreen change on instance itself )
Parameters:
*funcs: One or more callback functions
auto_update: Update automatically on widget changes
app_layout: Initial layout configuration, see relayout() method for details
- grid_css: CSS Grid properties for layout
Use :fullscreen at root level of dict to apply styles in fullscreen mode
Use [Button, ToggleButton, ToggleButtons].add_class(‘content-width-button’) to fix button widths easily.
See [CSS Grid Layout Guide](https://css-tricks.com/snippets/css/complete-guide-grid/).
**kwargs: Widget parameters
Widget Parameters:
Regular ipywidgets
Fixed widgets via ipw.fixed()
String pattern ‘widget.trait’ for trait observation, ‘widget’ must be in kwargs or ‘.trait’ to observe traits on this instance.
You can use ‘.fullscreen’ to detect fullscreen change and do actions based on that.
You can use changed = ‘.changed’ to detect which parameters of a callback changed by checking changed(‘param’) -> Bool in a callback.
Any DOM widget that needs display (inside fixed too). A widget and its observed trait in a single function are not allowed, such as f(fig, v) where v=’fig.selected’.
Plotly FigureWidgets (use patched_plotly)
- ipywidgets.Button for manual updates on callbacks besides global auto_update. Add tooltip for info on button when not synced.
You can have multiple buttons in a single callback and check btn.clicked attribute to run code based on which button was clicked.
Widget Updates:
Functions can modify widget traits (e.g. options, min/max)
Order matters for dependent updates
Parameter-less functions run with any interaction
Animation widgets work even with manual updates
- Output Widget Behavior:
Output widgets are created only if a CSS class is provided via @callback.
If no CSS class is provided, the callback will use the main output widget labeled as ‘out-main’.
CSS Classes:
Parameter names from kwargs
Custom ‘out-*’ classes from @callback, and ‘out-main’ class.
‘btn-main’ for manual update button
Notes:
Avoid modifying global slide state
Use widget descriptions to prevent name clashes
See set_css() method for styling options
interactive(no_args_func_which_may_fetch_data_on_click,) is perfectly valid and run on button click.
Python dictionary to CSS
CSS is formatted using a props nested dictionary to simplify the process. There are few special rules in props:
All nested selectors are joined with space, so hl`’.A’: {‘.B’: … }` becomes hl[‘css’]`.A .B {…}` in CSS.
A ‘^’ in start of a selector joins to parent selector without space, so hl`’.A’: {‘^:hover’: …}` becomes hl[‘css’]`.A:hover {…}` in CSS. You can also use hl`’.A:hover’` directly but it will restrict other nested keys to hover only.
A list/tuple of values for a key in dict generates CSS fallback, so hl`’.A’: {‘font-size’: (‘20px’,’2em’)}` becomes hl[‘css’]`.A {font-size: 20px; font-size: 2em;}` in CSS.
Read about specificity of CSS selectors [here](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity).
- interact(*funcs, auto_update=True, app_layout=None, grid_css={}, **kwargs)[source]¶
Enhanced interactive widget with multiple callbacks, grid layout and fullscreen support.
This function is used for quick dashboards. Subclass InteractBase for complex applications.
Features:
Multiple function support with selective updates
CSS Grid layout system
Extended widget trait observation
Dynamic widget property updates
Built-in fullscreen support
Basic Usage:
from ipyslides.interaction import interactive, callback, monitor import ipywidgets as ipw import plotly.graph_objects as go fig = go.FigureWidget() @callback('out-plot', timeit=True) # check execution time def update_plot(x, y, fig): fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) def resize_fig(fig, fs): fig.layout.autosize = False # double trigger fig.layout.autosize = True # plotly's figurewidget always make trouble with sizing # Above two functions can be merged since we can use changed detection @monitor # check execution time def respond(x, y, fig , fs, changed): if 'fs' in changed: # or changed('fs') fig.layout.autosize = False # double trigger fig.layout.autosize = True else: fig.data = [] fig.add_scatter(x=[0, x], y=[0, y]) dashboard = interactive( update_plot, resize_fig, # responds to fullscreen change # respond, instead of two functions x = ipw.IntSlider(0, 0, 100), y = ipw.FloatSlider(0, 1), fig = ipw.fixed(fig), changed = '.changed', # detect a change in parameter fs = '.isfullscreen', # detect fullscreen change on instance itself )
Parameters:
*funcs: One or more callback functions
auto_update: Update automatically on widget changes
app_layout: Initial layout configuration, see relayout() method for details
- grid_css: CSS Grid properties for layout
Use :fullscreen at root level of dict to apply styles in fullscreen mode
Use [Button, ToggleButton, ToggleButtons].add_class(‘content-width-button’) to fix button widths easily.
See [CSS Grid Layout Guide](https://css-tricks.com/snippets/css/complete-guide-grid/).
**kwargs: Widget parameters
Widget Parameters:
Regular ipywidgets
Fixed widgets via ipw.fixed()
String pattern ‘widget.trait’ for trait observation, ‘widget’ must be in kwargs or ‘.trait’ to observe traits on this instance.
You can use ‘.fullscreen’ to detect fullscreen change and do actions based on that.
You can use changed = ‘.changed’ to detect which parameters of a callback changed by checking changed(‘param’) -> Bool in a callback.
Any DOM widget that needs display (inside fixed too). A widget and its observed trait in a single function are not allowed, such as f(fig, v) where v=’fig.selected’.
Plotly FigureWidgets (use patched_plotly)
- ipywidgets.Button for manual updates on callbacks besides global auto_update. Add tooltip for info on button when not synced.
You can have multiple buttons in a single callback and check btn.clicked attribute to run code based on which button was clicked.
Widget Updates:
Functions can modify widget traits (e.g. options, min/max)
Order matters for dependent updates
Parameter-less functions run with any interaction
Animation widgets work even with manual updates
- Output Widget Behavior:
Output widgets are created only if a CSS class is provided via @callback.
If no CSS class is provided, the callback will use the main output widget labeled as ‘out-main’.
CSS Classes:
Parameter names from kwargs
Custom ‘out-*’ classes from @callback, and ‘out-main’ class.
‘btn-main’ for manual update button
Notes:
Avoid modifying global slide state
Use widget descriptions to prevent name clashes
See set_css() method for styling options
interactive(no_args_func_which_may_fetch_data_on_click,) is perfectly valid and run on button click.
Python dictionary to CSS
CSS is formatted using a props nested dictionary to simplify the process. There are few special rules in props:
All nested selectors are joined with space, so hl`’.A’: {‘.B’: … }` becomes hl[‘css’]`.A .B {…}` in CSS.
A ‘^’ in start of a selector joins to parent selector without space, so hl`’.A’: {‘^:hover’: …}` becomes hl[‘css’]`.A:hover {…}` in CSS. You can also use hl`’.A:hover’` directly but it will restrict other nested keys to hover only.
A list/tuple of values for a key in dict generates CSS fallback, so hl`’.A’: {‘font-size’: (‘20px’,’2em’)}` becomes hl[‘css’]`.A {font-size: 20px; font-size: 2em;}` in CSS.
Read about specificity of CSS selectors [here](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity).
Tips:
You can use this inside columns using delayed display trick, like hl`write(‘First column’, C2)` where hl`C2 = Slides.hold(Slides.ei.interact, f, x = 5) or Slides.ei.interactive(f, x = 5)`.
You can also use this under Slides.capture_content to display later in a specific place.
- map(func, to_df=False)[source]¶
Map files to a function that takes path as argument. If to_df=True, func may return a dict to create named columns, or just two columns will be created. Otherwise returns generator of elemnets (path, func(path)). If you need to operate on opened file pointer, use .mapf instead.
>>> import ipyvasp as ipv >>> files = ipv.Files(...) >>> files.map(lambda path: ipv.read(path, '<pattern>',apply = lambda line: float(line.split()[0]))) >>> files.map(lambda path: ipv.load(path), to_df=True)
- mapf(func, to_df=False, mode='r', encoding=None)[source]¶
Map files to a function that takes opened file pointer as argument. Opened files are automatically closed and should be in readonly mode. Load files content into a generator sequence of tuples like (path, func(open(path))) or DataFrame if to_df=True. If to_df=True, func may return a dict to create named columns, or just two columns will be created. If you need to operate on just path, use .map instead.
>>> import json >>> import ipyvasp as ipv >>> files = ipv.Files(...) >>> files.mapf(lambda fp: json.load(fp,cls=ipv.DecodeToNumpy),to_df=True) # or use ipv.load(path) in map >>> files.mapf(lambda fp: ipv.take(fp, range(5)) # read first five lines >>> files.mapf(lambda fp: ipv.take(fp, range(-5,0)) # read last five lines >>> files.mapf(lambda fp: ipv.take(fp, -1, 1, float) # read last line, second column as float
- class ipyvasp.widgets.PropsPicker(self, system_summary=None, N=3)[source]¶
Bases:
VBox
A widget to pick atoms and orbitals for plotting.
- Parameters:
- projections¶
An instance of a Python dict.
One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.
Changed in version 5.0: Added key_trait for validating dict keys.
Changed in version 5.0: Deprecated ambiguous
trait
,traits
args in favor ofvalue_trait
,per_key_traits
.
- class ipyvasp.widgets.BandsWidget(self, files, height='600px', store_clicks=None)[source]¶
Bases:
_ThemedFigureInteract
Visualize band structure from VASP calculation. You can click on the graph to get the data such as VBM, CBM, etc.
You can observe three traits:
file: Currently selected file
clicked_data: Last clicked point data, which can be directly passed to a dataframe.
selected_data: Last selection of points within a box or lasso, which can be directly passed to a dataframe and plotted accordingly.
You can use self.files.update method to change source files without effecting state of widget.
You can also use self.iplot, self.splot with self.kws to get static plts of current state, and self.results to get a dataframe.
You can use store_clicks to provide extra names of points you want to click and save data, besides default ones.
- file¶
A trait which allows any value.
- clicked_data¶
An instance of a Python dict.
One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.
Changed in version 5.0: Added key_trait for validating dict keys.
Changed in version 5.0: Deprecated ambiguous
trait
,traits
args in favor ofvalue_trait
,per_key_traits
.
- selected_data¶
An instance of a Python dict.
One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.
Changed in version 5.0: Added key_trait for validating dict keys.
Changed in version 5.0: Deprecated ambiguous
trait
,traits
args in favor ofvalue_trait
,per_key_traits
.
- results(exclude_keys=None)[source]¶
Generate a dataframe form result.json file in each folder, with optionally excluding keys.
- property source¶
Returns data source object such as Vasprun or Vaspout.
- property bands¶
Bands class initialized
- property kws¶
Selected keyword arguments from GUI
- class ipyvasp.widgets.KPathWidget(self, files, height='450px')[source]¶
Bases:
_ThemedFigureInteract
Interactively bulid a kpath for bandstructure calculation.
After initialization and disply:
Select a POSCAR file from “File:” dropdown menu. It will update the figure.
Add points to select box on left by clicking on plot points. When done with points click on Lock to avoid adding more points.
To update point(s), select point(s) from the select box and click on a scatter point in figure or use KPOINT input to update it manually, e.g. if a point is not available on plot.
Add labels to the points by typing in the “Labels” box such as “Γ,X” or “Γ 5,X” that will add 5 points in interval.
To break the path between two points “Γ” and “X” type “Γ 0,X” in the “Labels” box, zero means no points in interval.
You can use self.files.update method to change source files without effecting state of widget.
You can observe self.file trait to get current file selected and plot something, e.g. lattice structure.
- file¶
A trait which allows any value.
- property poscar¶
- get_kpath(n=5, weight: float = None, ibzkpt: str = None, outfile: str = None)[source]¶
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 average length of rec_basis.
- Parameters:
n (int) – Number of point per averge length of rec_basis, this makes uniform steps based on distance between points. If (x,y,z,[label], N) is provided, this is ignored for that specific interval. If rec_basis is not provided, each interval has exactly n points. Number of points in each interval is at least 2 even if n is less than 2 to keep end points anyway.
weight (float) – None by default to auto generates weights.
ibzkpt (PathLike) – Path to ibzkpt file, required for HSE calculations.
outfile (PathLike) – Path/to/file to write kpoints.
If outfile = None, KPONITS file content is printed.
- splot(plane=None, fmt_label=<function KPathWidget.<lambda>>, plot_kws={}, **kwargs)[source]¶
Same as ipyvasp.lattice.POSCAR.splot_bz except it also plots path on BZ.
- Parameters:
plane (str of plane like 'xy' to plot in 2D or None to plot in 3D) –
fmt_label (function, should take a string and return a string or (str, dict) of which dict is passed to plt.text.) –
plot_kws (dict of keyword arguments for plt.plot for kpath.) –
ipyvasp.lattice.POSCAR.splot_bz. (kwargs are passed to) –
Potential and Charge Density¶
- ipyvasp.potential.splot_potential(basis=None, values=None, operation='mean_c', ax=None, period=None, period_right=None, interface=None, lr_pos=(0.25, 0.75), smoothness=2, labels=('$V(z)$', '$\\langle V \\rangle _{roll}(z)$', '$\\langle V \\rangle $'), colors=((0, 0.2, 0.7), 'b', 'r'), annotate=True)[source]¶
Returns tuple(ax,Data) where Data contains resultatnt parameters of averaged potential of LOCPOT.
- Parameters:
values (epxort_potential().values is 3D grid data. As epxort_potential is slow, so compute it once and then plot the output data.) –
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 ipv.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.) –
- class ipyvasp.potential.LOCPOT(path=None, data_set=0)[source]¶
Bases:
object
Class for LOCPOT file. 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.) –
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.
- property poscar¶
POSCAR class object
- property data¶
- splot(operation='mean_c', basis=None, ax=None, period=None, period_right=None, interface=None, lr_pos=(0.25, 0.75), smoothness=2, labels=('$V(z)$', '$\\langle V \\rangle _{roll}(z)$', '$\\langle V \\rangle $'), colors=((0, 0.2, 0.7), 'b', 'r'), annotate=True)[source]¶
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 ipv.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.) –
- view_period(operation: str = 'mean_c', interface=0.5, lr_pos=(0.25, 0.75), smoothness=2, figsize=(5, 3), **kwargs)[source]¶
Check periodicity using ipywidgets interactive plot.
- Parameters:
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.) –
styling. (kwargs are passed to the plt.Axes.set(kwargs) method to handle the plot) –
- class ipyvasp.potential.CHG(path=None, data_set=0)[source]¶
Bases:
LOCPOT
Class for CHG file. 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.) –
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 ipyvasp.potential.ELFCAR(path=None, data_set=0)[source]¶
Bases:
LOCPOT
Class for ELFCAR file. 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.) –
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 ipyvasp.potential.PARCHG(path=None, data_set=0)[source]¶
Bases:
LOCPOT
Class for PARCHG file. 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.) –
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.
Miscellaneous¶
- ipyvasp.misc.parse_text(path, shape, slice, slices, raw: bool = False, dtype=<class 'float'>, delimiter='\\s+', include: str = None, exclude: str = '#', fix_format: bool = True)[source]¶
Convert a generator of text lines to numpy array while excluding comments, given matches and empty lines. Data is sliced and reshaped as per given shape and slices. It is very efficient for large data files to fetch only required data.
- Parameters:
path (Path to file containing data.) –
shape (tuple) – Tuple or list of integers. Given shape of data to be read. Last item is considered to be columns. User should keep track of empty lines and excluded lines.
slices (tuple) – Tuple or list of integers or range or -1. Given slices of data to be read along each dimension. Last item is considered to be columns.
raw (bool) – Returns raw data for quick visualizing and determining shape such as columns, if True.
dtype (object) – Data type of numpy array to be returned. Default is float.
delimiter (str) – Delimiter of data in text file.
include (str) – Match to include in each line to be read. If None, all lines are included.
exclude (str) – Match to exclude in each line to be read. If None, no lines are excluded.
fix_format (bool) – If True, it will fix the format of data in each line. It is useful when data is not properly formatted. like 0.500-0.700 -> 0.500 -0.700
- Returns:
numpy array of given shape and dtype.
- Return type:
ndarray
- ipyvasp.misc.get_E0(path: Path = 'OSZICAR', nsteps=0)[source]¶
Get the E0 from the last line of OSZICAR. If nsteps > 0, returns as many available last steps .
- class ipyvasp.misc.OUTCAR(path=None)[source]¶
Bases:
object
Parse some required data from OUTCAR file.
- property data¶
- property path¶
- read(start_match, stop_match='\\n', nth_match=1, skip_last=False, apply=None)[source]¶
Reads a part of the file between start_match and stop_match and returns a generator. It is lazy and fast. start_match and stop_match`(default is end of same line) are regular expressions. `nth_match is the number of occurence of start_match to start reading. skip_last is used to determine whether to keep or skip last line. apply should be None or func to transform each captured line.