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 : from abc import ABC, abstractmethod
6 1 : from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar
7 :
8 1 : import numpy as np
9 1 : from typing_extensions import deprecated
10 :
11 1 : from pairinteraction.state.state_base import get_index_with_largest_overlap
12 :
13 : if TYPE_CHECKING:
14 : from scipy.sparse import csr_matrix
15 : from typing_extensions import Self
16 :
17 : from pairinteraction import _backend
18 : from pairinteraction.ket import KetBase
19 : from pairinteraction.state import StateBase
20 :
21 1 : KetType = TypeVar("KetType", bound="KetBase")
22 1 : StateType = TypeVar("StateType", bound="StateBase[Any]")
23 1 : UnionCPPBasis: TypeAlias = "_backend.BasisAtomComplex | _backend.BasisPairComplex"
24 :
25 :
26 1 : class BasisBase(ABC, Generic[KetType, StateType]):
27 : """Base class for all Basis objects.
28 :
29 : The basis objects are meant to represent a set of kets, that span a Hilbert space and store a coefficient matrix,
30 : that describe the basis states in terms of the kets.
31 :
32 : All basis objects share a few common attributes and methods, that are defined in this base class, e.g.:
33 : - the number of kets and states,
34 : - the kets of the basis,
35 : - the coefficients stored as scipy sparse matrix,
36 : - ...
37 : """
38 :
39 1 : _cpp: UnionCPPBasis
40 1 : _ket_class: type[KetType] # should be ClassVar, but cannot be nested yet
41 1 : _state_class: type[StateType] # should be ClassVar, but cannot be nested yet
42 :
43 1 : def _post_init(self) -> None:
44 1 : if self.number_of_kets == 0:
45 0 : raise ValueError("Cannot create a basis with zero kets.")
46 1 : self._kets_cache: dict[int, KetType] = {}
47 1 : self._canonicalized_copy_cache: Self | None = None
48 :
49 1 : @classmethod
50 1 : def _from_cpp_object(cls: type[Self], cpp_obj: UnionCPPBasis, *args: Any, **kwargs: Any) -> Self:
51 1 : assert len(kwargs) == len(args) == 0, "No additional arguments expected."
52 1 : obj = cls.__new__(cls)
53 1 : obj._cpp = cpp_obj
54 1 : obj._post_init()
55 1 : return obj
56 :
57 1 : def _from_cpp_object_additional_args(self) -> tuple[Any, ...]:
58 : """Extra positional args ``_from_cpp_object`` needs to rebuild an object of this type."""
59 1 : return ()
60 :
61 1 : def __repr__(self) -> str:
62 1 : args = f"{self.get_ket(0)} ... {self.get_ket(self.number_of_kets - 1)}"
63 1 : return f"{type(self).__name__}({args})"
64 :
65 1 : def __str__(self) -> str:
66 1 : return self.__repr__()
67 :
68 1 : @property
69 1 : def kets(self) -> list[KetType]:
70 : """Return a list containing the kets of the basis."""
71 1 : return [self.get_ket(i) for i in range(self.number_of_kets)]
72 :
73 1 : def get_ket(self, index: int) -> KetType:
74 : """Return the ket at the given index."""
75 1 : if index not in self._kets_cache:
76 1 : if index < 0 or index >= self.number_of_kets:
77 0 : raise IndexError(f"Ket index {index} out of range (number of kets: {self.number_of_kets}).")
78 1 : ket_cpp = self._cpp.get_ket(index)
79 1 : self._kets_cache[index] = self._ket_class._from_cpp_object(ket_cpp)
80 1 : return self._kets_cache[index]
81 :
82 1 : @property # not cached_property since State objects are mutable
83 1 : def states(self) -> list[StateType]:
84 : """Return a list containing the states of the basis."""
85 0 : return [self.get_state(i) for i in range(self.number_of_states)]
86 :
87 1 : def get_state(self, index: int) -> StateType:
88 : """Return the state at the given index."""
89 1 : if index < 0 or index >= self.number_of_states:
90 0 : raise IndexError(f"State index {index} out of range (number of states: {self.number_of_states}).")
91 1 : state_cpp = self._cpp.get_state(index)
92 1 : return self._state_class._from_cpp_object(state_cpp)
93 :
94 1 : @property
95 1 : def number_of_kets(self) -> int:
96 : """Return the number of kets in the basis."""
97 1 : return self._cpp.get_number_of_kets()
98 :
99 1 : @property
100 1 : def number_of_states(self) -> int:
101 : """Return the number of states in the basis."""
102 1 : return self._cpp.get_number_of_states()
103 :
104 1 : def get_coefficients(self) -> csr_matrix:
105 : """Return the coefficients of the basis as a sparse matrix.
106 :
107 : The coefficients are stored in a sparse matrix with shape (number_of_kets, number_of_states),
108 : where the first index correspond to the kets and the second index correspond to the states.
109 : For example `basis.get_coefficients()[i, j]` is the i-th coefficient
110 : (i.e. the coefficient corresponding to the i-th ket) of the j-th state.
111 :
112 : The coefficients are normalized, i.e. the sum of the absolute values of the coefficients
113 : in each row is equal to 1.
114 :
115 : """
116 1 : coefficients = self._cpp.get_coefficients()
117 1 : coefficients.data = np.real_if_close(coefficients.data)
118 1 : return coefficients
119 :
120 1 : def get_corresponding_ket(self: Self, state: StateType) -> KetType:
121 : """Return the ket of the basis with the maximal overlap with the given state."""
122 1 : return self.get_ket(self.get_corresponding_ket_index(state))
123 :
124 1 : def get_corresponding_ket_index(self, state: StateType) -> int:
125 : """Return the index of the ket of the basis with the maximal overlap with the given state."""
126 1 : canonical_basis = self.get_canonicalized_copy()
127 1 : overlaps = canonical_basis.get_overlaps(state)
128 1 : err_msg = "ket for the given state in the basis"
129 1 : return get_index_with_largest_overlap(overlaps, err_msg=err_msg)
130 :
131 1 : def get_corresponding_state(self, ket: KetBase) -> StateType:
132 : """Return the state of the basis with the maximal overlap with the given ket."""
133 1 : return self.get_state(self.get_corresponding_state_index(ket))
134 :
135 1 : def get_corresponding_state_index(self, ket: KetBase) -> int:
136 : """Return the index of the state of the basis with the maximal overlap with the given ket."""
137 1 : overlaps = self.get_overlaps(ket)
138 1 : err_msg = "state for the given ket in the basis"
139 1 : return get_index_with_largest_overlap(overlaps, err_msg=err_msg)
140 :
141 1 : def get_canonicalized_copy(self: Self) -> Self:
142 : """Return the canonical basis with identity coefficients."""
143 : # the canonicalized copy only depends on the kets, which never change, so it can be cached
144 1 : if self._canonicalized_copy_cache is None:
145 1 : self._canonicalized_copy_cache = type(self)._from_cpp_object(
146 : self._cpp.get_canonicalized_copy(), *self._from_cpp_object_additional_args()
147 : )
148 1 : return self._canonicalized_copy_cache
149 :
150 1 : @deprecated("canonicalized is deprecated, use get_canonicalized_copy instead.")
151 1 : def canonicalized(self: Self) -> Self:
152 0 : return self.get_canonicalized_copy()
153 :
154 1 : @property
155 1 : def is_canonical(self) -> bool:
156 : """Return True if the basis is in canonical order with identity coefficients."""
157 0 : return self._cpp.is_canonical()
158 :
159 1 : def merge(self: Self, other: Self) -> Self:
160 : """Return a canonical basis containing the kets from both bases.
161 :
162 : The bases must be compatible, i.e. they must share the same species, database, ...
163 : For BasisPair they also must share the same underlying atomic basis.
164 : Both bases must be canonical (i.e. have identity coefficients).
165 : """
166 1 : if type(self) is not type(other):
167 0 : raise TypeError(
168 : f"Can only merge {type(self).__name__} with the same basis type, but got {type(other).__name__}."
169 : )
170 1 : return type(self)._from_cpp_object(self._cpp.merge(other._cpp), *self._from_cpp_object_additional_args()) # type: ignore [arg-type]
171 :
172 : @abstractmethod
173 : def get_amplitudes(self, other: Any) -> Any: ...
174 :
175 : @abstractmethod
176 : def get_overlaps(self, other: Any) -> Any: ...
177 :
178 : @abstractmethod
179 : def get_matrix_elements(self, other: Any, *args: Any, **kwargs: Any) -> Any: ...
|