opan.utils

Utility functions for Open Anharmonic, including execution automation.

Sub-Modules

decorate – Custom Open Anharmonic decorators

execute – Functions for execution of external computational software packages

inertia – Inertia-related tools (center of mass, rotational constants, principal moments/axes, etc.)

symm – Molecular symmetry utility functions (INCOMPLETE)

vector – Vector utility functions

Functions

opan.utils.base.assert_npfloatarray(obj, varname, desc, exc, tc, errsrc)

Assert a value is an np.array of NumPy floats.

Pass None to varname if obj itself is to be checked. Otherwise, varname is the string name of the attribute of obj to check. In either case, desc is a string description of the object to be checked, for use in raising of exceptions.

Raises the exception exc with typecode tc if the indicated object is determined not to be an np.array, with a NumPy float dtype.

Intended primarily to serve as an early check for proper implementation of subclasses of SuperOpanGrad and SuperOpanHess. Early type-checking of key attributes will hopefully avoid confusing bugs downstream.

Parameters:
  • obj – (arbitrary) – Object to be checked, or object with attribute to be checked.
  • varnamestr or None – Name of the attribute of obj to be type-checked. None indicates to check obj itself.
  • descstr – Description of the object being checked to be used in any raised exceptions.
  • exc – Subclass of OpanError to be raised on a failed typecheck.
  • tc – Typecode of exc to be raised on a failed typecheck.
  • errsrcstr – String description of the source of the data leading to a failed typecheck.
opan.utils.base.check_geom(c1, a1, c2, a2[, tol])

Check for consistency of two geometries and atom symbol lists

Cartesian coordinates are considered consistent with the input coords if each component matches to within tol. If coords or atoms vectors are passed that are of mismatched lengths, a False value is returned.

Both coords vectors must be three times the length of the atoms vectors or a ValueError is raised.

Parameters:
  • c1 – length-3N np.float_ – Vector of first set of stacked ‘lab-frame’ Cartesian coordinates
  • a1 – length-N str or int – Vector of first set of atom symbols or atomic numbers
  • c2 – length-3N np.float_ – Vector of second set of stacked ‘lab-frame’ Cartesian coordinates
  • a2 – length-N str or int – Vector of second set of atom symbols or atomic numbers
  • tolfloat, optional – Tolerance for acceptable deviation of each geometry coordinate from that in the reference instance to still be considered matching. Default value is specified by opan.const.DEF.XYZ_COORD_MATCH_TOL)
Returns:

  • matchbool – Whether input coords and atoms match (True) or not (False)

  • fail_typeEnumCheckGeomMismatch or None – Type of check failure

    If match == True:

    Returns as None

    If match == False:

    An EnumCheckGeomMismatch value indicating the reason for the failed match:

    DIMENSION – Mismatch in geometry size (number of atoms)

    COORDS – Mismatch in one or more coordinates

    ATOMS – Mismatch in one or more atoms

  • fail_loc – length-3N bool or length-N bool or None – Mismatched elements

    If match == True:

    Returns as None

    If match == False:

    For “array-level” problems such as a dimension mismatch, a None value is returned.

    For “element-level” problems, a vector is returned indicating positions of mismatch in either coords or atoms, depending on the value of fail_type.

    True elements indicate MATCHING values

    False elements mark MISMATCHES

Raises:

ValueError – If a pair of coords & atoms array lengths is inconsistent:

if len(c1) != 3 * len(a1) or len(c2) != 3 * len(a2):
    raise ValueError(...)
opan.utils.base.delta_fxn(a, b)

Kronecker delta for objects a and b.

Parameters:
  • a – First object
  • b – Second object
Returns:

deltaint – Value of Kronecker delta for provided indices, as tested by Python ==

opan.utils.base.iterable(y)

Check whether or not an object supports iteration.

Adapted directly from NumPy ~= 1.10 at commit 46d2e83.

Parameters:y – (arbitrary) – Object to be tested.
Returns:testbool – Returns False if iter() raises an exception when y is passed to it; True otherwise.

Examples

>>> opan.utils.iterable([1, 2, 3])
True
>>> opan.utils.iterable(2)
False
opan.utils.base.make_timestamp(el_time)

Generate an hour-minutes-seconds timestamp from an interval in seconds.

Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format “#h #m #s”, indicating the number of hours, minutes, and seconds in the interval. Intervals greater than 24h are unproblematic.

Parameters:el_timeint or float – Time interval in seconds to be converted to h/m/s format
Returns:stampstr – String timestamp in #h #m #s format
opan.utils.base.pack_tups(*args)

Pack an arbitrary set of iterables and non-iterables into tuples.

Function packs a set of inputs with arbitrary iterability into tuples. Iterability is tested with iterable(). Non-iterable inputs are repeated in each output tuple. Iterable inputs are expanded uniformly across the output tuples. For consistency, all iterables must be the same length.

The input arguments are parsed such that bare strings are treated as NON-ITERABLE, through the use of a local subclass of str that cripples the __iter__() method. Any strings passed are returned in the packed tuples as standard, ITERABLE instances of str, however.

The order of the input arguments is retained within each output tuple.

No structural conversion is attempted on the arguments.

If all inputs are non-iterable, a list containing a single tuple will be returned.

Parameters:*args – Arbitrary number of arbitrary mix of iterable and non-iterable objects to be packed into tuples.
Returns:tupslist of tuple – Number of tuples returned is equal to the length of the iterables passed in *args
Raises:ValueError – If any iterable objects are of different lengths
opan.utils.base.safe_cast(invar, totype)

Performs a “safe” typecast.

Ensures that invar properly casts to totype. Checks after casting that the result is actually of type totype. Any exceptions raised by the typecast itself are unhandled.

Parameters:
  • invar – (arbitrary) – Value to be typecast.
  • totypetype – Type to which invar is to be cast.
Returns:

outvartype ‘totype’ – Typecast version of invar

Raises:

TypeError – If result of typecast is not of type totype

opan.utils.base.template_subst(template, subs[, delims=['<', '>']])

Perform substitution of content into tagged string.

For substitutions into template input files for external computational packages, no checks for valid syntax are performed.

Each key in subs corresponds to a delimited substitution tag to be replaced in template by the entire text of the value of that key. For example, the dict {"ABC": "text"} would convert The <ABC> is working to The text is working, using the default delimiters of ‘<’ and ‘>’. Substitutions are performed in iteration order from subs; recursive substitution as the tag parsing proceeds is thus feasible if an OrderedDict is used and substitution key/value pairs are added in the proper order.

Start and end delimiters for the tags are modified by delims. For example, to substitute a tag of the form {|TAG|}, the tuple ("{|","|}") should be passed to subs_delims. Any elements in delims past the second are ignored. No checking is performed for whether the delimiters are “sensible” or not.

Parameters:
  • templatestr – Template containing tags delimited by subs_delims, with tag names and substitution contents provided in subs
  • subsdict of str – Each item’s key and value are the tag name and corresponding content to be substituted into the provided template.
  • delims – iterable of str – Iterable containing the ‘open’ and ‘close’ strings used to mark tags in the template, which are drawn from elements zero and one, respectively. Any elements beyond these are ignored.
Returns:

subst_textstr – String generated from the parsed template, with all tag substitutions performed.