snat_sim.utils.caching

The caching module defines numpy compatible function wrappers for implementing function level memoization.

Usage Example

The builtin Python memoization routines (e.g., lru_cache) are not compatible with numpy arrays because array objects are not hashable. The Cache decorator provides an alternative memoization solution that supports numpy arguments. Arguments that are numpy arguments must be specified by name when constructing the decorator:

>>> import numpy as np

>>> from snat_sim.utils.caching import Cache

>>> def add(x: np.array, y: np.array) -> np.array:
...     print('The function has been called!')
...     return x + y

>>> add = Cache(add, 1000, 'x', 'y')
>>> x_arr = np.arange(1, 5)
>>> y_arr = np.arange(5, 9)

>>> print(add(x_arr, y_arr))
The function has been called!
[ 6  8 10 12]

>>> print(add(x_arr, y_arr))
[ 6  8 10 12]

Module API

class snat_sim.utils.caching.MemoryCache(max_size=None)[source]

Ordered dictionary with an imposed limit on overall memory usage

__init__(max_size=None)[source]

Ordered dictionary with an imposed size limit im memory.

When memory usage exceeds the predefined amount, remove the oldest entry from the cache.

Parameters:

max_size (Optional[int]) – Maximum memory size in bytes

class snat_sim.utils.caching.Cache(function, cache_size, *numpy_args)[source]

Memoization function wrapper

__init__(function, cache_size, *numpy_args)[source]

Memoization decorator supporting numpy arrays.

Parameters:
  • *numpy_args – Function arguments to treat as numpy arrays

  • cache_size (int) – Maximum memory to allocate to cached data in bytes

Returns:

A callable function decorator