Skip to content

Commit c970701

Browse files
angular ket and radial ket cache matrix elements
1 parent 6fa2a17 commit c970701

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

src/rydstate/angular/angular_ket.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
is_angular_operator_type,
2323
is_not_set,
2424
is_unknown,
25+
lru_cache,
2526
minus_one_pow,
2627
try_trivial_spin_addition,
2728
)
@@ -600,6 +601,7 @@ def calc_reduced_overlap(self, other: AngularKetBase[Any]) -> float:
600601

601602
raise NotImplementedError(f"This method is not yet implemented for {self!r} and {other!r}.")
602603

604+
@lru_cache(maxsize=1_000_000)
603605
def calc_reduced_matrix_element( # noqa: C901, PLR0912
604606
self: Self, other: AngularKetBase[Any], operator: AngularOperatorType, kappa: int
605607
) -> float:

src/rydstate/radial/radial_ket.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from mpmath import whitw
99
from scipy.special import gamma
1010

11-
from rydstate.angular.utils import is_unknown
11+
from rydstate.angular.utils import is_unknown, lru_cache
1212
from rydstate.metaclass_cache import CachedABCMeta
1313
from rydstate.radial.numerov import _run_numerov_integration_python, run_numerov_integration
1414
from rydstate.radial.radial_matrix_element import calc_radial_matrix_element_from_w_z
@@ -554,9 +554,12 @@ def calc_matrix_element(
554554
The radial matrix element in the desired unit.
555555
556556
"""
557-
# Ensure wavefunctions are integrated before accessing the grid
558-
radial_matrix_element_au = calc_radial_matrix_element_from_w_z(
559-
self.z_list, self.w_list, other.z_list, other.w_list, k_radial, integration_method
557+
ket1, ket2 = self, other
558+
if hash(self) > hash(other):
559+
# we sort the kets by their hash to increase the cache hit rate of calc_matrix_element_au_cached
560+
ket1, ket2 = other, self
561+
radial_matrix_element_au = calc_matrix_element_au_cached(
562+
ket1, ket2, k_radial, integration_method=integration_method
560563
)
561564

562565
if unit == "a.u.":
@@ -565,3 +568,16 @@ def calc_matrix_element(
565568
if unit is None:
566569
return radial_matrix_element
567570
return radial_matrix_element.to(unit).magnitude
571+
572+
573+
@lru_cache(maxsize=100_000)
574+
def calc_matrix_element_au_cached(
575+
ket1: RadialKet,
576+
ket2: RadialKet,
577+
k_radial: int,
578+
*,
579+
integration_method: INTEGRATION_METHODS = "sum",
580+
) -> float:
581+
return calc_radial_matrix_element_from_w_z(
582+
ket1.z_list, ket1.w_list, ket2.z_list, ket2.w_list, k_radial, integration_method
583+
)

0 commit comments

Comments
 (0)