Operator Cache & Wrapper Example#
This example explores the operator cache and helper wrappers that reduce recomputation when compiling multiple related operators. It’s useful for understanding how to build custom backends that reuse precomputed local operators.
What you’ll learn#
How
BaseOperatorCacheorganizes subsystem order and identities.How to fetch local and global (tensor-embedded) operators efficiently.
Source#
1# flake8: noqa
2"""
3Minimal BaseOperatorCache wrapper showing identities and ordering.
4
5What this shows:
6- Subclassing `BaseOperatorCache` to get subsystem ordering and identity caches.
7- Inspecting `cache.subsystems` and `cache.global_identity`.
8- A minimal pattern backend authors can reuse for NumPy-like backends.
9"""
10
11from __future__ import annotations
12
13import sys
14from pathlib import Path
15
16import numpy as np
17
18ROOT = Path(__file__).resolve().parents[1]
19if str(ROOT) not in sys.path:
20 sys.path.insert(0, str(ROOT))
21
22from latex_parser.backend_cache import BaseOperatorCache
23from latex_parser.dsl import HilbertConfig, QubitSpec
24
25
26class NumpyCache(BaseOperatorCache[np.ndarray]):
27 def _local_identity(self, dim: int) -> np.ndarray:
28 return np.eye(dim)
29
30 def _kron(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
31 return np.kron(a, b)
32
33
34def main() -> None:
35 cfg = HilbertConfig(qubits=[QubitSpec(label="q", index=1)], bosons=[], customs=[])
36 cache = NumpyCache(cfg)
37 print("Subsystem order:", cache.subsystems)
38 print("Global identity:\n", cache.global_identity)
39
40
41if __name__ == "__main__":
42 main()
Run#
python examples/example_cache_wrapper.py
Notes#
Useful when building custom backends to avoid repeated Kronecker products.