Line data Source code
1 : // SPDX-FileCopyrightText: 2024 PairInteraction Developers
2 : // SPDX-License-Identifier: LGPL-3.0-or-later
3 :
4 : #include "pairinteraction/basis/Basis.hpp"
5 :
6 : #include "pairinteraction/basis/BasisAtom.hpp"
7 : #include "pairinteraction/basis/BasisPair.hpp"
8 : #include "pairinteraction/enums/SorterType.hpp"
9 : #include "pairinteraction/ket/KetAtom.hpp"
10 : #include "pairinteraction/ket/KetPair.hpp"
11 : #include "pairinteraction/utils/TaskControl.hpp"
12 : #include "pairinteraction/utils/eigen_assertion.hpp"
13 : #include "pairinteraction/utils/eigen_compat.hpp"
14 :
15 : #include <algorithm>
16 : #include <cassert>
17 : #include <cmath>
18 : #include <cstdint>
19 : #include <limits>
20 : #include <map>
21 : #include <set>
22 : #include <string>
23 : #include <vector>
24 :
25 : namespace pairinteraction {
26 :
27 : template <typename Scalar>
28 : class BasisAtom;
29 :
30 : namespace {
31 : // The states can only be labeled by quantum numbers by which they can be sorted
32 : template <typename Derived>
33 12477 : void check_quantum_number_name(const std::string &name) {
34 12477 : if (std::none_of(Derived::sorter_type_to_quantum_number_name.begin(),
35 : Derived::sorter_type_to_quantum_number_name.end(),
36 29177 : [&name](const auto &entry) { return entry.second == name; })) {
37 0 : throw std::invalid_argument("The states cannot be labeled by the quantum number " + name +
38 : ".");
39 : }
40 12477 : }
41 : } // namespace
42 :
43 : template <typename Derived>
44 666 : void Basis<Derived>::perform_blocks_checks(const std::set<SorterType> &unique_labels) const {
45 : // Currently, since states in a basis dont store the energy, they cannot be sorted by energy.
46 666 : if (unique_labels.contains(SorterType::ENERGY)) {
47 1 : throw std::invalid_argument("Blocks cannot be obtained by the energy. Note that sorting "
48 : "a system by the energy is supported nevertheless.");
49 : }
50 :
51 : // Check if the states are labeled by the requested labels
52 665 : std::vector<const std::vector<real_t> *> quantum_numbers_of_labels;
53 665 : quantum_numbers_of_labels.reserve(unique_labels.size());
54 2568 : for (const auto &label : unique_labels) {
55 1905 : quantum_numbers_of_labels.push_back(&get_quantum_numbers_of_states(label));
56 : }
57 :
58 : // Check if the states are sorted by the requested labels, i.e., if states that share the same
59 : // labels are contiguous. Otherwise, states belonging to the same block would be scattered over
60 : // several blocks and couplings between them would be lost.
61 : // The quantum numbers are (half-)integers, thus doubling them yields an exact integer
62 : using label_t = std::vector<int64_t>;
63 37325 : auto label_of = [&](Eigen::Index i) {
64 36662 : label_t label;
65 36662 : label.reserve(quantum_numbers_of_labels.size());
66 127663 : for (const auto *quantum_numbers : quantum_numbers_of_labels) {
67 91001 : label.push_back(std::llround(2 * (*quantum_numbers)[i]));
68 : }
69 36662 : return label;
70 0 : };
71 :
72 : // Collect the labels of the contiguous blocks of states
73 663 : std::vector<label_t> labels_of_blocks;
74 37325 : for (Eigen::Index i = 0; i < coefficients.cols(); ++i) {
75 36662 : label_t label = label_of(i);
76 36662 : if (labels_of_blocks.empty() || labels_of_blocks.back() != label) {
77 2613 : labels_of_blocks.push_back(label);
78 : }
79 : }
80 :
81 : // If the states are sorted, no two blocks share the same labels
82 663 : std::sort(labels_of_blocks.begin(), labels_of_blocks.end());
83 663 : if (std::adjacent_find(labels_of_blocks.begin(), labels_of_blocks.end()) !=
84 1326 : labels_of_blocks.end()) {
85 2 : throw std::invalid_argument("The states are not sorted by the requested labels.");
86 : }
87 667 : }
88 :
89 : template <typename Derived>
90 5780 : Basis<Derived>::Basis(std::shared_ptr<const ketvec_t> kets,
91 : Eigen::SparseMatrix<scalar_t, Eigen::RowMajor> &&coefficients,
92 : energies_t &&energy_of_states, quantum_numbers_t &&quantum_numbers_of_states)
93 5780 : : kets(std::move(kets)), coefficients(std::move(coefficients)),
94 5780 : quantum_numbers_of_states(std::move(quantum_numbers_of_states)),
95 5780 : energy_of_states(std::move(energy_of_states)) {
96 5780 : if (this->kets->empty()) {
97 0 : throw std::invalid_argument("The basis must contain at least one element.");
98 : }
99 5780 : check_states();
100 5816 : }
101 :
102 : template <typename Derived>
103 5780 : void Basis<Derived>::check_states() const {
104 5780 : auto num_states = static_cast<size_t>(coefficients.cols());
105 :
106 : // Neither infinite values nor the maximum value are accepted as energies or quantum numbers,
107 : // so that no value can be mistaken for marking an energy or quantum number as not well-defined
108 8921361 : auto is_valid_value = [](real_t value) {
109 8921361 : return std::isfinite(value) && std::abs(value) < std::numeric_limits<real_t>::max();
110 : };
111 :
112 5780 : if (static_cast<size_t>(coefficients.rows()) != kets->size()) {
113 0 : throw std::invalid_argument(
114 : "The number of rows of the coefficient matrix must match the number of kets.");
115 : }
116 :
117 : // The energy is either given for all states or not well-defined for the basis
118 5780 : if (energy_of_states.has_value()) {
119 4635 : if (energy_of_states->size() != num_states) {
120 1 : throw std::invalid_argument("The number of energies must match the number of states.");
121 : }
122 4634 : if (!std::ranges::all_of(*energy_of_states, is_valid_value)) {
123 4 : throw std::invalid_argument(
124 : "The energies of the states must be finite and smaller than the maximum value.");
125 : }
126 : }
127 :
128 : // A quantum number is either given for all states or not well-defined for the basis
129 18245 : for (const auto &[name, quantum_numbers] : quantum_numbers_of_states) {
130 12477 : check_quantum_number_name<Derived>(name);
131 12477 : if (quantum_numbers.size() != num_states) {
132 1 : throw std::invalid_argument("The number of values of the quantum number " + name +
133 : " must match the number of states.");
134 : }
135 :
136 : // The quantum numbers are (half-)integers, so that doubling them yields the exact integers
137 : // by which the states are sorted and block-diagonalized
138 6226338 : for (real_t quantum_number : quantum_numbers) {
139 6213868 : real_t doubled = 2 * quantum_number;
140 12427732 : if (!is_valid_value(quantum_number) || !std::isfinite(doubled) ||
141 6213864 : doubled != std::round(doubled)) {
142 6 : throw std::invalid_argument("The quantum number " + name +
143 : " must be an integer or a half-integer.");
144 : }
145 : }
146 : }
147 5768 : }
148 :
149 : template <typename Derived>
150 1816 : typename Basis<Derived>::StatesData Basis<Derived>::get_canonical_states(const ketvec_t &kets) {
151 1816 : StatesData states;
152 1816 : auto n = static_cast<Eigen::Index>(kets.size());
153 :
154 : // Make the i-th state equal to the i-th ket
155 1816 : states.coefficients.resize(n, n);
156 1816 : states.coefficients.setIdentity();
157 :
158 : // Assign each state the quantum numbers of the ket it is equal to. A quantum number is only
159 : // assigned if all kets have it.
160 7300 : for (const auto &entry : Derived::sorter_type_to_quantum_number_name) {
161 5484 : const std::string &name = entry.second;
162 5484 : if (!std::ranges::all_of(
163 183336 : kets, [&name](const auto &ket) { return ket->has_quantum_number(name); })) {
164 54 : continue;
165 : }
166 5430 : auto &quantum_numbers = states.quantum_numbers_of_states[name];
167 5430 : quantum_numbers.reserve(kets.size());
168 188712 : for (const auto &ket : kets) {
169 183282 : quantum_numbers.push_back(static_cast<real_t>(ket->get_quantum_number(name)));
170 : }
171 : }
172 :
173 : // Assign each state the energy of the ket it is equal to. The energy is only assigned if all
174 : // kets have it.
175 63327 : if (std::ranges::all_of(kets, [](const auto &ket) { return ket->has_energy(); })) {
176 1815 : auto &energies = states.energy_of_states.emplace();
177 1815 : energies.reserve(kets.size());
178 63325 : for (const auto &ket : kets) {
179 61510 : energies.push_back(static_cast<real_t>(ket->get_energy()));
180 : }
181 : }
182 :
183 1816 : return states;
184 0 : }
185 :
186 : template <typename Derived>
187 12289 : bool Basis<Derived>::has_quantum_number(const std::string &name) const {
188 12289 : return quantum_numbers_of_states.contains(name);
189 : }
190 :
191 : template <typename Derived>
192 84897 : bool Basis<Derived>::has_energy() const {
193 84897 : return energy_of_states.has_value();
194 : }
195 :
196 : template <typename Derived>
197 401 : bool Basis<Derived>::is_sorted_by_energy() const {
198 401 : return has_energy() && std::ranges::is_sorted(*energy_of_states);
199 : }
200 :
201 : template <typename Derived>
202 2834 : const Derived &Basis<Derived>::derived() const {
203 2834 : return static_cast<const Derived &>(*this);
204 : }
205 :
206 : template <typename Derived>
207 : const std::vector<typename Basis<Derived>::real_t> &
208 5712 : Basis<Derived>::get_quantum_numbers_of_states(SorterType label) const {
209 5712 : auto it = Derived::sorter_type_to_quantum_number_name.find(label);
210 5712 : if (it == Derived::sorter_type_to_quantum_number_name.end()) {
211 1 : throw std::invalid_argument(
212 : "The states of this basis cannot be labeled by the requested sorter type.");
213 : }
214 5711 : const std::string &name = it->second;
215 5711 : if (!has_quantum_number(name)) {
216 4 : throw std::invalid_argument(
217 4 : "States cannot be labeled and thus not sorted by the quantum number " + name + ".");
218 : }
219 11418 : return quantum_numbers_of_states.at(name);
220 : }
221 :
222 : template <typename Derived>
223 17736 : const typename Basis<Derived>::ketvec_t &Basis<Derived>::get_kets() const {
224 17736 : return *kets;
225 : }
226 :
227 : template <typename Derived>
228 : const Eigen::SparseMatrix<typename Basis<Derived>::scalar_t, Eigen::RowMajor> &
229 16652 : Basis<Derived>::get_coefficients() const {
230 16652 : return coefficients;
231 : }
232 :
233 : template <typename Derived>
234 10308509 : typename Basis<Derived>::real_t Basis<Derived>::get_quantum_number(const std::string &name,
235 : size_t state_index) const {
236 : // A quantum number by which the states are not labeled is not well-defined
237 10308509 : auto it = quantum_numbers_of_states.find(name);
238 10308509 : if (it == quantum_numbers_of_states.end()) {
239 0 : check_quantum_number_name<Derived>(name);
240 0 : throw std::invalid_argument("The state does not have a well-defined quantum number " +
241 0 : name + ".");
242 : }
243 20617018 : return it->second.at(state_index);
244 : }
245 :
246 : template <typename Derived>
247 80799 : typename Basis<Derived>::real_t Basis<Derived>::get_energy(size_t state_index) const {
248 80799 : if (!has_energy()) {
249 1 : throw std::invalid_argument("The state does not have a well-defined energy.");
250 : }
251 80798 : return energy_of_states->at(state_index);
252 : }
253 :
254 : template <typename Derived>
255 : const typename Basis<Derived>::quantum_numbers_t &
256 274 : Basis<Derived>::get_quantum_numbers_of_states() const {
257 274 : return quantum_numbers_of_states;
258 : }
259 :
260 : template <typename Derived>
261 1409 : std::shared_ptr<const Derived> Basis<Derived>::get_state(size_t state_index) const {
262 : // Create a basis that consists of the single requested state, without copying the other states.
263 : // The kets are shared with this basis.
264 1409 : Eigen::SparseMatrix<scalar_t, Eigen::RowMajor> coefficients_of_state =
265 1409 : coefficients.col(static_cast<Eigen::Index>(state_index));
266 1409 : quantum_numbers_t quantum_numbers_of_state;
267 4473 : for (const auto &[name, quantum_numbers] : quantum_numbers_of_states) {
268 3064 : quantum_numbers_of_state[name] = {quantum_numbers[state_index]};
269 : }
270 1409 : energies_t energy_of_state;
271 1409 : if (has_energy()) {
272 1408 : energy_of_state.emplace({energy_of_states->at(state_index)});
273 : }
274 4227 : return derived().get_modified_copy(std::move(coefficients_of_state), std::move(energy_of_state),
275 4227 : std::move(quantum_numbers_of_state));
276 1409 : }
277 :
278 : template <typename Derived>
279 : std::shared_ptr<const typename Basis<Derived>::ket_t>
280 172026 : Basis<Derived>::get_ket(size_t ket_index) const {
281 172026 : return (*kets)[ket_index];
282 : }
283 :
284 : template <typename Derived>
285 5 : typename Basis<Derived>::Iterator Basis<Derived>::begin() const {
286 5 : return kets->begin();
287 : }
288 :
289 : template <typename Derived>
290 5 : typename Basis<Derived>::Iterator Basis<Derived>::end() const {
291 5 : return kets->end();
292 : }
293 :
294 : template <typename Derived>
295 10 : Basis<Derived>::Iterator::Iterator(typename ketvec_t::const_iterator it) : it{std::move(it)} {}
296 :
297 : template <typename Derived>
298 497 : bool Basis<Derived>::Iterator::operator!=(const Iterator &other) const {
299 497 : return other.it != it;
300 : }
301 :
302 : template <typename Derived>
303 492 : std::shared_ptr<const typename Basis<Derived>::ket_t> Basis<Derived>::Iterator::operator*() const {
304 492 : return *it;
305 : }
306 :
307 : template <typename Derived>
308 492 : typename Basis<Derived>::Iterator &Basis<Derived>::Iterator::operator++() {
309 492 : ++it;
310 492 : return *this;
311 : }
312 :
313 : template <typename Derived>
314 94049 : size_t Basis<Derived>::get_number_of_states() const {
315 94049 : return coefficients.cols();
316 : }
317 :
318 : template <typename Derived>
319 49453 : size_t Basis<Derived>::get_number_of_kets() const {
320 49453 : return coefficients.rows();
321 : }
322 :
323 : template <typename Derived>
324 : Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic>
325 8 : Basis<Derived>::get_sorter(const std::vector<SorterType> &labels) const {
326 : // Note that sorting by the energy is rejected by get_sorter_without_checks
327 :
328 : // Initialize the sorter
329 8 : Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> sorter(coefficients.cols());
330 8 : sorter.setIdentity();
331 :
332 8 : get_sorter_without_checks(labels, sorter);
333 :
334 7 : return sorter;
335 1 : }
336 :
337 : template <typename Derived>
338 : std::vector<IndicesOfBlock>
339 9 : Basis<Derived>::get_indices_of_blocks(const std::vector<SorterType> &labels) const {
340 9 : std::set<SorterType> unique_labels(labels.begin(), labels.end());
341 9 : perform_blocks_checks(unique_labels);
342 :
343 : // Get the blocks
344 5 : IndicesOfBlocksCreator blocks_creator({0, static_cast<size_t>(coefficients.cols())});
345 5 : get_indices_of_blocks_without_checks(unique_labels, blocks_creator);
346 :
347 10 : return blocks_creator.create();
348 9 : }
349 :
350 : template <typename Derived>
351 605 : void Basis<Derived>::get_sorter_without_checks(
352 : const std::vector<SorterType> &labels,
353 : Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> &sorter) const {
354 605 : constexpr real_t numerical_precision = 100 * std::numeric_limits<real_t>::epsilon();
355 :
356 : // Currently, since states in a basis dont store the energy, they cannot be sorted by energy.
357 : // Checking this upfront also guarantees that only labels that refer to a quantum number are
358 : // encountered below.
359 605 : if (std::find(labels.begin(), labels.end(), SorterType::ENERGY) != labels.end()) {
360 0 : throw std::invalid_argument(
361 : "States in a basis do not store the energy and thus can not be sorted by it. "
362 : "Note that sorting a system by the energy is supported nevertheless.");
363 : }
364 :
365 605 : if (coefficients.cols() == 0) {
366 0 : return;
367 : }
368 :
369 605 : std::vector<const std::vector<real_t> *> quantum_numbers_of_labels;
370 605 : quantum_numbers_of_labels.reserve(labels.size());
371 2511 : for (const auto &label : labels) {
372 1907 : quantum_numbers_of_labels.push_back(&get_quantum_numbers_of_states(label));
373 : }
374 :
375 604 : int *perm_begin = sorter.indices().data();
376 604 : int *perm_end = perm_begin + coefficients.cols();
377 :
378 : // Sort the vector based on the requested labels
379 604 : set_task_status("Sorting basis states...");
380 167573 : std::stable_sort(perm_begin, perm_end, [&](int a, int b) {
381 458923 : for (const auto *quantum_numbers : quantum_numbers_of_labels) {
382 382298 : if (std::abs((*quantum_numbers)[a] - (*quantum_numbers)[b]) > numerical_precision) {
383 90344 : return (*quantum_numbers)[a] < (*quantum_numbers)[b];
384 : }
385 : }
386 76625 : return false; // Elements are equal
387 : });
388 605 : }
389 :
390 : template <typename Derived>
391 598 : void Basis<Derived>::get_indices_of_blocks_without_checks(
392 : const std::set<SorterType> &unique_labels, IndicesOfBlocksCreator &blocks_creator) const {
393 598 : constexpr real_t numerical_precision = 100 * std::numeric_limits<real_t>::epsilon();
394 :
395 598 : if (coefficients.cols() == 0) {
396 0 : return;
397 : }
398 :
399 598 : std::vector<const std::vector<real_t> *> quantum_numbers_of_labels;
400 598 : quantum_numbers_of_labels.reserve(unique_labels.size());
401 2498 : for (const auto &label : unique_labels) {
402 1900 : quantum_numbers_of_labels.push_back(&get_quantum_numbers_of_states(label));
403 : }
404 :
405 : // A new block starts whenever a state differs from its predecessor in one of the labels
406 598 : set_task_status("Identifying basis blocks...");
407 31830 : for (int i = 1; i < coefficients.cols(); ++i) {
408 116481 : for (const auto *quantum_numbers : quantum_numbers_of_labels) {
409 87183 : if (std::abs((*quantum_numbers)[i] - (*quantum_numbers)[i - 1]) > numerical_precision) {
410 1934 : blocks_creator.add(i);
411 1934 : break;
412 : }
413 : }
414 : }
415 598 : }
416 :
417 : template <typename Derived>
418 166 : std::shared_ptr<const Derived> Basis<Derived>::get_canonicalized_copy() const {
419 166 : auto [coefficients, energy_of_states, quantum_numbers_of_states] = get_canonical_states(*kets);
420 498 : return derived().get_modified_copy(std::move(coefficients), std::move(energy_of_states),
421 498 : std::move(quantum_numbers_of_states));
422 166 : }
423 :
424 : template <typename Derived>
425 115 : bool Basis<Derived>::is_canonical() const {
426 115 : constexpr real_t numerical_precision = 100 * std::numeric_limits<real_t>::epsilon();
427 :
428 : // The basis is canonical if and only if its coefficient matrix is the identity matrix, i.e.,
429 : // if the i-th state is the i-th ket
430 115 : if (coefficients.rows() != coefficients.cols()) {
431 0 : return false;
432 : }
433 :
434 115 : Eigen::Index num_ones = 0;
435 2356 : for (Eigen::Index row = 0; row < coefficients.outerSize(); ++row) {
436 2244 : for (typename Eigen::SparseMatrix<scalar_t, Eigen::RowMajor>::InnerIterator it(coefficients,
437 : row);
438 4493 : it; ++it) {
439 4495 : if (it.row() == it.col() &&
440 3213 : std::abs(it.value() - static_cast<scalar_t>(1)) <= numerical_precision) {
441 2241 : ++num_ones;
442 11 : } else if (std::abs(it.value()) > numerical_precision) {
443 3 : return false;
444 : }
445 : }
446 : }
447 112 : return num_ones == coefficients.rows();
448 : }
449 :
450 : template <typename Derived>
451 1259 : std::shared_ptr<const Derived> Basis<Derived>::get_sorted_copy(
452 : const Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> &sorter) const {
453 : // Create a copy of the current object
454 1259 : auto result = std::make_shared<Derived>(derived());
455 :
456 1259 : if (coefficients.cols() == 0) {
457 2 : return result;
458 : }
459 :
460 : // Apply the sorting
461 1257 : set_task_status("Applying basis sorting...");
462 1257 : result->coefficients = coefficients * sorter;
463 :
464 1257 : set_task_status("Relabeling sorted basis states...");
465 5344 : for (auto &[name, sorted_quantum_numbers] : result->quantum_numbers_of_states) {
466 4087 : const auto &quantum_numbers = quantum_numbers_of_states.at(name);
467 4087 : sorted_quantum_numbers.resize(sorter.size());
468 187357 : for (int i = 0; i < sorter.size(); ++i) {
469 183270 : sorted_quantum_numbers[i] = quantum_numbers[sorter.indices()[i]];
470 : }
471 : }
472 1257 : if (has_energy()) {
473 1257 : auto &sorted_energies = *result->energy_of_states;
474 64369 : for (int i = 0; i < sorter.size(); ++i) {
475 63112 : sorted_energies[i] = (*energy_of_states)[sorter.indices()[i]];
476 : }
477 : }
478 :
479 1257 : return result;
480 1259 : }
481 :
482 : // Explicit instantiations
483 : template class Basis<BasisAtom<double>>;
484 : template class Basis<BasisAtom<std::complex<double>>>;
485 : template class Basis<BasisPair<double>>;
486 : template class Basis<BasisPair<std::complex<double>>>;
487 : } // namespace pairinteraction
|