Memory full cache

This example shows how to manipulate a MemoryFullCache object.

from __future__ import annotations

from gemseo.api import configure_logger
from gemseo.caches.memory_full_cache import MemoryFullCache
from numpy import array

configure_logger()
<RootLogger root (INFO)>

Import

First, we import the array and the MemoryError classes.

Create

We can create an instance of the MemoryFullCache class. We can then print it, and we can see it is empty.

Warning

The MemoryFullCache relies on some multiprocessing features. When working on Windows, the execution of scripts containing instances of MemoryFullCache must be protected by an if __name__ == '__main__': statement.

cache = MemoryFullCache()
print(cache)
Name: MemoryFullCache
   Type: MemoryFullCache
   Tolerance: 0.0
   Input names: []
   Output names: []
   Length: 0

Cache

We can manually add data into the cache. However, it has to be noted that most of the time a cache is attached to an MDODiscipline. Then, the cache feeding has not to be performed explicitly by the user.

cache[{"x": array([1.0])}] = ({"y": array([2.0])}, None)
cache[{"x": array([2.0])}] = ({"y": array([3.0])}, None)
print(cache)
Name: MemoryFullCache
   Type: MemoryFullCache
   Tolerance: 0.0
   Input names: ['x']
   Output names: ['y']
   Length: 2

Get all data

Once the cache has been filled, the user can get the length of the cache. The user can also print all the data contained inside the cache.

print(len(cache))
for data in cache:
    print(data)
2
CacheEntry(inputs={'x': array([1.])}, outputs={'y': array([2.])}, jacobian=None)
CacheEntry(inputs={'x': array([2.])}, outputs={'y': array([3.])}, jacobian=None)

Get last cached data

The user can access the last entry (inputs or outputs) which have been entered in the cache.

last_entry = cache.last_entry
print(last_entry.inputs)
print(last_entry.outputs)
{'x': array([2.])}
{'y': array([3.])}

Clear

The user can clear an cache of all its entries by using the MemoryFullCache.clear() method:

cache.clear()
print(cache)
Name: MemoryFullCache
   Type: MemoryFullCache
   Tolerance: 0.0
   Input names: []
   Output names: []
   Length: 0

Total running time of the script: ( 0 minutes 0.019 seconds)

Gallery generated by Sphinx-Gallery