votca 2026-dev
Loading...
Searching...
No Matches
gw.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2023 The VOTCA Development Team
3 * (http://www.votca.org)
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License")
6 *
7 * You may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19
20// Standard includes
21#include <algorithm>
22#include <chrono>
23#include <cmath>
24#include <fstream>
25#include <iostream>
26
27// Local VOTCA includes
31#include "votca/xtp/citations.h"
33#include "votca/xtp/gw.h"
36#include "votca/xtp/rpa.h"
39
40namespace votca {
41namespace xtp {
42
43void GW::configure(const options& opt) {
44 opt_ = opt;
45
46 // Normalize legacy and new grid-search settings once at configuration time.
47 // From this point on, the solver operates only on the decoupled canonical
48 // controls, independent of how the user specified them in XML.
50 qptotal_ = opt_.qpmax - opt_.qpmin + 1;
51 rpa_.configure(opt_.homo, opt_.rpamin, opt_.rpamax);
52 rpa_.setOutOfWindowShift(opt_.out_of_window_shift);
53 sigma_ = SigmaFactory().Create(opt_.sigma_integration, Mmn_, rpa_);
54 sigma_->setTimings(&timings_);
55 rpa_.setTimings(&timings_);
56 Sigma_base::options sigma_opt;
57 sigma_opt.homo = opt_.homo;
58 sigma_opt.qpmax = opt_.qpmax;
59 sigma_opt.qpmin = opt_.qpmin;
60 sigma_opt.rpamin = opt_.rpamin;
61 sigma_opt.rpamax = opt_.rpamax;
62 sigma_opt.eta = opt_.eta;
63 sigma_opt.alpha = opt_.alpha;
64 sigma_opt.quadrature_scheme = opt_.quadrature_scheme;
65 sigma_opt.order = opt_.order;
66 sigma_->configure(sigma_opt);
67 Sigma_x_ = Eigen::MatrixXd::Zero(qptotal_, qptotal_);
68 Sigma_c_ = Eigen::MatrixXd::Zero(qptotal_, qptotal_);
69 Sigma_reac_ = Eigen::MatrixXd::Zero(qptotal_, qptotal_);
70}
71
72void GW::setReactionField(const Eigen::MatrixXd& R) {
75 : Eigen::MatrixXd();
76}
77
79 if (dressing_.size() > 0 && !Mmn_.Dressed()) {
80 Mmn_.DressAuxIndex(dressing_);
82 << TimeStamp()
83 << " Dressed 3c integrals with (1+R)^1/2 for environment screening"
84 << std::flush;
85 }
86}
87
89 const Index homo_rel = opt_.homo - opt_.qpmin;
91 << TimeStamp()
92 << " Environment reaction field, static COH+SEX, diagonal [eV]:"
93 << std::flush;
94 for (Index i = 0; i < qptotal_; i++) {
95 std::string level = " Level";
96 if (i == homo_rel) {
97 level = " HOMO ";
98 } else if (i == homo_rel + 1) {
99 level = " LUMO ";
100 }
102 << level
103 << (boost::format(" = %1$4d Sigma_reac = %2$+1.6f") % (i + opt_.qpmin) %
105 .str()
106 << std::flush;
107 }
108 if (homo_rel >= 0 && homo_rel + 1 < qptotal_) {
110 << (boost::format(" HOMO %1$+1.4f eV, LUMO %2$+1.4f eV, gap %3$+1.4f "
111 "eV") %
112 (Sigma_reac_(homo_rel, homo_rel) * tools::conv::hrt2ev) %
113 (Sigma_reac_(homo_rel + 1, homo_rel + 1) * tools::conv::hrt2ev) %
114 ((Sigma_reac_(homo_rel + 1, homo_rel + 1) -
115 Sigma_reac_(homo_rel, homo_rel)) *
117 .str()
118 << std::flush;
119 }
120}
121
122double GW::CalcHomoLumoShift(Eigen::VectorXd frequencies) const {
123 double DFTgap = dft_energies_(opt_.homo + 1) - dft_energies_(opt_.homo);
124 double QPgap = frequencies(opt_.homo + 1 - opt_.qpmin) -
125 frequencies(opt_.homo - opt_.qpmin);
126 return QPgap - DFTgap;
127}
128
129Eigen::MatrixXd GW::getHQP() const {
130 return Sigma_x_ + Sigma_c_ + Sigma_reac_ - vxc_ +
131 Eigen::MatrixXd(
132 dft_energies_.segment(opt_.qpmin, qptotal_).asDiagonal());
133}
134
135Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> GW::DiagonalizeQPHamiltonian()
136 const {
137 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> qpdiag(getHQP());
138 PrintQP_Energies(qpdiag.eigenvalues());
139 return qpdiag;
140}
141
143 Eigen::VectorXd gwa_energies = getGWAResults();
144 double shift = CalcHomoLumoShift(gwa_energies);
145
147 << (boost::format(
148 " ====== Perturbative quasiparticle energies (Hartree) ====== "))
149 .str()
150 << std::flush;
152 << (boost::format(" DeltaHLGap = %1$+1.6f Hartree") % shift).str()
153 << std::flush;
154
155 for (Index i = 0; i < qptotal_; i++) {
156 std::string level = " Level";
157 if ((i + opt_.qpmin) == opt_.homo) {
158 level = " HOMO ";
159 } else if ((i + opt_.qpmin) == opt_.homo + 1) {
160 level = " LUMO ";
161 }
162
163 // With an environment, its static part of the correlation gets a
164 // column of its own, S-R; S-C stays the dynamic correlation.
165 const std::string env =
166 (reaction_field_.size() > 0)
167 ? (boost::format(" S-R = %1$+1.4f") % Sigma_reac_(i, i)).str()
168 : std::string();
170 << level
171 << (boost::format(" = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = "
172 "%4$+1.4f S-C = %5$+1.4f") %
173 (i + opt_.qpmin) % dft_energies_(i + opt_.qpmin) % vxc_(i, i) %
174 Sigma_x_(i, i) % Sigma_c_(i, i))
175 .str()
176 << env << (boost::format(" GWA = %1$+1.4f") % gwa_energies(i)).str()
177 << std::flush;
178 }
179 return;
180}
181
182void GW::PrintQSGW_Composition(double threshold) const {
184 << TimeStamp()
185 << " ====== QSGW QP state composition (dominant KS contributions) ======"
186 << std::flush;
187
188 for (Index n = 0; n < qptotal_; n++) {
189 const Index abs_n = n + opt_.qpmin;
190 std::string level = " Level";
191 if (abs_n == opt_.homo)
192 level = " HOMO ";
193 else if (abs_n == opt_.homo + 1)
194 level = " LUMO ";
195
196 // Collect contributions above threshold, sorted by weight descending
197 Eigen::VectorXd weights = qsgw_rotation_.col(n).cwiseAbs2();
198 std::vector<std::pair<double, Index>> contribs;
199 for (Index m = 0; m < qptotal_; m++) {
200 if (weights(m) >= threshold) {
201 contribs.push_back({weights(m), m + opt_.qpmin});
202 }
203 }
204 std::sort(contribs.begin(), contribs.end(),
205 [](const auto& a, const auto& b) { return a.first > b.first; });
206
207 std::string line;
208 for (const auto& [w, ks] : contribs) {
209 std::string ks_label;
210 if (ks == opt_.homo)
211 ks_label = "(HOMO)";
212 else if (ks == opt_.homo + 1)
213 ks_label = "(LUMO)";
214
215 line += (boost::format(" %1$5.1f%% KS_%2$d%3$s") % (100.0 * w) % ks %
216 ks_label)
217 .str();
218 }
220 << level << (boost::format(" = %1$4d:") % abs_n).str() << line
221 << std::flush;
222 }
223}
224
225void GW::PrintQSGW_Energies(const std::string& seed_label,
226 const Eigen::VectorXd& seed_energies,
227 const Eigen::VectorXd& qsgw_energies) const {
229 << TimeStamp() << " QSGW quasiparticle energies" << std::flush;
231 << (boost::format(
232 " ====== QSGW quasiparticle energies (Hartree) ====== "))
233 .str()
234 << std::flush;
235
236 for (Index i = 0; i < qptotal_; i++) {
237 std::string level = " Level";
238 if ((i + opt_.qpmin) == opt_.homo) {
239 level = " HOMO ";
240 } else if ((i + opt_.qpmin) == opt_.homo + 1) {
241 level = " LUMO ";
242 }
244 << level
245 << (boost::format(" = %1$4d %2$s = %3$+1.6f QSGW = %4$+1.6f") %
246 (i + opt_.qpmin) % seed_label % seed_energies(i) % qsgw_energies(i))
247 .str()
248 << std::flush;
249 }
250}
251
252void GW::PrintQP_Energies(const Eigen::VectorXd& qp_diag_energies) const {
253 Eigen::VectorXd gwa_energies = getGWAResults();
255 << TimeStamp() << " Full quasiparticle Hamiltonian " << std::flush;
257 << (boost::format(
258 " ====== Diagonalized quasiparticle energies (Hartree) "
259 "====== "))
260 .str()
261 << std::flush;
262 for (Index i = 0; i < qptotal_; i++) {
263 std::string level = " Level";
264 if ((i + opt_.qpmin) == opt_.homo) {
265 level = " HOMO ";
266 } else if ((i + opt_.qpmin) == opt_.homo + 1) {
267 level = " LUMO ";
268 }
270 << level
271 << (boost::format(" = %1$4d PQP = %2$+1.6f DQP = %3$+1.6f ") %
272 (i + opt_.qpmin) % gwa_energies(i) % qp_diag_energies(i))
273 .str()
274 << std::flush;
275 }
276 return;
277}
278
280 const Eigen::VectorXd& dft_energies) const {
281 Eigen::VectorXd shifted_energies = dft_energies;
282 shifted_energies.segment(opt_.homo + 1, dft_energies.size() - opt_.homo - 1)
283 .array() += opt_.shift;
284 return shifted_energies;
285}
286
288 timings_.Reset();
289 qsgw_final_energies_.resize(0);
290 {
291 auto t = timings_.Measure("exchange Sigma_x");
292 Sigma_x_ = (1 - opt_.ScaHFX) * sigma_->CalcExchangeMatrix();
293 if (core_exchange_.size() > 0) {
294 Sigma_x_ += (1 - opt_.ScaHFX) * core_exchange_;
295 }
296 }
298 << TimeStamp() << " Calculated Hartree exchange contribution"
299 << std::flush;
300 // The environment's static correlation, W - v restricted to v_reac:
301 // part of Sigma_c by its physics, held apart because it is frequency
302 // independent. Not scaled by ScaHFX: the DFT starting point has no
303 // reaction field to double count.
304 if (reaction_field_.size() > 0) {
305 auto t = timings_.Measure("reaction field Sigma_reac");
306 Sigma_reac_ = sigma_->CalcReactionFieldMatrix(reaction_field_);
308 }
309 // From here on the RPA and Sigma_c see u = v + v_reac.
310 {
311 auto t = timings_.Measure("dress Mmn for the environment");
313 }
314 // dftenergies has size aobasissize
315 // rpaenergies/Mmn have size rpatotal
316 // gwaenergies/frequencies have size qptotal
317 // homo index is relative to dft_energies
319 << TimeStamp() << " Scissor shifting DFT energies by: " << opt_.shift
320 << " Hrt" << std::flush;
321 Eigen::VectorXd dft_shifted_energies = ScissorShift_DFTlevel(dft_energies_);
322 rpa_.setRPAInputEnergies(
323 dft_shifted_energies.segment(opt_.rpamin, opt_.rpamax - opt_.rpamin + 1));
324 Eigen::VectorXd frequencies =
325 dft_shifted_energies.segment(opt_.qpmin, qptotal_);
326
327 Anderson mixing_;
328 mixing_.Configure(opt_.gw_mixing_order, opt_.gw_mixing_alpha);
329 // The QP energies of the last QP solve and the RPA energies it saw (G and
330 // W); after the solve, the RPA energies and, with mixing, frequencies are
331 // already the input of the next iteration.
332 Eigen::VectorXd qp_solution = frequencies;
333 Eigen::VectorXd rpa_energies_solved = rpa_.getRPAInputEnergies();
334
335 ScreeningUpdate screening;
336 screening.Configure(ScreeningUpdate::Parse(opt_.screening_update),
337 opt_.screening_update_ratio,
338 opt_.screening_update_max_inner);
339 bool rebuild_screening = true;
340 // QP iterations since the mixing history was (re)started: it restarts when
341 // an adaptive update rebuilds W, since the fixed-point map changes then
342 Index mixing_iteration = 0;
343 Index n_iterations = 0;
344 // root tracking: off in the first iteration and for the verifying full
345 // search after convergence (and for the rest of the run if that search
346 // moves a level)
347 tracked_root_.resize(0);
348 tracking_active_ = false;
350 bool tracking_verified = false;
351 bool verifying = false; // this iteration is the verifying full search
352
353 for (Index i_gw = 0; i_gw < opt_.gw_sc_max_iterations; ++i_gw) {
354 gw_sc_iteration_ = i_gw;
355 tracking_active_ = opt_.qp_root_tracking && i_gw > 0 && !tracking_verified;
356 const Eigen::VectorXd roots_before = tracked_root_;
357 if (opt_.reset_3c > 0 && i_gw % opt_.reset_3c == 0 && i_gw != 0) {
358 auto t = timings_.Measure("rebuild Mmn");
359 Mmn_.Rebuild();
361 << TimeStamp() << " Rebuilding 3c integrals" << std::flush;
362 DressForEnvironment(); // Rebuild leaves them bare
363 rebuild_screening = true; // the screening frame is gone too
364 }
365 if (rebuild_screening) {
366 if (i_gw == 0) {
367 XTP_LOG(Log::error, log_) << TimeStamp() << " Building the screening; "
368 << MemoryBudget::Usage() << std::flush;
369 }
370 {
371 auto t = timings_.Measure("screening: other");
372 if (screening_hook_) {
373 screening_hook_(rpa_.getRPAInputEnergies());
374 }
375 sigma_->PrepareScreening();
376 }
377 screening.Built(rpa_.getRPAInputEnergies());
378 if (screening.mode() == ScreeningUpdate::Mode::Adaptive &&
379 screening.builds() > 1) {
380 mixing_ = Anderson();
381 mixing_.Configure(opt_.gw_mixing_order, opt_.gw_mixing_alpha);
382 mixing_iteration = 0;
383 }
384 if (const std::string summary = sigma_->ScreeningSummary();
385 !summary.empty()) {
386 const Log::Level level =
387 (i_gw == 0) ? Log::Level::error : Log::Level::info;
388 XTP_LOG(level, log_) << TimeStamp() << " " << summary << std::flush;
389 }
390 if (i_gw == 0) {
391 XTP_LOG(Log::error, log_) << TimeStamp() << " Screening built; "
392 << MemoryBudget::Usage() << std::flush;
393 }
395 << TimeStamp() << " Calculated screening via RPA (build "
396 << screening.builds() << ")" << std::flush;
397 }
399 << TimeStamp() << " Solving QP equations " << std::flush;
400 const bool mix = opt_.gw_mixing_order > 0 && mixing_iteration > 0;
401 if (mix) {
402 mixing_.UpdateInput(frequencies);
403 }
404
405 const Eigen::VectorXd qp_input = frequencies;
406 {
407 auto t = timings_.Measure("QP equations (Sigma_c diagonal)");
408 frequencies = SolveQP(frequencies);
409 }
410 qp_solution = frequencies;
411 rpa_energies_solved = rpa_.getRPAInputEnergies();
412 ++mixing_iteration;
413 ++n_iterations;
414
415 if (opt_.gw_sc_max_iterations > 1) {
416 Eigen::VectorXd rpa_energies_old = rpa_.getRPAInputEnergies();
417 if (mix) {
418 if (opt_.gw_mixing_order == 1) {
420 << "GWSC using linear mixing with alpha: " << opt_.gw_mixing_alpha
421 << std::flush;
422 } else {
424 << "GWSC using Anderson mixing with history "
425 << opt_.gw_mixing_order << ", alpha: " << opt_.gw_mixing_alpha
426 << std::flush;
427 }
428 mixing_.UpdateOutput(frequencies);
429 Eigen::VectorXd mixed_frequencies = mixing_.MixHistory();
430 rpa_.UpdateRPAInputEnergies(dft_energies_, mixed_frequencies,
431 opt_.qpmin);
432 frequencies = mixed_frequencies;
433
434 } else {
435 XTP_LOG(Log::debug, log_) << "GWSC using plain update " << std::flush;
436 rpa_.UpdateRPAInputEnergies(dft_energies_, frequencies, opt_.qpmin);
437 }
438
439 for (int i = 0; i < frequencies.size(); i++) {
441 << "... GWSC iter " << i_gw << " state " << i << " "
442 << std::setprecision(9) << frequencies(i) << std::flush;
443 }
444
446 << TimeStamp() << " GW_Iteration:" << i_gw
447 << " Shift[Hrt]:" << CalcHomoLumoShift(frequencies) << std::flush;
448 // logs the largest change of the (mixed) energies; the decision is
449 // ScreeningUpdate's, on the residual of the QP solve
450 Converged(rpa_.getRPAInputEnergies(), rpa_energies_old, opt_.gw_sc_limit);
451 const double residual = (qp_solution - qp_input).cwiseAbs().maxCoeff();
452 XTP_LOG(Log::info, log_) << TimeStamp() << " QP residual (solution - "
453 << "input) max=" << residual << std::flush;
455 << TimeStamp() << " Largest QP residuals (level: input -> solution): "
456 << qp_solver::LargestResiduals(qp_solution, qp_input, opt_.qpmin)
457 << std::flush;
458 double drift = 0.0;
459 const ScreeningUpdate::Next next = screening.Decide(
460 residual, rpa_.getRPAInputEnergies(), opt_.gw_sc_limit, &drift);
461 if (screening.mode() == ScreeningUpdate::Mode::Adaptive) {
463 << TimeStamp() << " Change since the screening was built: " << drift
464 << " Hrt after " << screening.inner() << " iteration(s)"
465 << ((next == ScreeningUpdate::Next::Rebuild) ? "; rebuilding W"
466 : "")
467 << std::flush;
468 }
469 if (verifying && roots_before.size() == qptotal_) {
470 // the full search after a converged tracked run: report levels it
471 // put on another root than tracking did
472 std::vector<Index> moved;
473 for (Index l = 0; l < qptotal_; ++l) {
474 if (std::abs(tracked_root_(l) - roots_before(l)) >
475 10.0 * opt_.gw_sc_limit) {
476 moved.push_back(l + opt_.qpmin);
477 }
478 }
479 if (!moved.empty() && next != ScreeningUpdate::Next::Converged) {
480 IndexParser rp;
482 << TimeStamp() << " QP root tracking: the full search chose "
483 << "other roots for levels " << rp.CreateIndexString(moved)
484 << "; continuing with the full search" << std::flush;
485 }
486 verifying = false;
487 }
488 if (next == ScreeningUpdate::Next::Converged && opt_.qp_root_tracking &&
489 !tracking_verified && i_gw > 0) {
490 // converged on the tracked roots: one QP solve with the full search
491 // (same G and W) checks that they are the roots the full search
492 // chooses; if so it converges at once
493 tracking_verified = true;
494 verifying = true;
495 rebuild_screening = false;
497 << TimeStamp()
498 << " QP root tracking converged; verifying with a full search"
499 << std::flush;
500 if (i_gw < opt_.gw_sc_max_iterations - 1) {
501 continue;
502 }
503 }
505 XTP_LOG(Log::info, log_) << TimeStamp() << " Converged after "
506 << i_gw + 1 << " GW iterations." << std::flush;
507 break;
508 } else if (i_gw == opt_.gw_sc_max_iterations - 1) {
510 << TimeStamp()
511 << " WARNING! GW-self-consistency cycle not converged after "
512 << opt_.gw_sc_max_iterations << " iterations." << std::flush;
514 << TimeStamp() << " Run continues. Inspect results carefully!"
515 << std::flush;
516 break;
517 }
518 rebuild_screening = (next == ScreeningUpdate::Next::Rebuild);
519 }
520 }
521 screening_builds_ = screening.builds();
522 qp_iterations_ = n_iterations;
523 tracking_active_ = false;
524 if (opt_.gw_sc_max_iterations > 1) {
526 << TimeStamp() << " evGW: " << n_iterations << " QP iterations, "
527 << screening.builds() << " screening builds ("
528 << ScreeningUpdate::Name(screening.mode()) << ")"
529 << (opt_.qp_root_tracking
530 ? "; root tracking solved " +
531 std::to_string(tracked_local_total_) + " of " +
532 std::to_string(n_iterations * qptotal_) +
533 " level solves locally"
534 : std::string())
535 << std::flush;
536 }
537 {
538 // Sigma_c of the last QP solve, at its solution and with the energies in
539 // G it saw, so that the PQP energies solve their QP equation. The RPA
540 // energies updated after the solve (input of a next iteration) stay.
542 auto t = timings_.Measure("QP equations (Sigma_c diagonal)");
543 const Eigen::VectorXd rpa_energies_next = rpa_.getRPAInputEnergies();
544 rpa_.setRPAInputEnergies(rpa_energies_solved);
545 Sigma_c_.diagonal() = sigma_->CalcCorrelationDiag(qp_solution);
546 rpa_.setRPAInputEnergies(rpa_energies_next);
547 qp_solution_ = qp_solution;
548 rpa_energies_solved_ = rpa_energies_solved;
549 }
551 timings_.Report(log_, Log::error, "GW timing summary");
552}
553
554Eigen::VectorXd GW::getGWAResults() const {
555 // When QSGW with virtual trimming has run, return the pre-computed merged
556 // energy vector (QSGW for the trimmed window, seed for excluded virtuals).
557 // This avoids recomputing from sigma matrices which were zeroed post-loop.
558 if (qsgw_final_energies_.size() > 0) {
560 }
561 return Sigma_x_.diagonal() + Sigma_c_.diagonal() + Sigma_reac_.diagonal() -
562 vxc_.diagonal() + dft_energies_.segment(opt_.qpmin, qptotal_);
563}
564
566 Index n = 0;
567 for (const auto& c : competing_roots_) {
568 n += c.competing ? 1 : 0;
569 }
570 if (n == 0) {
571 return;
572 }
573 XTP_LOG(level, log_) << TimeStamp() << " " << n
574 << " QP level(s) with two roots of comparable weight "
575 "(second Z at least half the largest):"
576 << std::flush;
577 for (Index i = 0; i < Index(competing_roots_.size()); ++i) {
578 const auto& c = competing_roots_[std::size_t(i)];
579 if (c.competing) {
580 XTP_LOG(level, log_)
581 << (boost::format(" Level = %1$4d chosen %2$+1.6f (Z = %3$.3f), "
582 "other %4$+1.6f (Z = %5$.3f)") %
583 (i + opt_.qpmin) % c.omega % c.Z % c.omega_alt % c.Z_alt)
584 .str()
585 << std::flush;
586 }
587 }
588}
589
590Eigen::VectorXd GW::SolveQP(const Eigen::VectorXd& frequencies) const {
591 sigma_->ResetDiagEvalCounter();
593 Eigen::VectorXd env = Eigen::VectorXd::Zero(qptotal_);
594
595 const Eigen::VectorXd intercepts =
596 dft_energies_.segment(opt_.qpmin, qptotal_) + Sigma_x_.diagonal() +
597 Sigma_reac_.diagonal() - vxc_.diagonal();
598
599 Eigen::VectorXd frequencies_new = frequencies;
600 Eigen::Array<bool, Eigen::Dynamic, 1> converged =
601 Eigen::Array<bool, Eigen::Dynamic, 1>::Zero(qptotal_);
602
603 QPStats total_stats;
604 const bool track = opt_.qp_root_tracking;
605 const bool use_tracked =
606 track && tracking_active_ && tracked_root_.size() == qptotal_;
607 Eigen::VectorXd roots_new = frequencies;
608 Eigen::VectorXd Z_new = Eigen::VectorXd::Zero(qptotal_);
609 Index n_local = 0;
610
611 // HOMO-LUMO midpoint of the current QP guesses (DFT energies where a
612 // level is outside the QP range), for SolveQP_Grid's restricted window.
613 {
614 const Index h = opt_.homo - opt_.qpmin;
615 const double e_homo =
616 (h >= 0 && h < qptotal_) ? frequencies[h] : dft_energies_(opt_.homo);
617 const double e_lumo = (h + 1 >= 0 && h + 1 < qptotal_)
618 ? frequencies[h + 1]
619 : dft_energies_(opt_.homo + 1);
620 qp_midgap_ = 0.5 * (e_homo + e_lumo);
621 }
622
623#ifdef _OPENMP
624 Index use_threads =
626#else
627 Index use_threads = 1;
628#endif
629
630#pragma omp parallel for schedule(dynamic) num_threads(use_threads)
631 for (Index gw_level = 0; gw_level < qptotal_; ++gw_level) {
632
633 double initial_f = frequencies[gw_level];
634 double intercept = intercepts[gw_level];
635 boost::optional<double> newf;
636 QPStats local_stats;
637 double Z_root = 0.0;
638
639 if (use_tracked) {
640 auto cand = SolveQP_Tracked(intercept, initial_f, gw_level, &local_stats);
641 if (cand) {
642 newf = cand->omega;
643 Z_root = cand->Z;
644#pragma omp atomic
645 ++n_local;
646 }
647 }
648 if (!newf && opt_.qp_solver == "fixedpoint") {
649 newf = SolveQP_FixedPoint(intercept, initial_f, gw_level, &local_stats);
650 }
651 if (newf) {
652 frequencies_new[gw_level] = newf.value();
653 converged[gw_level] = true;
654 } else {
655 QPStats grid_stats;
656 newf = SolveQP_Grid(intercept, initial_f, gw_level, &grid_stats);
657 local_stats.Add(grid_stats);
658 if (newf) {
659 frequencies_new[gw_level] = newf.value();
660 converged[gw_level] = true;
661 } else {
662 QPStats lin_stats;
663 newf =
664 SolveQP_Linearisation(intercept, initial_f, gw_level, &lin_stats);
665 local_stats.Add(lin_stats);
666 if (newf) {
667 frequencies_new[gw_level] = newf.value();
668 }
669 }
670 }
671 if (track && newf) {
672 roots_new[gw_level] = newf.value();
673 if (Z_root <= 0.0) {
674 // weight of a root from the full search, for the next local one
675 QPFunc fqp(gw_level, *sigma_.get(), intercept);
676 const double d = fqp.deriv(newf.value());
677 Z_root = (std::abs(d) > 1e-14) ? -1.0 / d : 0.0;
678 }
679 Z_new[gw_level] = Z_root;
680 }
681
682#pragma omp critical
683 {
684 total_stats.Add(local_stats);
685 }
686 }
687
688 if (track) {
690 (tracked_root_.size() == qptotal_)
691 ? Eigen::VectorXd((roots_new - tracked_root_).cwiseAbs())
692 : Eigen::VectorXd::Zero(qptotal_);
693 tracked_root_ = roots_new;
694 tracked_Z_ = Z_new;
695 tracked_local_ = n_local;
696 tracked_local_total_ += n_local;
697 if (use_tracked) {
699 << TimeStamp() << " QP root tracking: " << n_local << " of "
700 << qptotal_ << " levels solved near their previous root"
701 << std::flush;
702 }
703 }
704
705 if (!converged.all()) {
706 std::vector<Index> states;
707 for (Index s = 0; s < converged.size(); s++) {
708 if (!converged[s]) {
709 states.push_back(s);
710 }
711 }
712 IndexParser rp;
713 XTP_LOG(Log::error, log_) << TimeStamp() << " Not converged PQP states are:"
714 << rp.CreateIndexString(states) << std::flush;
716 << TimeStamp() << " Increase the grid search interval" << std::flush;
717 }
718
720 << " Sigma diagonal evaluations in SolveQP: "
721 << sigma_->GetDiagEvalCounter() << std::flush;
722
723 XTP_LOG(Log::info, log_) << TimeStamp() << " QP diagnostics: " << "scan="
724 << total_stats.sigma_scan_calls
725 << " refine=" << total_stats.sigma_refine_calls
726 << " deriv_sigma="
727 << total_stats.sigma_derivative_calls
728 << " other=" << total_stats.sigma_other_calls
729 << " total_sigma=" << total_stats.TotalSigmaCalls()
730 << " unique_omega="
731 << total_stats.sigma_unique_frequencies
732 << " repeat_sigma=" << total_stats.sigma_repeat_calls
733 << " deriv_calls=" << total_stats.deriv_calls
734 << std::flush;
735
736 return frequencies_new;
737}
738
739boost::optional<qp_solver::RootCandidate> GW::SolveQP_Tracked(
740 double intercept0, double frequency0, Index gw_level,
741 QPStats* stats) const {
742 const double center = tracked_root_(gw_level);
743 // a few times the last change of the root or of the input, within limits
744 const double moved =
745 std::max(tracked_change_(gw_level), std::abs(frequency0 - center));
746 const double halfwidth = std::clamp(4.0 * moved, 0.01, 0.1);
747 QPFunc fqp(gw_level, *sigma_.get(), intercept0);
748 qp_solver::SolverOptions solver_opt;
749 solver_opt.g_sc_limit = opt_.g_sc_limit;
750 solver_opt.qp_bisection_max_iter = opt_.g_sc_max_iterations;
751 solver_opt.qp_dense_spacing = opt_.qp_dense_spacing;
752 auto cand = qp_solver::SolveQP_Tracked(fqp, center, halfwidth,
753 tracked_Z_(gw_level), 0.5, solver_opt,
754 opt_.qp_root_finder == "brent");
755 if (stats != nullptr) {
756 *stats = fqp.GetStats();
757 }
758 return cand;
759}
760
761boost::optional<double> GW::SolveQP_Linearisation(double intercept0,
762 double frequency0,
763 Index gw_level,
764 QPStats* stats) const {
765 boost::optional<double> newf = boost::none;
766
767 QPFunc fqp(gw_level, *sigma_.get(), intercept0);
768
769 // fqp.deriv is f'(w) = dSigma_c/dw - 1
770 newf = qp_solver::LinearisedRoot(frequency0,
771 fqp.value(frequency0, EvalStage::Other),
772 fqp.deriv(frequency0));
773
774 if (stats != nullptr) {
775 *stats = fqp.GetStats();
776 }
777 return newf;
778}
779
781 double intercept0, double frequency0, Index gw_level, double left_limit,
782 double right_limit, bool allow_rejected_return, QPStats* stats) const {
783
784 QPFunc fqp(gw_level, *sigma_.get(), intercept0);
785
786 qp_solver::SolverOptions solver_opt;
787
788 // Pass only canonical search controls into the shared grid-search utility.
789 // RKS and UKS intentionally use the same search semantics; only the sigma
790 // evaluator differs between the two implementations.
791 solver_opt.g_sc_limit = opt_.g_sc_limit;
792 solver_opt.qp_bisection_max_iter = opt_.g_sc_max_iterations;
793 solver_opt.qp_full_window_half_width = opt_.qp_full_window_half_width;
794 solver_opt.qp_dense_spacing = opt_.qp_dense_spacing;
795 solver_opt.qp_adaptive_shell_width = opt_.qp_adaptive_shell_width;
796 solver_opt.qp_adaptive_shell_count = opt_.qp_adaptive_shell_count;
797 solver_opt.prefer_nearest_root =
798 opt_.qp_root_continuity && gw_sc_iteration_ > 0;
799
801 std::vector<QPRootCandidate> accepted_roots;
802 std::vector<QPRootCandidate> rejected_roots;
803
804 bool use_brent = false;
805 if (opt_.qp_root_finder == "brent") {
806 use_brent = true;
807 }
808
810 fqp, frequency0, left_limit, right_limit, gw_sc_iteration_, solver_opt,
811 &wdiag, &accepted_roots, &rejected_roots, use_brent);
812
814#pragma omp critical
815 {
816 if (!accepted_roots.empty() || !rejected_roots.empty()) {
818 << " Adaptive scan qplevel:" << gw_level << " center="
819 << std::max(left_limit, std::min(right_limit, frequency0))
820 << " shells=" << wdiag.shells_explored
821 << " first_interval_shell=" << wdiag.first_interval_shell
822 << " first_accepted_shell=" << wdiag.first_accepted_shell
823 << " intervals=" << wdiag.intervals_found << std::flush;
824 }
825 }
826 }
827
828 if (stats != nullptr) {
829 *stats = fqp.GetStats();
830 }
831
832 if (!accepted_roots.empty()) {
833 if (result) {
834 RecordCompetingRoots(gw_level, accepted_roots, result.value());
835 }
836 return result;
837 }
838
839 if (!rejected_roots.empty() && !allow_rejected_return) {
841#pragma omp critical
842 {
844 << " Adaptive scan qplevel:" << gw_level
845 << " produced only rejected roots in [" << left_limit << ", "
846 << right_limit << "], forcing wider retry" << std::flush;
847 }
848 }
849 return boost::none;
850 }
851
852 return result;
853}
854
855boost::optional<double> GW::SolveQP_Grid_Windowed_Dense(
856 double intercept0, double frequency0, Index gw_level, double left_limit,
857 double right_limit, bool allow_rejected_return, QPStats* stats) const {
858
859 QPFunc fqp(gw_level, *sigma_.get(), intercept0);
860
861 qp_solver::SolverOptions solver_opt;
862
863 // The dense path performs a uniform sign-change scan over the requested
864 // interval. Its spacing is qp_dense_spacing, not the adaptive shell width.
865 solver_opt.g_sc_limit = opt_.g_sc_limit;
866 solver_opt.qp_bisection_max_iter = opt_.g_sc_max_iterations;
867 solver_opt.qp_full_window_half_width = opt_.qp_full_window_half_width;
868 solver_opt.qp_dense_spacing = opt_.qp_dense_spacing;
869 solver_opt.qp_adaptive_shell_width = opt_.qp_adaptive_shell_width;
870 solver_opt.qp_adaptive_shell_count = opt_.qp_adaptive_shell_count;
871 solver_opt.prefer_nearest_root =
872 opt_.qp_root_continuity && gw_sc_iteration_ > 0;
873
874 const bool use_brent = (opt_.qp_root_finder == "brent");
875
876 std::vector<QPRootCandidate> accepted_roots;
877 std::vector<QPRootCandidate> rejected_roots;
878 std::vector<std::pair<double, double>> roots; // omega : Z
879
880 if (left_limit < right_limit) {
881 double freq_prev = left_limit;
882 double targ_prev = fqp.value(freq_prev, EvalStage::Scan);
883
884 // Dense scanning is the robustness path: it uniformly samples the entire
885 // interval to avoid missing sign changes that a coarser adaptive shell
886 // search might step over.
887 const Index n_steps = std::max<Index>(
888 2, static_cast<Index>(
889 std::ceil((right_limit - left_limit) / opt_.qp_dense_spacing)) +
890 1);
891
892 auto node = [&](Index i_node) {
893 return (i_node == n_steps - 1)
894 ? right_limit
895 : std::min(right_limit,
896 left_limit + static_cast<double>(i_node) *
897 opt_.qp_dense_spacing);
898 };
899 {
900 // all scan nodes in one batch
901 std::vector<double> nodes;
902 for (Index i_node = 1; i_node < n_steps; ++i_node) {
903 nodes.push_back(node(i_node));
904 }
905 qp_solver::PrefetchIfAvailable(fqp, nodes, 0);
906 }
907
908 for (Index i_node = 1; i_node < n_steps; ++i_node) {
909 const double freq = node(i_node);
910
911 const double targ = fqp.value(freq, EvalStage::Scan);
912
913 if (targ_prev * targ < 0.0) {
914 auto cand =
915 qp_solver::RefineQPInterval(freq_prev, targ_prev, freq, targ, fqp,
916 frequency0, solver_opt, use_brent);
917 if (cand) {
918 roots.emplace_back(cand->omega, cand->Z);
919 if (cand->accepted) {
920 accepted_roots.push_back(*cand);
921 } else {
922 rejected_roots.push_back(*cand);
923 }
924 }
925 }
926
927 freq_prev = freq;
928 targ_prev = targ;
929 }
930 }
931
933#pragma omp critical
934 {
935 if (accepted_roots.empty() && rejected_roots.empty()) {
937 << " Dense scan qplevel:" << gw_level << " found no roots in ["
938 << left_limit << ", " << right_limit << "]" << std::flush;
939 } else {
941 << " Dense scan qplevel:" << gw_level << " roots (omega:Z)\n\t\t";
942 for (const auto& root : roots) {
943 XTP_LOG(Log::info, log_) << std::setprecision(5) << root.first << ":"
944 << root.second << " ";
945 }
946 XTP_LOG(Log::info, log_) << std::flush;
947 }
948 }
949 }
950
951 if (stats != nullptr) {
952 *stats = fqp.GetStats();
953 }
954
955 if (!accepted_roots.empty()) {
956 const double best = qp_solver::SelectRoot(accepted_roots, solver_opt).omega;
957 RecordCompetingRoots(gw_level, accepted_roots, best);
958 return best;
959 }
960
961 if (!rejected_roots.empty()) {
962 if (!allow_rejected_return) {
964#pragma omp critical
965 {
967 << " Dense scan qplevel:" << gw_level
968 << " produced only rejected roots in [" << left_limit << ", "
969 << right_limit << "], forcing wider retry" << std::flush;
970 }
971 }
972 return boost::none;
973 }
974
975 auto least_bad = std::max_element(
976 rejected_roots.begin(), rejected_roots.end(),
977 [](const QPRootCandidate& a, const QPRootCandidate& b) {
978 return qp_solver::ScoreRoot(a) < qp_solver::ScoreRoot(b);
979 });
980 return least_bad->omega;
981 }
982
983 return boost::none;
984}
985
986boost::optional<double> GW::SolveQP_Grid_Windowed(
987 double intercept0, double frequency0, Index gw_level, double left_limit,
988 double right_limit, bool allow_rejected_return, QPStats* stats) const {
989
990 if (opt_.qp_grid_search_mode == "adaptive") {
991 return SolveQP_Grid_Windowed_Adaptive(intercept0, frequency0, gw_level,
992 left_limit, right_limit,
993 allow_rejected_return, stats);
994 }
995
996 if (opt_.qp_grid_search_mode == "dense") {
997 return SolveQP_Grid_Windowed_Dense(intercept0, frequency0, gw_level,
998 left_limit, right_limit,
999 allow_rejected_return, stats);
1000 }
1001
1002 if (opt_.qp_grid_search_mode == "adaptive_with_dense_fallback") {
1003 QPStats total_stats;
1004 auto adaptive = SolveQP_Grid_Windowed_Adaptive(
1005 intercept0, frequency0, gw_level, left_limit, right_limit,
1006 allow_rejected_return, &total_stats);
1007 if (adaptive) {
1008 if (stats != nullptr) {
1009 *stats = total_stats;
1010 }
1011 return adaptive;
1012 }
1013
1014 QPStats dense_stats;
1015 auto dense = SolveQP_Grid_Windowed_Dense(
1016 intercept0, frequency0, gw_level, left_limit, right_limit,
1017 allow_rejected_return, &dense_stats);
1018 total_stats.Add(dense_stats);
1019
1021#pragma omp critical
1022 {
1024 << " Adaptive QP scan failed for qplevel:" << gw_level
1025 << ", retrying dense grid scan in [" << left_limit << ", "
1026 << right_limit << "]" << std::flush;
1027 }
1028 }
1029
1030 if (stats != nullptr) {
1031 *stats = total_stats;
1032 }
1033 return dense;
1034 }
1035
1036 throw std::runtime_error("Unknown gw.qp_grid_search_mode '" +
1037 opt_.qp_grid_search_mode + "'");
1038}
1039
1040boost::optional<double> GW::SolveQP_Grid(double intercept0, double frequency0,
1041 Index gw_level, QPStats* stats) const {
1042 // The full QP search window is now controlled explicitly and no longer
1043 // inferred from the dense-grid spacing.
1044 const double range = opt_.qp_full_window_half_width;
1045
1046 const double full_left_limit = frequency0 - range;
1047 const double full_right_limit = frequency0 + range;
1048
1049 double restricted_left_limit = full_left_limit;
1050 double restricted_right_limit = full_right_limit;
1051
1052 bool use_restricted_window = false;
1053
1054 if (opt_.qp_restrict_search) {
1055 const Index mo_level = gw_level + opt_.qpmin;
1056 const bool is_occupied = (mo_level <= opt_.homo);
1057
1058 // The fixed bounds (-qp_zero_margin for occupied levels,
1059 // qp_virtual_min_energy for virtual ones) assume the level itself lies
1060 // inside them. An environment can move it outside -- an embedded LUMO
1061 // below -0.1 Ha -- and then every restricted scan fails and falls back
1062 // to the full dense window. In that case only, the bound moves to the
1063 // HOMO-LUMO midpoint, which separates occupied from virtual levels
1064 // wherever they are.
1065 if (is_occupied) {
1066 const double bound = (frequency0 < -opt_.qp_zero_margin)
1067 ? -opt_.qp_zero_margin
1068 : qp_midgap_;
1069 restricted_right_limit = std::min(full_right_limit, bound);
1070 } else {
1071 const double bound = (frequency0 > opt_.qp_virtual_min_energy)
1072 ? opt_.qp_virtual_min_energy
1073 : qp_midgap_;
1074 restricted_left_limit = std::max(full_left_limit, bound);
1075 }
1076
1077 const double tol = 1e-12;
1078 use_restricted_window =
1079 (std::abs(restricted_left_limit - full_left_limit) > tol) ||
1080 (std::abs(restricted_right_limit - full_right_limit) > tol);
1081 }
1082
1083 if (use_restricted_window && restricted_left_limit < restricted_right_limit) {
1084 auto restricted =
1085 SolveQP_Grid_Windowed(intercept0, frequency0, gw_level,
1086 restricted_left_limit, restricted_right_limit,
1087 false, // accepted roots only
1088 stats);
1089 if (restricted) {
1090 return restricted;
1091 }
1092
1094#pragma omp critical
1095 {
1097 << " Restricted QP search failed for qplevel:" << gw_level
1098 << " in window [" << restricted_left_limit << ", "
1099 << restricted_right_limit << "], forcing full dense window ["
1100 << full_left_limit << ", " << full_right_limit << "]" << std::flush;
1101 }
1102 }
1103
1104 // Important: do NOT go back to adaptive here.
1105 // The restricted window already failed to produce an accepted root.
1106 // Force the old robust full-window dense search.
1107 return SolveQP_Grid_Windowed_Dense(intercept0, frequency0, gw_level,
1108 full_left_limit, full_right_limit, true,
1109 stats);
1110 }
1111
1112 return SolveQP_Grid_Windowed(intercept0, frequency0, gw_level,
1113 full_left_limit, full_right_limit, true, stats);
1114}
1115
1116boost::optional<double> GW::SolveQP_FixedPoint(double intercept0,
1117 double frequency0,
1118 Index gw_level,
1119 QPStats* stats) const {
1120 boost::optional<double> newf = boost::none;
1121 QPFunc f(gw_level, *sigma_.get(), intercept0);
1123 opt_.g_sc_max_iterations, opt_.g_sc_limit, opt_.qp_solver_alpha);
1124 double freq_new = newton.FindRoot(f, frequency0);
1125 if (newton.getInfo() == NewtonRapson<QPFunc>::success) {
1126 newf = freq_new;
1127 }
1128 if (stats != nullptr) {
1129 *stats = f.GetStats();
1130 }
1131 return newf;
1132}
1133
1134bool GW::Converged(const Eigen::VectorXd& e1, const Eigen::VectorXd& e2,
1135 double epsilon) const {
1136 Index state = 0;
1137 bool energies_converged = true;
1138 double diff_max = (e1 - e2).cwiseAbs().maxCoeff(&state);
1139 if (diff_max > epsilon) {
1140 energies_converged = false;
1141 }
1142 XTP_LOG(Log::info, log_) << TimeStamp() << " E_diff max=" << diff_max
1143 << " StateNo:" << state << std::flush;
1144 return energies_converged;
1145}
1146
1148 if (!sigma_->HasOffDiagonal()) {
1150 << TimeStamp() << " WARNING: no off-diagonal Sigma_c for sigma "
1151 << "integration " << opt_.sigma_integration
1152 << "; the DQP Hamiltonian has no off-diagonal correlation"
1153 << std::flush;
1154 }
1155 const auto start = std::chrono::steady_clock::now();
1156 Eigen::VectorXd diag_backup = Sigma_c_.diagonal();
1157 Sigma_c_ = sigma_->CalcCorrelationOffDiag(getGWAResults());
1158 Sigma_c_.diagonal() = diag_backup;
1160 << TimeStamp() << " Sigma_c off-diagonal ("
1161 << qptotal_ * (qptotal_ - 1) / 2 << " pairs) took "
1162 << std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1163 .count()
1164 << " s" << std::flush;
1165}
1166
1167// =============================================================================
1168// GW::CalculateQSGW
1169//
1170// Quasiparticle self-consistent GW: iterates the rotation of the
1171// three-centre integrals until the QP energies are converged.
1172//
1173// Index conventions (same as evGW throughout):
1174// gw_level : 0-based index within the QP window [0, qptotal_)
1175// MO level : absolute MO index = gw_level + opt_.qpmin
1176//
1177// In the DFT-MO basis of the window
1178// H_QSGW = (diag(e_DFT) - V_xc) + U tilde_Sigma U^T,
1179// with U the current QP orbitals (columns, phi_i = sum_k U_ki psi_k) and
1180// tilde_Sigma_ij = Sigma_x,ij + 1/2 [Sigma_c,ij(E_i) + Sigma_c,ij(E_j)]
1181// in the QP basis, E_i the QP energy of phi_i. tilde_Sigma is evaluated
1182// with the integrals rotated to the QP orbitals (both orbital indices), so
1183// external indices, internal sums, energies and screening all refer to the
1184// same orbitals. CalcCorrelationOffDiag returns the symmetrised off-diagonal
1185// part, CalcCorrelationDiag the diagonal.
1186// =============================================================================
1189 << TimeStamp() << " Starting QSGW self-consistency loop " << std::flush;
1190
1192 << TimeStamp() << " QSGW start: qptotal_=" << qptotal_
1193 << " vxc rows=" << vxc_.rows() << " cols=" << vxc_.cols()
1194 << " Sigma_x rows=" << Sigma_x_.rows() << std::flush;
1195
1196 // Initialise: start from evGW/G0W0 seed energies.
1197 const Eigen::VectorXd e_qp_full = getGWAResults(); // full [qpmin,qpmax]
1198 qsgw_seed_energies_ = e_qp_full;
1199
1200 // ── Virtual-level threshold: auto-trim qpmax ─────────────────────────────
1201 // Scan virtual levels from LUMO upward. Exclude the first virtual whose
1202 // perturbative correction |e_QP - e_DFT| exceeds qsgw_max_virt_correction.
1203 // Occupied states are never excluded — large core corrections are physical.
1204 Index qsgw_qpmax = opt_.qpmax;
1205 {
1206 const Index lumo_local = opt_.homo - opt_.qpmin + 1;
1207 bool trimmed = false;
1208 for (Index n = lumo_local; n < qptotal_; n++) {
1209 const double corr =
1210 std::abs(e_qp_full(n) - dft_energies_(opt_.qpmin + n));
1211 if (corr > opt_.qsgw_max_virt_correction) {
1212 qsgw_qpmax = opt_.qpmin + n - 1;
1213 trimmed = true;
1215 << TimeStamp() << " QSGW virtual threshold: level "
1216 << (opt_.qpmin + n)
1217 << " correction = " << corr * votca::tools::conv::hrt2ev
1218 << " eV exceeds "
1219 << opt_.qsgw_max_virt_correction * votca::tools::conv::hrt2ev
1220 << " eV. Trimming QSGW window to [" << opt_.qpmin << ","
1221 << qsgw_qpmax << "]." << std::flush;
1222 break;
1223 }
1224 }
1225 if (!trimmed) {
1227 << TimeStamp() << " QSGW virtual threshold: all corrections within "
1228 << opt_.qsgw_max_virt_correction * votca::tools::conv::hrt2ev
1229 << " eV. Using full window [" << opt_.qpmin << "," << qsgw_qpmax
1230 << "]." << std::flush;
1231 }
1232 }
1233
1234 const Index qsgw_qptotal = qsgw_qpmax - opt_.qpmin + 1;
1235 const bool window_trimmed = (qsgw_qpmax < opt_.qpmax);
1236
1237 // If trimmed, reconfigure sigma for the reduced window
1238 if (window_trimmed) {
1239 Sigma_base::options sigma_opt;
1240 sigma_opt.homo = opt_.homo;
1241 sigma_opt.qpmin = opt_.qpmin;
1242 sigma_opt.qpmax = qsgw_qpmax;
1243 sigma_opt.rpamin = opt_.rpamin;
1244 sigma_opt.rpamax = opt_.rpamax;
1245 sigma_opt.eta = opt_.eta;
1246 sigma_opt.quadrature_scheme = opt_.quadrature_scheme;
1247 sigma_opt.order = opt_.order;
1248 sigma_opt.alpha = opt_.alpha;
1249 sigma_->configure(sigma_opt);
1250 Sigma_x_ = Eigen::MatrixXd::Zero(qsgw_qptotal, qsgw_qptotal);
1251 Sigma_c_ = Eigen::MatrixXd::Zero(qsgw_qptotal, qsgw_qptotal);
1252 }
1253
1254 Eigen::VectorXd e_qp = e_qp_full.head(qsgw_qptotal);
1255 qsgw_rotation_ = Eigen::MatrixXd::Identity(qsgw_qptotal, qsgw_qptotal);
1256
1257 if (opt_.sigma_integration == "cda") {
1258 throw std::runtime_error(
1259 "GW::CalculateQSGW: QSGW is not supported with the CDA sigma "
1260 "integration method. The Gaussian quadrature grid used by CDA becomes "
1261 "ill-conditioned as the QP wavefunctions rotate away from the DFT-MO "
1262 "basis, causing numerical divergence. Use sigma_integration=ppm or "
1263 "sigma_integration=exact instead.");
1264 }
1265 if (opt_.qsgw_regularization == "srg") {
1266 citations::Cite("Marie:2023");
1268 << TimeStamp()
1269 << " QSGW static self-energy: SRG regularization (Marie and Loos), "
1270 "s = "
1271 << opt_.qsgw_srg_s << " Ha^-2 (eta-equivalent "
1272 << std::sqrt(0.5 / opt_.qsgw_srg_s) << " Ha)" << std::flush;
1273 }
1274
1275 // H0 = diag(e_DFT) - V_xc in the DFT-MO basis of the window (the full
1276 // V_xc matrix: H_KS is diagonal there, H_KS - V_xc is not)
1277 Eigen::MatrixXd H0 = -vxc_.topLeftCorner(qsgw_qptotal, qsgw_qptotal);
1278 H0.diagonal() += dft_energies_.segment(opt_.qpmin, qsgw_qptotal);
1279
1280 // Store a copy of the original (unrotated) Mmn_ QP-window slices.
1281 // At each iteration we restore Mmn_ to the DFT-MO state and apply the full
1282 // rotation qsgw_rotation_ in one shot.
1283 // This is necessary because dU (eigenvectors of H_QSGW, always in DFT-MO
1284 // basis) gives the total rotation from DFT-MOs directly, not an incremental
1285 // rotation relative to the previous QP basis.
1286 // Store ALL m-slices in the full RPA window, not just the QP window.
1287 // PrepareScreening (PPM, CDA) calls MultiplyRightWithAuxMatrix which
1288 // overwrites all slices including those outside the QP window (e.g. the
1289 // core level when qpmin > rpamin). If we only restore QP-window slices,
1290 // out-of-window slices accumulate PPM-basis corruption across iterations,
1291 // causing the persistent oscillation seen when qpmin > rpamin.
1292 // Dressed for the correlation part, as in CalculateGWPerturbation --
1293 // the caller may have refilled the integrals since. Exchange and the
1294 // reaction-field self-energy are computed with kernels that undo it.
1296 const Index mtotal = Mmn_.msize();
1297 std::vector<Eigen::MatrixXd> Mmn_orig(mtotal);
1298 for (Index m = 0; m < mtotal; m++) {
1299 Mmn_orig[m] = Mmn_[m];
1300 }
1301 // The auxiliary frame the snapshot is in (PrepareScreening of the seed
1302 // run may have rotated it), restored with it below. The bare Coulomb
1303 // terms are blind to it; an environment reaction field is not.
1304 const Eigen::MatrixXd aux_frame_orig = Mmn_.AuxFrame();
1305
1306 // Hybrid starting points. H_KS = h + J + a K[rho_DFT] + v_xc^sl, and V_xc
1307 // holds only the semilocal part (perturbative GW uses (1 - a) Sigma_x for
1308 // that reason), so diag(e_DFT) - V_xc still contains a K[rho_DFT]. The loop
1309 // adds the full exchange of the current QP orbitals; remove the starting
1310 // point's share once, here, so that H = h + J + Sigma_x[QP] + Sigma_c for
1311 // any functional. K[rho_DFT] is the exchange matrix in the unrotated DFT
1312 // orbitals, with the frozen core (the same terms as in the loop, at
1313 // iteration 0). For a = 0 nothing changes.
1314 if (opt_.ScaHFX > 0.0) {
1315 Eigen::MatrixXd K0 = sigma_->CalcExchangeMatrix();
1316 if (core_exchange_.size() > 0) {
1317 K0 += core_exchange_.topLeftCorner(qsgw_qptotal, qsgw_qptotal);
1318 }
1319 H0 -= opt_.ScaHFX * K0;
1321 << TimeStamp() << " QSGW from a hybrid start: removed " << opt_.ScaHFX
1322 << " x exchange of the DFT orbitals from H0" << std::flush;
1323 if (opt_.rpamin > 0 && core_exchange_.size() == 0) {
1324 // H_KS holds a K of the frozen core too; without core exchange the
1325 // loop neither removes it nor adds the full one back, so the core
1326 // exchange enters with weight a instead of 1 and the fixed point
1327 // depends on the functional.
1329 << TimeStamp()
1330 << " WARNING: QSGW from a hybrid start with a frozen core and "
1331 "core_exchange=false: the exchange with the core stays at "
1332 << opt_.ScaHFX
1333 << " x its full value, so the result depends on the starting "
1334 "functional. Use core_exchange=true."
1335 << std::flush;
1336 }
1337 }
1338
1339 // Hartree: H_KS contains J[rho_DFT]. With hartree update on, the loop adds
1340 // J[rho_QP] - J[rho_DFT] of the active occupied levels (the frozen core
1341 // does not change), so H = h + J[rho_QP] + Sigma_x[QP] + Sigma_c: the
1342 // occupied space is then fully self-consistent.
1343 //
1344 // In an environment H_KS also holds the potential of the dipoles that
1345 // rho_DFT induced in the QM/MM loop. Those must follow the density as
1346 // well: the update is then with u = v + v_reac, the interaction the
1347 // dressed W is built from, J_u[rho_QP] - J_u[rho_DFT]. The response is
1348 // that of the GW reaction field (smeared sites), not of the point Thole
1349 // sites of the ground-state loop; it is linear, so only the change of
1350 // the density enters.
1351 const bool hartree_screened = opt_.qsgw_hartree_update &&
1352 opt_.qsgw_hartree_screened &&
1353 reaction_field_.size() > 0;
1354 Eigen::MatrixXd J0; // J (or J_u) of the DFT orbitals
1355 Eigen::MatrixXd J0_bare; // bare part, for the decomposition in the log
1356 if (opt_.qsgw_hartree_update) {
1357 J0_bare = sigma_->CalcHartreeMatrix();
1358 J0 =
1359 hartree_screened ? sigma_->CalcHartreeMatrix(reaction_field_) : J0_bare;
1360 if (reaction_field_.size() > 0) {
1362 << TimeStamp() << " QSGW Hartree update with "
1363 << (hartree_screened ? "u = v + v_reac (screened)"
1364 : "the bare v (environment does not follow)")
1365 << std::flush;
1366 }
1367 }
1368 // Diagnostics of what drives the environment's effect, per iteration
1369 const Index homo_w = opt_.homo - opt_.qpmin; // HOMO in the window
1370 const Index nocc_w = homo_w + 1;
1371 const Index nvirt_w = qsgw_qptotal - nocc_w;
1372 Eigen::VectorXd sigma_reac_diag0;
1373
1374 // Fixed-point problem in tilde_Sigma (DFT-MO basis of the window):
1375 // S_in -> H = H0 + S_in -> (E, U) -> S_out = F(S_in),
1376 // solved with Anderson/Pulay mixing of the pairs (S_in, S_out); energies
1377 // and orbitals always come from the same H. Converged when the residual
1378 // max|S_out - S_in| and the change of the QP energies are below
1379 // qsgw_sc_limit; the result is the eigensystem of H0 + S_out.
1380 // Reuses gw_mixing_order and gw_mixing_alpha.
1381 Anderson qsgw_mixer;
1382 qsgw_mixer.Configure(opt_.gw_mixing_order, opt_.gw_mixing_alpha);
1384 << TimeStamp() << " QSGW mixer: order=" << opt_.gw_mixing_order
1385 << " alpha=" << opt_.gw_mixing_alpha << std::flush;
1386
1387 // Start consistently: G and W with the seed QP energies in iteration 0
1388 // (after G0W0 the RPA energies are still the DFT ones).
1389 rpa_.UpdateRPAInputEnergies(dft_energies_, e_qp, opt_.qpmin);
1390
1391 const Index nflat = qsgw_qptotal * qsgw_qptotal;
1392 auto diagonalise = [&](const Eigen::VectorXd& S, Index iter) {
1393 const Eigen::MatrixXd H = H0 + Eigen::Map<const Eigen::MatrixXd>(
1394 S.data(), qsgw_qptotal, qsgw_qptotal);
1395 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(H);
1396 if (es.info() != Eigen::ComputationInfo::Success) {
1397 throw std::runtime_error(
1398 "GW::CalculateQSGW: diagonalisation of H_QSGW failed at iter " +
1399 std::to_string(iter));
1400 }
1401 return es;
1402 };
1403
1404 Eigen::VectorXd S_in; // the tilde_Sigma the current (e_qp, U) came from
1405 bool converged = false;
1406 for (Index iter = 0; iter < opt_.qsgw_max_iterations; iter++) {
1407
1408 // ── Step 1: integrals in the current QP orbitals ────────────────────────
1409 for (Index m = 0; m < mtotal; m++) {
1410 Mmn_[m] = Mmn_orig[m];
1411 }
1412 Mmn_.RestoreAuxFrame(aux_frame_orig);
1413 if (iter > 0) {
1414 Mmn_.RotateOrbitals(qsgw_rotation_, opt_.qpmin, qsgw_qpmax);
1415 }
1416
1417 // Environment reaction field in the current QP basis: it depends on
1418 // the wavefunctions, not on the energies, so it is recomputed with the
1419 // rotation, like the exchange.
1420 Eigen::MatrixXd sigma_reac;
1421 if (reaction_field_.size() > 0) {
1422 sigma_reac = sigma_->CalcReactionFieldMatrix(reaction_field_);
1423 }
1424
1425 // Recompute screening W and Sigma in current QP basis.
1426 sigma_->PrepareScreening();
1427
1428 // Exchange: symmetric, frequency-independent. The frozen-core part is
1429 // fixed in the DFT MO basis; in the QP orbitals phi U it is U^T X U.
1430 Sigma_x_ = sigma_->CalcExchangeMatrix();
1431 if (core_exchange_.size() > 0) {
1432 const Eigen::MatrixXd Xw =
1433 core_exchange_.topLeftCorner(qsgw_qptotal, qsgw_qptotal);
1434 Sigma_x_ += qsgw_rotation_.transpose() * Xw * qsgw_rotation_;
1435 }
1436
1437 // ── Step 2: S_out, the symmetrised static self-energy in the QP basis
1438 // (e_qp(i) is the energy of QP orbital i), then in the DFT-MO basis
1439 Eigen::MatrixXd tilde_Sigma = Sigma_x_;
1440 if (opt_.qsgw_regularization == "srg") {
1441 tilde_Sigma += sigma_->CalcCorrelationSRG(e_qp, opt_.qsgw_srg_s);
1442 } else {
1443 tilde_Sigma += sigma_->CalcCorrelationOffDiag(e_qp);
1444 tilde_Sigma.diagonal() += sigma_->CalcCorrelationDiag(e_qp);
1445 }
1446 if (sigma_reac.size() > 0) {
1447 tilde_Sigma += sigma_reac; // static, symmetric: no symmetrization
1448 }
1449 tilde_Sigma = qsgw_rotation_ * tilde_Sigma * qsgw_rotation_.transpose();
1450 double dj_max = 0.0; // max |J[rho_QP] - J[rho_DFT]|, bare v
1451 double dj_reac_max = 0.0; // max of its v_reac part (screened only)
1452 if (opt_.qsgw_hartree_update) {
1453 // J of the current QP orbitals, in the DFT-MO basis, minus J[rho_DFT]
1454 const Eigen::MatrixXd dJ_bare = qsgw_rotation_ *
1455 sigma_->CalcHartreeMatrix() *
1456 qsgw_rotation_.transpose() -
1457 J0_bare;
1458 dj_max = dJ_bare.cwiseAbs().maxCoeff();
1459 if (hartree_screened) {
1460 const Eigen::MatrixXd dJ =
1461 qsgw_rotation_ * sigma_->CalcHartreeMatrix(reaction_field_) *
1462 qsgw_rotation_.transpose() -
1463 J0;
1464 dj_reac_max = (dJ - dJ_bare).cwiseAbs().maxCoeff();
1465 tilde_Sigma += dJ;
1466 } else {
1467 tilde_Sigma += dJ_bare;
1468 }
1469 }
1470 if (opt_.qsgw_hartree_update || sigma_reac.size() > 0) {
1471 // Occupied-virtual mixing of the current QP orbitals: the largest
1472 // principal angle between the QP and the DFT occupied spaces, the
1473 // only rotation the density (and so the Hartree update) sees.
1474 double angle = 0.0;
1475 if (nocc_w > 0 && nvirt_w > 0) {
1476 const Eigen::MatrixXd Uvo =
1477 qsgw_rotation_.bottomLeftCorner(nvirt_w, nocc_w);
1478 const double s =
1479 Eigen::JacobiSVD<Eigen::MatrixXd>(Uvo).singularValues().maxCoeff();
1480 angle = std::asin(std::min(1.0, s)) * 180.0 / tools::conv::Pi;
1481 }
1482 std::string reac_text;
1483 if (sigma_reac.size() > 0) {
1484 if (iter == 0) {
1485 sigma_reac_diag0 = sigma_reac.diagonal();
1486 }
1487 const Eigen::VectorXd dsr = sigma_reac.diagonal() - sigma_reac_diag0;
1488 reac_text = (boost::format(" dSigma_reac HOMO %1$+.4f LUMO %2$+.4f "
1489 "max|.| %3$.4f") %
1490 (nocc_w > 0 ? dsr(homo_w) * tools::conv::hrt2ev : 0.0) %
1491 (nvirt_w > 0 ? dsr(nocc_w) * tools::conv::hrt2ev : 0.0) %
1492 (dsr.cwiseAbs().maxCoeff() * tools::conv::hrt2ev))
1493 .str();
1494 }
1496 << TimeStamp() << " QSGW iter " << iter
1497 << (boost::format(" max|dJ| %1$.4f max|dJ_reac| %2$.4f") %
1498 (dj_max * tools::conv::hrt2ev) %
1499 (dj_reac_max * tools::conv::hrt2ev))
1500 .str()
1501 << reac_text
1502 << (boost::format(" eV occ-virt rotation %1$.3f deg") % angle).str()
1503 << std::flush;
1504 }
1505 const Eigen::VectorXd S_out =
1506 Eigen::Map<const Eigen::VectorXd>(tilde_Sigma.data(), nflat);
1507
1508 // ── Step 3: residual and next input ──────────────────────────────────────
1509 Eigen::VectorXd S_next;
1510 double residual = std::numeric_limits<double>::infinity();
1511 if (iter == 0) {
1512 // the seed state is not of the form H0 + S_in: start from its output
1513 S_next = S_out;
1514 } else {
1515 residual = (S_out - S_in).cwiseAbs().maxCoeff();
1516 qsgw_mixer.UpdateInput(S_in);
1517 qsgw_mixer.UpdateOutput(S_out);
1518 S_next = qsgw_mixer.MixHistory();
1519 }
1520
1521 // ── Step 4: QP energies and orbitals of the next input ───────────────────
1522 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1523 diagonalise(S_next, iter);
1524 const double diff_max = (es.eigenvalues() - e_qp).cwiseAbs().maxCoeff();
1526 << TimeStamp() << " QSGW iter " << iter
1527 << " max|dE_QP| = " << diff_max * votca::tools::conv::hrt2ev
1528 << " eV max|Sigma_out - Sigma_in| = "
1529 << residual * votca::tools::conv::hrt2ev << " eV" << std::flush;
1530
1531 if (residual < opt_.qsgw_sc_limit && diff_max < opt_.qsgw_sc_limit) {
1532 XTP_LOG(Log::error, log_) << TimeStamp() << " QSGW converged in "
1533 << iter + 1 << " iterations." << std::flush;
1534 converged = true;
1535 // the result: the eigensystem of H0 + S_out, the output of the last
1536 // evaluation (it differs from the input by less than the residual)
1537 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es_out =
1538 diagonalise(S_out, iter);
1539 e_qp = es_out.eigenvalues();
1540 qsgw_rotation_ = es_out.eigenvectors();
1541 rpa_.UpdateRPAInputEnergies(dft_energies_, e_qp, opt_.qpmin);
1542 break;
1543 }
1544
1545 S_in = S_next;
1546 e_qp = es.eigenvalues();
1547 qsgw_rotation_ = es.eigenvectors();
1548 rpa_.UpdateRPAInputEnergies(dft_energies_, e_qp, opt_.qpmin);
1549 }
1550 if (!converged) {
1552 << TimeStamp() << " WARNING: QSGW did not converge in "
1553 << opt_.qsgw_max_iterations << " iterations. Inspect results carefully."
1554 << std::flush;
1555 }
1556
1557 // The QSGW energies are the eigenvalues of H_QSGW, the QP orbitals its
1558 // eigenvectors; getGWAResults() returns the former. Sigma_x_ holds the
1559 // last iteration's exchange in the QP basis of that iteration.
1560 qsgw_final_energies_ = e_qp;
1561
1562 // If the virtual window was trimmed, merge converged QSGW energies for
1563 // [qpmin, qsgw_qpmax] with perturbative seed energies for (qsgw_qpmax,
1564 // qpmax]. Pad rotation matrix with identity for excluded virtuals so that
1565 // getQSGWRotation() returns a qptotal_ x qptotal_ matrix for BSE hookup.
1566 if (window_trimmed) {
1567 const Index n_excluded = qptotal_ - qsgw_qptotal;
1569 << TimeStamp() << " QSGW: merging converged energies [" << opt_.qpmin
1570 << "," << qsgw_qpmax << "] with perturbative seed energies for "
1571 << n_excluded << " excluded virtual(s) [" << qsgw_qpmax + 1 << ","
1572 << opt_.qpmax << "]" << std::flush;
1573
1574 // Pad rotation with identity for excluded virtual levels
1575 Eigen::MatrixXd U_full = Eigen::MatrixXd::Identity(qptotal_, qptotal_);
1576 U_full.topLeftCorner(qsgw_qptotal, qsgw_qptotal) = qsgw_rotation_;
1577 qsgw_rotation_ = U_full;
1578
1579 // Build merged energy vector: QSGW for trimmed window, seed for rest.
1580 // Store in qsgw_final_energies_ so getGWAResults() returns the correct
1581 // full-window result without needing to recompute from sigma matrices.
1582 Eigen::VectorXd e_merged = e_qp_full;
1583 e_merged.head(qsgw_qptotal) = e_qp;
1584 qsgw_final_energies_ = e_merged;
1585
1586 // Update RPA with merged energies so RPAInputEnergies() is consistent.
1587 rpa_.UpdateRPAInputEnergies(dft_energies_, e_merged, opt_.qpmin);
1588
1589 // Restore Sigma_x_ and Sigma_c_ to full qptotal_ x qptotal_ size so that
1590 // any downstream code doesn't encounter a size mismatch with
1591 // vxc_.diagonal() (which has qptotal_ elements). getGWAResults() bypasses
1592 // these matrices via qsgw_final_energies_, so zeroing them is safe.
1593 Sigma_x_ = Eigen::MatrixXd::Zero(qptotal_, qptotal_);
1594 Sigma_c_ = Eigen::MatrixXd::Zero(qptotal_, qptotal_);
1595
1596 // Restore the full-size sigma configuration.
1597 Sigma_base::options sigma_opt_full;
1598 sigma_opt_full.homo = opt_.homo;
1599 sigma_opt_full.qpmin = opt_.qpmin;
1600 sigma_opt_full.qpmax = opt_.qpmax;
1601 sigma_opt_full.rpamin = opt_.rpamin;
1602 sigma_opt_full.rpamax = opt_.rpamax;
1603 sigma_opt_full.eta = opt_.eta;
1604 sigma_opt_full.quadrature_scheme = opt_.quadrature_scheme;
1605 sigma_opt_full.order = opt_.order;
1606 sigma_opt_full.alpha = opt_.alpha;
1607 sigma_->configure(sigma_opt_full);
1608 }
1609
1611 << TimeStamp() << " QSGW loop complete." << std::flush;
1612}
1613
1614namespace {
1615// Restores the RPA input energies on scope exit
1616class RPAEnergyGuard {
1617 public:
1618 RPAEnergyGuard(RPA& rpa, const Eigen::VectorXd& energies)
1619 : rpa_(rpa), saved_(rpa.getRPAInputEnergies()) {
1620 if (energies.size() == saved_.size()) {
1621 rpa_.setRPAInputEnergies(energies);
1622 }
1623 }
1624 ~RPAEnergyGuard() { rpa_.setRPAInputEnergies(saved_); }
1625 RPAEnergyGuard(const RPAEnergyGuard&) = delete;
1626 RPAEnergyGuard& operator=(const RPAEnergyGuard&) = delete;
1627
1628 private:
1629 RPA& rpa_;
1630 Eigen::VectorXd saved_;
1631};
1632} // namespace
1633
1634Eigen::MatrixXd GW::SigmaCurves(const std::vector<Index>& levels, Index steps,
1635 double spacing) const {
1636 // grid of level n: e_dft(n) + (k - (steps-1)/2) spacing, the same for all
1637 // GW flavours computed from one DFT calculation
1638 const Index nlev = Index(levels.size());
1639 Eigen::MatrixXd curves = Eigen::MatrixXd::Zero(nlev, steps);
1640 // One batched evaluation per level and chunk of frequencies: the
1641 // integrals (PPM) or residues (exact) of a level are read once per
1642 // chunk instead of once per point, and poles far from the chunk are
1643 // summed at a few Chebyshev nodes (exact_pole_sums::Values). Chunks keep
1644 // all threads busy for few levels and narrow the frequency range, which
1645 // moves more poles into the interpolated far field.
1646 const Index chunk = std::min<Index>(std::max<Index>(steps, 1), 96);
1647 const Index nchunks = (steps + chunk - 1) / chunk;
1648#pragma omp parallel for schedule(dynamic)
1649 for (Index task = 0; task < nlev * nchunks; task++) {
1650 const Index i = task / nchunks;
1651 const Index first = (task % nchunks) * chunk;
1652 const Index n = std::min(chunk, steps - first);
1653 const Index gw_level = levels[std::size_t(i)];
1654 const double center = dft_energies_(opt_.qpmin + gw_level);
1655 Eigen::VectorXd omega(n);
1656 for (Index k = 0; k < n; ++k) {
1657 omega(k) =
1658 center + (double(first + k) - (double(steps - 1) / 2.0)) * spacing;
1659 }
1660 curves.block(i, first, 1, n) =
1661 sigma_->CalcCorrelationDiagElements(gw_level, omega).transpose();
1662 }
1663 return curves;
1664}
1665
1666void GW::PlotSigma(std::string filename, Index steps, double spacing,
1667 std::string states) {
1668
1669 // The energies in G of the last QP solve (as for Sigma_c_ and the PQP
1670 // energies; in evGW the RPA energies were updated after it).
1671 RPAEnergyGuard guard(rpa_, rpa_energies_solved_);
1672
1673 // states are absolute MO indices; the GW arrays start at qpmin
1674 std::vector<Index> state_inds;
1675 IndexParser rp;
1676 std::vector<Index> parsed_states = rp.CreateIndexVector(states);
1677 for (Index gw_level : parsed_states) {
1678 if (gw_level >= opt_.qpmin && gw_level <= opt_.qpmax) {
1679 state_inds.push_back(gw_level);
1680 }
1681 }
1682 std::vector<Index> levels;
1683 for (Index s : state_inds) {
1684 levels.push_back(s - opt_.qpmin);
1685 }
1686 const Index num_states = Index(state_inds.size());
1687 const Eigen::VectorXd intercept =
1688 dft_energies_.segment(opt_.qpmin, qptotal_) + Sigma_x_.diagonal() +
1689 Sigma_reac_.diagonal() - vxc_.diagonal();
1690
1691 auto t0 = std::chrono::steady_clock::now();
1692 const Eigen::MatrixXd curves = SigmaCurves(levels, steps, spacing);
1693 const double seconds =
1694 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
1695 .count();
1697 << TimeStamp() << " PQP(omega) written to '" << filename
1698 << "' for states " << rp.CreateIndexString(state_inds) << " ("
1699 << num_states * steps << " points, " << seconds << " s)" << std::flush;
1700
1701 Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(steps, 2 * num_states);
1702 for (Index i = 0; i < num_states; i++) {
1703 const Index n = levels[std::size_t(i)];
1704 const double center = dft_energies_(opt_.qpmin + n);
1705 for (Index k = 0; k < steps; ++k) {
1706 mat(k, 2 * i) =
1707 center + (double(k) - (double(steps - 1) / 2.0)) * spacing;
1708 }
1709 mat.col(2 * i + 1) = curves.row(i).transpose().array() + intercept(n);
1710 }
1711
1712 std::ofstream out;
1713 out.open(filename);
1714 for (Index i = 0; i < num_states; i++) {
1715 const Index gw_level = state_inds[std::size_t(i)];
1716 out << boost::format("#%1$somega_%2$d\tE_QP(omega)_%2$d") %
1717 (i == 0 ? "" : "\t") % gw_level;
1718 }
1719 out << std::endl;
1720 boost::format numFormat("%+1.6f");
1721 Eigen::IOFormat matFormat(Eigen::StreamPrecision, 0, "\t", "\n");
1722 out << numFormat % mat.format(matFormat) << std::endl;
1723 out.close();
1724}
1725
1726void GW::DumpSigma(const sigma_dump_options& dopt, const std::string& gw_mode,
1727 const std::string& version) {
1728 if (!sigma_->HasPoleForm()) {
1729 throw std::runtime_error(
1730 "gw.sigma_dump needs sigma_integrator ppm or exact");
1731 }
1732 if (qp_solution_.size() != qptotal_) {
1733 throw std::runtime_error(
1734 "GW::DumpSigma called before CalculateGWPerturbation");
1735 }
1736 auto t0 = std::chrono::steady_clock::now();
1737 XTP_LOG(Log::error, log_) << TimeStamp() << " Dumping self-energy data to '"
1738 << dopt.filename << "'" << std::flush;
1739
1740 // the energies in G of the last QP solve, as for Sigma_c_
1741 RPAEnergyGuard guard(rpa_, rpa_energies_solved_);
1742
1743 const Index homo = opt_.homo;
1744 const double e_lumo = dft_energies_(homo + 1);
1745 // fixed reference of the imaginary axis: the DFT midgap, the same for all
1746 // GW flavours from one DFT calculation
1747 const double mu = 0.5 * (dft_energies_(homo) + e_lumo);
1748 const double eta2 = opt_.eta * opt_.eta;
1749
1750 // levels with spectra and imaginary-axis data: qpmin .. qpmin + nspec - 1
1751 Index nspec = qptotal_;
1752 if (dopt.levels_emax_ev > 0.0) {
1753 const double limit = e_lumo + dopt.levels_emax_ev * tools::conv::ev2hrt;
1754 nspec = 0;
1755 while (nspec < qptotal_ && dft_energies_(opt_.qpmin + nspec) <= limit) {
1756 ++nspec;
1757 }
1758 }
1759
1760 // Gauss-Legendre nodes on (-1, 1) (Golub-Welsch), mapped to (0, inf):
1761 // nu = s (1+x)/(1-x)
1762 const Index nimag = dopt.imag_points;
1763 Eigen::VectorXd nu = Eigen::VectorXd::Zero(nimag);
1764 Eigen::VectorXd nu_weights = Eigen::VectorXd::Zero(nimag);
1765 if (nimag > 0) {
1766 Eigen::MatrixXd J = Eigen::MatrixXd::Zero(nimag, nimag);
1767 for (Index k = 1; k < nimag; k++) {
1768 const double kd = double(k);
1769 J(k, k - 1) = J(k - 1, k) = kd / std::sqrt(4.0 * kd * kd - 1.0);
1770 }
1771 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(J);
1772 for (Index k = 0; k < nimag; k++) {
1773 const double x = es.eigenvalues()(k);
1774 const double w = 2.0 * std::pow(es.eigenvectors()(0, k), 2);
1775 nu(k) = dopt.imag_scale * (1.0 + x) / (1.0 - x);
1776 nu_weights(k) = w * dopt.imag_scale * 2.0 / ((1.0 - x) * (1.0 - x));
1777 }
1778 }
1779
1780 const Index nbins = std::max<Index>(
1781 1, Index(std::round((dopt.spectral_max - dopt.spectral_min) /
1782 dopt.spectral_binwidth)));
1783 Eigen::VectorXd bin_edges(nbins + 1);
1784 for (Index b = 0; b <= nbins; b++) {
1785 bin_edges(b) = dopt.spectral_min + double(b) * dopt.spectral_binwidth;
1786 }
1787
1788 Eigen::VectorXd sigma_check = Eigen::VectorXd::Zero(qptotal_);
1789 Eigen::VectorXd dsigma = Eigen::VectorXd::Zero(qptotal_);
1790 Eigen::VectorXd d2sigma = Eigen::VectorXd::Zero(qptotal_);
1791 Eigen::VectorXd sigma_dft = Eigen::VectorXd::Zero(qptotal_);
1792 Eigen::MatrixXf spectral = Eigen::MatrixXf::Zero(nspec, nbins);
1793 Eigen::VectorXd weight_below = Eigen::VectorXd::Zero(nspec);
1794 Eigen::VectorXd weight_above = Eigen::VectorXd::Zero(nspec);
1795 Eigen::VectorXd weight_total = Eigen::VectorXd::Zero(nspec);
1796 Eigen::VectorXd first_moment = Eigen::VectorXd::Zero(nspec);
1797 Eigen::MatrixXd imag_re = Eigen::MatrixXd::Zero(nspec, nimag);
1798 Eigen::MatrixXd imag_im = Eigen::MatrixXd::Zero(nspec, nimag);
1799
1800#pragma omp parallel for schedule(dynamic)
1801 for (Index n = 0; n < qptotal_; n++) {
1802 const Sigma_base::DiagPoleForm pf = sigma_->PoleForm(n);
1803 const ExactPoles& poles = pf.poles;
1804 const Index B = poles.nlevels();
1805 const double eqp = qp_solution_(n);
1806 const bool spec = (n < nspec);
1807 double s_qp = 0.0, d2 = 0.0, wsum = 0.0, m1 = 0.0, below = 0.0, above = 0.0;
1808 Eigen::VectorXd hist = Eigen::VectorXd::Zero(spec ? nbins : 0);
1809 Eigen::ArrayXd re = Eigen::ArrayXd::Zero(spec ? nimag : 0);
1810 Eigen::ArrayXd im = Eigen::ArrayXd::Zero(spec ? nimag : 0);
1811 // work arrays of the level, allocated once: per-mode temporaries were
1812 // 29 allocations per mode and level, which serialise the threads in
1813 // malloc on macOS
1814 Eigen::ArrayXd z(B), a(B), x(B), x2(B), den(B), xm(B), xm2(B), ad(B);
1815 for (Index s = 0; s < poles.nmodes(); ++s) {
1816 const double c =
1817 pf.prefactor * (pf.mode_factors ? pf.mode_factors[s] : 1.0);
1818 if (c == 0.0) {
1819 continue;
1820 }
1821 const double omega = poles.omegas(s);
1822 const double* r = pf.residues + B * s;
1823 for (Index m = 0; m < B; ++m) {
1824 z(m) = poles.energies(m) + ((m < poles.n_occ) ? -omega : omega);
1825 a(m) = c * r[m] * r[m];
1826 }
1827 // real axis at the QP solution, same broadening as the QP solver
1828 x = eqp - z;
1829 x2 = x.square();
1830 den = x2 + eta2;
1831 s_qp += (a * x / den).sum();
1832 d2 += (a * 2.0 * x * (x2 - 3.0 * eta2) / (den.square() * den)).sum();
1833 if (!spec) {
1834 continue;
1835 }
1836 wsum += a.sum();
1837 m1 += (a * z).sum();
1838 for (Index m = 0; m < B; ++m) {
1839 const double b =
1840 std::floor((z(m) - dopt.spectral_min) / dopt.spectral_binwidth);
1841 if (b < 0) {
1842 below += a(m);
1843 } else if (b >= double(nbins)) {
1844 above += a(m);
1845 } else {
1846 hist(Index(b)) += a(m);
1847 }
1848 }
1849 // imaginary axis mu + i nu: sum_p a_p / (mu + i nu - z_p)
1850 xm = mu - z;
1851 xm2 = xm.square();
1852 for (Index k = 0; k < nimag; k++) {
1853 ad = a / (xm2 + nu(k) * nu(k));
1854 re(k) += (ad * xm).sum();
1855 im(k) -= nu(k) * ad.sum();
1856 }
1857 }
1858 sigma_check(n) = s_qp;
1859 d2sigma(n) = d2;
1860 dsigma(n) = sigma_->CalcCorrelationDiagElementDerivative(n, eqp);
1861 sigma_dft(n) =
1862 sigma_->CalcCorrelationDiagElement(n, dft_energies_(opt_.qpmin + n));
1863 if (spec) {
1864 spectral.row(n) = hist.transpose().cast<float>();
1865 weight_below(n) = below;
1866 weight_above(n) = above;
1867 weight_total(n) = wsum;
1868 first_moment(n) = m1;
1869 imag_re.row(n) = re.matrix().transpose();
1870 imag_im.row(n) = im.matrix().transpose();
1871 }
1872 }
1873
1874 const Eigen::VectorXd sigma_c = Sigma_c_.diagonal();
1875 const double max_dev = (sigma_check - sigma_c).cwiseAbs().maxCoeff();
1877 << TimeStamp()
1878 << " Sigma dump: max |Sigma_c(pole sum) - Sigma_c| at the QP solution = "
1879 << max_dev << " Ha" << std::flush;
1880 const Eigen::VectorXd Z = (1.0 - dsigma.array()).inverse().matrix();
1881
1882 const Sigma_base::ScreeningData scr = sigma_->ScreeningDump(nu);
1883
1884 // Sigma_c(omega) of every QP level on a grid around its DFT energy
1885 Eigen::MatrixXf curves;
1886 if (dopt.plot_steps > 0) {
1887 std::vector<Index> all(static_cast<std::size_t>(qptotal_));
1888 for (Index n = 0; n < qptotal_; ++n) {
1889 all[std::size_t(n)] = n;
1890 }
1891 curves = SigmaCurves(all, dopt.plot_steps, dopt.plot_spacing).cast<float>();
1892 }
1893
1894 Eigen::Matrix<Index, Eigen::Dynamic, 1> levels(qptotal_);
1895 Eigen::Matrix<Index, Eigen::Dynamic, 1> competing(qptotal_);
1896 Eigen::VectorXd omega_alt = Eigen::VectorXd::Zero(qptotal_);
1897 Eigen::VectorXd Z_alt = Eigen::VectorXd::Zero(qptotal_);
1898 for (Index n = 0; n < qptotal_; n++) {
1899 levels(n) = n + opt_.qpmin;
1900 competing(n) = 0;
1901 if (n < Index(competing_roots_.size())) {
1902 const auto& c = competing_roots_[std::size_t(n)];
1903 competing(n) = c.competing ? 1 : 0;
1904 omega_alt(n) = c.omega_alt;
1905 Z_alt(n) = c.Z_alt;
1906 }
1907 }
1908
1910 {
1911 CheckpointWriter w = cpf.getWriter("/sigma");
1912 w(std::string(
1913 "Sigma_c,nn(w) = sum_p a_p Re[1/(w - z_p +- i eta)]; Hartree; "
1914 "levels = absolute MO indices qpmin..qpmax; per-level spectra "
1915 "and imaginary axis (z = mu + i nu) and the matrices vxc, sigma_x, "
1916 "Hqp for the first n_spec levels; sigma_c_curves(n, k) = "
1917 "Sigma_c(e_dft(n) + (k - (curve_steps-1)/2) curve_spacing) for all "
1918 "levels"),
1919 "description");
1920 w(std::string("2"), "format_version");
1921 w(version, "xtp_version");
1922 w(opt_.sigma_integration, "sigma_integrator");
1923 w(gw_mode, "gw_mode");
1924 w(homo, "homo");
1925 w(opt_.qpmin, "qpmin");
1926 w(opt_.qpmax, "qpmax");
1927 w(opt_.rpamin, "rpamin");
1928 w(opt_.rpamax, "rpamax");
1929 w(opt_.eta, "eta");
1930 w(opt_.ScaHFX, "ScaHFX");
1931 w(mu, "mu");
1932 w(nspec, "n_spec");
1933 w(dopt.levels_emax_ev, "levels_emax_ev");
1934 w(dopt.imag_scale, "imag_scale");
1935 w(dopt.spectral_binwidth, "spectral_binwidth");
1936 w(qp_iterations_, "qp_iterations");
1937 w(screening_builds_, "screening_builds");
1938 w(max_dev, "sigma_c_check_max_dev");
1939
1940 w(levels, "levels");
1941 w(Eigen::VectorXd(dft_energies_), "e_dft_all");
1942 w(Eigen::VectorXd(dft_energies_.segment(opt_.qpmin, qptotal_)), "e_dft");
1943 // diagonals for all QP levels, matrices for the first n_spec levels
1944 // (the full QP window of a G0W0 over all levels would dominate the file)
1945 w(Eigen::VectorXd(vxc_.diagonal()), "vxc_diag");
1946 w(Eigen::VectorXd(Sigma_x_.diagonal()), "sigma_x_diag");
1947 w(Eigen::VectorXd(Sigma_reac_.diagonal()), "sigma_reac");
1948 w(Eigen::MatrixXd(vxc_.topLeftCorner(nspec, nspec)), "vxc");
1949 w(Eigen::MatrixXd(Sigma_x_.topLeftCorner(nspec, nspec)), "sigma_x");
1950 w(Eigen::MatrixXd(getHQP().topLeftCorner(nspec, nspec)), "Hqp");
1951 w(getGWAResults(), "e_qp");
1952 w(qp_solution_, "qp_solution");
1953 w(sigma_c, "sigma_c");
1954 w(dsigma, "dsigma_c");
1955 w(d2sigma, "d2sigma_c");
1956 w(Z, "Z");
1957 w(sigma_dft, "sigma_c_at_e_dft");
1958 w(competing, "competing_roots");
1959 w(omega_alt, "omega_alt");
1960 w(Z_alt, "Z_alt");
1961 w(rpa_energies_solved_, "g_energies");
1962 w(scr.energies, "w_energies");
1963
1964 w(nu, "imag_nu");
1965 w(nu_weights, "imag_weights");
1966 w(imag_re, "sigma_c_imag_re");
1967 w(imag_im, "sigma_c_imag_im");
1968 w(bin_edges, "spectral_bin_edges");
1969 w(spectral, "spectral_weights");
1970 w(weight_below, "spectral_weight_below");
1971 w(weight_above, "spectral_weight_above");
1972 w(weight_total, "pole_weight_total");
1973 w(first_moment, "pole_first_moment");
1974 if (dopt.plot_steps > 0) {
1975 w(dopt.plot_steps, "curve_steps");
1976 w(dopt.plot_spacing, "curve_spacing");
1977 w(curves, "sigma_c_curves");
1978 }
1979 }
1980 {
1981 CheckpointWriter w = cpf.getWriter("/screening");
1982 w(std::string(
1983 "W_c = W - v in modes s (omegas) and in the plasmon-pole frame i "
1984 "(eigenvectors of eps^-1(0)): eps^-1_ii(i nu) - 1 = -sum_s a_is "
1985 "Omega_s/(nu^2 + Omega_s^2); frame_moments(i,k) = sum_s a_is "
1986 "Omega_s^(k-1); frame_weights = -(eps^-1(0) - 1)_ii"),
1987 "description");
1988 w(scr.omegas, "omegas");
1989 w(Eigen::VectorXf(scr.strength.cast<float>()), "strength");
1990 w(scr.frame_weights, "frame_weights");
1991 w(scr.frame_moments, "frame_moments");
1992 w(Eigen::MatrixXf(scr.frame_eps_inv_imag.cast<float>()),
1993 "frame_eps_inv_imag");
1994 w(nu, "imag_nu");
1995 }
1996 const double seconds =
1997 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
1998 .count();
2000 << TimeStamp() << " Sigma dump: " << nspec << " of " << qptotal_
2001 << " levels with spectra, " << scr.omegas.size() << " screening modes, "
2002 << seconds << " s" << std::flush;
2003}
2004
2005} // namespace xtp
2006} // namespace votca
virtual std::unique_ptr< T > Create(const key_t &key, args_t &&...arguments)
Anderson mixing as convergence acceleration in SCF/fixed point problems.
void UpdateInput(const Eigen::VectorXd &newInput)
const Eigen::VectorXd MixHistory()
void UpdateOutput(const Eigen::VectorXd &newOutput)
void Configure(const Index order, const double alpha)
CheckpointWriter getWriter()
static Eigen::MatrixXd DressingMatrix(const Eigen::MatrixXd &R)
S = (1 + R)^(1/2), the dressing of the auxiliary index that turns the bare interaction into u = v + v...
double value(double frequency, EvalStage stage=EvalStage::Other) const
Definition gw.h:406
const QPStats & GetStats() const
Definition gw.h:417
double deriv(double frequency) const
Definition gw.h:410
boost::optional< double > SolveQP_Grid_Windowed(double intercept0, double frequency0, Index gw_level, double left_limit, double right_limit, bool allow_rejected_return=true, QPStats *stats=nullptr) const
Definition gw.cc:986
Index qptotal_
Definition gw.h:310
DFTTimings timings_
Definition gw.h:320
Eigen::MatrixXd reaction_field_
Definition gw.h:324
void setReactionField(const Eigen::MatrixXd &R)
Screen by a static polarizable environment (embedded GW).
Definition gw.cc:72
Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > DiagonalizeQPHamiltonian() const
Definition gw.cc:135
void PrintGWA_Energies() const
Definition gw.cc:142
Eigen::VectorXd tracked_change_
Definition gw.h:473
double qp_midgap_
Definition gw.h:464
void DumpSigma(const sigma_dump_options &dopt, const std::string &gw_mode, const std::string &version)
Write the self-energy and screening data of the finished GW (G0W0 or evGW, ppm or exact) to a separat...
Definition gw.cc:1726
RPA rpa_
Definition gw.h:352
boost::optional< qp_solver::RootCandidate > SolveQP_Tracked(double intercept0, double frequency0, Index gw_level, QPStats *stats) const
Definition gw.cc:739
void PrintQSGW_Energies(const std::string &seed_label, const Eigen::VectorXd &seed_energies, const Eigen::VectorXd &qsgw_energies) const
Print a two-column comparison of seed (G0W0 or evGW) vs converged QSGW quasiparticle energies.
Definition gw.cc:225
void PrintCompetingRoots(Log::Level level) const
Definition gw.cc:565
void CalculateQSGW()
Run quasiparticle self-consistent GW (QSGW).
Definition gw.cc:1187
bool Converged(const Eigen::VectorXd &e1, const Eigen::VectorXd &e2, double epsilon) const
Definition gw.cc:1134
Index qp_iterations_
Definition gw.h:349
bool tracking_active_
Definition gw.h:474
void configure(const options &opt)
Definition gw.cc:43
boost::optional< double > SolveQP_Grid_Windowed_Adaptive(double intercept0, double frequency0, Index gw_level, double left_limit, double right_limit, bool allow_rejected_return=true, QPStats *stats=nullptr) const
Definition gw.cc:780
options opt_
Definition gw.h:339
Eigen::MatrixXd SigmaCurves(const std::vector< Index > &levels, Index steps, double spacing) const
Definition gw.cc:1634
Eigen::VectorXd qp_solution_
Definition gw.h:317
Eigen::MatrixXd getHQP() const
Definition gw.cc:129
Index tracked_local_total_
Definition gw.h:476
Eigen::VectorXd SolveQP(const Eigen::VectorXd &frequencies) const
Definition gw.cc:590
TCMatrix_gwbse & Mmn_
Definition gw.h:343
Index screening_builds_
Definition gw.h:348
Index gw_sc_iteration_
Definition gw.h:350
void PrintReactionFieldShifts() const
Definition gw.cc:88
Eigen::VectorXd rpa_energies_solved_
Definition gw.h:318
qp_solver::Stats QPStats
Definition gw.h:43
boost::optional< double > SolveQP_Grid_Windowed_Dense(double intercept0, double frequency0, Index gw_level, double left_limit, double right_limit, bool allow_rejected_return=true, QPStats *stats=nullptr) const
Definition gw.cc:855
Eigen::MatrixXd Sigma_c_
Definition gw.h:323
qp_solver::RootCandidate QPRootCandidate
Definition gw.h:44
void PrintQSGW_Composition(double threshold=0.01) const
Print the dominant DFT-KS orbital contributions to each converged QSGW quasiparticle state.
Definition gw.cc:182
Eigen::MatrixXd Sigma_reac_
Definition gw.h:328
Eigen::VectorXd qsgw_seed_energies_
Definition gw.h:332
const Eigen::VectorXd & dft_energies_
Definition gw.h:345
std::unique_ptr< Sigma_base > sigma_
Definition gw.h:341
void CalculateHQP()
Definition gw.cc:1147
std::vector< qp_solver::CompetingRoots > competing_roots_
Definition gw.h:467
Eigen::VectorXd qsgw_final_energies_
Definition gw.h:337
Logger & log_
Definition gw.h:342
Eigen::VectorXd getGWAResults() const
Definition gw.cc:554
Eigen::VectorXd tracked_Z_
Definition gw.h:472
void DressForEnvironment()
Definition gw.cc:78
qp_solver::WindowDiagnostics QPWindowDiagnostics
Definition gw.h:45
double CalcHomoLumoShift(Eigen::VectorXd frequencies) const
Definition gw.cc:122
boost::optional< double > SolveQP_Grid(double intercept0, double frequency0, Index gw_level, QPStats *stats=nullptr) const
Definition gw.cc:1040
const Eigen::MatrixXd & vxc_
Definition gw.h:344
void RecordCompetingRoots(Index gw_level, const std::vector< QPRootCandidate > &roots, double chosen) const
Definition gw.h:480
void PrintQP_Energies(const Eigen::VectorXd &qp_diag_energies) const
Definition gw.cc:252
Index tracked_local_
Definition gw.h:475
void PlotSigma(std::string filename, Index steps, double spacing, std::string states)
Definition gw.cc:1666
boost::optional< double > SolveQP_FixedPoint(double intercept0, double frequency0, Index gw_level, QPStats *stats=nullptr) const
Definition gw.cc:1116
Eigen::VectorXd ScissorShift_DFTlevel(const Eigen::VectorXd &dft_energies) const
Definition gw.cc:279
Eigen::MatrixXd Sigma_x_
Definition gw.h:322
boost::optional< double > SolveQP_Linearisation(double intercept0, double frequency0, Index gw_level, QPStats *stats=nullptr) const
Definition gw.cc:761
void CalculateGWPerturbation()
Definition gw.cc:287
Eigen::MatrixXd qsgw_rotation_
Definition gw.h:330
Eigen::MatrixXd dressing_
Definition gw.h:326
Eigen::MatrixXd core_exchange_
Definition gw.h:347
ScreeningHook screening_hook_
Definition gw.h:325
Eigen::VectorXd tracked_root_
Definition gw.h:471
std::vector< Index > CreateIndexVector(const std::string &Ids) const
std::string CreateIndexString(const std::vector< Index > &indeces) const
static std::string Usage()
Newton Rapson rootfinder for 1d functions.
double FindRoot(const Func &f, double x0)
When evGW rebuilds the screening W.
void Built(const Eigen::VectorXd &energies)
W has just been built from these energies.
void Configure(Mode mode, double ratio, Index max_inner)
static std::string Name(Mode mode)
Next Decide(double residual, const Eigen::VectorXd &new_energies, double limit, double *drift_out=nullptr)
static Mode Parse(const std::string &name)
Index inner() const
QP iterations since W was last built (before the current one).
Timestamp returns the current time as a string Example: cout << TimeStamp().
Definition logger.h:224
#define XTP_LOG(level, log)
Definition logger.h:40
const double ev2hrt
Definition constants.h:54
const double hrt2ev
Definition constants.h:53
const double Pi
Definition constants.h:36
Index getMaxThreads()
Definition eigen.h:145
void Cite(const std::string &key)
marks a reference as used (thread safe; unknown keys are printed as such)
Definition citations.cc:289
boost::optional< RootCandidate > SolveQP_Tracked(QPFunc &fqp, double center, double halfwidth, double Z_previous, double min_Z_fraction, const SolverOptions &opt, bool use_brent=false)
boost::optional< double > SolveQP_Grid_Windowed(QPFunc &fqp, double frequency0, double left_limit, double right_limit, Index gw_sc_iteration, const SolverOptions &opt, WindowDiagnostics *wdiag=nullptr, std::vector< RootCandidate > *accepted_roots_out=nullptr, std::vector< RootCandidate > *rejected_roots_out=nullptr, bool use_brent=false)
auto PrefetchIfAvailable(const QPFunc &fqp, const std::vector< double > &nodes, int) -> decltype(fqp.Prefetch(nodes), void())
std::string LargestResiduals(const Eigen::VectorXd &solution, const Eigen::VectorXd &input, Index first_level, Index n=5)
void NormalizeGridSearchOptions(Opt &opt)
boost::optional< double > LinearisedRoot(double w0, double f0, double fprime)
const RootCandidate & SelectRoot(const std::vector< RootCandidate > &roots, const SolverOptions &opt)
boost::optional< RootCandidate > RefineQPInterval(double lowerbound, double f_lowerbound, double upperbound, double f_upperbound, const QPFunc &f, double reference, const SolverOptions &opt, bool use_brent)
Charge transport classes.
Definition ERIs.h:28
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26
static Level current_level
Definition globals.h:30
Level
be loud and noisy
Definition globals.h:28
Pole sums of the exact (RPA spectral) correlation self-energy.
const Eigen::VectorXd & energies
const Eigen::VectorXd & omegas
Options of DumpSigma (energies in Hartree unless noted).
Definition gw.h:269
void Add(const Stats &other)
std::size_t TotalSigmaCalls() const