# HDF5 cache¶

In this example, we will see how to use HDF5Cache.

from __future__ import division, unicode_literals

from numpy import array

from gemseo.api import configure_logger
from gemseo.caches.hdf5_cache import HDF5Cache

configure_logger()


Out:

<RootLogger root (INFO)>


## Import¶

Let’s first import the array and the HDF5Cache classes.

## Create¶

A instance of HDF5Cache can be instantiated with the following statement. The user has to provide the file path of the HDF5 file, as well as the node name, which usually is a discipline name.

cache = HDF5Cache("my_cache.hdf5", "node1")


It is possible to see the principal attributes of the cache by printing it, either using a print statement or using the logguer:

print(cache)


Out:

Name: node1
Type: HDF5Cache
Tolerance: 0.0
Input names: None
Output names: None
Length: 0
HDF file path my_cache.hdf5
HDF node path node1


## Cache¶

In this example, we manually add data in the cache from the data dictionary to illsutrate its use. Yet, it has to be noted that a cache can be attached to an MDODiscipline instance, and the user does not have to feed the cache manually. Here, we provide to the cache the data dictionary, and we set x as input and y as output.

data = {"x": array([1.0]), "y": array([2.0])}
cache.cache_outputs(data, ["x"], data, ["y"])
data = {"x": array([2.0]), "y": array([3.0])}
cache.cache_outputs(data, ["x"], data, ["y"])
print(cache)


Out:

Name: node1
Type: HDF5Cache
Tolerance: 0.0
Input names: ['x']
Output names: ['y']
Length: 2
HDF file path my_cache.hdf5
HDF node path node1


## Get all data¶

We can now print some information from the cache, such as its length. We can also display all the cached data so far.

print(cache.get_length())
print(cache.get_all_data())


Out:

2
{1: {'inputs': {'x': array([1.])}, 'outputs': {'y': array([2.])}, 'jacobian': None}, 2: {'inputs': {'x': array([2.])}, 'outputs': {'y': array([3.])}, 'jacobian': None}}


## Get last cached data¶

It is also possible to display the last entry cached, for the inputs and the outputs.

print(cache.get_last_cached_inputs())
print(cache.get_last_cached_outputs())


Out:

{'x': array([2.])}
{'y': array([3.])}


## Clear the cache¶

It is also possible to clear the cache, which removes all the data which has been stored so far in the HDF5 file.

cache.clear()
print(cache)


Out:

Name: node1
Type: HDF5Cache
Tolerance: 0.0
Input names: None
Output names: None
Length: 0
HDF file path my_cache.hdf5
HDF node path node1


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

Gallery generated by Sphinx-Gallery