11from __future__ import annotations
22
33import logging
4+ import weakref
45from abc import ABC
56from typing import TYPE_CHECKING , Any , ClassVar , Generic , Literal , TypeVar , overload
67
@@ -59,6 +60,7 @@ class AngularKetBase(ABC, Generic[GenericT_Unknown], metaclass=CachedABCMeta):
5960 "quantum_numbers" ,
6061 "_allow_unknown" ,
6162 "_initialized" ,
63+ "_reduced_matrix_element_cache" ,
6264 "__weakref__" ,
6365 )
6466
@@ -119,6 +121,10 @@ def __init__( # noqa: C901, PLR0912
119121 Atomic species, e.g. 'Rb87', will not be used for calculation,
120122 only for convenience to infer the core electron spin and nuclear spin quantum numbers.
121123 """
124+ self ._reduced_matrix_element_cache : weakref .WeakKeyDictionary [
125+ AngularKetBase [Any ], dict [tuple [AngularOperatorType , int ], float ]
126+ ] = weakref .WeakKeyDictionary ()
127+
122128 if species is not None :
123129 from rydstate .species .element_properties import get_element_properties # noqa: PLC0415
124130
@@ -600,8 +606,8 @@ def calc_reduced_overlap(self, other: AngularKetBase[Any]) -> float:
600606
601607 raise NotImplementedError (f"This method is not yet implemented for { self !r} and { other !r} ." )
602608
603- def calc_reduced_matrix_element ( # noqa: C901, PLR0912
604- self : Self , other : AngularKetBase [Any ], operator : AngularOperatorType , kappa : int
609+ def calc_reduced_matrix_element (
610+ self , other : AngularKetBase [Any ], operator : AngularOperatorType , kappa : int
605611 ) -> float :
606612 r"""Calculate the reduced angular matrix element.
607613
@@ -612,6 +618,15 @@ def calc_reduced_matrix_element( # noqa: C901, PLR0912
612618 \left\langle self || \hat{O}^{(\kappa)} || other \right\rangle
613619
614620 """
621+ cache = self ._reduced_matrix_element_cache .setdefault (other , {})
622+ cache_key = (operator , kappa )
623+ if cache_key not in cache :
624+ cache [cache_key ] = self ._calc_reduced_matrix_element (other , operator , kappa )
625+ return cache [cache_key ]
626+
627+ def _calc_reduced_matrix_element ( # noqa: C901, PLR0912
628+ self : Self , other : AngularKetBase [Any ], operator : AngularOperatorType , kappa : int
629+ ) -> float :
615630 if not is_angular_operator_type (operator ):
616631 raise NotImplementedError (f"calc_reduced_matrix_element is not implemented for operator { operator } ." )
617632
0 commit comments