The util package implements various utilities that are commonly used by various packages.
Utilities for manipulating coordinates or list of coordinates, under periodic boundary conditions or otherwise. Many of these are heavily vectorized in numpy for performance.
Converts a list of coordinates to barycentric coordinates, given a simplex with d+1 points. Only works for d >= 2.
Find the indices of matches of a particular coord in a coord_list.
Get the indices of all points in a fractional coord list that are equal to a fractional coord (with a tolerance), taking into account periodic boundary conditions.
Calculates the angle between two vectors.
Returns an interpolated value by linear interpolation between two values. This method is written to avoid dependency on scipy, which causes issues on threading servers.
Find all points within a sphere from the point taking into account periodic boundary conditions. This includes sites in other periodic images.
Algorithm:
place sphere of radius r in crystal and determine minimum supercell (parallelpiped) which would contain a sphere of radius r. for this we need the projection of a_1 on a unit vector perpendicular to a_2 & a_3 (i.e. the unit vector in the direction b_1) to determine how many a_1”s it will take to contain the sphere.
Nxmax = r * length_of_b_1 / (2 Pi)
keep points falling within r.
Tests if a particular coord is within a coord_list.
Tests if a particular fractional coord is within a fractional coord_list.
Returns the distances between two lists of coordinates taking into account periodic boundary conditions and the lattice. Note that this computes an MxN array of distances (i.e. the distance between each point in fcoords1 and every coordinate in fcoords2). This is different functionality from pbc_diff.
Returns the ‘fractional distance’ between two coordinates taking into account periodic boundary conditions.
Returns the shortest vectors between two lists of coordinates taking into account periodic boundary conditions and the lattice.
This module contains useful decorators for a variety of functions.
Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency.
Note that this should be used for immutable classes only. Having a cached mutable class makes very little sense. For efficiency, avoid using this decorator for situations where there are many constructor arguments permutations.
The keywords argument dictionary is converted to a tuple because dicts are mutable; keywords themselves are strings and so are always hashable, but if any arguments (keyword or positional) are non-hashable, that set of arguments is not cached.
Decorator to mark classes or functions as deprecated, with a possible replacement.
Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level.
Bases: object
Decorator to mark classes or functions as requiring a specified condition to be true. This can be used to present useful error messages for optional dependencies. For example, decorating the following code will check if scipy is present and if not, a runtime error will be raised if someone attempts to call the use_scipy function:
try:
import scipy
except ImportError:
scipy = None
@requires(scipy is not None, "scipy is not present.")
def use_scipy():
print scipy.majver
This module provides utility classes for io operations.
Bases: object
A file locking mechanism that has context-manager support so you can use it in a with statement. This should be relatively cross-compatible as it doesn’t rely on msvcrt or fcntl for the locking. Taken from http://www.evanfosmark.com/2009/01/cross-platform-file-locking -support-in-python/
Prepare the file locker. Specify the file to lock and optionally the maximum timeout and the delay between each attempt to lock.
This method cleans an input json-like dict object, either a list or a dict, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings.
Strips whitespace, carriage returns and empty lines from a list of strings.
Small awk-mimicking search routine.
‘file’ is file to search through. ‘search’ is the “search program”, a list of lists/tuples with 3 elements; i.e. [[regex,test,run],[regex,test,run],...] ‘results’ is a an object that your search program will have access to for storing results.
Here regex is either as a Regex object, or a string that we compile into a Regex. test and run are callable objects.
This function goes through each line in filename, and if regex matches that line and test(results,line)==True (or test == None) we execute run(results,match),where match is the match object from running Regex.match.
The default results is an empty dictionary. Passing a results object let you interact with it in run() and test(). Hence, in many occasions it is thus clever to use results=self.
Author: Rickard Armiento
Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German. http://code.activestate.com/recipes/439045-read-a-text-file-backwards -yet-another-implementat/
Reads file forwards and reverses in memory for files smaller than the max_mem parameter, or for gzip files where reverse seeks are not supported.
Files larger than max_mem are dynamically read backwards.
This wrapper wraps around the bz2, gzip and standard python’s open function to deal intelligently with bzipped, gzipped or standard text files.
This module provides utilities for basic math operations.
Yield successive n-sized chunks from a list-like object.
>>> import pprint
>>> pprint.pprint(list(chunks(range(1, 25), 10)))
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24]]
Constructs an iterator given a slice object s.
Note
The function returns an infinite iterator if s.stop is None
Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value:
Sorts a dict by value.
Utilities for generating nicer plots.
Provides a publication quality plot, with nice defaults for font sizes etc.
This module provides utility classes for string operations.
Bases: object
This function is used to make pretty formulas by formatting the amounts. Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4.
Generates a string latex table from a sequence of sequence.
Generates a latex formatted formula. E.g., Fe2O3 is transformed to Fe$_{2}$O$_{3}$.
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to P2$_{1}$/c and P-1 is converted to P$overline{1}$.
Always return a list of strings, given a string or list of strings as input.
| Examples : |
|---|
>>> list_strings('A single string')
['A single string']
>>> list_strings(['A single string in a list'])
['A single string in a list']
>>> list_strings(['A','list','of','strings'])
['A', 'list', 'of', 'strings']
Prints out a table of data, padded for alignment Each row must have the same number of columns.
Given a tuple, generate a nicely aligned string form. >>> results = [[“a”,”b”,”cz”],[“d”,”ez”,”f”],[1,2,3]] >>> print str_aligned(results) a b cz d ez f 1 2 3
Given a tuple of tuples, generate a delimited string form. >>> results = [[“a”,”b”,”c”],[“d”,”e”,”f”],[1,2,3]] >>> print str_delimited(results,delimiter=”,”) a,b,c d,e,f 1,2,3
Common test support for pymatgen test scripts.
This single module should provide all the common functionality for pymatgen tests in a single location, so that test scripts can just import it and work right away.
Bases: unittest.case.TestCase
Extends unittest.TestCase with functions (taken from numpy.testing.utils) that support the comparison of arrays.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
Tests if two arrays are almost equal to a tolerance. The CamelCase naming is so that it is consistent with standard unittest methods.