my_code_base.core.utils

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.

clear()[source]

D.clear() -> None. Remove all items from D.

copy()[source]

D.copy() -> a shallow copy of D

get()[source]

Return the value for key if key is in the dictionary, else default.

items()[source]

D.items() -> a set-like object providing a view on D’s items

keys()[source]

D.keys() -> a set-like object providing a view on D’s keys

pop()[source]

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()[source]

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault()[source]

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update()[source]

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()[source]

D.values() -> an object providing a view on D’s values

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, pivot)[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)[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.