Skip to content

Commit

Permalink
PR 997 - noisy local basis
Browse files Browse the repository at this point in the history
Add cache_method decorator

This supports caching regular methods of class instances with optionally support for including hashable arg values in cache key.

Add noise mitigation support to local basis

Adds ability to initialize local preparation and measurement bases with custom noisy states, povms, or instructions for generating the noisy basis matrices.

Add mitigation support to PauliMeasurementBasis

Add mitigated basis unit tests

Add release note

Address review comments

* Use lru_cache internally for method_cache
* remove cache kwarg from method cache and use fixed cache name based on the instances type

fix simulator seed in tests
  • Loading branch information
chriseclectic committed Jan 24, 2023
1 parent 0df9dbb commit 867fb6c
Show file tree
Hide file tree
Showing 7 changed files with 809 additions and 172 deletions.
68 changes: 68 additions & 0 deletions qiskit_experiments/library/tomography/basis/cache_method.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Method decorator for caching regular methods in class instances.
"""

from typing import Dict, Callable, Optional
import functools


def _method_cache_name(instance: any) -> str:
"""Attribute name for storing cache in an instance"""
return "_CACHE_" + type(instance).__name__


def _get_method_cache(instance: any) -> Dict:
"""Return instance cache for cached methods"""
cache_name = _method_cache_name(instance)
try:
return getattr(instance, cache_name)
except AttributeError:
setattr(instance, cache_name, {})
return getattr(instance, cache_name)


def cache_method(maxsize: Optional[int] = None) -> Callable:
"""Decorator for caching class instance methods.
Args:
maxsize: The maximum size of this method's LRU cache.
Returns:
The decorator for caching methods.
"""

def cache_method_decorator(method: Callable) -> Callable:
"""Decorator for caching method.
Args:
method: A method to cache.
Returns:
The wrapped cached method.
"""

@functools.wraps(method)
def _cached_method(self, *args, **kwargs):
cache = _get_method_cache(self)
key = method.__name__
try:
meth = cache[key]
except KeyError:
meth = cache[key] = functools.lru_cache(maxsize)(functools.partial(method, self))

return meth(*args, **kwargs)

return _cached_method

return cache_method_decorator
Loading

0 comments on commit 867fb6c

Please sign in to comment.