hikari.utility
The module containing relatively simple functions, which are not necessarily strictly connected to the actual contents of the whole library, but do significantly improve clarity of the code present in other modules.
Submodules
- hikari.utility.artists
- hikari.utility.certain_float
- hikari.utility.chem_tools
- hikari.utility.dict_tools
- hikari.utility.interval
- hikari.utility.list_tools
- hikari.utility.math_tools
- hikari.utility.numpy_tools
- hikari.utility.os_tools
- hikari.utility.palettes
- hikari.utility.singleton
- hikari.utility.typing
Attributes
Tuple containing 2-letter symbols of the first 118 chemical elements. |
|
Classes
A class handling [A, B] line segments and numpy operations on them. |
|
A metaclass based on https://stackoverflow.com/q/6760685/. |
Functions
|
Create "certain float" (ufloat.n) from string by converting it first |
|
Split atomic label used in ref or cif formats into computer-readable parts. |
|
Return a union of dicts; if conflicts, later dicts take precedence. |
|
Interpret a unit of given angle value and return this value in radians. |
|
Convert Cartesian coordinates x, y, z |
|
Convert conventional spherical coordinates r, p, a |
|
Calculate a determinant of a 3x3 matrix. Should be usually substituted |
|
Return a 3D cartesian coordinates of samples number of points |
|
Return matrix associated with rotation of vector from_ onto to. |
|
Return matrix associated with counterclockwise rotation about axis through |
|
A function to approximate quantiles based on many weighted points. Quantiles |
|
Return sequence of num floats between start and stop. |
|
Parse a list of strings and return the "best" element based on criteria. |
|
Linearly rescale values in original list to limits (minimum and maximum). |
|
Linearly rescale source list of numeral values to |
|
Return a string with absolute path to a specified file. Accepts zero or more |
|
Create a numpy int8 array using its compact representation saved as string. |
Package Contents
- hikari.utility.cfloat(string)[source]
Create “certain float” (ufloat.n) from string by converting it first to uncertainties.ufloat and then taking the nominal value.
- Parameters:
string (str) – string to be converted
- Returns:
float with no uncertainty
- Return type:
float
- hikari.utility.chemical_elements = ('H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl',...
Tuple containing 2-letter symbols of the first 118 chemical elements.
- hikari.utility.split_atom_label(label)[source]
Split atomic label used in ref or cif formats into computer-readable parts. :param label: Short atomic label such as “C12A” or “Fe1”. :type label: str :return: 3-element tuple with element, number, and suffix, as str. :rtype: tuple
- hikari.utility.dict_union(*dicts)[source]
Return a union of dicts; if conflicts, later dicts take precedence.
- Parameters:
dicts (dict)
- Return type:
dict
- class hikari.utility.Interval(left, right)[source]
A class handling [A, B] line segments and numpy operations on them. The following magic methods have been implemented for Interval:
creation using Interval(A, B) syntax (if A == B, represents a point)
comparison operations with numbers (True if holds for the whole Interval)
arithmetic operations, which act element-wise for left and right edge
access methods: A == Interval(A, B)[0] == Interval(A, B).left
container methods: 5 and 6.2 are in Interval(5, 7), but 7. might not be
- left
- right
- arange(step=1)[source]
Return a 1D-list of values from left to right every step :param step: spacing between adjacent values, default 1. :type step: int or float :return: array of values from left to right (including right) every step :rtype: np.array
- comb_with(*others, step=1)[source]
Return combinations of self.arange(step) with every other.arange(step) :param others: interval or iterable of intervals to comb self with :type others: Interval or tuple or list :param step: spacing between adjacent values, default 1. :type step: int or float :return: array of all combinations found in numpy.meshgrid every step :rtype: np.array
- mesh_with(*others, step=1)[source]
Return a numpy.mesh of self.arange(step) with every other.arange(step) :param others: interval or iterable of intervals to mesh self with :type others: Interval or tuple or list :param step: spacing between adjacent values, default 1. :type step: int or float :return: array of values meshed by numpy.meshgrid every step :rtype: np.array
- hikari.utility.angle2rad(value)[source]
Interpret a unit of given angle value and return this value in radians. Values in range between -3.15 and 3.15 are interpreted as given in radians. Values outside this range are interpreted as given in degrees.
The function can be used to dynamically interpret and accept both radian and degrees and return the value in angles. Should you not need this functionality, please use numpy’s rad2deg and deg2rad instead.
- Example:
>>> angle2rad(np.pi) 3.141592653589793 >>> angle2rad(180) 3.141592653589793 >>> angle2rad(2*np.pi) 0.1096622711232151
Please mind that in the last case the value given in radians was treated as given in degrees and wrongly recalculated to radians again.
- Parameters:
value (float) – Angle value given in angles or radians
- Returns:
Angle value expressed in radians
- Return type:
float
- hikari.utility.cart2sph(x, y, z)[source]
Convert Cartesian coordinates x, y, z to conventional spherical coordinates r, p, a
- Parameters:
x (float or np.ndarray) – Cartesian coordinate or vector x
y (float or np.ndarray) – Cartesian coordinate or vector y
z (float or np.ndarray) – Cartesian coordinates or vector z
- Returns:
Spherical coordinates: radius, polar angle, and azimuth angle
- Return type:
np.ndarray
- hikari.utility.sph2cart(r, p, a)[source]
Convert conventional spherical coordinates r, p, a to Cartesian coordinates x, y, z
- Parameters:
r (float or np.ndarray) – Spherical coordinate or vector radius
p (float or np.ndarray) – Spherical coordinate or vector polar angle
a (float or np.ndarray) – Spherical coordinate or vector azimuth angle
- Returns:
Cartesian coordinates: x, y, and z
- Return type:
np.ndarray
- hikari.utility.det3x3(matrix)[source]
Calculate a determinant of a 3x3 matrix. Should be usually substituted by numpy.linalg.det, but is indispensable for matrices with uncertainties.
- Parameters:
matrix (numpy.ndarray or uncertainties.unumpy.matrix) – 3x3 array/matrix which allows for 2d indexing
- Returns:
Determinant of the matrix
- Return type:
int or float or uncertainties.core.Variable
- hikari.utility.fibonacci_sphere(samples=1, seed=1337)[source]
Return a 3D cartesian coordinates of samples number of points evenly distributed on a surface of a unit sphere at (0, 0, 0).
The algorithm utilised in this function gives a uniform distribution on the sphere. Contrary to an uniform distribution on coordinates, this algorithm does not favour points close to poles. For more details see this article.
The function is written so that it does always return the same set of points in order to ensure reproducibility of other methods. A list of other points can be obtained by changing (or even randomising) the value of a seed.
- Example:
>>> fibonacci_sphere(4) array([[ 0.62069, -0.75, -0.22857], [-0.44395, -0.25, 0.86047], [ 0.41275, 0.25, 0.87587], [-0.61208, 0.75, -0.25072]]) >>> fibonacci_sphere(4) array([[ 0.62069, -0.75, -0.22857], [-0.44395, -0.25, 0.86047], [ 0.41275, 0.25, 0.87587], [-0.61208, 0.75, -0.25072]]) >>> fibonacci_sphere(4, seed=420) array([[ 0.64040, -0.75, 0.16550], [-0.85489, -0.25, 0.45460], [ 0.32329, 0.25, -0.91268], [ 0.25831, 0.75, 0.60892]])
- Parameters:
samples (int) – Number of points to be generated.
seed (any) – A seed value used once to slightly randomise point position.
- Returns:
(x,y,z) arrays representing points’ cartesian coordinates.
- Return type:
np.array
- hikari.utility.rotation_from(from_, to)[source]
Return matrix associated with rotation of vector from_ onto to.
- Parameters:
from (np.ndarray) – A 3D vector which will have been rotated onto to.
to (np.ndarray) – A 3D vector onto which from will have been rotated.
- Returns:
Matrix associated with rotation of from onto to.
- Return type:
np.ndarray
- hikari.utility.rotation_around(axis, by)[source]
Return matrix associated with counterclockwise rotation about axis through by radians. See Euler-Rodrigues form.,https://stackoverflow.com/q/6802577/
- Parameters:
axis (np.ndarray) – A 3D vector about which rotation is performed
by (float) – Angle of rotation in radians
- Returns:
Matrix associated with rotation around axis through by.
- Return type:
np.ndarray
- hikari.utility.weighted_quantile(values, quantiles, weights=None)[source]
A function to approximate quantiles based on many weighted points. Quantiles are derived exactly using method 7 of H&F from an unweighted distribution, otherwise they are approximated by comparing two opposing interpolations.
Let A: {1, 2, 2, 2, 3} and B: {1, 2(x3), 3} be seemingly equivalent sets where (x3) denotes triple weight of the “2”. Let q[n] denote quantiles. For set A, q[1/4](A) = q[3/4](A) = 2. However, for set B we need to extrapolate and read quantile from PDF, obtained via linear interpolation. As a result, q[1/4](B) = 4/3 < q[3/4](B) = 2 since f(0) = 1 and f(3/4) = 2 at f(1/4) and the results are always underestimated.
To combat this effect, we can repeat the process for -B: {-3, -2(x3), -1}. Here, q[1/4](-B) = -8/3 and q[3/4](-B) = -2. As a result, the quantile q[n](A) is described a bit better using formula (q[n](B) - q[1-n](-B)) / 2.
- Parameters:
values (tuple or list or np.ndarray) – data to be evaluated
quantiles (tuple or list or np.ndarray) – iterable containing desired quartiles between 0 and 1
weights (tuple or list or np.ndarray) – weights of data in the same order
- Returns:
array containing approximated quartiles
- Return type:
np.ndarray
- hikari.utility.cubespace(start, stop=False, num=10, include_start=True)[source]
Return sequence of num floats between start and stop. Analogously to numpy’s linspace, values in returned list are chosen so that their cubes (hence name) are spread evenly in equal distance.
If the parameter stop is not given, the value of start is used as the upper limit instead. In such case the lower limit is set to 0.
The values of lower limit, start, and upper limit, stop, are included in the list. The start value can be excluded by setting the include_start keyword to False.
- Example:
- Parameters:
start (hikari.utility.typing.Number)
stop (hikari.utility.typing.Number)
num (int)
include_start (bool)
>>> cubespace(10, num=3) array([ 0. , 7.93700526, 10. ]) >>> cubespace(0, -10, num=3) array([ 0. , -7.93700526, -10. ]) >>> cubespace(0, 10, num=3, include_start=False) array([ 6.93361274, 8.73580465, 10. ])
- Parameters:
start (float) – The starting value of a sequence.
stop (float) – The ending value of a sequence. If False (default), start is used as the ending value, while the starting value is set to 0.
num (int) – Number of samples to generate. Default is 10.
include_start (bool) – If False, the value of start is not included in returned list. Nonetheless, it is still considered as a starting point.
- Returns:
An array with num spaced samples in the start-stop interval.
- Return type:
numpy.ndarray
- hikari.utility.find_best(strings, criteria)[source]
Parse a list of strings and return the “best” element based on criteria.
- Parameters:
strings (list[str]) – List of string where best will be found based on criteria.
criteria (str) – ‘>’-separated substrings sought in descending order. ‘+’ is a logical ‘and’, ‘=’ substitutes: A=B returns B if A is found.
- Returns:
Best string based on given criteria or `` if no best found.
- Return type:
str
- hikari.utility.rescale_list_to_range(original, limits)[source]
Linearly rescale values in original list to limits (minimum and maximum).
- Example:
- Parameters:
original (Sequence)
limits (Sequence)
- Return type:
list
>>> rescale_list_to_range([1, 2, 3], (0, 10)) [0.0, 5.0, 10.0] >>> rescale_list_to_range([1, 2, 3], (-10, 0)) [-10.0, -5.0, 0.0] >>> rescale_list_to_range([1, 2, 3], (0j, 10j)) [0j, 5j, 10j]
- Parameters:
original (list) – Original list or list-like to be rescaled.
limits (Sequence) – Sequence of two floats, min and max, to constrain the new list
- Returns:
Original list rescaled to fit between min and max
- Return type:
list
- hikari.utility.rescale_list_to_other(source, target)[source]
Linearly rescale source list of numeral values to elements of iterable scale in target. The numeric values in the first list are rescaled to the length of other using
rescale_list_to_range(), changed to integers and used as pointers in other to retrieve final value.- Example:
- Parameters:
source (Sequence)
target (Sequence)
- Return type:
list
>>> rescale_list_to_other([1, 2, 3], [-7.7, -6.6, -5.5, -4.4, -3.3]) [-7.7, -5.5, -3.3] >>> rescale_list_to_other([-7.7, -6.6, -5.5, -4.4, -3.3], [1, 2, 3]) [1, 1, 2, 3, 3] >>> rescale_list_to_other([1, 2, 3], 'holy grail') ['h', ' ', 'l']
- Parameters:
source (Sequence) – Sequence of numerals to be rescaled to other.
target (Sequence) – Sequence from which the values in new list will be selected.
- Returns:
List with elements from other assigned using values in original.
- Return type:
list
- hikari.utility.make_abspath(*path_elements)[source]
Return a string with absolute path to a specified file. Accepts zero or more strings, which are joined according to system-specific syntax. Relative paths are intepreted as having root at current working directory (cwd). Links and symbols such as ‘~’, ‘..’ or ‘/’ are expanded and interpreted. As such, function calls with no argument and ‘~’ as argument will yield string-paths to current working directory and home directory, respectively.
- Example:
>>> make_abspath() PosixPath('/home/username/hikari/hikari/utility') >>> make_abspath('~') PosixPath('/home/username') >>> make_abspath('~', 'cocoa/is', 'not/../hot.txt') PosixPath('/home/username/cocoa/is/hot.txt')
Running the script on Windows machine will yield an appropriate Windows Path. In particular, ‘cocoa/is’ will be intepreted as single directory.
- Parameters:
path_elements (str) – path element(s) to join and intepret, defaults to cwd.
- Returns:
string containing resolved absolute path to the specified location
- Return type:
str
- hikari.utility.gnuplot_map_palette
- hikari.utility.mpl_map_palette
- hikari.utility.artist_factory
- hikari.utility.str2array(s)[source]
Create a numpy int8 array using its compact representation saved as string. The input string might contain only digits and special characters. Every individual digit is treated as a new element, while the special characters induce special behaviour and include:
slash / - if present, divides main list into multiple sub-lists;
hyphen - - the next digit will be read as negative
Please mind that the compact form used as this function’s input is unfit to store floating point numbers or integers with absolute value above 9.
- Parameters:
s (str) – input string containing only digits and special characters
- Returns:
a two-dimensional numpy array with integers
- Return type:
numpy.ndarray