zea.utils¶
General utility functions.
Functions
|
Calculates the hash of a file. |
Checks the architecture of the system. |
|
|
Converts a date string to a more readable format. |
|
Recursively compare two objects for equality. |
|
Decorator to mark a function, method, or attribute as deprecated. |
|
Find the index of the first non-zero element along a specified axis in a NumPy array. |
|
Find key in dictionary that contains partly the string contains |
|
Find all methods in a class that have the specified return type hint. |
|
Finds and returns the first non-None item in the given array. |
|
Returns True if the function requires the argument 'arg_name'. |
|
Generate a date string for current time, according to format specified by string. |
|
Get the names of the arguments of a function. |
|
Converts a grayscale image to an RGB image. |
|
Keep trying to run a function until it succeeds. |
|
Maps negative indices for array indexing to positive indices. |
|
Preprocesses images for saving to GIF or MP4. |
Clears line. |
|
|
Reduce the kwargs to the signature of the function. |
|
Safely initialize a class by removing any invalid arguments. |
|
Saves a sequence of images to a GIF file. |
|
Saves a sequence of images to an MP4 file. |
|
Convert a string representation of truth to True or False. |
|
Map values in array from one range to other. |
|
Updates dict1 with values dict2 |
Classes
A decorator class for timing the execution of functions. |
- class zea.utils.FunctionTimer[source]¶
Bases:
object
A decorator class for timing the execution of functions.
Example
>>> from zea.utils import FunctionTimer >>> timer = FunctionTimer() >>> my_function = lambda: sum(range(10)) >>> my_function = timer(my_function) >>> _ = my_function() >>> print(timer.get_stats("my_function"))
- zea.utils.calculate_file_hash(file_path, omit_line_str=None)[source]¶
Calculates the hash of a file.
- Parameters:
file_path (str) – Path to file.
omit_line_str (str, optional) – If this string is found in a line, the line will be omitted when calculating the hash. This is useful for example when the file contains the hash itself.
- Returns:
The hash of the file.
- Return type:
str
- zea.utils.date_string_to_readable(date_string, include_time=False)[source]¶
Converts a date string to a more readable format.
- Parameters:
date_string (str) – The input date string.
include_time (bool, optional) – Whether to include the time in the output. Defaults to False.
- Returns:
The date string in a more readable format.
- Return type:
str
- zea.utils.deprecated(replacement=None)[source]¶
Decorator to mark a function, method, or attribute as deprecated.
- Parameters:
replacement (str, optional) – The name of the replacement function, method, or attribute.
- Returns:
The decorated function, method, or property.
- Return type:
callable
- Raises:
DeprecationWarning – A warning is issued when the deprecated item is called or accessed.
Example
>>> from zea.utils import deprecated >>> class MyClass: ... @deprecated(replacement="new_method") ... def old_method(self): ... print("This is the old method.") ... ... @deprecated(replacement="new_attribute") ... def __init__(self): ... self._old_attribute = "Old value" ... ... @deprecated(replacement="new_property") ... @property ... def old_property(self): ... return self._old_attribute
>>> # Using the deprecated method >>> obj = MyClass() >>> obj.old_method() This is the old method. >>> # Accessing the deprecated attribute >>> print(obj.old_property) Old value >>> # Setting value to the deprecated attribute >>> obj.old_property = "New value"
- zea.utils.find_first_nonzero_index(arr, axis, invalid_val=-1)[source]¶
Find the index of the first non-zero element along a specified axis in a NumPy array.
- Parameters:
arr (numpy.ndarray) – The input array to search for the first non-zero element.
axis (int) – The axis along which to perform the search.
invalid_val (int, optional) – The value to assign to elements where no non-zero values are found along the axis.
- Returns:
- An array of indices where the first non-zero element
occurs along the specified axis. Elements with no non-zero values along the axis are replaced with the ‘invalid_val’.
- Return type:
numpy.ndarray
- zea.utils.find_key(dictionary, contains, case_sensitive=False)[source]¶
Find key in dictionary that contains partly the string contains
- Parameters:
dictionary (dict) – Dictionary to find key in.
contains (str) – String which the key should .
case_sensitive (bool, optional) – Whether the search is case sensitive. Defaults to False.
- Returns:
the key of the dictionary that contains the query string.
- Return type:
str
- Raises:
TypeError – if not all keys are strings.
KeyError – if no key is found containing the query string.
- zea.utils.find_methods_with_return_type(cls, return_type_hint)[source]¶
Find all methods in a class that have the specified return type hint.
- Parameters:
cls – The class to inspect.
return_type_hint – The return type hint to match (as a string).
- Returns:
A list of method names that match the return type hint.
- zea.utils.first_not_none_item(arr)[source]¶
Finds and returns the first non-None item in the given array.
- Parameters:
arr (list) – The input array.
- Returns:
The first non-None item found in the array, or None if no such item exists.
- zea.utils.fn_requires_argument(fn, arg_name)[source]¶
Returns True if the function requires the argument ‘arg_name’.
- zea.utils.get_date_string(string=None)[source]¶
Generate a date string for current time, according to format specified by string. Refer to the documentation of the datetime module for more information on the formatting options.
If no string is specified, the default format is used: “%Y_%m_%d_%H%M%S”.
- zea.utils.grayscale_to_rgb(image)[source]¶
Converts a grayscale image to an RGB image.
- Parameters:
image (ndarray) – Grayscale image. Must have shape (height, width).
- Returns:
RGB image.
- Return type:
ndarray
- zea.utils.keep_trying(fn, args=None, required_set=None)[source]¶
Keep trying to run a function until it succeeds.
- Parameters:
fn (callable) – Function to run.
args (dict, optional) – Arguments to pass to function.
required_set (set, optional) – Set of required outputs. If output is not in required_set, function will be rerun.
- Returns:
The output of the function if successful.
- Return type:
Any
- zea.utils.map_negative_indices(indices, length)[source]¶
Maps negative indices for array indexing to positive indices. .. rubric:: Example
>>> from zea.utils import map_negative_indices >>> map_negative_indices([-1, -2], 5) [4, 3]
- zea.utils.preprocess_for_saving(images)[source]¶
Preprocesses images for saving to GIF or MP4.
- Parameters:
images (ndarray, list[ndarray]) – Images. Must have shape (n_frames, height, width, channels) or (n_frames, height, width).
- zea.utils.print_clear_line()[source]¶
Clears line. Helpful when printing in a loop on the same line.
- zea.utils.reduce_to_signature(func, kwargs)[source]¶
Reduce the kwargs to the signature of the function.
- zea.utils.safe_initialize_class(cls, **kwargs)[source]¶
Safely initialize a class by removing any invalid arguments.
- zea.utils.save_to_gif(images, filename, fps=20, shared_color_palette=False)[source]¶
Saves a sequence of images to a GIF file.
- Parameters:
images (list or np.ndarray) – List or array of images. Must have shape (n_frames, height, width, channels) or (n_frames, height, width). If channel axis is not present, or is 1, grayscale image is assumed, which is then converted to RGB. Images should be uint8.
filename (str or Path) – Filename to which data should be written.
fps (int) – Frames per second of rendered format.
shared_color_palette (bool, optional) – If True, creates a global color palette across all frames, ensuring consistent colors throughout the GIF. Defaults to False, which is default behavior of PIL.Image.save. Note: True can cause slow saving for longer sequences.
- zea.utils.save_to_mp4(images, filename, fps=20)[source]¶
Saves a sequence of images to an MP4 file.
- Parameters:
images (list or np.ndarray) – List or array of images. Must have shape (n_frames, height, width, channels) or (n_frames, height, width). If channel axis is not present, or is 1, grayscale image is assumed, which is then converted to RGB. Images should be uint8.
filename (str or Path) – Filename to which data should be written.
fps (int) – Frames per second of rendered format.
- Returns:
Success message.
- Return type:
str
- zea.utils.strtobool(val)[source]¶
Convert a string representation of truth to True or False.
True values are ‘y’, ‘yes’, ‘t’, ‘true’, ‘on’, and ‘1’; false values are ‘n’, ‘no’, ‘f’, ‘false’, ‘off’, and ‘0’. Raises ValueError if ‘val’ is anything else.
- zea.utils.translate(array, range_from=None, range_to=(0, 255))[source]¶
Map values in array from one range to other.
- Parameters:
array (ndarray) – input array.
range_from (Tuple, optional) – lower and upper bound of original array. Defaults to min and max of array.
range_to (Tuple, optional) – lower and upper bound to which array should be mapped. Defaults to (0, 255).
- Returns:
translated array
- Return type:
(ndarray)
- zea.utils.update_dictionary(dict1, dict2, keep_none=False)[source]¶
Updates dict1 with values dict2
- Parameters:
dict1 (dict) – base dictionary
dict2 (dict) – update dictionary
keep_none (bool, optional) – whether to keep keys with None values in dict2. Defaults to False.
- Returns:
updated dictionary
- Return type:
dict