hikari.utility ============== .. py:module:: hikari.utility .. autoapi-nested-parse:: 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 ---------- .. toctree:: :maxdepth: 1 /autoapi/hikari/utility/artists/index /autoapi/hikari/utility/certain_float/index /autoapi/hikari/utility/chem_tools/index /autoapi/hikari/utility/dict_tools/index /autoapi/hikari/utility/interval/index /autoapi/hikari/utility/list_tools/index /autoapi/hikari/utility/math_tools/index /autoapi/hikari/utility/numpy_tools/index /autoapi/hikari/utility/os_tools/index /autoapi/hikari/utility/palettes/index /autoapi/hikari/utility/singleton/index /autoapi/hikari/utility/typing/index Attributes ---------- .. autoapisummary:: hikari.utility.chemical_elements hikari.utility.gnuplot_map_palette hikari.utility.mpl_map_palette hikari.utility.artist_factory Classes ------- .. autoapisummary:: hikari.utility.Interval hikari.utility.Singleton Functions --------- .. autoapisummary:: hikari.utility.cfloat hikari.utility.split_atom_label hikari.utility.dict_union hikari.utility.angle2rad hikari.utility.cart2sph hikari.utility.sph2cart hikari.utility.det3x3 hikari.utility.fibonacci_sphere hikari.utility.rotation_from hikari.utility.rotation_around hikari.utility.weighted_quantile hikari.utility.cubespace hikari.utility.find_best hikari.utility.rescale_list_to_range hikari.utility.rescale_list_to_other hikari.utility.make_abspath hikari.utility.str2array Package Contents ---------------- .. py:function:: cfloat(string) Create "certain float" (`ufloat.n`) from string by converting it first to `uncertainties.ufloat` and then taking the nominal value. :param string: string to be converted :type string: str :return: float with no uncertainty :rtype: float .. py:data:: chemical_elements :value: ('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. .. py:function:: 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 .. py:function:: dict_union(*dicts) Return a union of dicts; if conflicts, later dicts take precedence. .. py:class:: Interval(left, right) 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 .. py:attribute:: left .. py:attribute:: right .. py:method:: __eq__(other) .. py:method:: __lt__(other) .. py:method:: __gt__(other) .. py:method:: __le__(other) .. py:method:: __ge__(other) .. py:method:: __pos__() .. py:method:: __neg__() .. py:method:: __add__(other) .. py:method:: __sub__(other) .. py:method:: __mul__(other) .. py:method:: __truediv__(other) .. py:method:: __str__() .. py:method:: __repr__() .. py:method:: __iter__() .. py:method:: __getitem__(key) .. py:method:: __setitem__(key, value) .. py:method:: __contains__(item) .. py:method:: __len__() .. py:method:: _min(item) :staticmethod: Recursively returns minimum of args if possible, otherwise args .. py:method:: _max(item) :staticmethod: Recursively returns maximum of args if possible, otherwise args .. py:method:: 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 .. py:method:: 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 .. py:method:: 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 .. py:function:: 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. :param value: Angle value given in angles or radians :type value: float :return: Angle value expressed in radians :rtype: float .. py:function:: cart2sph(x, y, z) Convert Cartesian coordinates x, y, z to conventional spherical coordinates r, p, a :param x: Cartesian coordinate or vector x :type x: float or np.ndarray :param y: Cartesian coordinate or vector y :type y: float or np.ndarray :param z: Cartesian coordinates or vector z :type z: float or np.ndarray :return: Spherical coordinates: radius, polar angle, and azimuth angle :rtype: np.ndarray .. py:function:: sph2cart(r, p, a) Convert conventional spherical coordinates r, p, a to Cartesian coordinates x, y, z :param r: Spherical coordinate or vector radius :type r: float or np.ndarray :param p: Spherical coordinate or vector polar angle :type p: float or np.ndarray :param a: Spherical coordinate or vector azimuth angle :type a: float or np.ndarray :return: Cartesian coordinates: x, y, and z :rtype: np.ndarray .. py:function:: det3x3(matrix) Calculate a determinant of a 3x3 matrix. Should be usually substituted by `numpy.linalg.det`, but is indispensable for matrices with uncertainties. :param matrix: 3x3 array/matrix which allows for 2d indexing :type matrix: numpy.ndarray or uncertainties.unumpy.matrix :return: Determinant of the matrix :rtype: int or float or uncertainties.core.Variable .. py:function:: 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]]) :param samples: Number of points to be generated. :type samples: int :param seed: A seed value used once to slightly randomise point position. :type seed: any :return: (x,y,z) arrays representing points' cartesian coordinates. :rtype: np.array .. py:function:: rotation_from(from_, to) Return matrix associated with rotation of vector `from_` onto `to`. :param from_: A 3D vector which will have been rotated onto `to`. :type from_: np.ndarray :param to: A 3D vector onto which `from` will have been rotated. :type to: np.ndarray :return: Matrix associated with rotation of `from` onto `to`. :rtype: np.ndarray .. py:function:: rotation_around(axis, by) Return matrix associated with counterclockwise rotation about `axis` through `by` radians. See Euler-Rodrigues form.,https://stackoverflow.com/q/6802577/ :param axis: A 3D vector about which rotation is performed :type axis: np.ndarray :param by: Angle of rotation in radians :type by: float :return: Matrix associated with rotation around `axis` through `by`. :rtype: np.ndarray .. py:function:: 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. :param values: data to be evaluated :type values: tuple or list or np.ndarray :param quantiles: iterable containing desired quartiles between 0 and 1 :type quantiles: tuple or list or np.ndarray :param weights: weights of data in the same order :type weights: tuple or list or np.ndarray :return: array containing approximated quartiles :rtype: np.ndarray .. py:function:: 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. ]) :param start: The starting value of a sequence. :type start: float :param stop: The ending value of a sequence. If False (default), *start* is used as the ending value, while the starting value is set to 0. :type stop: float :param num: Number of samples to generate. Default is 10. :type num: int :param include_start: If False, the value of *start* is not included in returned list. Nonetheless, it is still considered as a starting point. :type include_start: bool :return: An array with *num* spaced samples in the *start*-*stop* interval. :rtype: numpy.ndarray .. py:function:: find_best(strings, criteria) Parse a list of `strings` and return the "best" element based on `criteria`. :param strings: List of string where best will be found based on `criteria`. :type strings: list[str] :param criteria: '>'-separated substrings sought in descending order. '+' is a logical 'and', '=' substitutes: `A=B` returns B if A is found. :type criteria: str :return: Best string based on given `criteria` or `` if no best found. :rtype: str .. py:function:: 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] :param original: Original list or list-like to be rescaled. :type original: list :param limits: Sequence of two floats, min and max, to constrain the new list :type limits: Sequence :return: Original list rescaled to fit between min and max :rtype: list .. py:function:: 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 :func:`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'] :param source: Sequence of numerals to be rescaled to *other*. :type source: Sequence :param target: Sequence from which the values in new list will be selected. :type target: Sequence :return: List with elements from *other* assigned using values in original. :rtype: list .. py:function:: 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. :param path_elements: path element(s) to join and intepret, defaults to cwd. :type path_elements: str :return: string containing resolved absolute path to the specified location :rtype: str .. py:data:: gnuplot_map_palette .. py:data:: mpl_map_palette .. py:data:: artist_factory .. py:function:: str2array(s) 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. :param s: input string containing only digits and special characters :return: a two-dimensional numpy array with integers .. py:class:: Singleton Bases: :py:obj:`type` A metaclass based on https://stackoverflow.com/q/6760685/. Declare a singleton class using `MyClass(BaseClass, metaclass=Singleton)` .. py:attribute:: _instances .. py:method:: __call__(*args, **kwargs)