hikari.utility package

Submodules

hikari.utility.artists module

class hikari.utility.artists.AngularHeatmapArtist

Bases: Artist, ABC

Base class used for plotting angular heatmaps

HEAT_EXTENSION = '.lst'
HISTOGRAM_EXTENSION = '.his'
property azimuth_limits
property focus
property heat_limits
property polar_limits
property x_axis
property y_axis
property z_axis
class hikari.utility.artists.Artist

Bases: object

Base class used for plotting matplotlib and gnuplot plots

abstract plot(path)
exception hikari.utility.artists.ArtistError(message)

Bases: Exception

Exception raised when a problem with plotting in hikari occurs.

class hikari.utility.artists.ArtistFactory

Bases: object

A factory method for creating artists.

create(name, **kwargs)
register(name, artist)
class hikari.utility.artists.GnuplotAngularHeatmapArtist

Bases: GnuplotArtist, AngularHeatmapArtist

Base class used for plotting gnuplot angular heatmaps

property focus_string
plot(path)
template = '# prepare output\nreset\nset encoding utf8\nset terminal pngcairo size 800,600 enhanced font \'Sans,16\' solid\nset output \'{job_name}_gnu.png\'\n\n# load variables from python\nmake_histogram = {histogram}\nmin_heat = 100. * {cplt_min}\nmax_heat = 100. * {cplt_max}\nmin_ph = {min_ph}\nmax_ph = {max_ph}\nmin_th = {min_th}\nmax_th = {max_th}\nX1 = {axis_x1}\nX2 = {axis_x2}\nX3 = {axis_x3}\nY1 = {axis_y1}\nY2 = {axis_y2}\nY3 = {axis_y3}\nZ1 = {axis_z1}\nZ2 = {axis_z2}\nZ3 = {axis_z3}\n\n# color definitions\nset style line 1  lt 1 lc rgb "#000000" lw 2     # map edge\nset style arrow 1 lt 1 lc rgb "#ff0000" lw 5     # x arrow\nset style arrow 2 lt 1 lc rgb "#008000" lw 5     # y arrow\nset style arrow 3 lt 1 lc rgb "#0000ff" lw 5     # z arrow\n\n# unset border and tics\nunset key\nunset border\nset format x \'\'\nset format y \'\'\nset format z \'\'\nset tics scale 0\nset format cb "%.0f%%"\nset colorbox user origin 0.825, 0.05 size 0.075, 0.90\nset lmargin screen 0.00\nset bmargin screen 0.00\nset rmargin screen 0.72\nset tmargin screen 0.90\n\n# prepare mapping on sphere\nset mapping spherical\nset angles degrees\nset xyplane at -1\nset view (max_th+min_th)/2, (max_ph+min_ph)/2+90\n\n# prepare spherical coordinate system\nset parametric\nset isosamples 25\nset urange[min_ph:max_ph]\nset vrange[min_th:max_th]\nset cbrange[min_heat:max_heat]\nset xrange[-1.1:1.1]\nset yrange[-1.1:1.1]\nset zrange[-1.1:1.1]\nset palette maxcolors 32\n{palette}\n\n# define axes\nset arrow from X1, X2, X3 to 1.2*X1, 1.2*X2, 1.2*X3 as 1 front\nset arrow from Y1, Y2, Y3 to 1.2*Y1, 1.2*Y2, 1.2*Y3 as 2 front\nset arrow from Z1, Z2, Z3 to 1.2*Z1, 1.2*Z2, 1.2*Z3 as 3 front\nset label at 1.2*X1, 1.2*X2, 1.2*X3 \'(100)\' offset screen 0.01, 0 nopoint front\nset label at 1.2*Y1, 1.2*Y2, 1.2*Y3 \'(010)\' offset screen 0.01, 0 nopoint front\nset label at 1.2*Z1, 1.2*Z2, 1.2*Z3 \'(001)\' offset screen 0.01, 0 nopoint front\n\nset style line 10 pt 12 ps 3 lw 3 lc rgb \'#000000\'\n{focus_string}\n\nset multiplot\n\n# draw everything, minding different coordinate system of splot\nr = 1.001\nsplot \'{job_name}.lst\' using 2:(90-$1):(1):($3*100) with pm3d, \\\n      r*cos(min_ph)*sin(v),r*sin(min_ph)*sin(v),r*cos(v) with line ls 1, \\\n      r*cos(max_ph)*sin(v),r*sin(max_ph)*sin(v),r*cos(v) with line ls 1, \\\n      r*cos(u)*sin(max_th),r*sin(u)*sin(max_th),r*cos(max_th) with line ls 1\n\n# if asked, add histogram based on .his file\nif (make_histogram == 1) {{\nunset parametric\nstats \'{job_name}.his\' u 3 prefix \'heat\' nooutput\nset lmargin screen 0.825 - 0.15 / heat_max\nset bmargin screen 0.050\nset rmargin screen 0.825\nset tmargin screen 0.950\nunset label\nunset arrow\nset xrange [1:0]\nset yrange [min_heat:max_heat]\nset style fill solid border lt 0\nplot \'{job_name}.his\' using (0):1:(0):3:($1*100):($2*100):(($1+$2)*50.0) with boxxy lc pal notitle\n}}\n\nunset multiplot'
class hikari.utility.artists.GnuplotArtist

Bases: ABC

Base class used for plotting gnuplot plots

GNUPLOT_EXTENSION = '.gnu'
property heat_palette
class hikari.utility.artists.MatplotlibAngularHeatmapArtist

Bases: MatplotlibArtist, AngularHeatmapArtist

Base class used for plotting matplotlib angular heatmaps

MESH_EXTENSION = '.dat'
plot(path)
class hikari.utility.artists.MatplotlibArtist

Bases: ABC

Base class used for plotting matplotlib plots

property heat_palette

hikari.utility.certain_float module

hikari.utility.certain_float.cfloat(string)

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.chem_tools module

This file contains all constants and functions containing purely chemical information / methods used in the package.

hikari.utility.chem_tools.chemical_elements = ('H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og')

Tuple containing 2-letter symbols of the first 118 chemical elements.

hikari.utility.chem_tools.split_atom_label(label)

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.interval module

class hikari.utility.interval.Interval(left, right)

Bases: object

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

arange(step=1)

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)

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)

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.list_tools module

This file contains tools to work with tuples and lists used in the package.

hikari.utility.list_tools.cubespace(start, stop=False, num=10, include_start=True)

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

>>> 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 a 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.list_tools.find_best(strings, criteria)

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.list_tools.rescale_list_to_other(source, target)

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

>>> 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 (Iterable) – Iterable of numerals to be rescaled to other.

  • target (Iterable) – Iterable 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.list_tools.rescale_list_to_range(original, limits)

Linearly rescale values in original list to limits (minimum and maximum).

Example

>>> 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 (tuple) – Tuple 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.math_tools module

This file contains constants and functions containing purely mathematical information / methods used in the package.

hikari.utility.math_tools.angle2rad(value)

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.math_tools.cart2sph(x, y, z)

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.math_tools.det3x3(matrix)

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.math_tools.euler_rodrigues_matrix(a, b, c, d)

Return a rotation matrix based on a Euler-Rodrigues parametrisation. For details, see https://en.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_formula.

Parameters
  • a (Union[int, float, uncertainties.UFloat]) – Euler-Rodrigues parameter a

  • b (Union[int, float, uncertainties.UFloat]) – Euler-Rodrigues parameter b

  • c (Union[int, float, uncertainties.UFloat]) – Euler-Rodrigues parameter c

  • d (Union[int, float, uncertainties.UFloat]) – Euler-Rodrigues parameter d

Returns

3x3 matrix describing rotation

Return type

ndarray

hikari.utility.math_tools.fibonacci_sphere(samples=1, seed=1337)

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.math_tools.rotation_around(axis, by)

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.math_tools.rotation_from(from_, to)

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.math_tools.sph2cart(r, p, a)

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.math_tools.weighted_quantile(values, quantiles, weights=None)

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.os_tools module

This file contains constants and functions containing operating system and path information / methods used in the package.

hikari.utility.os_tools.make_abspath(*path_elements)

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.palettes module

Module contents

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.