Skip to content

Commit

Permalink
Added 2 Backend methods for netpyneunit
Browse files Browse the repository at this point in the history
  • Loading branch information
lakesare committed Jul 22, 2021
1 parent 7e8635e commit 2f88974
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/source/basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ capability, and it can be executed to simulate and output results.
Backend

After being registered by ``register_backends`` function, a ``Backend`` instance
can be executed by a Ruunable Model at the back end. It usually does some background
can be executed by a Runnable Model at the back end. It usually does some background
computing for the runnable model.


Expand Down
32 changes: 29 additions & 3 deletions sciunit/models/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,42 @@ def backend_run(self) -> Any:
if self.use_memory_cache or self.use_disk_cache:
key = self.model.hash()
if self.use_memory_cache and self.get_memory_cache(key):
return self._results
return self.cache_to_results(self._results)
if self.use_disk_cache and self.get_disk_cache(key):
return self._results
results = self._backend_run()
return self.cache_to_results(self._results)
results = self.results_to_cache(self._backend_run())
if self.use_memory_cache:
self.set_memory_cache(results, key)
if self.use_disk_cache:
self.set_disk_cache(results, key)
return results

def cache_to_results(self, cache: Any) -> Any:
"""A method you should override if you have to make some adjustments
to the simulation results after they've been restored from the cache.
Args:
cache (Any): An object returned from .get_memory_cache() or .get_disk_cache().
Returns:
Any (optional): Either an object with the results of the simulation,
or None (e.g. if cache_to_results() simply injects the results into some global object).
"""
return cache

def results_to_cache(self, results: Any) -> Any:
"""A method you should override if you have to make some adjustments
to the way your simulation results are stored in cache.
Args:
results (Any): An object returned from your ._backend_run().
Returns:
Any: The results in the format that's good for storing in cache
(usually a simple dictionary or an array).
"""
return results

def _backend_run(self) -> Any:
"""Run the model via the backend."""
raise NotImplementedError("Each backend must implement '_backend_run'")
Expand Down

0 comments on commit 2f88974

Please sign in to comment.