You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.py 3.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. from typing import Callable, Generic, TypeVar
  2. K = TypeVar("K")
  3. T = TypeVar("T")
  4. PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
  5. class Cache(Generic[K, T]):
  6. def __init__(self, func: Callable[[K], T]):
  7. """Create cache
  8. :param func: Function this cache evaluates
  9. :param cache: If true, do in memory caching.
  10. :param cache_root: If not None, cache to files at the provided path.
  11. :param key_func: Convert the key into a hashable object if needed
  12. """
  13. self.func = func
  14. self.has_init = False
  15. def __getitem__(self, obj, *args) -> T:
  16. return self.get_from_dict(obj, *args)
  17. def clear_cache(self):
  18. """Invalidate entire cache."""
  19. self.cache_dict.clear()
  20. def _init_cache(self, obj):
  21. if self.has_init:
  22. return
  23. self.cache = True
  24. self.cache_dict = dict()
  25. self.key_func = obj.key_func
  26. self.max_size = obj.cache_size
  27. self.hits, self.misses = 0, 0
  28. self.full = False
  29. self.root = [] # root of the circular doubly linked list
  30. self.root[:] = [self.root, self.root, None, None]
  31. self.has_init = True
  32. def get_from_dict(self, obj, *args) -> T:
  33. """Implements dict based cache."""
  34. # x is not used in cache key
  35. pred_pseudo_label, y, x, *res_args = args
  36. cache_key = (self.key_func(pred_pseudo_label), self.key_func(y), *res_args)
  37. link = self.cache_dict.get(cache_key)
  38. if link is not None:
  39. # Move the link to the front of the circular queue
  40. link_prev, link_next, _key, result = link
  41. link_prev[NEXT] = link_next
  42. link_next[PREV] = link_prev
  43. last = self.root[PREV]
  44. last[NEXT] = self.root[PREV] = link
  45. link[PREV] = last
  46. link[NEXT] = self.root
  47. self.hits += 1
  48. return result
  49. self.misses += 1
  50. result = self.func(obj, *args)
  51. if self.full:
  52. # Use the old root to store the new key and result.
  53. oldroot = self.root
  54. oldroot[KEY] = cache_key
  55. oldroot[RESULT] = result
  56. # Empty the oldest link and make it the new root.
  57. self.root = oldroot[NEXT]
  58. oldkey = self.root[KEY]
  59. self.root[KEY] = self.root[RESULT] = None
  60. # Now update the cache dictionary.
  61. del self.cache_dict[oldkey]
  62. self.cache_dict[cache_key] = oldroot
  63. else:
  64. # Put result in a new link at the front of the queue.
  65. last = self.root[PREV]
  66. link = [last, self.root, cache_key, result]
  67. last[NEXT] = self.root[PREV] = self.cache_dict[cache_key] = link
  68. if isinstance(self.max_size, int):
  69. self.full = len(self.cache_dict) >= self.max_size
  70. return result
  71. def abl_cache():
  72. def decorator(func):
  73. cache_instance = Cache(func)
  74. def wrapper(obj, *args):
  75. if obj.use_cache:
  76. cache_instance._init_cache(obj)
  77. return cache_instance.get_from_dict(obj, *args)
  78. else:
  79. return func(obj, *args)
  80. return wrapper
  81. return decorator

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.