1#ifndef LINEARALGEBRA_SRC_MOLPRO_LINALG_ITSOLV_ITERATIVESOLVERTEMPLATE_H
2#define LINEARALGEBRA_SRC_MOLPRO_LINALG_ITSOLV_ITERATIVESOLVERTEMPLATE_H
3#include <molpro/Profiler.h>
4#include <molpro/iostream.h>
5#include <molpro/linalg/itsolv/IterativeSolver.h>
6#include <molpro/linalg/itsolv/Logger.h>
7#include <molpro/linalg/itsolv/MetricChecker.h>
8#include <molpro/linalg/itsolv/subspace/ISubspaceSolver.h>
9#include <molpro/linalg/itsolv/subspace/IXSpace.h>
10#include <molpro/linalg/itsolv/subspace/Matrix.h>
11#include <molpro/linalg/itsolv/subspace/util.h>
12#include <molpro/linalg/itsolv/util.h>
13#include <molpro/linalg/itsolv/wrap.h>
14#include <molpro/profiler/Profiler.h>
27 auto batches = std::vector<std::pair<size_t, size_t>>{};
39template <
class R,
class Q>
43 bool empty()
const {
return r.empty() &&
q.empty(); }
48 const size_t oP,
const size_t nP) {
49 auto vectorP = std::vector<std::vector<T>>{};
50 for (
auto root : roots) {
51 vectorP.emplace_back();
52 for (
size_t j = 0;
j < nP; ++
j)
53 vectorP.back().push_back(solutions(root, oP +
j));
58template <
class R,
typename T>
60 assert(residual.size() >= errors.size());
61 for (
size_t i = 0;
i < errors.size(); ++
i)
69 for (
size_t i = 0;
i < errors.size(); ++
i) {
73 auto working_set = std::vector<int>{};
75 std::transform(begin(
ordered_errors), end, std::back_inserter(working_set), [](
const auto&
el) {
return el.second; });
76 std::sort(working_set.begin(), working_set.end());
93template <
typename Scalar>
95 static constexpr std::string_view
name =
"SolveStarted";
104 return std::format(
"n_roots = {}, max_iter = {}, convergence threshold = {}, P-space dimension = {}, initial "
105 "guess generated = {}",
106 p.n_roots,
p.max_iter,
stringify(
p.convergence_threshold),
p.pspace_size,
107 p.initial_guess_generated);
114template <
typename Scalar>
116 static constexpr std::string_view
name =
"NewIteration";
128template <
typename Scalar>
130 static constexpr std::string_view
name =
"IterationCompleted";
140 return std::format(
"{}, roots {}, errors {}, values {}, next {}",
p.iter,
stringify(
p.roots),
stringify(
p.errors),
148template <
typename Scalar>
150 static constexpr std::string_view
name =
"SolveFinished";
158 return std::format(
"iterations = {}, converged = {}, errors {}, values {}",
p.iterations,
p.converged,
167 static constexpr std::string_view
name =
"IterationReport";
175 static constexpr std::string_view
name =
"SummaryReport";
186template <
template <
class,
class,
class>
class Solver,
class R,
class Q,
class P>
189 using typename Solver<R, Q, P>::fapply_on_p_type;
190 using typename Solver<R, Q, P>::fapply_metric_type;
191 using typename Solver<R, Q, P>::PSpaceMetric;
192 using typename Solver<R, Q, P>::scalar_type;
193 using typename Solver<R, Q, P>::value_type;
194 using typename Solver<R, Q, P>::value_type_abs;
195 using typename Solver<R, Q, P>::VectorP;
217 throw std::logic_error(
"The actions of the metric declared with set_metric() have to be given to add_vector()");
223 throw std::logic_error(
"Actions of a metric given to add_vector(), but no metric was declared with set_metric()");
226 throw std::invalid_argument(
"IterativeSolver::add_vector(): fewer actions of the metric than parameters");
233 fapply_metric_type apply_metric = {})
override {
238 throw std::invalid_argument(
"A function applying the metric has to be given exactly for MetricStorage::OnTheFly");
239 if (
m_xspace->dimensions().nX() == 0)
252 int add_vector(std::vector<R>& parameters, std::vector<R>& actions)
override {
262 throw std::logic_error(
263 "With a metric, the P space has to be added with the overload of add_p() taking the metric "
271 throw std::logic_error(
"A metric in the P space was given, but no metric was declared with set_metric()");
273 throw std::invalid_argument(
"A function applying the metric in the P space is needed unless the metric is "
274 "applied on the fly");
287 void solution(
const std::vector<int>& roots, std::vector<R>& parameters, std::vector<R>& residual)
override {
290 void solution(R& parameters, R& residual)
override {
294 void solution_params(
const std::vector<int>& roots, std::vector<R>& parameters)
override {
327 if (
options.convergence_threshold)
342 auto options = std::make_shared<Options>();
365 cout <<
", |residual| = ";
421 scalar_type
value()
const override {
423 :
nan(
"molpro::linalg::itsolv::IterativeSolver::value");
427 m_profiler = std::shared_ptr<molpro::profiler::Profiler>(std::shared_ptr<molpro::profiler::Profiler>{}, &
profiler);
431 throw std::invalid_argument(
"IterativeSolver::set_profiler: null profiler");
434 const std::shared_ptr<molpro::profiler::Profiler>&
profiler()
const override {
return m_profiler; }
439 return this->eigenvalues();
449 throw std::invalid_argument(
"A problem with a metric has to be solved with the overload of "
450 "IterativeSolver::solve() taking buffers for the actions of the metric");
457 throw std::invalid_argument(
"IterativeSolver::solve(): metric_actions has to hold as many vectors as parameters");
464 bool solve(std::vector<R>& parameters, std::vector<R>& actions,
const Problem<R>& problem,
471 value_type_abs
step = 1
e-4;
472 if (this->nonlinear()) {
477 std::cout <<
"value0 " <<
value0 << std::endl;
501 value_type(12 *
step);
508 auto check_scaling = [&](
const auto& apply,
const std::string& name) {
519 std::cout <<
"Length of " << name <<
": " <<
norm2_residual <<
", scaling defect: " <<
norm2 << std::endl;
544 if (parameters.empty())
545 throw std::runtime_error(
"Empty container passed to IterativeSolver::solve()");
546 if (parameters.size() != actions.size())
547 throw std::runtime_error(
"Inconsistent container sizes in IterativeSolver::solve()");
555 this->
m_logger->enable_data_dumps(
true);
564 throw std::runtime_error(
"Default initial guess requested, but diagonal elements are not available");
565 std::unique_ptr<Q> diagonals;
567 diagonals.reset(
new Q{
m_handlers->qr().copy(actions.at(0))});
568 std::unique_ptr<Q> metric_diagonals;
571 throw std::invalid_argument(
"The problem provides diagonals() but not metric_diagonals(), without which the "
572 "default preconditioner would ignore the metric");
573 metric_diagonals.reset(
new Q{
m_handlers->qr().copy(actions.at(0))});
577 std::unique_ptr<Q>
ratios;
581 m_handlers->rq().copy(parameters.at(0), *diagonals);
583 static_cast<const R*
>(
nullptr),
false);
587 std::vector<P> pspace;
599 int nwork = parameters.size();
617 std::vector<int> roots;
628 if (this->nonlinear())
630 else if (iter > 0
or pspace.empty())
639 if (this->nonlinear()) {
640 value = problem.
residual(*parameters.begin(), *actions.begin());
642 }
else if (iter > 0
or pspace.empty()) {
654 if (metric_diagonals) {
656 m_handlers->rq().copy(parameters.at(0), *diagonals);
662 m_handlers->rq().copy(parameters.at(0), *diagonals);
668 nwork = this->end_iteration(parameters, actions);
673 std::size_t(std::max(
nwork, 0))};
695 }
else if (!errors_converged) {
697 }
else if (!converged) {
700 this->
m_logger->info(
"Solver converged");
726 template <
typename ConstructRes
idual>
736 prof->start(
"apply metric");
737 const auto solutions =
cwrap(parameters.begin(), parameters.begin() + roots.size());
741 :
wrap(residual.begin(), residual.begin() + roots.size());
754 prof->start(
"apply");
770 prof->start(
"construct_solution (parameters)");
787 prof->start(
"construct_solution (residual)");
791 prof->start(
"apply_p");
800 std::shared_ptr<Logger>
logger)
803 m_profiler_saved_depth(m_profiler->get_max_depth()) {
812 if (molpro::mpi::rank_global() == 0) {
813 auto file =
options()->parameter(
"PROFILER_OUTPUT",
"");
815 std::find_if(
file.begin(),
file.end(), [](
unsigned char ch) { return !std::isspace(ch); }) !=
file.end())
818 if (molpro::mpi::rank_global() == 0) {
819 auto file =
options()->parameter(
"PROFILER_DOTGRAPH",
"");
821 std::find_if(
file.begin(),
file.end(), [](
unsigned char ch) { return !std::isspace(ch); }) !=
file.end())
824 }
catch (
const std::exception&
e) {
825 std::cerr <<
"~IterativeSolverTemplate: failed to write profiler output: " <<
e.what() << std::endl;
827 std::cerr <<
"~IterativeSolverTemplate: failed to write profiler output" << std::endl;
841 std::optional<std::pair<Q, Q>> u;
851 std::cout <<
"<v|M v> = " <<
vmv <<
" is not real" << (
positive ?
" and non-negative" :
"") << std::endl;
856 const auto scale = std::sqrt(std::abs(
m_handlers->qq().dot(u->first, u->first)) *
857 std::abs(
m_handlers->qq().dot(u->second, u->second))) *
863 std::cout <<
"The metric is not Hermitian: <u|M v> = " <<
umv <<
", <M u|v> = " <<
conjugate(
muv)
865 }
else if (verbosity > 0)
866 std::cout <<
"Hermiticity defect of the metric: " <<
defect << std::endl;
889 const std::vector<value_type_abs>& solution_norms, std::vector<value_type_abs>&
errors) {
891 if (!solution_norms.empty())
892 for (
size_t i = 0;
i < roots.size(); ++
i)
893 errors[
i] /= solution_norms[roots[
i]];
901 const std::vector<value_type_abs>& solution_norms,
902 std::vector<value_type_abs>&
errors) {
913 auto prof =
profiler()->push(
"itsolv::add_p");
915 throw std::runtime_error(
"P space must be empty or at least as large as number of roots sought");
934 if (pp_metric_matrix.
size() !=
n *
n)
935 throw std::invalid_argument(
"The metric matrix in the P space must have as many rows and columns as there are "
943 std::vector<value_type>(pp_metric_matrix.
data(), pp_metric_matrix.
data() +
n *
n), {n, n}),
950 throw std::invalid_argument(
"This solver does not support the requested kind of metric");
954 throw std::logic_error(
"The metric, or how its actions are obtained, cannot be changed once the subspace is not "
977 auto outer =
profiler()->push(
"itsolv::add_vector");
979 m_logger->trace(
"IterativeSolverTemplate::add_vector iteration = ",
m_stats->iterations);
980 m_logger->debug(
"IterativeSolverTemplate::add_vector size of {params, actions, working_set} = ", parameters.size(),
983 throw std::runtime_error(
984 "Solver contains P space but no valid apply_p function. Make sure add_p was called correctly.");
986 throw std::runtime_error(
"Solver contains P space but no valid function applying the metric to it. Make sure "
987 "add_p was called correctly.");
997 prof->start(
"update_qspace");
1004 prof->start(
"solve_and_generate_working_set");
1023 auto p = prof->push(
"itsolv::solve_and_generate_working_set");
1024 prof->start(
"itsolv::solve");
1028 prof->start(
"itsolv::temp_solutions");
1035 const auto solution_norms =
1038 : std::
vector<value_type_abs>{};
1042 std::iota(begin(roots), end(roots),
start_sol);
1043 auto errors = std::vector<value_type_abs>(roots.size(), 0);
1044 solution_with_errors(roots, parameters, action,
scratch, solution_norms, errors);
1046 for (
size_t i = 0;
i < roots.size(); ++
i)
1047 temp_solutions.emplace_back(m_handlers->qr().copy(parameters[
i]), m_handlers->qr().copy(action[
i]));
1048 m_stats->q_creations += 2 * roots.size();
1050 m_subspace_solver->set_error(roots, errors);
1055 m_errors = m_subspace_solver->errors();
1057 m_convergence_threshold_value);
1058 for (
size_t i = 0;
i < m_working_set.size(); ++
i) {
1059 size_t root = m_working_set[
i];
1065 throw std::logic_error(
"incorrect ordering of roots");
1066 if (root >
i && root < parameters.size()) {
1067 m_handlers->rr().copy(parameters[
i], parameters[root]);
1068 m_handlers->rr().copy(action[
i], action[root]);
1072 m_logger->trace(
"add_vector::errors = ", m_errors);
1073 return m_working_set.size();
1076 template <
typename TTT>
1078 if (m_solutions_outdated)
1079 throw std::logic_error(
"solutions are not available after an end_iteration() that reset the D space; they are "
1080 "returned in its parameters and available again after the next add_vector()");
1082 throw std::runtime_error(
"asking for more roots than parameters");
1084 if (!roots.empty() &&
1085 size_t(*std::max_element(roots.begin(), roots.end())) >= m_subspace_solver->solutions().rows())
1086 throw std::runtime_error(
"asking for more roots than there are solutions");
1104 const auto nguess = std::min(parameters.size(), m_working_set.size());
1107 this->m_logger->info(
"No initial guess generated, as no roots remain in the working set");
1110 auto guess = m_handlers->qq().select(
nguess, diagonals);
1113 this->m_logger->info(
"Initial guess generated from diagonal elements for ",
guess.size(),
" vectors");
1114 for (
const auto&
g :
guess) {
1115 m_handlers->rp().copy(parameters[root], P{{
g.first, 1}});
1117 m_logger->debug(
"-> initial guess with index ",
g.first);
1129 auto selectp = m_handlers->qq().select(m_max_p, diagonals);
1135 [](
const auto&
a,
const auto&
b) {
1136 return real_part(a.second) < real_part(b.second);
1147 this->m_logger->warn(
"P space smaller than number of roots is not used, starting from the diagonal elements "
1148 "instead; dimension and number of roots",
1153 this->m_logger->info(
"P-space dimension, threshold and limit",
selectp.size(), m_p_threshold, m_max_p);
1157 this->m_logger->debug(std::format(
"P space element {}: {:.6e}",
s.first,
double(
real_part(
s.second))));
1160 std::vector<P> pspace;
1162 pspace.emplace_back((P){{
s.first, 1}});
1173 std::pair<std::vector<value_type>, std::vector<value_type>>
1191 std::pair<std::vector<value_type>, std::vector<value_type>>&
matrices,
1193 fapply_on_p_type
apply_on_p = [&problem](
const std::vector<std::vector<value_type>>&
pcoeff,
1216 value_type_abs m_convergence_threshold{1.0e-8};
1217 value_type_abs m_convergence_threshold_value{
1218 std::numeric_limits<value_type_abs>::max()};
1221 fapply_on_p_type m_apply_p = {};
1222 std::optional<Verbosity> m_verbosity = {};
1223 int m_max_iter = 100;
1227 fapply_metric_type m_apply_metric = {};
1228 bool m_check_metric =
true;
1230 fapply_on_p_type m_apply_metric_p = {};
1231 value_type_abs m_p_threshold = std::numeric_limits<value_type_abs>::max();
1233 mutable std::shared_ptr<molpro::profiler::Profiler> m_profiler;
1234 int m_profiler_saved_depth;
1236 bool m_end_iteration_needed =
true;
1237 bool m_solutions_outdated =
false;
Enhances various operations between pairs of arrays and allows dynamic code injection with uniform in...
Definition ArrayHandler.h:163
Non-owning container taking a pointer to the data buffer and its size and exposing routines for itera...
Definition Span.h:31
size_type size() const
Definition Span.h:80
iterator data()
Definition Span.h:69
Class, containing a collection of array handlers used in IterativeSolver Provides a Builder sub-class...
Definition ArrayHandlers.h:25
Implements IterativeSolver interface that is common to all solvers.
Definition IterativeSolverTemplate.h:187
std::vector< value_type_abs > m_value_errors
value errors from the most recent solution
Definition IterativeSolverTemplate.h:1213
void check_metric_positive()
For a positive (semi)definite metric, throws if the metric matrix shows that it is not,...
Definition IterativeSolverTemplate.h:959
void set_convergence_threshold(value_type_abs thresh) override
Definition IterativeSolverTemplate.h:389
void iteration_report() const
Definition IterativeSolverTemplate.h:372
MetricKind metric_kind() const override
Definition IterativeSolverTemplate.h:247
void set_profiler(std::shared_ptr< molpro::profiler::Profiler > profiler) override
Definition IterativeSolverTemplate.h:429
void set_profiler(molpro::profiler::Profiler &profiler) override
Definition IterativeSolverTemplate.h:425
std::optional< Verbosity > m_verbosity
how much output to print in solve()
Definition IterativeSolverTemplate.h:1222
value_type_abs m_p_threshold
threshold for selecting P space
Definition IterativeSolverTemplate.h:1231
size_t add_p(const CVecRef< P > &pparams, const array::Span< value_type > &pp_action_matrix, const VecRef< R > ¶meters, const VecRef< R > &actions, fapply_on_p_type apply_p) override
Definition IterativeSolverTemplate.h:259
fapply_on_p_type m_apply_metric_p
adds the action of the metric on the P space, if its actions are stored
Definition IterativeSolverTemplate.h:1230
value_type_abs convergence_threshold_value() const override
Definition IterativeSolverTemplate.h:392
int get_max_iter() const override
Definition IterativeSolverTemplate.h:414
void solution_params(const std::vector< int > &roots, std::vector< R > ¶meters) override
Definition IterativeSolverTemplate.h:294
void report(std::ostream &cout, bool endl=true) const override
Definition IterativeSolverTemplate.h:357
std::vector< int > m_working_set
indices of roots in the working set
Definition IterativeSolverTemplate.h:1214
value_type_abs convergence_threshold() const override
Definition IterativeSolverTemplate.h:390
void generate_initial_guess_from_diagonals(const VecRef< R > ¶meters, const Q &diagonals)
Fills parameters with unit vectors at the positions of the lowest diagonal elements.
Definition IterativeSolverTemplate.h:1102
void summary_report() const
Definition IterativeSolverTemplate.h:378
scalar_type value() const override
Definition IterativeSolverTemplate.h:421
std::shared_ptr< subspace::IXSpace< R, Q, P > > m_xspace
manages the subspace and associated data
Definition IterativeSolverTemplate.h:1210
size_t initialise_pspace(const std::vector< P > &pspace, const Problem< R > &problem, std::pair< std::vector< value_type >, std::vector< value_type > > &matrices, const VecRef< R > ¶meters, const VecRef< R > &actions)
Adds the P space to the subspace with the matrices of pspace_problem_matrices(); returns the working-...
Definition IterativeSolverTemplate.h:1190
void set_n_roots(size_t roots) override
Definition IterativeSolverTemplate.h:318
std::vector< scalar_type > current_values() const
The values reported in the iteration events: eigenvalues of eigensystems, the function value otherwis...
Definition IterativeSolverTemplate.h:437
bool solve_impl(const VecRef< R > ¶meters, const VecRef< R > &actions, const VecRef< R > &metric_actions, const Problem< R > &problem, bool generate_initial_guess)
Implements both overloads of solve(), with empty metric_actions for a problem without a metric.
Definition IterativeSolverTemplate.h:542
std::shared_ptr< ArrayHandlers< R, Q, P > > m_handlers
Array handlers.
Definition IterativeSolverTemplate.h:1209
fapply_on_p_type m_apply_p
function that evaluates effect of action on the P space projection
Definition IterativeSolverTemplate.h:1221
virtual void compute_errors(const std::vector< int > &roots, const CVecRef< R > ¶ms, const CVecRef< R > &residuals, const std::vector< value_type_abs > &solution_norms, std::vector< value_type_abs > &errors)
Computes the errors of roots, given their parameters and residuals; by default the norms of the resid...
Definition IterativeSolverTemplate.h:888
int add_vector_impl(const VecRef< R > ¶meters, const VecRef< R > &actions, const VecRef< R > &metric_actions)
Implements add_vector()
Definition IterativeSolverTemplate.h:976
void solution(const std::vector< int > &roots, std::vector< R > ¶meters, std::vector< R > &residual) override
Definition IterativeSolverTemplate.h:287
void set_max_iter(int n) override
Definition IterativeSolverTemplate.h:413
MetricKind m_metric_kind
the metric declared with set_metric()
Definition IterativeSolverTemplate.h:1225
void check_consistent_number_of_roots_and_solutions(const std::vector< TTT > &roots, const size_t nparams)
Definition IterativeSolverTemplate.h:1077
virtual void solution_with_errors(const std::vector< int > &roots, const VecRef< R > ¶meters, const VecRef< R > &residual, const VecRef< R > &scratch, const std::vector< value_type_abs > &solution_norms, std::vector< value_type_abs > &errors)
Constructs the parameters and residuals of roots, as solution_impl() does, and computes their errors,...
Definition IterativeSolverTemplate.h:899
detail::MetricChecker< R, Q, P > m_metric_checker
checks the properties of the metric
Definition IterativeSolverTemplate.h:1229
virtual void prepare_solve(const Problem< R > &problem, const VecRef< R > &actions)
Prepares solving problem in solve(), after the problem has been checked and before the solver changes...
Definition IterativeSolverTemplate.h:539
void set_max_p(int n) override
Definition IterativeSolverTemplate.h:415
void construct_actions(const std::vector< int > &rows, const subspace::Matrix< value_type > &solutions, const VecRef< R > &actions)
Constructs the actions on the subspace vectors with the coefficients in the given rows of solutions.
Definition IterativeSolverTemplate.h:783
std::shared_ptr< subspace::ISubspaceSolver< R, Q, P > > m_subspace_solver
solves the subspace problem
Definition IterativeSolverTemplate.h:1211
void set_p_threshold(value_type_abs threshold) override
Definition IterativeSolverTemplate.h:417
std::vector< size_t > suggest_p(const CVecRef< R > &solution, const CVecRef< R > &residual, size_t max_number, value_type_abs threshold) override
Definition IterativeSolverTemplate.h:309
bool get_check_metric() const override
Definition IterativeSolverTemplate.h:249
int get_max_p() const override
Definition IterativeSolverTemplate.h:416
void solution_impl(const std::vector< int > &roots, const VecRef< R > ¶meters, const VecRef< R > &residual, const VecRef< R > &scratch, ConstructResidual &&construct_residual_with)
Implements solution(), with the residuals constructed by the given function in place of construct_res...
Definition IterativeSolverTemplate.h:727
size_t n_roots() const override
Definition IterativeSolverTemplate.h:316
std::vector< value_type_abs > m_errors
errors from the most recent solution
Definition IterativeSolverTemplate.h:1212
std::shared_ptr< Options > get_options() const override
Definition IterativeSolverTemplate.h:341
bool m_solutions_outdated
whether the subspace was changed since the solutions of its problem were found
Definition IterativeSolverTemplate.h:1237
void solution_impl(const std::vector< int > &roots, const VecRef< R > ¶meters, const VecRef< R > &residual, const VecRef< R > &scratch)
Implements solution()
Definition IterativeSolverTemplate.h:717
bool m_check_metric
whether the properties of the metric are checked
Definition IterativeSolverTemplate.h:1228
void construct_solutions(const std::vector< int > &rows, const subspace::Matrix< value_type > &solutions, const VecRef< R > ¶meters)
Constructs the subspace vectors with the coefficients in the given rows of solutions.
Definition IterativeSolverTemplate.h:766
size_t m_max_p
maximum size of P space
Definition IterativeSolverTemplate.h:1224
const subspace::Dimensions & dimensions() const override
Access dimensions of the subspace.
Definition IterativeSolverTemplate.h:420
const std::shared_ptr< molpro::profiler::Profiler > & profiler() const override
Definition IterativeSolverTemplate.h:434
bool verbosity_at_least(Verbosity v) const
Whether output of verbosity v is printed in solve(); everything is printed if no verbosity was set.
Definition IterativeSolverTemplate.h:1094
bool test_metric(const Problem< R > &problem, R &v0, R &v1, int verbosity, value_type_abs threshold) const
Tests that the metric of a problem is Hermitian, <u|M v> = <M u|v>, and, if its kind says so,...
Definition IterativeSolverTemplate.h:837
bool supports_metric(MetricKind kind) const override
Definition IterativeSolverTemplate.h:230
IterativeSolverTemplate(std::shared_ptr< subspace::IXSpace< R, Q, P > > xspace, std::shared_ptr< subspace::ISubspaceSolver< R, Q, P > > solver, std::shared_ptr< ArrayHandlers< R, Q, P > > handlers, std::shared_ptr< Statistics > stats, std::shared_ptr< Logger > logger)
Definition IterativeSolverTemplate.h:797
std::vector< P > select_pspace(const Q &diagonals)
Selects the P space from the lowest diagonal elements, subject to max_p and p_threshold.
Definition IterativeSolverTemplate.h:1128
virtual ~IterativeSolverTemplate()
Definition IterativeSolverTemplate.h:810
int add_vector(std::vector< R > ¶meters, std::vector< R > &actions) override
Definition IterativeSolverTemplate.h:252
bool test_problem(const Problem< R > &problem, R &v0, R &v1, int verbosity, value_type_abs threshold) const override
Definition IterativeSolverTemplate.h:469
void solution_params(R ¶meters) override
Definition IterativeSolverTemplate.h:306
virtual bool linearEigensystem() const
Definition IterativeSolverTemplate.h:906
const Statistics & statistics() const override
Definition IterativeSolverTemplate.h:355
const std::vector< value_type_abs > & errors() const override
Definition IterativeSolverTemplate.h:353
void solution(R ¶meters, R &residual) override
Definition IterativeSolverTemplate.h:290
size_t m_nroots
number of roots the solver is searching for
Definition IterativeSolverTemplate.h:1215
bool m_end_iteration_needed
whether end_iteration should be called after any preconditioner
Definition IterativeSolverTemplate.h:1236
void solution_params(const std::vector< int > &roots, const VecRef< R > ¶meters) override
Definition IterativeSolverTemplate.h:298
std::pair< std::vector< value_type >, std::vector< value_type > > pspace_problem_matrices(const std::vector< P > &pspace, const Problem< R > &problem, const bool metric, const bool store_metric_actions) const
Adds the P space to the subspace using the P-space kernel provided by problem; returns the working-se...
Definition IterativeSolverTemplate.h:1174
void check_pspace_metric(MetricKind kind, const CVecRef< P > &pparams, const array::Span< value_type > &pp_metric_matrix) const
Throws if the metric matrix in the P space is not given for a metric of this kind,...
Definition IterativeSolverTemplate.h:929
int add_vector(const VecRef< R > ¶meters, const VecRef< R > &actions) override
Definition IterativeSolverTemplate.h:215
void clearP() override
Definition IterativeSolverTemplate.h:281
bool solve(R ¶meters, R &actions, const Problem< R > &problem, bool generate_initial_guess=false) override
Definition IterativeSolverTemplate.h:461
bool end_iteration_needed() override
Definition IterativeSolverTemplate.h:1089
MetricStorage metric_storage() const override
Definition IterativeSolverTemplate.h:250
IterativeSolverTemplate(const IterativeSolverTemplate< Solver, R, Q, P > &)=delete
size_t n_added_vectors(const VecRef< R > ¶meters) const
The number of the given parameters that add_vector() takes up: no more than there are in the working ...
Definition IterativeSolverTemplate.h:967
MetricStorage m_metric_storage
how the actions of the metric are obtained
Definition IterativeSolverTemplate.h:1226
void report() const override
Definition IterativeSolverTemplate.h:384
const std::vector< int > & working_set() const override
Definition IterativeSolverTemplate.h:314
std::shared_ptr< Logger > m_logger
logger
Definition IterativeSolverTemplate.h:1220
void set_convergence_threshold_value(value_type_abs thresh) override
Definition IterativeSolverTemplate.h:391
virtual void set_value_errors()
Implementation class should overload this to set errors in the current values (e.g....
Definition IterativeSolverTemplate.h:876
bool solve(std::vector< R > ¶meters, std::vector< R > &actions, const Problem< R > &problem, bool generate_initial_guess=false) override
Definition IterativeSolverTemplate.h:464
void set_logger(std::shared_ptr< Logger > logger) override
Definition IterativeSolverTemplate.h:203
void set_options(const Options &options) override
Definition IterativeSolverTemplate.h:324
size_t add_p(const CVecRef< P > &pparams, const array::Span< value_type > &pp_action_matrix, const VecRef< R > ¶meters, const VecRef< R > &actions, fapply_on_p_type apply_p, const PSpaceMetric &metric) override
Definition IterativeSolverTemplate.h:268
int add_vector(const VecRef< R > ¶meters, const VecRef< R > &actions, const VecRef< R > &metric_actions) override
Definition IterativeSolverTemplate.h:221
int add_vector(R ¶meters, R &actions, value_type value=0) override
Definition IterativeSolverTemplate.h:255
value_type_abs m_convergence_threshold_value
value changes less than this mark a converged solution
Definition IterativeSolverTemplate.h:1217
IterativeSolverTemplate()=delete
virtual void combine_errors()
Implementation class can overload this to combine the errors of solutions, once those of all are know...
Definition IterativeSolverTemplate.h:874
size_t add_p_impl(const CVecRef< P > &pparams, const array::Span< value_type > &pp_action_matrix, const array::Span< value_type > &pp_metric_matrix, const VecRef< R > ¶meters, const VecRef< R > &actions, fapply_on_p_type apply_p)
Implements add_p(), with an empty pp_metric_matrix for a problem without a metric.
Definition IterativeSolverTemplate.h:910
virtual void construct_residual(const std::vector< int > &roots, const CVecRef< R > ¶ms, const VecRef< R > &actions, const detail::MetricSolutions< R, Q > &metric_solutions)=0
Constructs residual for given roots provided their parameters and actions.
void finalize() override
Definition IterativeSolverTemplate.h:1091
void set_verbosity(Verbosity v) override
Definition IterativeSolverTemplate.h:393
bool solve(const VecRef< R > ¶meters, const VecRef< R > &actions, const Problem< R > &problem, bool generate_initial_guess=false) override
Definition IterativeSolverTemplate.h:446
bool solve(const VecRef< R > ¶meters, const VecRef< R > &actions, const VecRef< R > &metric_actions, const Problem< R > &problem, bool generate_initial_guess=false) override
Definition IterativeSolverTemplate.h:454
void check_metric_change(MetricKind kind, MetricStorage storage) const
Throws if set_metric() with these arguments is not possible, apart from the function applying the met...
Definition IterativeSolverTemplate.h:948
void set_check_metric(bool check) override
Definition IterativeSolverTemplate.h:248
int m_max_iter
maximum number of iterations in solve()
Definition IterativeSolverTemplate.h:1223
std::shared_ptr< Statistics > m_stats
accumulates statistics of operations performed by the solver
Definition IterativeSolverTemplate.h:1219
size_t solve_and_generate_working_set(const VecRef< R > ¶meters, const VecRef< R > &action, const VecRef< R > &scratch={})
Solves the subspace problems and selects the working set of roots, returning their parameters and res...
Definition IterativeSolverTemplate.h:1020
value_type_abs get_p_threshold() const override
Definition IterativeSolverTemplate.h:418
Logger & logger() override
Definition IterativeSolverTemplate.h:210
fapply_metric_type m_apply_metric
applies the metric on the fly, if its actions are not stored
Definition IterativeSolverTemplate.h:1227
value_type_abs m_convergence_threshold
residual norms less than this mark a converged solution
Definition IterativeSolverTemplate.h:1216
void set_verbosity(int v) override
Definition IterativeSolverTemplate.h:394
Verbosity get_verbosity() const override
Definition IterativeSolverTemplate.h:412
void solution(const std::vector< int > &roots, const VecRef< R > ¶meters, const VecRef< R > &residual) override
Definition IterativeSolverTemplate.h:283
void set_metric(MetricKind kind, MetricStorage storage=MetricStorage::Stored, fapply_metric_type apply_metric={}) override
Definition IterativeSolverTemplate.h:232
IterativeSolverTemplate(IterativeSolverTemplate< Solver, R, Q, P > &&) noexcept=default
Interface for a specific iterative solver, it can add special member functions or variables.
Definition IterativeSolver.h:770
Logger class implementation. Provides (customizable) logging functionalities.
Definition Logger.h:370
Abstract class defining the problem-specific interface for the simplified solver interface to Iterati...
Definition IterativeSolver.h:125
virtual MetricKind metric_kind() const
The kind of metric M of the problem. Anything other than MetricKind::Identity turns the eigenproblem ...
Definition IterativeSolver.h:211
virtual void action(const CVecRef< R > ¶meters, const VecRef< R > &action) const
Calculate the action of the kernel matrix on a set of parameters. Used by linear solvers,...
Definition IterativeSolver.h:149
virtual MetricStorage metric_storage() const
How IterativeSolver::solve() obtains the actions of the metric on its subspace vectors,...
Definition IterativeSolver.h:221
virtual void precondition(const VecRef< R > &residual, const std::vector< value_t > &shift) const
Apply preconditioning to a residual vector in order to predict a step towards the solution.
Definition IterativeSolver.h:175
virtual bool metric_diagonals(R &d) const
Provide the diagonal elements of the metric. For a problem with a metric that provides diagonals(),...
Definition IterativeSolver.h:256
virtual void p_metric_action(const std::vector< std::vector< value_t > > &p_coefficients, const CVecRef< P > &pparams, const VecRef< container_t > &metric_actions) const
Calculate the action of the metric on a set of vectors in the P space, for a problem with a metric (m...
Definition IterativeSolver.h:311
virtual bool diagonals(container_t &d) const
Optionally provide the diagonal elements of the underlying kernel. If implemented and returning true,...
Definition IterativeSolver.h:161
virtual void precondition_with_metric(const VecRef< R > &residual, const std::vector< value_t > &shift, const R &diagonals, const R &metric_diagonals) const
Apply preconditioning to a residual vector of a generalised eigenproblem. Used instead of preconditio...
Definition IterativeSolver.h:200
virtual void p_action(const std::vector< std::vector< value_t > > &p_coefficients, const CVecRef< P > &pparams, const VecRef< container_t > &actions) const
Calculate the action of the kernel matrix on a set of vectors in the P space.
Definition IterativeSolver.h:284
virtual std::vector< value_t > pp_action_matrix(const std::vector< P > &pparams) const
Calculate the kernel matrix in the P space.
Definition IterativeSolver.h:272
virtual void action_with_metric(const CVecRef< R > ¶meters, const VecRef< R > &actions, const VecRef< R > &metric_actions) const
Calculate the actions of the kernel and of the metric on a set of parameters together....
Definition IterativeSolver.h:241
virtual void metric_action(const CVecRef< R > ¶meters, const VecRef< R > &metric_actions) const
Calculate the action of the metric on a set of parameters. Called only if metric_kind() is not Metric...
Definition IterativeSolver.h:229
virtual value_t residual(const R ¶meters, R &residual) const
Calculate the residual vector. Used by non-linear solvers (NonLinearEquations, Optimize) only.
Definition IterativeSolver.h:141
virtual bool test_parameters(unsigned int instance, R ¶meters) const
Provide values of R vectors for testing the problem class. For use in a non-linear solver,...
Definition IterativeSolver.h:326
virtual std::vector< value_t > pp_metric_matrix(const std::vector< P > &pparams) const
Calculate the metric matrix in the P space, for a problem with a metric (metric_kind())
Definition IterativeSolver.h:295
Checks that the metric of a generalised problem has the properties that its kind declares,...
Definition MetricChecker.h:28
static void check_positive(const subspace::Matrix< value_type > &metric, const subspace::Matrix< value_type > &overlap)
Definition MetricChecker.h:177
void check_hermitian(const CVecRef< R > ¶ms, const CVecRef< R > &metric_actions, const subspace::IXSpace< R, Q, P > &xspace, ArrayHandlers< R, Q, P > &handlers) const
Checks that the metric is Hermitian on new parameters before they are added to the subspace.
Definition MetricChecker.h:66
Full subspace.
Definition IXSpace.h:21
Matrix container that allows simple data access, slicing, copying and resizing without loosing data.
Definition Matrix.h:32
static std::shared_ptr< Profiler > single()
std::vector< std::vector< T > > construct_vectorP(const std::vector< int > &roots, const subspace::Matrix< T > &solutions, const size_t oP, const size_t nP)
Definition IterativeSolverTemplate.h:47
std::vector< std::pair< size_t, size_t > > parameter_batches(const size_t nsol, const size_t nparam)
Definition IterativeSolverTemplate.h:26
std::vector< int > select_working_set(const size_t nw, const std::vector< T > &errors, const T threshold, const std::vector< T > &value_errors, const T value_threshold)
Definition IterativeSolverTemplate.h:66
void update_errors(std::vector< T > &errors, const CVecRef< R > &residual, array::ArrayHandler< R, R > &handler)
Definition IterativeSolverTemplate.h:59
void precondition_default(const VecRef< T > &action, const std::vector< S > &shift, const T &diagonals, const T *metric_diagonals, const bool regularise)
Definition IterativeSolver.h:44
decltype(std::abs(std::declval< Scalar >())) real_t
Definition Logger.h:89
std::string stringify(const T &t, std::size_t precision=default_precision)
Converts the given object into a string.
Definition Logger.h:178
auto overlap(const CVecRef< R > &left, const CVecRef< Q > &right, array::ArrayHandler< Z, W > &handler) -> std::enable_if_t< detail::Z_and_W_are_one_of_R_and_Q< R, Q, Z, W >, Matrix< typename array::ArrayHandler< Z, W >::value_type > >
Calculates overlap matrix between left and right vectors.
Definition util.h:57
std::vector< real_type_t< T > > solution_norms(const Matrix< T > &solutions, const Matrix< T > &overlap)
The Euclidean norms of the solutions x_i = sum_j c_ij b_j, from their subspace coefficients c (one ro...
Definition util.h:82
void construct_solutions(const VecRef< R > ¶ms, const std::vector< int > &roots, const subspace::Matrix< value_type > &solutions, const CVecRef< P > &pparams, const CVecRef< Q > &qparams, const CVecRef< Q > &dparams, size_t oP, size_t oQ, size_t oD, array::ArrayHandler< R, R > &handler_rr, array::ArrayHandler< R, P > &handler_rp, array::ArrayHandler< R, Q > &handler_rq)
Construct solutions.
Definition util.h:82
auto norm(array::ArrayHandler< R, R > &handler, const std::type_identity_t< R > &x) -> typename array::ArrayHandler< R, R >::value_type_abs
The length of x, sqrt(|<x|x>|), which is real also for complex values.
Definition util.h:21
4-parameter interpolation of a 1-dimensional function given two points for which function values and ...
Definition helper.h:14
auto cwrap(ForwardIt begin, ForwardIt end)
Takes a begin and end iterators and returns a vector of references to each element.
Definition wrap.h:52
auto wrap_arg(T &&arg, S &&... args) -> std::enable_if_t< std::conjunction_v< std::is_same< decay_t< T >, decay_t< S > >... >, VecRef< decay_t< T > > >
Constructs a vector of reference wrappers with provided arguments.
Definition wrap.h:135
std::unique_ptr< LinearEigensystem< R, Q, P > > create_LinearEigensystem(const LinearEigensystemOptions &options, const std::shared_ptr< ArrayHandlers< R, Q, P > > &handlers=std::make_shared< molpro::linalg::itsolv::ArrayHandlers< R, Q, P > >())
Definition SolverFactory.h:111
auto wrap(ForwardIt begin, ForwardIt end)
Takes a begin and end iterators and returns a vector of references to each element.
Definition wrap.h:32
std::vector< std::reference_wrapper< const A > > CVecRef
Definition wrap.h:14
MetricStorage
How a solver obtains the actions of a metric on its subspace vectors, see IterativeSolver::set_metric...
Definition Metric.h:21
@ Stored
the actions of the metric on all subspace vectors are kept
@ OnTheFly
the metric is applied to the solutions whenever residuals are constructed
std::vector< std::reference_wrapper< A > > VecRef
Definition wrap.h:11
Verbosity
Specifies how much detail IterativeSolver::solve should write to output.
Definition Options.h:12
@ Summary
only summary at the start and end of solve
@ Detailed
Iteration plus more detail such as operation count.
@ Iteration
Summary plus minimal results at each iteration.
MetricKind
The kind of metric M of a generalised problem, such as the eigenproblem A v = lambda M v.
Definition Metric.h:13
@ HermitianPositiveSemidefinite
Hermitian and positive semidefinite, i.e. possibly singular.
@ HermitianPositiveDefinite
Hermitian and positive definite, e.g. the overlap matrix of a non-orthogonal basis.
@ Identity
M = 1, i.e. no metric.
void read_handler_counts(std::shared_ptr< Statistics > stats, std::shared_ptr< ArrayHandlers< R, Q, P > > handlers)
Definition Statistics.h:30
real_type_t< T > real_part(const T &x)
The real part of a scalar; the value itself for a real type.
Definition scalar_traits.h:58
T conjugate(const T &x)
Complex conjugate, staying within the scalar type; the identity for a real type.
Definition scalar_traits.h:47
const std::shared_ptr< const molpro::Options > options()
Get the Options object associated with iterative-solver.
Definition linalg_options.cpp:4
Access point for different options in iterative solvers.
Definition Options.h:20
The metric of a problem in the P space, for IterativeSolver::add_p()
Definition IterativeSolver.h:335
Information about performance of IterativeSolver instance.
Definition Statistics.h:10
The actions of a metric applied on the fly on solutions, in R vectors or, if there are not enough of ...
Definition IterativeSolverTemplate.h:40
CVecRef< R > r
Definition IterativeSolverTemplate.h:41
CVecRef< Q > q
Definition IterativeSolverTemplate.h:42
bool empty() const
Definition IterativeSolverTemplate.h:43
Definition IterativeSolverTemplate.h:131
std::vector< real_t< Scalar > > errors
current errors of all roots
Definition IterativeSolverTemplate.h:134
std::vector< int > roots
roots whose vectors were worked on in this iteration
Definition IterativeSolverTemplate.h:133
int iter
0-based iteration number
Definition IterativeSolverTemplate.h:132
std::vector< Scalar > values
Definition IterativeSolverTemplate.h:135
std::size_t n_next
number of vectors to work on in the next iteration (0 if done)
Definition IterativeSolverTemplate.h:137
Definition IterativeSolverTemplate.h:129
static std::string format(const Payload &p)
Definition IterativeSolverTemplate.h:139
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:130
Definition IterativeSolverTemplate.h:168
Definition IterativeSolverTemplate.h:166
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:167
Definition IterativeSolverTemplate.h:117
std::vector< int > roots
Definition IterativeSolverTemplate.h:119
int iter
0-based iteration number
Definition IterativeSolverTemplate.h:118
Definition IterativeSolverTemplate.h:115
static std::string format(const Payload &p)
Definition IterativeSolverTemplate.h:122
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:116
Definition IterativeSolverTemplate.h:151
std::vector< Scalar > values
see IterationCompleted::Payload::values
Definition IterativeSolverTemplate.h:155
bool converged
same as the return value of solve()
Definition IterativeSolverTemplate.h:153
std::vector< real_t< Scalar > > errors
final errors of all roots
Definition IterativeSolverTemplate.h:154
int iterations
number of iterations performed
Definition IterativeSolverTemplate.h:152
Definition IterativeSolverTemplate.h:149
static std::string format(const Payload &p)
Definition IterativeSolverTemplate.h:157
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:150
Definition IterativeSolverTemplate.h:96
real_t< Scalar > convergence_threshold
threshold on the errors
Definition IterativeSolverTemplate.h:99
int max_iter
maximum number of iterations
Definition IterativeSolverTemplate.h:98
std::size_t n_roots
number of roots sought
Definition IterativeSolverTemplate.h:97
std::size_t pspace_size
dimension of the P space (0 if none is used)
Definition IterativeSolverTemplate.h:100
bool initial_guess_generated
whether an initial guess was generated from the diagonal elements
Definition IterativeSolverTemplate.h:101
Definition IterativeSolverTemplate.h:94
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:95
static std::string format(const Payload &p)
Definition IterativeSolverTemplate.h:103
Definition IterativeSolverTemplate.h:176
Definition IterativeSolverTemplate.h:174
static constexpr std::string_view name
Definition IterativeSolverTemplate.h:175
Definition Dimensions.h:9
Manages solution of the subspace problem and storage of those solutions.
Definition ISubspaceSolver.h:21