nirs4all.visualization.prediction_cache module
PredictionCache - Caching layer for expensive prediction computations.
This module provides caching for aggregated predictions to avoid redundant computations when multiple charts use the same data.
- class nirs4all.visualization.prediction_cache.CacheKey(aggregate: str | None, rank_metric: str, rank_partition: str, display_partition: str, group_by: Tuple[str, ...] | None, filters: Tuple[Tuple[str, Any], ...])[source]
Bases:
objectImmutable cache key for prediction queries.
- class nirs4all.visualization.prediction_cache.PredictionCache(max_entries: int = 50)[source]
Bases:
objectLRU-style cache for prediction query results.
Caches expensive computations like aggregations to speed up repeated chart rendering with the same parameters.
The cache stores: - Aggregated prediction results (keyed by aggregate + filters) - Top-k results (keyed by full query parameters)
Cache invalidation happens when: - Max size is exceeded (LRU eviction) - clear() is called explicitly - Predictions data is modified (user must call clear())
Example
>>> cache = PredictionCache(max_entries=100) >>> # First call computes and caches >>> result = cache.get_or_compute(key, compute_fn) >>> # Second call returns cached result >>> result = cache.get_or_compute(key, compute_fn) # Fast!
- get(key: CacheKey) Any | None[source]
Get cached result if available.
- Parameters:
key – Cache key to look up.
- Returns:
Cached result or None if not found.
- get_or_compute(key: CacheKey, compute_fn: callable) Any[source]
Get cached result or compute and cache.
This is the primary method for cache usage. It handles the cache lookup, computation, and storage in one call.
- Parameters:
key – Cache key.
compute_fn – Function to call if cache miss (no args).
- Returns:
Result from cache or computation.
- get_stats() Dict[str, Any][source]
Get cache statistics.
- Returns:
Dictionary with hits, misses, evictions, hit_rate, etc.
- static make_key(aggregate: str | None, rank_metric: str, rank_partition: str = 'val', display_partition: str = 'test', group_by: str | List[str] | None = None, **filters) CacheKey[source]
Create a cache key from query parameters.
- Parameters:
aggregate – Aggregation column name or None.
rank_metric – Metric for ranking.
rank_partition – Partition for ranking.
display_partition – Partition for display.
group_by – Grouping column(s).
**filters – Additional filter criteria.
- Returns:
CacheKey for the query.