ichor.core.common package
Subpackages
Submodules
ichor.core.common.arith module
- kronecker_delta(p1, p2)
- order_of_magnitude(n: Scalar) int
Returns the order of magnitude of n e.g.
>>> order_of_magnitude(100) 2 >>> order_of_magnitude(0.0001) -4
- Parameters:
n – number to calculate order of magnitude of
- Returns:
order of magnitude of n
ichor.core.common.bool module
- check_bool(val: str | bool, default: bool = True)
Convert a string value to a boolean value and return the boolean
- Parameters:
val – A string or boolean value. If a boolean value is given, return this directly. If a string value is given, check if it should return True of False.
default – Whether or not to accept no input, i.e. “” as True.
ichor.core.common.constants module
Contains all avalable settings for Gaussian, AIMALL, FEREBUS, as well as constant values that are used throughout ICHOR to make conversions, etc.
- class Orbital(name, value)
Bases:
object
ichor.core.common.conversion module
- try_convert(inp: Any, ty: Type, default: Type | None) Type
Tries to convert input to ty, if it fails and a default is specified, the default value is returned otherwise the original ValueError is raised :param inp: input to convert to ty :param default: optional ty to return in case inp fails :return: converted ty :raises: ValueError if ty conversion fails and no default is specified
- try_float(inp: Any, default: float | None = None) float
Tries to convert input to float, if it fails and a default is specified, the default value is returned otherwise the original ValueError is raised :param inp: input to convert to float :param default: optional float to return in case inp fails :return: converted float :raises: ValueError if float conversion fails and no default is specified
- try_int(inp: Any, default: int | None = None) int
Tries to convert input to integer, if it fails and a default is specified, the default value is returned otherwise the original ValueError is raised :param inp: input to convert to integer :param default: optional integer to return in case inp fails :return: converted integer :raises: ValueError if int conversion fails and no default is specified
ichor.core.common.dict module
- exception DictionaryMergeConflict
Bases:
Exception
- find(key: KT, d: MutableMapping[KT, VT]) MutableMapping[KT, VT]
Recursively searches dictionary
dfor the givenkeye.g. .. code-block:: text>>> find("iqa", {"energy": -76.54, "O1": {"iqa": -75.40, "q00": -0.22}, "H2": {"iqa": -0.52, "q00": 0.15}}) {"O1": {"iqa": -75.40}, "H2": {"iqa": -0.52}}
- Parameters:
key – The key to search for
d – The dictionary to search in
- find_in_inner_dicts(key: KT, d: MutableMapping[KT, VT]) MutableMapping[KT, VT]
Recursively searches dictionary
dfor the givenkeye.g.>>> find("iqa", {"energy": -76.54, "O1": {"iqa": -75.40, "q00": -0.22}, "H2": {"iqa": -0.52, "q00": 0.15}}) {"O1": {"iqa": -75.40}, "H2": {"iqa": -0.52}}- Parameters:
key – The key to search for
d – The dictionary to search in
- merge(*dicts)
Merges dictionaries (dicts) immutably e.g.
>>> {"total_energy": -76.4}, {"O1": {"iqa": -75.2}}, {"O1": {"dispersion": -1.0}} {"total_energy": -76.4, "O1": {"iqa": -75.2, "dispersion": -1.0}}- Parameters:
*dicts – Dictionaries to merge
- merge_mutable(a, b, path=None)
merges b into a, modifies a
- remove_items(d: MutableMapping[KT, VT], items: Set[KT]) MutableMapping[KT, VT]
- unwrap_item(d: MutableMapping[KT, VT], item: KT) MutableMapping[KT, VT] | VT
Unwraps the dictionary if the given ‘item’ is the only item in the dictionary e.g.
>>> unwrap_single_item({"energy": -76.54}, "energy") -76.54 >>> unwrap_single_item({"O1": {"iqa": -75.40}, "H2": {"iqa": -0.52}}, "iqa") {"O1": -75.40, "H2": -0.52}- Parameters:
d – dictionary to unwrap
item – key to look for
- unwrap_single_entry(d: MutableMapping[KT, VT]) MutableMapping[KT, VT] | VT
Unwraps the dictionary if there is only a single item in the dictionary.
>>> unwrap_single_entry({"energy": -76.54}) -76.54 >>> unwrap_single_entry({"O1": {"iqa": -75.40}) 75.40 >>> unwrap_single_entry({"O1": {"iqa": -75.40}, "H2": {"iqa": -0.52}}) {"O1": -75.40, "H2": -0.52}- Parameters:
d – dictionary to unwrap
- unwrap_single_item(d: MutableMapping[KT, VT], item: KT) MutableMapping[KT, VT] | VT
Unwraps the dictionary if the given ‘item’ is the only item in the dictionary
>>> unwrap_single_item({"energy": -76.54}, "energy") -76.54 >>> unwrap_single_item({"O1": {"iqa": -75.40}, "H2": {"iqa": -0.52}}, "iqa") {"O1": -75.40, "H2": -0.52}- Parameters:
d – Dictionary to unwrap single item
ichor.core.common.excel module
- col2idx(col: str) int
Returns the column number as a 0-index from the column name e.g.
` >>> col2idx('A') 0 >>> col2idx('Z') 25 >>> col2idx('AB') 27 `- Parameters:
col – column name as string
- Returns:
column number as 0-index
- col2num(col: str) int
Returns the column number from the column name e.g.
` >>> col2num('A') 1 >>> col2num('Z') 26 >>> col2num('AB') 28 `- Parameters:
col – column name as string
- Returns:
column number
- idx2col(n: int) str
Returns the name of the column given the column index e.g.
` >>> num2col(0) 'A' >>> num2col(25) 'Z' >>> num2col(27) 'AB' `:param n: column index :return: column name as string
- num2col(n: int) str
Returns the name of the column given the column number e.g.
` >>> num2col(1) 'A' >>> num2col(26) 'Z' >>> num2col(28) 'AB' `:param n: column number :return: column name as string
ichor.core.common.float module
- from_scientific_double(x: str) float
e.g. “1.0D-2” -> 0.01
ichor.core.common.formatting module
- format_number_with_comma(n: Scalar) str
10000 -> ‘10,000’
- Parameters:
n –
- temperature_formatter(temperature: float, unit: Temperature = Temperature.Kelvin) str
100 -> ‘100 K’
- Parameters:
temperature –
unit –
ichor.core.common.int module
- count_digits(n: int) int
Count number of digits in n, see https://stackoverflow.com/q/24176789/11699003 for example/explanation
- truncate(n: int, nbits: int = 32) int
truncates an integer to the specified number of bits
- Parameters:
n – integer to truncate
nbits – number of bits to truncate the integer to
- Returns:
truncated integer
ichor.core.common.io module
- cat(outfile: Path, infiles: List[Path]) None
Mimics unix cat command by concatenating all infiles to outfile :param outfile: path to concatenate infiles to :param infiles: list of one or more paths to concatenatr to outfile :return: none
- convert_to_path(func: F) F
Used as a decorator which converts any function inputs which have type annotation Path to a Path object.
- copyfile(src: Path, dst: Path)
Copy contents and metadata (such as date created, etc.) from src to dst.
- Parameters:
src – The source directory where the file/directory are currently
dst – The destination directory where the file/directory are to be copied to
- copytree(src: Path, dst: Path, symlinks=False, ignore=None)
Copy a whole tree (a folder and all of its inside contents such as subdirectories, sub-subdirectories, files, etc.)
- Parameters:
src – The source directory where the tree is currently
dst – The destination directory where the tree is to be copied to
symlinks – Whether or not to keep symlinks or copy the files corresponding to the symlinks (default is False, so copies the files directly)
ignore – A callable which indicates which files should not be copied over.
- cp(src: Path, dst: Path, *args, **kwargs)
See copyfile function below
- get_files_of_type(filetype: str | List[str], directory: Path = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/ichor/checkouts/latest/docs/source'), recursive: bool = False, sort: F | None = None) List[Path]
Returns a list of all files that end in a certain file extension/suffix (such as .txt).
- Parameters:
filetype – A string or list of strings corresponding to the suffixes that files should have
directory – The directory where to do the searching for particular files.
recursive – Boolean flag to recursively search subdirectories for files
sort – Optional function to sort files
- last_line(path: Path) str
Alias for tail for getting the last line of a file
- Parameters:
path – the path of the file to read last line of
- Returns:
last line of file as string
- last_modified(f: Path) str
- ln(f: Path, link: Path, force: bool = True)
Creates symlink between f and link. If the link links to a directory, but a file is passed as f, then the symbolic link to f. is created inside the link directory. :param f: file or directory to which to create a symbolic link for :param link: link to create :param force: if the path exists then unlink first
- mkdir(path: Path, empty: bool = False, fail_ok: bool = False)
Makes a directory.
- Parameters:
path – Where to make the directory
empty – Whether to overwrite an existing directory.
fail_ok – When set to False (default), raise OSError if cannot make directory
- move(src: Path, dst: Path, exist_ok=False) None
Move the object from src to dst.
- pushd(new_dir: Path)
Works like the UNIX pushd commmand whereby it changes the current directory and stores the previous directory on the stack By exiting the context manager, the equivalent of
popdis called and the location is reverted to the previous e.g.# currently in /home with pushd('usr/bin'): # now in /home/usr/bin ... with pushd('/foo/bar'): # now in /foo/bar ... # now in /home/usr/bin # now back in /home
Is good to use to temporarily change the current working directory as it is easy to return to the original location
- recursive_move(src: Path, dst: Path) None
Move a whole tree (a folder and all of its inside contents such as subdirectories, sub-subdirectories, files, etc.) or a file to a new location.
- Parameters:
src – The current location of directory of file
dst – The location where the directory or file should be moved to
- relpath(path: Path, start: Path) Path
Returns relative path of ‘path’ from ‘start’
- Parameters:
path – Path to return relative path of
start – Path to return relative path from
- Returns:
relative path of ‘path; from ‘start’
- remove(path: Path) None
Remove a file or directory and all of its contents.
- Parameters:
path – Relative or absolute path to the file/directory to be removed.
- remove_with_suffix(suffix: str, path_to_search: Path = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/ichor/checkouts/latest/docs/source'), recursive: bool = False) None
Remove all files with given suffix ‘suffix’
- Parameters:
suffix – suffix to search and remove
path_to_search – path to search for files with suffix, defaults to cwd
recursive – boolean to search recursively in subdirectories for files with suffix
- symlink(f: Path, link: Path, force=True)
Same as ln function.
- tail(path: Path, lines: int = 20) str
Works in the same way as the unix tail command giving the last n lines of a file
- Parameters:
path – the path of the file to read last m lines of
lines – specifies how many lines from the bottom of the file to return
- Returns:
last n lines of file as string
ichor.core.common.itertools module
- chunker(iterable: Iterable, size: int)
ichor.core.common.linalg module
- get_plane(a, b, c)
- mag(x: ndarray) float
Calculates the magnitude of vector x :param x: vector of length n :return: the magnitude of vector x as float
- mirror_point(plane, p)
ichor.core.common.np module
- batched_array(a: ndarray, batch_size: int) ndarray
- Parameters:
a – list
batch_size – size of each group
- Returns:
Yields successive group-sized lists from l.
- dict_of_list_to_dict_of_array(dict_of_list: Dict[Any, List[Scalar]]) Dict[Any, ndarray]
Converst a dictionary of list of scalars to a dictionary of numpy arrays :param dict_of_list: dictionary mapping a key to a list of scalars (int or float) :return: dictionary mapping original keys to a numpy array converted from dict_of_list
- ensure_array(a: Scalar | List[Scalar] | ndarray) ndarray
ichor.core.common.obj module
- object_get_properties(obj: object) List[str]
- object_get_properties_and_values(obj: object) Dict[str, Any]
- object_getattribute(obj: object, attr: str)
- object_getdict(obj: object) Dict[str, Any]
- object_hasattr(obj: object, attr: str) bool
- object_setattr(obj: object, attr: str, value: Any)
ichor.core.common.os module
- clear_screen()
Clear the currently displayed lines in the terminal
- current_user() str
- current_user_groups() List[str]
Returns the list of user groups the current user is in
- getch()
- input_with_prefill(prompt: str, prefill: str = '') str
Use over the builtin input function when wanting to prefill the input with text e.g.
`python >>> input_with_prefill("ENTER YOUR ANSWER: ", "example answer here") ENTER YOUR ANSWER: example answer here `The user can then choose to replace the prefill text or use what is already there
This is currently used in the settings menu in ichor when editing variables so that the current value is already prefilled and the user can just edit it but is general purpose code so can be used anywhere (unless you’re on windows as readline isn’t available… just defaults to normal input)
- kill_pid(pid: int)
- permissions(path: Path) Tuple[bool, bool, bool]
- pid_exists(pid: int) bool
Check whether pid exists in the current process table.
- run_cmd(cmd) Tuple[str, str]
Run a command in the terminal. This is used to submit jobs through ICHOR (e.g. via qsub on CSF3).
- Parameters:
cmd – command to run in terminal.
- set_permission(path: Path, permission: int)
ichor.core.common.pairwise module
- pairwise(iterable: Iterable) Iterator[Tuple[int, int]]
s -> (s0,s1), (s1,s2), (s2, s3), …
ichor.core.common.patterns module
Contains patterns that ICHOR looks for in output files from Gaussian/AIMALL.
ichor.core.common.search module
- class Comparable(*args, **kwargs)
Bases:
Protocol
- class Node(state: T, parent: Node | None, cost: float = 0.0, heuristic: float = 0.0)
Bases:
Generic[T]
- astar(initial: T, goal_test: Callable[[T], bool], successors: Callable[[T], List[T]], heuristic: Callable[[T], float]) Tuple[Node[T] | None, int]
- bfs(initial: T, goal_test: Callable[[T], bool], successors: Callable[[T], List[T]]) Tuple[Node[T] | None, int]
- binary_contains(sequence: Sequence[C], key: C) bool
- dfs(initial: T, goal_test: Callable[[T], bool], successors: Callable[[T], List[T]]) Tuple[Node[T] | None, int]
- linear_contains(iterable: Iterable[T], key: T) bool
ichor.core.common.sorting module
- get_int(matchobj)
- ignore_alpha(x)
ichor.core.common.str module
Useful functions which are used to manipulate a str or return a str.
- cleanup_str(str_in: str) str
Removes single and double quotes from the string, as well as any whitespace from the given string.
- decode(binary_str: bytes | None) str
Decodes the incoming binary into ascii (which contains letters and numbers) and returns the string containing the ascii characters.
- get_characters(str_in: str) str
Removes the digits from a string and returns resulting string
- get_digits(str_in: str) int
Gets the digits in a string and returns the integer number corresponding to the joined digits.
- in_sensitive(value: str, lst: List[str]) bool
Case insensitive ‘in’ :param value: value to search list for :param lst: list of strings to search value in :return: boolean based on whether value is in lst ignoring case
- join(iterable: Iterable) str
Converts every element of the iterable object into a string and joins with a space. Returns the joined string.
- split_by(s: str, n: List[int], strip: bool = True, return_remainder: bool = True) List[str]
split s by integer list n e.g.
`python >>> split_by('abcdefg', [1, 2, 3]) ['a', 'bc', 'def', 'g'] >>> split_by('abcdefg', [1, 2, 3], return_remainder=False) ['a', 'bc', 'def'] `:param s: string to split :param n: list of integers to split s by :return: list of strings split from original
- split_every(s: str, n: int) List[str]
split string s every n characters :param s: string to split :param n: n to split s by :return: list of strings split every n characters
ichor.core.common.units module
Implements an Enum for atomic distances to decrease the chance of spelling mistakes / typos.
- class AtomicDistance(value)
Bases:
EnumEnum that encapsulates units that are used in ICHOR.
- Angstroms = 'angstroms'
- Bohr = 'bohr'
- degrees_to_radians(a)
- radians_to_degrees(a)