my_code_base.core.utils

Classes

BunchDict

BunchDict is a subclass of the built-in dict class that allows

Functions

add_metadata(func)

A decorator that adds metadata to the function's output.

centered_bins(x)

Create centered bin boundaries from a given array with the values of the array as centers.

find_nearest(→ float)

Find the element inside items that is closest to the pivot element.

get_obj_type_str(obj)

Transform the output of type to a simplified descriptor:

order_of_magnitude(→ numpy.ndarray)

Determine the order of magnitude of the numeric input.

save(obj, path, *args, **kwargs)

Save the given object including metadata.

Module Contents

class my_code_base.core.utils.BunchDict[source]

BunchDict is a subclass of the built-in dict class that allows accessing dictionary keys as attributes.

This class overrides the __getattr__ and __setattr__ methods to provide attribute-style access to dictionary keys. When an attribute is accessed, it is treated as a dictionary key and the corresponding value is returned. When an attribute is set, it is treated as a dictionary key and the corresponding value is updated.

Note

This is now also implemented in sklearn.utils.Bunch

Example

>>> bd = BunchDict()
>>> bd['key'] = 'value'
>>> print(bd.key)
value
>>> bd.key = 'new value'
>>> print(bd['key'])
new value

Initialize self. See help(type(self)) for accurate signature.

my_code_base.core.utils.add_metadata(func)[source]

A decorator that adds metadata to the function’s output.

The metadata includes the relative path of the file, line number, and git commit hash.

Parameters:
func : callable

The function to be decorated.

Returns:

The decorated function.

Return type:

callable

my_code_base.core.utils.centered_bins(x)[source]

Create centered bin boundaries from a given array with the values of the array as centers.

Example

>>> x = np.arange(-3, 4)
>>> x
array([-3, -2, -1,  0,  1,  2,  3])
>>> centered_bins(x)
array([-3.5, -2.5, -1.5, -0.5,  0.5,  1.5,  2.5,  3.5])
my_code_base.core.utils.find_nearest(items: list | numpy.ndarray, pivot: float) float[source]

Find the element inside items that is closest to the pivot element.

Parameters:
items : list | numpy.ndarray

A list of elements to search from.

pivot : float

The pivot element to find the closest element to.

Returns:

The element from items that is closest to the pivot element.

Return type:

float

Examples

>>> result = find_nearest(np.array([2,4,5,7,9,10]), 4.6)
>>> int(result)      # Cast to int for consistent comparison
5
my_code_base.core.utils.get_obj_type_str(obj)[source]

Transform the output of type to a simplified descriptor:

Turns

“<class ‘xarray.core.dataset.Dataset’>”

into “Dataset”

my_code_base.core.utils.order_of_magnitude(x: int | float | numpy.ndarray | pandas.Series) numpy.ndarray[source]

Determine the order of magnitude of the numeric input.

Examples

>>> order_of_magnitude(11)
array([1.])
>>> order_of_magnitude(234)
array([2.])
>>> order_of_magnitude(1)
array([0.])
>>> order_of_magnitude(.15)
array([-1.])
>>> order_of_magnitude(np.array([24.13, 254.2]))
array([1., 2.])
>>> order_of_magnitude(pd.Series([24.13, 254.2]))
array([1., 2.])
Parameters:
x : int | float | numpy.ndarray | pandas.Series

Return type:

numpy.ndarray

my_code_base.core.utils.save(obj, path, *args, **kwargs)[source]

Save the given object including metadata.

This is a dispatchable function. That is, there are several implementations for different types of objects (e.g. matplotlib.figure.Figure, pandas.DataFrame, xarray.Dataset). In case there is no implementation, the function will throw a NotImplementedError.

Parameters:
obj : object

The object to be saved.

path : str

The path to which the object will be saved.

Raises:

NotImplementedError – If the according function is not dispatched.

Notes

This function raises a NotImplementedError because it is meant to be overridden by subclasses. To save objects of a specific type, please use the native method provided by that type.

Examples

>>> ds = xr.tutorial.load_dataset('air_temperature')
>>> save(ds, '/tmp/mynetcdf.nc', add_hash=True)
>>> !ncdump -h /tmp/mynetcdf_500e15f.nc | grep history
:history = "2024-06-12 16:18:16: File saved by myscript.py#3 @git-commit:500e15f;"
>>> save(my_object, '/tmp/myobj')
NotImplementedError: Cannot save object of type <class 'type'> using `save` method. Please use the native method.