LCOV - code coverage report
Current view: top level - src/pairinteraction/basis - basis_pair.py (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.2 % 142 138
Test Date: 2026-11-02 09:44:19 Functions: 100.0 % 13 13

            Line data    Source code
       1              : # SPDX-FileCopyrightText: 2024 PairInteraction Developers
       2              : # SPDX-License-Identifier: LGPL-3.0-or-later
       3            1 : from __future__ import annotations
       4              : 
       5            1 : import logging
       6            1 : from collections.abc import Sequence
       7            1 : from typing import TYPE_CHECKING, Any, TypeGuard, cast, overload
       8              : 
       9            1 : import numpy as np
      10            1 : from scipy.sparse import csr_matrix
      11            1 : from typing_extensions import Self, TypeAliasType
      12              : 
      13            1 : from pairinteraction import _backend
      14            1 : from pairinteraction.basis.basis_atom import BasisAtom, get_cpp_basis_atom_from_kets
      15            1 : from pairinteraction.basis.basis_base import BasisBase
      16            1 : from pairinteraction.enums import OperatorType, Parity, get_cpp_operator_type, parity_to_int
      17            1 : from pairinteraction.ket import KetPair, KetPairReal, is_ket_atom_tuple
      18            1 : from pairinteraction.ket.ket_pair import get_ketpairlike_energy, get_ketpairlike_m, is_ket_pair_like
      19            1 : from pairinteraction.state import StatePair, StatePairReal
      20            1 : from pairinteraction.state.state_pair import is_state_atom_tuple, is_state_pair_like
      21            1 : from pairinteraction.units import QuantityArray, QuantityScalar, QuantitySparse
      22              : 
      23              : if TYPE_CHECKING:
      24              :     from pairinteraction.basis.basis_base import UnionCPPBasis
      25              :     from pairinteraction.enums import OperatorType, Parity
      26              :     from pairinteraction.ket import KetAtomTuple, KetPairLike
      27              :     from pairinteraction.state.state_pair import StatePairLike
      28              :     from pairinteraction.system import SystemAtom
      29              :     from pairinteraction.units import NDArray, PintArray, PintFloat, PintSparse
      30              : 
      31            1 : logger = logging.getLogger(__name__)
      32              : 
      33              : 
      34            1 : def is_basis_pair_like(obj: Any) -> TypeGuard[BasisPairLike]:
      35            1 :     return isinstance(obj, BasisPair) or is_basis_atom_tuple(obj)
      36              : 
      37              : 
      38            1 : def is_basis_atom_tuple(obj: Any) -> TypeGuard[tuple[BasisAtom, BasisAtom]]:
      39            1 :     return hasattr(obj, "__len__") and len(obj) == 2 and all(isinstance(x, BasisAtom) for x in obj)
      40              : 
      41              : 
      42            1 : class BasisPair(BasisBase[KetPair, StatePair]):
      43              :     """Basis for a pair of atoms.
      44              : 
      45              :     Add all product states of the eigenstates of two given SystemAtom objects to the basis,
      46              :     which pair energy is within the given energy range.
      47              :     You can also specify which total magnetic quantum number m the pair should have (if it is conserved).
      48              :     If the same SystemAtom is used for both atoms, the basis is by default symmetrized, i.e.
      49              :     every state has a well-defined parity under permutation and, if the parities of the single-atom
      50              :     states are well-defined, under inversion. The basis can be restricted to states with given parities.
      51              :     Due to the possible restrictions of the basis states, the BasisPair coefficients matrix will in general
      52              :     not be square but (n x d),
      53              :     where n is the number of all involved kets (typically basis1.number_of_kets * basis2.number_of_kets)
      54              :     and d is the number of basis states (after applying the restrictions).
      55              : 
      56              :     Examples:
      57              :         >>> import pairinteraction as pi
      58              :         >>> ket = pi.KetAtom("Rb", n=60, l=0, m=0.5)
      59              :         >>> basis = pi.BasisAtom("Rb", n=(58, 63), l=(0, 3))
      60              :         >>> system = pi.SystemAtom(basis).set_magnetic_field([0, 0, 1], unit="G").diagonalize()
      61              :         >>> pair_energy = 2 * system.get_corresponding_energy(ket, unit="GHz")
      62              :         >>> pair_basis = pi.BasisPair(
      63              :         ...     [system, system],
      64              :         ...     energy=(pair_energy - 3, pair_energy + 3),
      65              :         ...     energy_unit="GHz",
      66              :         ... )
      67              :         >>> print(pair_basis)
      68              :         BasisPair(|Rb:59,S_1/2,-1/2; Rb:61,S_1/2,-1/2⟩ ... |Rb:60,S_1/2,1/2; Rb:60,S_1/2,1/2⟩)
      69              : 
      70              :     """
      71              : 
      72            1 :     _cpp: _backend.BasisPairComplex
      73            1 :     _cpp_creator = _backend.BasisPairCreatorComplex
      74            1 :     _ket_class = KetPair
      75            1 :     _state_class = StatePair
      76              : 
      77            1 :     system_atoms: tuple[SystemAtom, SystemAtom]
      78            1 :     """The two SystemAtom objects, from which the BasisPair is build."""
      79              : 
      80            1 :     def __init__(
      81              :         self,
      82              :         system_atoms: Sequence[SystemAtom],
      83              :         m: tuple[float, float] | None = None,
      84              :         parity_under_inversion: Parity | None = None,
      85              :         parity_under_permutation: Parity | None = None,
      86              :         energy: tuple[float, float] | tuple[PintFloat, PintFloat] | None = None,
      87              :         energy_unit: str | None = None,
      88              :         *,
      89              :         product_of_parities: Parity | None = None,
      90              :         symmetrize: bool | None = None,
      91              :     ) -> None:
      92              :         """Create a basis for a pair of atoms.
      93              : 
      94              :         Args:
      95              :             system_atoms: tuple of two SystemAtom objects, which define the two atoms, from which the BasisPair is build
      96              :                 Both system_atoms have to be diagonalized before creating the BasisPair.
      97              :             m: tuple of (min, max) values for the total magnetic quantum number m of the pair state.
      98              :                 Default None, i.e. no restriction.
      99              :             parity_under_inversion: Restrict to pair states with this parity under inversion.
     100              :                 Default None, i.e. no restriction.
     101              :                 Requires the pair basis to be symmetrized, see ``symmetrize``.
     102              :             parity_under_permutation: Restrict to pair states with this parity under permutation.
     103              :                 Default None, i.e. no restriction.
     104              :                 Requires the pair basis to be symmetrized, see ``symmetrize``.
     105              :             energy: tuple of (min, max) value for the pair energy. Default None, i.e. add all available states.
     106              :             energy_unit: In which unit the energy values are given, e.g. "GHz".
     107              :                 Default None, i.e. energy is provided as pint object.
     108              :             product_of_parities: Restrict to pair states with this product of the parities of the two atoms.
     109              :                 Default None, i.e. no restriction.
     110              :             symmetrize: Whether to symmetrize the pair basis under the permutation of the atoms.
     111              :                 Symmetrization is only possible if the same SystemAtom is passed for both atoms,
     112              :                 since it is only defined for two identical atoms. Default None, i.e. the pair
     113              :                 basis is symmetrized whenever possible. Otherwise, the pair states are the
     114              :                 product states of the two atoms.
     115              : 
     116              :         """
     117            1 :         assert len(system_atoms) == 2, "BasisPair requires exactly two SystemAtom objects."
     118            1 :         creator = self._cpp_creator(*(system._cpp.get_eigenbasis() for system in system_atoms))
     119            1 :         if symmetrize is not None:
     120            1 :             creator.set_symmetrization_enabled(symmetrize)
     121            1 :         if m is not None:
     122            1 :             creator.restrict_quantum_number("m", *m)
     123            1 :         if product_of_parities is not None:
     124            1 :             parity_int = parity_to_int(product_of_parities)
     125            1 :             creator.restrict_quantum_number("product_of_parities", parity_int, parity_int)
     126            1 :         if parity_under_inversion is not None:
     127            1 :             parity_int = parity_to_int(parity_under_inversion)
     128            1 :             creator.restrict_quantum_number("parity_under_inversion", parity_int, parity_int)
     129            1 :         if parity_under_permutation is not None:
     130            1 :             parity_int = parity_to_int(parity_under_permutation)
     131            1 :             creator.restrict_quantum_number("parity_under_permutation", parity_int, parity_int)
     132            1 :         if energy is not None:
     133            1 :             min_energy_au = QuantityScalar.convert_user_to_au(energy[0], energy_unit, "energy")
     134            1 :             max_energy_au = QuantityScalar.convert_user_to_au(energy[1], energy_unit, "energy")
     135              :             # in atomic units all energies should be on the order of -0.5 * Z^2 to 0
     136              :             # so choosing some very large values for the limits should be fine
     137              :             # (we cant use np.inf here, since this is passed to cpp code)
     138            1 :             min_energy_au = np.clip(min_energy_au, -1e10, 1e10)  # FIXME
     139            1 :             max_energy_au = np.clip(max_energy_au, -1e10, 1e10)  # FIXME
     140            1 :             creator.restrict_energy(min_energy_au, max_energy_au)
     141            1 :         self._cpp = creator.create()
     142              : 
     143            1 :         self.system_atoms = tuple(system_atoms)  # type: ignore [assignment]
     144              : 
     145            1 :         self._post_init()
     146              : 
     147            1 :     @classmethod
     148            1 :     def from_kets(  # noqa: C901
     149              :         cls: type[Self],
     150              :         kets: KetPairLike | Sequence[KetPairLike],
     151              :         system_atoms: Sequence[SystemAtom],
     152              :         delta_m: float | None = None,
     153              :         parity_under_inversion: Parity | None = None,
     154              :         parity_under_permutation: Parity | None = None,
     155              :         delta_energy: float | PintFloat | None = None,
     156              :         delta_energy_unit: str | None = None,
     157              :         number_of_kets: int | None = None,
     158              :         *,
     159              :         warn_number_of_kets: bool = True,
     160              :         product_of_parities: Parity | None = None,
     161              :         symmetrize: bool | None = None,
     162              :     ) -> Self:
     163              :         """Create a BasisPair from one or more pairs of kets with optional energy/m windows.
     164              : 
     165              :         Currently a single big basis including all kets for the quantum numbers
     166              :         from min_value - delta to max_value + delta is returned.
     167              :         In the future this might change to return a basis including all states around the given kets +/- delta,
     168              :         but not necessarily all states between the given kets.
     169              : 
     170              :         You can either give a ``delta_energy`` to restrict the basis size in energy,
     171              :         or give an (approximate) number_of_kets, which is used to construct a basis centered around
     172              :         the provided ket pairs with approximately that many kets. If there are multiple states with the same energy,
     173              :         the actual number of kets may be a bit higher than the specified number.
     174              : 
     175              :         Args:
     176              :             kets: A single ket pair (given either as tuple ``(ket1, ket2)`` of
     177              :                 :class:`~pairinteraction.KetAtom` objects or as a :class:`~pairinteraction.KetPair` object)
     178              :                 or a list of ket pairs.
     179              :                 Must not be empty.
     180              :             system_atoms: A collection of exactly two diagonalized
     181              :                 :class:`~pairinteraction.SystemAtom` objects, one per atom.
     182              :             delta_m: Half-width of the total magnetic quantum number window
     183              :                 ``m = m1 + m2``. Default None means no m restriction.
     184              :             parity_under_inversion: Restrict to pair states with this parity under inversion.
     185              :                 Default None means no restriction.
     186              :                 Requires the pair basis to be symmetrized, see ``symmetrize``.
     187              :             parity_under_permutation: Restrict to pair states with this parity under permutation.
     188              :                 Default None means no restriction.
     189              :                 Requires the pair basis to be symmetrized, see ``symmetrize``.
     190              :             delta_energy: Half-width of the energy window. Mutually exclusive with
     191              :                 ``number_of_kets``. Default None means no energy restriction.
     192              :             delta_energy_unit: Unit for ``delta_energy`` and the pair energies
     193              :                 (e.g. ``"GHz"``). Default None means pint quantities are used.
     194              :             number_of_kets: Target number of pair kets to include. The method
     195              :                 keeps the ``number_of_kets`` states closest in energy to the
     196              :                 reference ket pairs. Mutually exclusive with ``delta_energy``.
     197              :                 Default None means no count restriction.
     198              :             warn_number_of_kets: Don't warn about the possible issues with using number_of_kets.
     199              :             product_of_parities: Restrict to pair states with this product of the parities of the two atoms.
     200              :                 Default None means no restriction.
     201              :             symmetrize: Whether to symmetrize the pair basis under the permutation of the atoms,
     202              :                 see :class:`BasisPair`. Default None, i.e. symmetrize whenever possible.
     203              : 
     204              :         Returns:
     205              :             A new :class:`BasisPair` whose energy (and optionally m) range is
     206              :             determined by the provided ket pairs and the chosen restrictions.
     207              : 
     208              :         Examples:
     209              :             >>> import pairinteraction as pi
     210              :             >>> ket = pi.KetAtom("Rb", n=60, l=0, m=0.5)
     211              :             >>> basis_atom = pi.BasisAtom("Rb", n=(58, 62), l=(0, 2))
     212              :             >>> system = pi.SystemAtom(basis_atom).diagonalize()
     213              :             >>> pair_basis = pi.BasisPair.from_kets(
     214              :             ...     (ket, ket), [system, system], delta_energy=3, delta_energy_unit="GHz"
     215              :             ... )
     216              : 
     217              :         """
     218            1 :         assert len(system_atoms) == 2, "BasisPair requires exactly two SystemAtom objects."
     219              : 
     220            1 :         if number_of_kets is not None:
     221            1 :             if delta_energy is not None:
     222            1 :                 raise ValueError("Cannot specify both number_of_kets and delta_energy. Please choose one of them.")
     223            1 :             if number_of_kets <= 0:
     224            0 :                 raise ValueError("number_of_kets must be positive.")
     225            1 :             if warn_number_of_kets:
     226            1 :                 logger.warning(
     227              :                     "Use number_of_kets with caution and only if you know what you are doing! "
     228              :                     "It might lead to unexpected results. "
     229              :                     "E.g. loosening other restrictions while keeping number_of_kets fixed can lead to worse results!"
     230              :                 )
     231              : 
     232            1 :         if is_ket_atom_tuple(kets) or isinstance(kets, KetPair):
     233            1 :             kets = [kets]
     234            1 :         if not all(is_ket_pair_like(t) for t in kets):
     235            0 :             raise ValueError("kets must be a KetPairLike or a list of KetPairLike.")
     236            1 :         if len(kets) == 0:
     237            1 :             raise ValueError("kets must not be empty.")
     238            1 :         kets = cast("Sequence[KetAtomTuple | KetPair]", kets)
     239              : 
     240            1 :         energy_range: tuple[Any, Any] | None = None
     241            1 :         if delta_energy is not None:
     242            1 :             pair_energies = [get_ketpairlike_energy(ket, system_atoms, delta_energy_unit) for ket in kets]
     243            1 :             energy_range = (min(pair_energies) - delta_energy, max(pair_energies) + delta_energy)
     244              : 
     245            1 :         m_range = None
     246            1 :         if delta_m is not None:
     247            1 :             pair_ms = [get_ketpairlike_m(ket) for ket in kets]
     248            1 :             m_range = (min(pair_ms) - delta_m, max(pair_ms) + delta_m)
     249              : 
     250            1 :         basis_pair = cls(
     251              :             system_atoms,
     252              :             m=m_range,
     253              :             parity_under_inversion=parity_under_inversion,
     254              :             parity_under_permutation=parity_under_permutation,
     255              :             product_of_parities=product_of_parities,
     256              :             energy=energy_range,
     257              :             energy_unit=delta_energy_unit,
     258              :             symmetrize=symmetrize,
     259              :         )
     260            1 :         if number_of_kets is None or number_of_kets >= basis_pair.number_of_kets:
     261            1 :             return basis_pair
     262              : 
     263            1 :         pair_energies_au = [get_ketpairlike_energy(ket, system_atoms, "hartree") for ket in kets]
     264            1 :         min_energy_au, max_energy_au = min(pair_energies_au), max(pair_energies_au)
     265              : 
     266            1 :         cpp_kets = basis_pair._cpp.get_kets()
     267            1 :         all_energies_au = np.array([ket_cpp.get_energy() for ket_cpp in cpp_kets])
     268            1 :         deltas = np.maximum(np.maximum(min_energy_au - all_energies_au, all_energies_au - max_energy_au), 0)
     269            1 :         delta_energy = float(np.partition(deltas, number_of_kets - 1)[number_of_kets - 1]) + 1e-10
     270              : 
     271            1 :         return cls(
     272              :             system_atoms,
     273              :             m=m_range,
     274              :             parity_under_inversion=parity_under_inversion,
     275              :             parity_under_permutation=parity_under_permutation,
     276              :             product_of_parities=product_of_parities,
     277              :             energy=(min_energy_au - delta_energy, max_energy_au + delta_energy),
     278              :             energy_unit="hartree",
     279              :             symmetrize=symmetrize,
     280              :         )
     281              : 
     282            1 :     @classmethod
     283            1 :     def _from_cpp_object(cls: type[Self], cpp_obj: UnionCPPBasis, system_atoms: tuple[SystemAtom, SystemAtom]) -> Self:
     284            1 :         obj = super()._from_cpp_object(cpp_obj)
     285            1 :         obj.system_atoms = system_atoms
     286            1 :         return obj
     287              : 
     288            1 :     def _from_cpp_object_additional_args(self) -> tuple[Any, ...]:
     289            1 :         return (self.system_atoms,)
     290              : 
     291            1 :     def get_corresponding_state(self, ket: KetPairLike) -> StatePair:  # type: ignore [override]
     292              :         # override the accepted ket type
     293            1 :         return super().get_corresponding_state(ket)  # type: ignore [arg-type]
     294              : 
     295            1 :     def get_corresponding_state_index(self, ket: KetPairLike) -> int:  # type: ignore [override]
     296              :         # override the accepted ket type
     297            1 :         return super().get_corresponding_state_index(ket)  # type: ignore [arg-type]
     298              : 
     299            1 :     def get_corresponding_ket(self, state: StatePairLike) -> KetPair:
     300              :         # override the accepted state type
     301            1 :         return super().get_corresponding_ket(state)  # type: ignore [arg-type]
     302              : 
     303            1 :     def get_corresponding_ket_index(self, state: StatePairLike) -> int:
     304              :         # override the accepted state type
     305            1 :         return super().get_corresponding_ket_index(state)  # type: ignore [arg-type]
     306              : 
     307              :     @overload
     308              :     def get_amplitudes(self, other: KetPairLike | StatePairLike) -> NDArray: ...
     309              : 
     310              :     @overload
     311              :     def get_amplitudes(self, other: BasisPairLike) -> csr_matrix: ...
     312              : 
     313            1 :     def get_amplitudes(self, other: KetPairLike | StatePairLike | BasisPairLike) -> NDArray | csr_matrix:
     314            1 :         return self.get_matrix_elements(other, ("identity", "identity"), (0, 0), unit="")
     315              : 
     316              :     @overload
     317              :     def get_overlaps(self, other: KetPairLike | StatePairLike) -> NDArray: ...
     318              : 
     319              :     @overload
     320              :     def get_overlaps(self, other: BasisPairLike) -> csr_matrix: ...
     321              : 
     322            1 :     def get_overlaps(self, other: KetPairLike | StatePairLike | BasisPairLike) -> NDArray | csr_matrix:
     323            1 :         amplitudes = self.get_amplitudes(other)
     324            1 :         if isinstance(amplitudes, csr_matrix):
     325            1 :             return amplitudes.multiply(amplitudes.conj()).real  # type: ignore [no-any-return]
     326            1 :         return np.abs(amplitudes) ** 2
     327              : 
     328              :     @overload
     329              :     def get_matrix_elements(
     330              :         self,
     331              :         other: KetPairLike | StatePairLike,
     332              :         operators: tuple[OperatorType, OperatorType],
     333              :         qs: tuple[int, int],
     334              :         unit: None = None,
     335              :     ) -> PintArray: ...
     336              : 
     337              :     @overload
     338              :     def get_matrix_elements(
     339              :         self,
     340              :         other: KetPairLike | StatePairLike,
     341              :         operators: tuple[OperatorType, OperatorType],
     342              :         qs: tuple[int, int],
     343              :         unit: str,
     344              :     ) -> NDArray: ...
     345              : 
     346              :     @overload
     347              :     def get_matrix_elements(
     348              :         self,
     349              :         other: BasisPairLike,
     350              :         operators: tuple[OperatorType, OperatorType],
     351              :         qs: tuple[int, int],
     352              :         unit: None = None,
     353              :     ) -> PintSparse: ...
     354              : 
     355              :     @overload
     356              :     def get_matrix_elements(
     357              :         self,
     358              :         other: BasisPairLike,
     359              :         operators: tuple[OperatorType, OperatorType],
     360              :         qs: tuple[int, int],
     361              :         unit: str,
     362              :     ) -> csr_matrix: ...
     363              : 
     364            1 :     def get_matrix_elements(
     365              :         self,
     366              :         other: KetPairLike | StatePairLike | BasisPairLike,
     367              :         operators: tuple[OperatorType, OperatorType],
     368              :         qs: tuple[int, int],
     369              :         unit: str | None = None,
     370              :     ) -> NDArray | PintArray | csr_matrix | PintSparse:
     371            1 :         operators_cpp = (get_cpp_operator_type(operators[0]), get_cpp_operator_type(operators[1]))
     372            1 :         is_real = isinstance(self._cpp, _backend.BasisPairReal)
     373              : 
     374            1 :         if is_ket_pair_like(other) or is_state_pair_like(other):
     375              :             # KetPair like
     376            1 :             if isinstance(other, KetPair):
     377            1 :                 other_cpp = self._cpp_creator(*other._cpp.get_atomic_states()).create()
     378            1 :             elif is_ket_atom_tuple(other):
     379            1 :                 other_cpp = self._cpp_creator(
     380              :                     *(get_cpp_basis_atom_from_kets([ket], real=is_real) for ket in other)
     381              :                 ).create()
     382              :             # StatePair like
     383            1 :             elif isinstance(other, StatePair):
     384            1 :                 other_cpp = other._cpp
     385            1 :             elif is_state_atom_tuple(other):
     386            1 :                 other_cpp = self._cpp_creator(*(state._cpp for state in other)).create()
     387              :             else:
     388            0 :                 raise TypeError(f"Unknown type: {type(other)=}")
     389              : 
     390            1 :             matrix_elements_au = self._cpp.get_matrix_elements(other_cpp, *operators_cpp, *qs).toarray().ravel()
     391            1 :             matrix_elements_au = np.real_if_close(matrix_elements_au)
     392            1 :             return QuantityArray.convert_au_to_user(matrix_elements_au, operators, unit)
     393              : 
     394              :         # BasisPair like
     395            1 :         if is_basis_pair_like(other):
     396            1 :             if isinstance(other, BasisPair):
     397            1 :                 other_cpp = other._cpp
     398            1 :             elif is_basis_atom_tuple(other):
     399              :                 # The symmetrization is disabled so that the pair states are the product states
     400            1 :                 other_cpp = (
     401              :                     self._cpp_creator(*(basis._cpp for basis in other)).set_symmetrization_enabled(False).create()
     402              :                 )
     403              :             else:
     404            0 :                 raise TypeError(f"Unknown type: {type(other)=}")
     405              : 
     406            1 :             matrix_elements_sparse_au = self._cpp.get_matrix_elements(other_cpp, *operators_cpp, *qs)
     407            1 :             matrix_elements_sparse_au.data = np.real_if_close(matrix_elements_sparse_au.data)
     408            1 :             return QuantitySparse.convert_au_to_user(matrix_elements_sparse_au, operators, unit)
     409              : 
     410            1 :         raise TypeError(f"Unknown type: {type(other)=}")
     411              : 
     412              : 
     413            1 : class BasisPairReal(BasisPair):
     414            1 :     _cpp: _backend.BasisPairReal  # type: ignore [assignment]
     415            1 :     _cpp_creator = _backend.BasisPairCreatorReal  # type: ignore [assignment]
     416            1 :     _ket_class = KetPairReal
     417            1 :     _state_class = StatePairReal
     418              : 
     419              : 
     420            1 : BasisPairLike = TypeAliasType("BasisPairLike", BasisPair | tuple[BasisAtom, BasisAtom] | Sequence[BasisAtom])
        

Generated by: LCOV version 2.0-1