tools Package¶
tools
Module¶
Helper functions.
bessel
Module¶
This module provides functions to compute integrals of Bessel functions.
- abipy.tools.bessel.spline_int_jlqr(l, qmax, rcut, numq=None, numr=None)[source]¶
Compute \(j_n(z) = \int_0^{rcut} r^2 j_l(qr) dr\) where \(j_l\) is the Spherical Bessel function.
- Parameters:
l – Angular momentum
qmax – Max \(|q|\) in integral in Ang-1
rcut – Sphere radius in Angstrom.
numq – Number of q-points in qmesh.
numr – Number of r-points for integration.
- Returns:
Spline object.
cli_parsers
Module¶
Tools and helper functions to build the command line interface of the AbiPy scripts.
- abipy.tools.cli_parsers.user_wants_to_abort() bool [source]¶
Interactive prompt, return False if user entered n or no.
- abipy.tools.cli_parsers.pn_serve_parser(**kwargs) ArgumentParser [source]¶
Parent parser implementing cli options for panel.serve
- abipy.tools.cli_parsers.get_pn_serve_kwargs(options) dict [source]¶
Return dict with the arguments to be passed to pn.serve.
- abipy.tools.cli_parsers.add_expose_options_to_parser(parser, with_mpl_options=True) None [source]¶
Add Expose options to the parser.
- class abipy.tools.cli_parsers.EnumAction(**kwargs)[source]¶
Bases:
Action
Argparse action for handling Enums
Usage:
- class Do(enum.Enum):
Foo = “foo” Bar = “bar”
parser = argparse.ArgumentParser() parser.add_argument(‘do’, type=Do, action=EnumAction)
Taken from https://stackoverflow.com/questions/43968006/support-for-enum-arguments-in-argparse
context_managers
Module¶
Context managers
- class abipy.tools.context_managers.Timer(footer=None, header=None, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Bases:
object
Context manager to time code section.
or
- with Timer(header=f”Begin ABINIT”, footer=”ABINIT GS”) as timer:
do_stuff()
- abipy.tools.context_managers.temporary_change_attributes(something, **kwargs)[source]¶
https://stackoverflow.com/questions/38531851/how-to-assign-member-variables-temporarily/38532086
Usage:
- class Something(object):
- def __init__(self, x, y):
self.x = x self.y = y
- def say_hello(self):
print(“hello”, self.x, self.y)
s = Something(1, 2) s.say_hello() # hello 1 2 with temporary_change_attributes(s, x=4, y=5):
s.say_hello() # hello 4 5
s.say_hello() # hello 1 2
decorators
Module¶
Decorators.
- abipy.tools.decorators.return_straceback_ifexc(func: Callable)[source]¶
Decorator for functions that are supposed to return a string for logging purposes (e.g. str) Instead of raising an exception, the decorated function returns a string with the traceback so that execution can continue.
- abipy.tools.decorators.timeit(method)[source]¶
timeit decorator adapted from: https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d sets the timing of the routine as an attribute of the class
- abipy.tools.decorators.memoized_method(*lru_args, **lru_kwargs)[source]¶
Implements lru_cache for class methods. It takes the exact same parameters as lru_cache, and works exactly the same. However it never passes self to lru_cache and instead uses a per-instance lru_cache.
Taken from: https://stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object
… example:
@memoized_method(maxsize=12, typed=False) def method(self, a, b): ....
- abipy.tools.decorators.dump_args(func: Callable)[source]¶
Decorator to print function call details.
This includes parameters names and effective values.
- class abipy.tools.decorators.Appender(addendum, join='', indents=0, dedent=True, debug=False)[source]¶
Bases:
object
A function decorator that appends an addendum to the docstring of the target function. This decorator should be robust even if func.__doc__ is None (for example, if -OO was passed to the interpreter). Usage: construct a docstring.Appender with a string to be joined to the original docstring. An optional ‘join’ parameter may be supplied which will be used to join the docstring and addendum. e.g.
add_copyright = Appender(“Copyright (c) 2009”, join=’n’)
@add_copyright def my_dog(has=’fleas’):
“This docstring will have a copyright below” pass
MG took it from: https://github.com/pandas-dev/pandas/blob/3a7f956c30528736beaae5784f509a76d892e229/pandas/util/_decorators.py#L156
MG: Added dedent and debug args.
derivatives
Module¶
Tools for computing derivatives by finite differences.
- abipy.tools.derivatives.finite_diff(arr, h, order=1, acc=4, index=None)[source]¶
Compute the derivative of order order by finite difference. For each point in arr, the function tries to use central differences and fallbacks to forward/backward approximations for points that are close to the extrema. Note that high accuracy levels can fail and raise ValueError if not enough points are available in arr.
- Parameters:
arr – Input array with y-values.
h – Spacing along x
order – Derivative order
acc – accuracy level.
index – If not None, gives the index of the single element in arr where the derivative is wanted. In this case a namedtuple with the derivative, the number of points used and the mode is returned
- Returns:
numpy array or (value, npts, mode) if index is not None .
devtools
Module¶
- abipy.tools.devtools.profile(statement, global_vars, local_vars)[source]¶
Run statement under profiler, supplying your own globals and locals
Example:
stats = profile("main()", global_vars=globals(), local_vars=locals())
- class abipy.tools.devtools.HtmlDiff(filepaths: list[str])[source]¶
Bases:
object
This object produces diff files in HTML format and displays them in the browser.
Usage example:
HtmlDiff(filepaths).open_browser()
- open_browser(diffmode='difflib', **kwargs)[source]¶
Generate diff with
diffmode
, open browser, return exit code.
- abipy.tools.devtools.display_top(snapshot, key_type='lineno', limit=3)[source]¶
Profile memory usage in Python. Taken from https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python
Example:
tracemalloc.start() main() snapshot = tracemalloc.take_snapshot() display_top(snapshot)
- abipy.tools.devtools.get_size(bytes, suffix='B')[source]¶
Scale bytes to its proper format e.g:
1253656 => ‘1.20MB’ 1253656678 => ‘1.17GB’
- abipy.tools.devtools.print_hardware_system_info() None [source]¶
Taken from <https://thepythoncode.com/article/get-hardware-system-information-python>
duck
Module¶
Duck-typing tests
- abipy.tools.duck.is_string(s: Any) bool [source]¶
True if s behaves like a string (duck typing test).
- abipy.tools.duck.is_intlike(obj: Any) bool [source]¶
True if obj represents an integer (floats such as 1.0 are included as well).
- abipy.tools.duck.list_ints(arg: Any) list [source]¶
Always return a list of int, given a int or list of integers as input.
- Examples:
>>> list_ints(1) [1]
- abipy.tools.duck.torange(obj: Any) range [source]¶
Convert obj into a range. Accepts integer, slice object or any object with an __iter__ method. Note that an integer is converted into range(int, int+1)
>>> list(torange(1)) [1] >>> list(torange(slice(0, 4, 2))) [0, 2] >>> list(torange([1, 4, 2])) [1, 4, 2]
- abipy.tools.duck.as_slice(obj: Any) slice [source]¶
Convert an integer, a string or a slice object into slice.
>>> assert as_slice(5) == slice(5, 6, 1) >>> assert as_slice("[1:4]") == slice(1, 4, 1) >>> assert as_slice("1::2") == slice(1, None, 2)
- abipy.tools.duck.hasattrd(obj: Any, name: str) bool [source]¶
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. Unlike the builtin hasattr, hasattrd supports dot notation e.g. hasattr(int, “__class__.__name__”) (This is implemented by calling getattrd(object, name) and seeing whether it raises an exception or not.)
- abipy.tools.duck.getattrd(obj: ~typing.Any, name: str, default=<class 'abipy.tools.duck.NoDefaultProvided'>) Any [source]¶
Same as getattr(), but allows dot notation lookup e.g. getattrd(obj, “a.b”)
Raises: AttributeError if
name
is not found anddefault
is not given.Discussed in: http://stackoverflow.com/questions/11975781
fftprof
Module¶
Python interface to fftprof. Provides objects to benchmark the FFT libraries used by ABINIT and plot the results with matplotlib.
- class abipy.tools.fftprof.FFTBenchmark(title, FFT_tests)[source]¶
Bases:
object
Container class storing the results of the FFT benchmark.
Use the class method
from_file
to generate a new instance.- plot(exclude_algs=None, exclude_threads=None, **kwargs) Any [source]¶
Plot the wall-time and the speed-up.
Keyword arguments controlling the display of the figure:
kwargs
Meaning
title
Title of the plot (Default: None).
show
True to show the figure (default: True).
savefig
“abc.png” or “abc.eps” to save the figure to a file.
size_kwargs
Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)
tight_layout
True to call fig.tight_layout (default: False)
ax_grid
True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.
ax_annotate
Add labels to subplots e.g. (a), (b). Default: False
fig_close
Close figure. Default: False.
plotly
Try to convert mpl figure to plotly.
iotools
Module¶
IO related utilities.
- abipy.tools.iotools.try_files(filepaths: list[str | PathLike]) Path [source]¶
Return the first existent file in filepaths or raise RuntimeError.
- abipy.tools.iotools.file_with_ext_indir(ext: str, directory: str | PathLike) Path [source]¶
Find file with extension ext inside directory. Raise RuntimeError if no file can be found.
- abipy.tools.iotools.yaml_safe_load_path(filepath: str) Any [source]¶
Load Yaml document from filepath
- abipy.tools.iotools.dataframe_from_filepath(filepath: str, **kwargs) DataFrame [source]¶
Try to read a dataframe from an external file according to the file extension.
- class abipy.tools.iotools.ExitStackWithFiles[source]¶
Bases:
ExitStack
Context manager for dynamic management of a stack of file-like objects. Mainly used in a callee that needs to return files to the caller
Usage example:
exit_stack = ExitStackWithFiles() exit_stack.enter_context(phbst_file) return exit_stack
- abipy.tools.iotools.get_input(prompt: str)[source]¶
Wraps python builtin input so that we can easily mock it in unit tests using:
Example
from unittest.mock import patch with patch(‘abipy.tools.iotools.get_input’, return_value=’no’):
do_something_that_uses_get_input
- abipy.tools.iotools.ask_yes_no(prompt: str, default=None)[source]¶
Ask a question and return a boolean (y/n) answer.
If default is given (one of ‘y’,’n’), it is used if the user input is empty. Otherwise the question is repeated until an answer is given.
An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops.
Valid answers are: y/yes/n/no (match is not case sensitive).
- exception abipy.tools.iotools.EditorError[source]¶
Bases:
Exception
Base class for exceptions raised by Editor
- class abipy.tools.iotools.Editor(editor=None)[source]¶
Bases:
object
- DEFAULT_EDITOR = 'vi'¶
- Error¶
alias of
EditorError
- abipy.tools.iotools.ask_yesno(question: str, default=True)[source]¶
- Parameters:
() (default)
()
Returns:
- class abipy.tools.iotools.AtomicFile(name, mode='w+b', createmode=None, encoding=None)[source]¶
Bases:
object
This is a straight port of Alexander Saltanov’s atomicfile package. Writeable file object that atomically writes a file. All writes will go to a temporary file. Call
close()
when you are done writing, and AtomicFile will rename the temporary copy to the original name, making the changes visible. If the object is destroyed without being closed, all your writes are discarded. If anencoding
argument is specified, codecs.open will be called to open the file in the wanted encoding.
- abipy.tools.iotools.workdir_with_prefix(workdir, prefix, exist_ok=False) Path [source]¶
if workdir is None, create temporary directory with prefix else check that workdir does not exist. If exist_ok is False (the default), a FileExistsError is raised if the target directory already exists.
- abipy.tools.iotools.change_ext_from_top(top: str | PathLike, old_ext: str, new_ext: str) int [source]¶
Change the extension of all the files with extension old_ext with new_ext.
- Parameters:
top – Walk the file system starting from top.
old_ext – Old file extension.
new_ext – New file extension.
Return: Number of files whose extension has been changed.
notebooks
Module¶
Tools for ipython notebooks.
- abipy.tools.notebooks.find_free_port()[source]¶
Find and return free port
https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number
- abipy.tools.notebooks.print_source_in_module(function, module)[source]¶
For use inside an jupyter notebook: given a module and a function, print the source code.
Based on:
- abipy.tools.notebooks.print_source(function, **kwargs)[source]¶
For use inside a jupyter notebook: given a function, print the source code.
- Parameters:
**kwargs – Passed to HtmlFormatter
- Returns:
HTML string.
- abipy.tools.notebooks.print_doc(function, **kwargs)[source]¶
For use inside a jupyter notebook: given a function, print the docstring.
- Parameters:
**kwargs – Passed to HtmlFormatter
- Returns:
HTML string.
- abipy.tools.notebooks.ipw_listdir(top='.', recurse=True, widget_type='dropdown')[source]¶
Return an ipython widget listing all the files located within the directory
top
that can be inspected with abiopen.py. The user can select the file in the widget and print info on the corresponding file inside the notebook.- Parameters:
top – Initial directory.
recurse – False to ignore directories within
top
.widget_type – Specify the widget to create. Possible values in: [“tooglebuttons”, “dropdown”, “radiobuttons”]
numtools
Module¶
Numeric tools.
- abipy.tools.numtools.print_stats_arr(arr: ndarray, take_abs=False) None [source]¶
Print statistics on a NumPy array.
- Parameters:
take_abs – use abs(arr) if True.
- abipy.tools.numtools.nparr_to_df(name: str, arr: np.ndarrays, columns: list[str]) pd.DataFrame [source]¶
Insert a numpy array in a DataFrame with columns giving the indices.
- Parameters:
name – Name of column with the values of the numpy array.
arr – numpy array
columns – List with the name of columns with the indices.
- abipy.tools.numtools.build_mesh(x0: float, num: int, step: float, direction: str) tuple[list, int] [source]¶
Generate a linear mesh of step step that is centered on x0 if directions == “centered” or a mesh that starts/ends at x0 if direction is >/<. Return mesh and index of x0.
- abipy.tools.numtools.transpose_last3dims(arr) ndarray [source]¶
Transpose the last three dimensions of arr: (…,x,y,z) –> (…,z,y,x).
- abipy.tools.numtools.add_periodic_replicas(arr: ndarray) ndarray [source]¶
Returns a new array of shape=(…, nx+1,ny+1,nz+1) with redundant data points.
Periodicity in enforced only on the last three dimensions.
- abipy.tools.numtools.data_from_cplx_mode(cplx_mode: str, arr, tol=None)[source]¶
Extract the data from the numpy array
arr
depending on the values ofcplx_mode
.- Parameters:
cplx_mode – Possible values in (“re”, “im”, “abs”, “angle”) “re” for the real part, “im” for the imaginary part. “all” for both re and im. “abs” means that the absolute value of the complex number is shown. “angle” will display the phase of the complex number in radians.
tol – If not None, values below tol are set to zero. Cannot be used with “angle”
- abipy.tools.numtools.alternate(*iterables)[source]¶
[a[0], b[0], … , a[1], b[1], …, a[n], b[n] …] >>> alternate([1,4], [2,5], [3,6]) [1, 2, 3, 4, 5, 6]
- abipy.tools.numtools.iflat(iterables)[source]¶
Iterator over all elements of a nested iterable. It’s recursive!
>>> list(iflat([[0], [1,2, [3,4]]])) [0, 1, 2, 3, 4]
- abipy.tools.numtools.grouper(n, iterable, fillvalue=None)[source]¶
>>> assert grouper(3, "ABCDEFG", "x") == [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] >>> assert grouper(3, [1, 2, 3, 4]) == [(1, 2, 3), (4, None, None)]
- abipy.tools.numtools.sort_and_groupby(items, key=None, reverse=False, ret_lists=False)[source]¶
Sort
items
usingkey
function and invoke itertools.groupby to group items. If ret_lists is True, a tuple of lists (keys, groups) is returned else iterator. See itertools.groupby for further info.>>> sort_and_groupby([1, 2, 1], ret_lists=True) ([1, 2], [[1, 1], [2]])
- abipy.tools.numtools.prune_ord(alist: list) list [source]¶
Return new list where all duplicated items in alist are removed
The order of items in alist is preserved.
items in alist MUST be hashable.
Taken from http://code.activestate.com/recipes/52560/ >>> prune_ord([1, 1, 2, 3, 3]) [1, 2, 3]
- abipy.tools.numtools.gaussian(x, width, center=0.0, height=None)[source]¶
Returns the values of gaussian(x) where x is array-like.
- Parameters:
x – Input array.
width – Width of the gaussian.
center – Center of the gaussian.
height – height of the gaussian. If height is None, a normalized gaussian is returned.
- abipy.tools.numtools.lorentzian(x, width, center=0.0, height=None)[source]¶
Returns the values of gaussian(x) where x is array-like.
- Parameters:
x – Input array.
width – Width of the Lorentzian (half-width at half-maximum)
center – Center of the Lorentzian.
height – height of the Lorentzian. If height is None, a normalized Lorentzian is returned.
- abipy.tools.numtools.smooth(x, window_len=11, window='hanning')[source]¶
smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. Taken from http://www.scipy.org/Cookbook/SignalSmooth
- Parameters:
x – the input signal
window_len – the dimension of the smoothing window. it should be an odd integer
window – the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’. ‘flat’ window will produce a moving average smoothing.
- Returns:
the smoothed signal.
example:
t = linspace(-2,2,0.1) x = sin(t)+randn(len(t))*0.1 y = smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
- abipy.tools.numtools.find_convindex(values, tol, min_numpts=1, mode='abs', vinf=None)[source]¶
Given a list of values and a tolerance tol, returns the leftmost index for which
abs(value[i] - vinf) < tol if mode == “abs”
- or
abs(value[i] - vinf) / vinf < tol if mode == “rel”
- Parameters:
tol – Tolerance
min_numpts – Minimum number of points that must be converged.
mode – “abs” for absolute convergence, “rel” for relative convergence.
vinf – Used to specify an alternative value instead of values[-1]. By default, vinf = values[-1]
- Returns:
-1 if convergence is not achieved else the index in values.
- abipy.tools.numtools.find_degs_sk(enesb, atol)[source]¶
Return list of lists with the indices of the degenerated bands.
- Parameters:
enesb – Iterable with energies for the different bands. Energies are assumed to be ordered.
atol – Absolute tolerance. Two states are degenerated if they differ by less than atol.
- Returns:
- List of lists. The i-th item contains the indices of the degenerates states
for the i-th degenerated set.
- Examples:
>>> find_degs_sk([1, 1, 2, 3.4, 3.401], atol=0.01) [[0, 1], [2], [3, 4]]
- class abipy.tools.numtools.BlochRegularGridInterpolator(structure, datar, add_replicas=True, **kwargs)[source]¶
Bases:
object
This object interpolates the periodic part of a Bloch wavefunction in real space.
- eval_points(frac_coords, idat=None, cartesian=False, kpoint=None, **kwargs) ndarray [source]¶
Interpolate values on an arbitrary list of points.
- Parameters:
frac_coords – List of points in reduced coordinates unless cartesian.
idat – Index of the sub-array to interpolate. If None, all sub-arrays are interpolated.
cartesian – True if points are in cartesian coordinates.
kpoint – k-point in reduced coordinates. If not None, the phase-factor e^{ikr} is included.
- Returns:
[ndat, npoints] array or [1, npoints] if idat is not None
- eval_line(point1, point2, num=200, cartesian=False, kpoint=None, **kwargs)[source]¶
Interpolate values along a line.
- Parameters:
point1 – First point of the line. Accepts 3d vector or integer. The vector is in reduced coordinates unless cartesian == True. If integer, the first point of the line is given by the i-th site of the structure e.g. point1=0, point2=1 gives the line passing through the first two atoms.
point2 – Second point of the line. Same API as point1.
num – Number of points sampled along the line.
cartesian – By default, point1 and point1 are interpreted as points in fractional coordinates (if not integers). Use True to pass points in cartesian coordinates.
kpoint – k-point in reduced coordinates. If not None, the phase-factor e^{ikr} is included.
- Return: named tuple with
site1, site2: None if the points do not represent atomic sites. points: Points in fractional coords. dist: the distance of points along the line in Ang. values: numpy array of shape [ndat, num] with interpolated values.
parallel
Module¶
Tools used to parallelize sections of python code.
- abipy.tools.parallel.get_max_nprocs() int [source]¶
Return the maximum number of procs that can be used by AbiPy.
- abipy.tools.parallel.set_max_nprocs(max_nprocs: int | None) int [source]¶
Set the maximum number of procs that can be used. If max_nprocs is None, os.cpu_count() is used.
- abipy.tools.parallel.pool_nprocs_pmode(nprocs: int | None, pmode: str)[source]¶
Helper function that allows one to switch from ThreadPool to multiprocessing Pool. Returns named tuple with (nprocs, pool_class, using_msg)
- Parameters:
nprocs – Number of procs to use. If None, use cpu_count.
pmode – “threads”: for ThreadPool. “processes” for multiprocessing Pool. “seq” for sequential execution (debugging)
plotting
Module¶
Utilities for generating matplotlib plots.
Note
Avoid importing matplotlib or plotly in the module namespace otherwise startup is very slow.
- abipy.tools.plotting.set_axlims(ax, lims: tuple, axname: str) tuple [source]¶
Set the data limits for the axis ax.
- Parameters:
lims – tuple(2) for (left, right), tuple(1) or scalar for left only.
axname – “x” for x-axis, “y” for y-axis.
Return: (left, right)
- abipy.tools.plotting.add_fig_kwargs(func)[source]¶
Decorator that adds keyword arguments for functions returning matplotlib figures.
The function should return either a matplotlib figure or None to signal some sort of error/unexpected event. See doc string below for the list of supported options.
- abipy.tools.plotting.get_ax_fig_plt(ax=None, **kwargs)[source]¶
Helper function used in plot functions supporting an optional Axes argument. If ax is None, we build the matplotlib figure and create the Axes else we return the current active figure.
- Parameters:
ax (Axes, optional) – Axes object. Defaults to None.
kwargs –
keyword arguments are passed to plt.figure if ax is not None.
- Returns:
ax:
Axes
object figure: matplotlib figure plt: matplotlib pyplot module.
- abipy.tools.plotting.get_axarray_fig_plt(ax_array, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)[source]¶
Helper function used in plot functions that accept an optional array of Axes as argument. If ax_array is None, we build the matplotlib figure and create the array of Axes by calling plt.subplots else we return the current active figure.
- Returns:
Array of Axes objects figure: matplotlib figure plt: matplotlib pyplot module.
- Return type:
ax
- abipy.tools.plotting.get_ax3d_fig_plt(ax=None, **kwargs)[source]¶
Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the matplotlib figure and create the Axes3D else we return the current active figure.
- Parameters:
ax (Axes3D, optional) – Axes3D object. Defaults to None.
kwargs – keyword arguments are passed to plt.figure if ax is not None.
- Returns:
matplotlib Axes3D and corresponding figure objects
- Return type:
tuple[Axes3D, Figure]
- abipy.tools.plotting.plot_array(array, color_map=None, cplx_mode='abs', **kwargs) Any [source]¶
Use imshow for plotting 2D or 1D arrays. Return:
matplotlib.figure.Figure
Example:
plot_array(np.random.rand(10,10))
See <http://stackoverflow.com/questions/7229971/2d-grid-data-visualization-in-python>
- Parameters:
array – Array-like object (1D or 2D).
color_map – color map.
cplx_mode – Flag defining how to handle complex arrays. Possible values in (“re”, “im”, “abs”, “angle”) “re” for the real part, “im” for the imaginary part. “abs” means that the absolute value of the complex number is shown. “angle” will display the phase of the complex number in radians.
figure (Keyword arguments controlling the display of the)
==================================================== (================)
Meaning (kwargs)
====================================================
(Default (title Title of the plot) – None).
(default (tight_layout True to call fig.tight_layout) – True).
file. (savefig "abc.png" or "abc.eps" to save the figure to a)
fig.set_size_inches (size_kwargs Dictionary with options passed to) – e.g. size_kwargs=dict(w=3, h=4)
(default – False)
True (ax_grid) – Default: None i.e. fig is left unchanged.
e.g. (ax_annotate Add labels to subplots) – Default: False
Default (fig_close Close figure.) – False.
plotly. (plotly Try to convert mpl figure to)
====================================================
- class abipy.tools.plotting.ArrayPlotter(*labels_and_arrays)[source]¶
Bases:
object
- add_arrays(labels: list, arr_list: list) None [source]¶
Add a list of arrays
- Parameters:
labels – List of labels.
arr_list – List of arrays.
- plot(cplx_mode='abs', colormap='jet', fontsize=8, **kwargs) Any [source]¶
- Parameters:
cplx_mode – “abs” for absolute value, “re”, “im”, “angle”
colormap – matplotlib colormap.
fontsize – legend and label fontsize.
Keyword arguments controlling the display of the figure:
kwargs
Meaning
title
Title of the plot (Default: None).
show
True to show the figure (default: True).
savefig
“abc.png” or “abc.eps” to save the figure to a file.
size_kwargs
Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)
tight_layout
True to call fig.tight_layout (default: False)
ax_grid
True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.
ax_annotate
Add labels to subplots e.g. (a), (b). Default: False
fig_close
Close figure. Default: False.
plotly
Try to convert mpl figure to plotly.
- abipy.tools.plotting.data_from_cplx_mode(cplx_mode: str, arr, tol=None)[source]¶
Extract the data from the numpy array
arr
depending on the values ofcplx_mode
.- Parameters:
cplx_mode – Possible values in (“re”, “im”, “abs”, “angle”) “re” for the real part, “im” for the imaginary part. “all” for both re and im. “abs” means that the absolute value of the complex number is shown. “angle” will display the phase of the complex number in radians.
tol – If not None, values below tol are set to zero. Cannot be used with “angle”
- class abipy.tools.plotting.Marker(x, y, s, **scatter_kwargs)[source]¶
Bases:
object
Stores the position and the size of the marker. A marker is a list of tuple(x, y, s) where x, and y are the position in the graph and s is the size of the marker. Used for plotting purpose e.g. QP data, energy derivatives…
Example:
x, y, s = [1, 2, 3], [4, 5, 6], [0.1, 0.2, -0.3] marker = Marker(x, y, s)
- abipy.tools.plotting.plot_unit_cell(lattice, ax=None, **kwargs) tuple[Any, Any] [source]¶
Adds the unit cell of the lattice to a matplotlib Axes3D
- Parameters:
lattice – Lattice object
ax – matplotlib
Axes3D
or None if a new figure should be created.kwargs – kwargs passed to the matplotlib function ‘plot’. Color defaults to black and linewidth to 3.
- Returns:
matplotlib figure and ax
- class abipy.tools.plotting.GenericDataFilePlotter(filepath: str)[source]¶
Bases:
object
Extract data from a generic text file with results in tabular format and plot data with matplotlib. Multiple datasets are supported. No attempt is made to handle metadata (e.g. column name) Mainly used to handle text files written without any schema.
- plot(use_index=False, fontsize=8, **kwargs) Any [source]¶
Plot all arrays. Use multiple axes if datasets.
- Parameters:
use_index – By default, the x-values are taken from the first column. If use_index is False, the x-values are the row index.
fontsize – fontsize for title.
kwargs – options passed to
ax.plot
.
Return:
matplotlib.figure.Figure
Keyword arguments controlling the display of the figure:
kwargs
Meaning
title
Title of the plot (Default: None).
show
True to show the figure (default: True).
savefig
“abc.png” or “abc.eps” to save the figure to a file.
size_kwargs
Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)
tight_layout
True to call fig.tight_layout (default: False)
ax_grid
True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.
ax_annotate
Add labels to subplots e.g. (a), (b). Default: False
fig_close
Close figure. Default: False.
plotly
Try to convert mpl figure to plotly.
- class abipy.tools.plotting.GenericDataFilesPlotter[source]¶
Bases:
object
- classmethod from_files(filepaths: list[str]) GenericDataFilesPlotter [source]¶
Build object from a list of filenames.
- plot(use_index=False, fontsize=8, colormap='viridis', **kwargs) Any [source]¶
Plot all arrays. Use multiple axes if datasets.
- Parameters:
use_index – By default, the x-values are taken from the first column. If use_index is False, the x-values are the row index.
fontsize – fontsize for title.
colormap – matplotlib color map.
kwargs – options passed to
ax.plot
.
Return:
matplotlib.figure.Figure
Keyword arguments controlling the display of the figure:
kwargs
Meaning
title
Title of the plot (Default: None).
show
True to show the figure (default: True).
savefig
“abc.png” or “abc.eps” to save the figure to a file.
size_kwargs
Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)
tight_layout
True to call fig.tight_layout (default: False)
ax_grid
True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.
ax_annotate
Add labels to subplots e.g. (a), (b). Default: False
fig_close
Close figure. Default: False.
plotly
Try to convert mpl figure to plotly.
- abipy.tools.plotting.add_plotly_fig_kwargs(func: Callable) Callable [source]¶
Decorator that adds keyword arguments for functions returning plotly figures. The function should return either a plotly figure or None to signal some sort of error/unexpected event. See doc string below for the list of supported options.
- abipy.tools.plotting.get_fig_plotly(fig=None, **fig_kw)[source]¶
Helper function used in plot functions that build the plotly figure by calling plotly.graph_objects.Figure if fig is None else return fig
- Returns:
plotly graph_objects figure go: plotly graph_objects module.
- Return type:
figure
- abipy.tools.plotting.get_figs_plotly(nrows=1, ncols=1, subplot_titles=(), sharex=False, sharey=False, **fig_kw)[source]¶
Helper function used in plot functions that build the plotly figure by calling plotly.subplots.
- Returns:
plotly graph_objects figure go: plotly graph_objects module.
- Return type:
figure
printing
Module¶
Utilities for pandas dataframes
- abipy.tools.printing.print_dataframe(df: ~pandas.core.frame.DataFrame, title=None, precision=6, sortby=None, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, end=None, display=None) None [source]¶
Print entire pandas DataFrame.
- Parameters:
df – pandas DataFrame.
title – Optional string to print as initial title.
precision – Floating point output precision (number of significant digits). This is only a suggestion [default: 6] [currently: 6]
sortby – string name or list of names which refer to the axis items to be sorted (dataframe is not changed)
file – a file-like object (stream); defaults to the current sys.stdout. If file == “string”, a temporary stream is created and a string is returned.
end – End string.
display – Use ipython rich display protocol by invoking _repr_`display_ and returning the result. Use e.g. display=”html” to get HTML table.
serialization
Module¶
Most features of this module has been moved to monty. Please refer to monty.json and monty.serialization documentation.
- abipy.tools.serialization.pmg_serialize(method)[source]¶
Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details
- abipy.tools.serialization.json_pretty_dump(obj: Any, filename: str) None [source]¶
Serialize obj as a JSON formatted stream to the given filename ( pretty printing version)
- class abipy.tools.serialization.PmgPickler(file, protocol=None, fix_imports=True, buffer_callback=None)[source]¶
Bases:
Pickler
Persistence of External Objects as described in section 12.1.5.1 of https://docs.python.org/3/library/pickle.html
- class abipy.tools.serialization.PmgUnpickler(file, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=())[source]¶
Bases:
Unpickler
Persistence of External Objects as described in section 12.1.5.1 of https://docs.python.org/3/library/pickle.html
- abipy.tools.serialization.pmg_pickle_load(filobj, **kwargs) Any [source]¶
Loads a pickle file and deserialize it with PmgUnpickler.
- Parameters:
filobj – File-like object
**kwargs – Any of the keyword arguments supported by PmgUnpickler
- Returns:
Deserialized object.
- abipy.tools.serialization.pmg_pickle_dump(obj: Any, filobj, **kwargs)[source]¶
Dump an object to a pickle file using PmgPickler.
- Parameters:
obj – Object to dump.
fileobj – File-like object
**kwargs – Any of the keyword arguments supported by PmgPickler
- abipy.tools.serialization.mjson_load(filepath: str, **kwargs) Any [source]¶
Read JSON file in MSONable format with MontyDecoder.
- abipy.tools.serialization.mjson_loads(string: str, **kwargs) Any [source]¶
Read JSON string in MSONable format with MontyDecoder.
- abipy.tools.serialization.mjson_write(obj: Any, filepath: str, **kwargs) None [source]¶
Write object to filepath in JSON format using MontyDecoder.
tensors
Module¶
This modules provides subclasses of pymatgen tensor objects.
- class abipy.tools.tensors.Stress(stress_matrix)[source]¶
Bases:
Stress
,_Tensor33
Stress tensor. rank2 symmetric tensor with shape [3, 3].
Inheritance Diagram
- class abipy.tools.tensors.DielectricTensor(input_array: NDArray, vscale: NDArray | None = None)[source]¶
Bases:
SquareTensor
,_Tensor33
Subclass of
pymatgen.core.tensors.Tensor
describing a dielectric tensor. rank2 symmetric tensor with shape [3, 3].Inheritance Diagram
- class abipy.tools.tensors.ZstarTensor(input_array: NDArray, vscale: NDArray | None = None)[source]¶
Bases:
SquareTensor
,_Tensor33
Born effective charge tensor (for a single atom).
Inheritance Diagram
- class abipy.tools.tensors.NLOpticalSusceptibilityTensor(input_array: NDArray, vscale: NDArray | None = None, check_rank: int | None = None)[source]¶
Bases:
Tensor
Subclass of
pymatgen.core.tensors.Tensor
containing the non-linear optical susceptibility tensor.Inheritance Diagram
- classmethod from_file(filepath: str) NLOpticalSusceptibilityTensor [source]¶
Creates the tensor from an anaddb.nc netcdf file containing
dchide
. This requires to run anaddb withtnlflag
> 0
text
Module¶
Utilities for working with strings and text.
- abipy.tools.text.tonumber(s: str) float [source]¶
Convert string to number, raise ValueError if s cannot be converted.
- abipy.tools.text.rreplace(s, old, new, occurrence)[source]¶
replace old with new in string but, instead of starting from the beginning as replace does, starting from the end.
>>> s = '1232425' >>> assert rreplace(s, '2', ' ', 2) == '123 4 5' >>> assert rreplace(s, '2', ' ', 3) == '1 3 4 5' >>> assert rreplace(s, '2', ' ', 4) == '1 3 4 5' >>> assert rreplace(s, '2', ' ', 0) == '1232425'
typing
Module¶
This module defines convenience types for type hinting purposes. It extends the types provided by pymatgen with Abipy-specific ones.