iterative-solver 0.0
 
Loading...
Searching...
No Matches
OptimizeBFGS.h
1#ifndef LINEARALGEBRA_SRC_MOLPRO_LINALG_ITSOLV_OPTIMIZEBFGS_H
2#define LINEARALGEBRA_SRC_MOLPRO_LINALG_ITSOLV_OPTIMIZEBFGS_H
3#include <molpro/linalg/itsolv/CastOptions.h>
4#include <molpro/linalg/itsolv/DSpaceResetter.h>
5#include <molpro/linalg/itsolv/Interpolate.h>
6#include <molpro/linalg/itsolv/IterativeSolverTemplate.h>
7#include <molpro/linalg/itsolv/propose_rspace.h>
8#include <molpro/linalg/itsolv/subspace/SubspaceSolverOptBFGS.h>
9#include <molpro/linalg/itsolv/subspace/XSpace.h>
10
11#include <cmath>
12#include <limits>
13#include <map>
14#include <memory>
15
16namespace molpro::linalg::itsolv {
25template <class R, class Q = R, class P = std::map<size_t, typename R::value_type>>
26class OptimizeBFGS : public IterativeSolverTemplate<Optimize, R, Q, P> {
27public:
30 using typename SolverTemplate::scalar_type;
31 using typename SolverTemplate::value_type;
32 using typename SolverTemplate::value_type_abs;
34
35 explicit OptimizeBFGS(const std::shared_ptr<ArrayHandlers<R, Q, P>>& handlers,
36 const std::shared_ptr<Logger>& logger_ = std::make_shared<Logger>())
37 : SolverTemplate(std::make_shared<subspace::XSpace<R, Q, P>>(handlers, logger_),
38 std::static_pointer_cast<subspace::ISubspaceSolver<R, Q, P>>(
39 std::make_shared<subspace::SubspaceSolverOptBFGS<R, Q, P>>(logger_)),
41
42 bool nonlinear() const override { return true; }
43
44 int add_vector(R& parameters, R& residual, value_type value) override {
45 auto prof = this->profiler()->push("itsolv::add_vector");
46 using namespace subspace;
47 auto& xspace = this->m_xspace;
48 auto& xdata = xspace->data;
49 const auto& H = xdata[EqnData::H];
50 const auto& S = xdata[EqnData::S];
51 auto& Value = xdata[EqnData::value];
52 // std::cout << "updated value to" << as_string(Value) << std::endl;
53
54 // std::cout << "H "<<as_string(H)<<std::endl;
55 // std::cout << "Value "<<as_string(Value)<<std::endl;
56 while (xspace->size() >= size_t(this->m_max_size_qspace)) {
57 // std::cout << "delete Q" << std::endl;
58 xspace->eraseq(xspace->size() - 1);
59 }
60 // std::cout << "H after delete Q "<<as_string(H)<<std::endl;
61 // std::cout << "Value after delete Q "<<as_string(Value)<<std::endl;
62
63 // augment space with current point
64 auto oldValue = Value;
65 Value.resize({xspace->size() + 1, 1});
66 if (xspace->size() > 0)
67 Value.slice({1, 0}, {xspace->size() + 1, 1}) = oldValue.slice();
68 Value(0, 0) = value;
70 // std::cout << "H after add_vector "<<as_string(H)<<std::endl;
71 // std::cout << "Value after add_vector "<<as_string(Value)<<std::endl;
72
73 if (xspace->size() > 1) { // see whether a line search is needed
74 // the objective and its directional gradients are real; a complex element type carries them
75 // with a vanishing imaginary part
76 const value_type_abs fprev = real_part(Value(1, 0)); // the previous point
77 const value_type_abs fcurrent = real_part(Value(0, 0)); // the current point
78 const value_type_abs gprev = real_part(H(0, 1) - H(1, 1));
79 const value_type_abs gcurrent = real_part(H(0, 0) - H(1, 0));
80 // a change in the value within its rounding error says nothing about sufficient decrease
81 const value_type_abs f_noise =
82 10 * std::numeric_limits<value_type_abs>::epsilon() * std::max(std::abs(fprev), std::abs(fcurrent));
83 bool Wolfe_1 = fcurrent <= fprev + m_Wolfe_1 * gprev + f_noise;
84 bool Wolfe_2 = m_strong_Wolfe ? gcurrent >= m_Wolfe_2 * gprev : std::abs(gcurrent) <= m_Wolfe_2 * std::abs(gprev);
85 const value_type_abs step = real_part(S(0, 0) - S(1, 0) - S(0, 1) + S(1, 1));
86 if (false) {
87 molpro::cout << "Size of Q=" << xspace->size() << std::endl;
88 molpro::cout << "step=" << step << std::endl;
89 molpro::cout << "fprev=" << fprev << std::endl;
90 molpro::cout << "fcurrent=" << fcurrent << std::endl;
91 molpro::cout << " m_Wolfe_1 =" << m_Wolfe_1 << std::endl;
92 molpro::cout << " m_Wolfe_1 * gprev=" << m_Wolfe_1 * gprev << std::endl;
93 molpro::cout << "fprev + m_Wolfe_1 * gprev=" << fprev + m_Wolfe_1 * gprev << std::endl;
94 molpro::cout << "gprev=" << gprev << std::endl;
95 molpro::cout << "gcurrent=" << gcurrent << std::endl;
96 molpro::cout << "m_convergence_threshold=" << this->m_convergence_threshold << std::endl;
97 molpro::cout << "Wolfe conditions: " << Wolfe_1 << Wolfe_2 << std::endl;
98 }
99 // a point that already meets the convergence threshold is kept, rather than line-searched away
100 if (this->m_errors.front() <= this->m_convergence_threshold or (Wolfe_1 && Wolfe_2))
101 goto accept;
102 // molpro::cout << "evaluating line search" << std::endl;
104 interpolator inter(typename interpolator::point{-1, fprev, gprev},
105 typename interpolator::point{0, fcurrent, gcurrent});
106 auto [x, f, g, h] = inter.minimize(-1 - this->m_linesearch_grow_factor, this->m_linesearch_grow_factor);
107 // molpro::cout << "interpolation" << x << " f=" << f << " g=" << g << " h=" << h << std::endl;
108 if (std::isnan(x))
109 throw std::runtime_error("NaN in line search");
110 if (std::abs(x) > m_linesearch_tolerance) {
111 // molpro::cout << "taking line search" << std::endl;
112 this->m_logger->info("Line search step taken");
113 this->m_handlers->rr().scal(1 + x, parameters);
114 this->m_handlers->rq().axpy(-x, xspace->paramsq()[1], parameters);
115 auto erased = fprev < fcurrent ? 0 : 1;
116 // std::cout << "Value before erasure: "<<as_string(Value)<<std::endl;
117 // std::cout << "erased="<<erased<<"; removing point with value "<<Value(erased,0)<<std::endl;
118 xspace->eraseq(erased);
119 // std::cout << "Value after erasure: "<<as_string(Value)<<std::endl;
120 m_linesearch = true;
121 if (false) {
122 while (xspace->size() >= 2) {
123 std::cout << "delete Q because line searching" << std::endl;
124 xspace->eraseq(xspace->size() - 1);
125 }
126 }
127 return -1;
128 }
129 }
130
131 accept:
132 m_linesearch = false;
133 this->m_logger->info("Quasi-Newton step taken");
134 // this->m_errors.front() = std::sqrt(this->m_handlers->rr().dot(residual,residual));
135 for (size_t a = 0; a < xspace->size() - 1; a++) {
136 if (std::abs(H(a, a) - H(a, a + 1) - H(a + 1, a) + H(a + 1, a + 1)) <
137 std::max(precision_scaled<value_type_abs>(5e-14) * std::abs(H(a, a)),
139 xspace->eraseq(a + 1);
140 this->m_logger->info("Erase redundant Q");
141 goto accept;
142 }
143 }
144 BFGS_update_1(residual, xspace, H);
145 return nwork;
146 }
147
148 void BFGS_update_1(R& residual, std::shared_ptr<const subspace::IXSpace<R, Q, P>> xspace,
150 m_BFGS_update_alpha.resize(xspace->size() - 1);
151 const auto& q = xspace->paramsq();
152 const auto& u = xspace->actionsq();
153 for (size_t a = 0; a < m_BFGS_update_alpha.size(); a++) {
155 (this->m_handlers->rq().dot(residual, q[a]) - this->m_handlers->rq().dot(residual, q[a + 1])) /
156 (H(a, a) - H(a, a + 1) - H(a + 1, a) + H(a + 1, a + 1));
157 this->m_handlers->rq().axpy(-m_BFGS_update_alpha[a], u[a], residual);
158 this->m_handlers->rq().axpy(m_BFGS_update_alpha[a], u[a + 1], residual);
159 }
160 }
161
162 void BFGS_update_2(R& z, std::shared_ptr<const subspace::IXSpace<R, Q, P>> xspace,
164 const auto& q = xspace->paramsq();
165 const auto& u = xspace->actionsq();
166 for (int a = m_BFGS_update_alpha.size() - 1; a >= 0; a--) {
167 auto beta = (this->m_handlers->rq().dot(z, u[a]) - this->m_handlers->rq().dot(z, u[a + 1])) /
168 (H(a, a) - H(a, a + 1) - H(a + 1, a) + H(a + 1, a + 1));
169 this->m_handlers->rq().axpy(+m_BFGS_update_alpha[a] - beta, q[a], z);
170 this->m_handlers->rq().axpy(-m_BFGS_update_alpha[a] + beta, q[a + 1], z);
171 }
172 }
173
174 size_t end_iteration(const VecRef<R>& parameters, const VecRef<R>& action) override {
175 auto prof = this->profiler()->push("itsolv::end_iteration");
176 this->m_working_set = {0};
177 this->m_end_iteration_needed = false;
178 if (not m_linesearch) { // action is expected to hold the preconditioned residual
180 this->solution_params(this->m_working_set, parameters);
181 if (this->m_errors.front() < this->m_convergence_threshold) {
182 this->m_working_set.clear();
183 return 0;
184 }
185 this->m_working_set.assign(1, 0);
186 auto& z = action.front();
187 const auto& xspace = this->m_xspace;
188 auto& xdata = xspace->data;
189 const auto& H = xdata[subspace::EqnData::H];
190 BFGS_update_2(z, xspace, H);
191 const value_type_abs len_z = std::sqrt(std::abs(this->m_handlers->rr().dot(z, z)));
192 if (len_z > this->m_quasinewton_maximum_step)
193 this->m_handlers->rr().scal(this->m_quasinewton_maximum_step / len_z, z);
194 this->m_handlers->rr().axpy(-1, z, parameters.front());
195 } else {
196 this->m_stats->line_search_steps++;
198 this->m_stats->line_searches++;
199 m_last_iteration_linesearching = true;
200 }
201 this->m_stats->iterations++;
202 // a line-search step has to be evaluated; the errors still belong to the point it replaces
203 return m_linesearch ? 1 : (this->errors().front() < this->m_convergence_threshold ? 0 : 1);
204 }
205
206 size_t end_iteration(std::vector<R>& parameters, std::vector<R>& action) override {
207 auto result = end_iteration(wrap(parameters), wrap(action));
208 return result;
209 }
210
211 size_t end_iteration(R& parameters, R& actions) override {
212 auto wparams = std::vector<std::reference_wrapper<R>>{std::ref(parameters)};
213 auto wactions = std::vector<std::reference_wrapper<R>>{std::ref(actions)};
215 }
216
217 void set_value_errors() override {
218 auto& Value = this->m_xspace->data[subspace::EqnData::value];
219 this->m_value_errors.assign(1, std::numeric_limits<value_type_abs>::max());
220 if (this->m_xspace->size() > 1 and real_part(Value(0, 0)) < real_part(Value(1, 0)))
221 this->m_value_errors.front() = real_part(Value(1, 0)) - real_part(Value(0, 0));
222 }
223
228
229 void set_options(const Options& options) override {
231 if (auto opt2 = dynamic_cast<const molpro::linalg::itsolv::OptimizeBFGSOptions*>(&options)) {
233 if (opt.max_size_qspace)
234 set_max_size_qspace(opt.max_size_qspace.value());
235 if (opt.strong_Wolfe)
236 m_strong_Wolfe = opt.strong_Wolfe.value();
237 if (opt.Wolfe_1)
238 m_Wolfe_1 = opt.Wolfe_1.value();
239 if (opt.Wolfe_2)
240 m_Wolfe_2 = opt.Wolfe_2.value();
241 if (opt.linesearch_tolerance)
242 m_linesearch_tolerance = opt.linesearch_tolerance.value();
243 if (opt.linesearch_grow_factor)
244 m_linesearch_grow_factor = opt.linesearch_grow_factor.value();
245 if (opt.quasinewton_maximum_step)
246 m_quasinewton_maximum_step = opt.quasinewton_maximum_step.value();
247 }
248 }
249
250 std::shared_ptr<Options> get_options() const override {
251 auto opt = std::make_shared<OptimizeBFGSOptions>();
253 opt->max_size_qspace = get_max_size_qspace();
254 opt->strong_Wolfe = m_strong_Wolfe;
255 opt->Wolfe_1 = m_Wolfe_1;
256 opt->Wolfe_2 = m_Wolfe_2;
257 opt->linesearch_tolerance = m_linesearch_tolerance;
258 opt->linesearch_grow_factor = m_linesearch_grow_factor;
259 opt->quasinewton_maximum_step = m_quasinewton_maximum_step;
260 return opt;
261 }
262
263 void report(std::ostream& cout, bool endl = true) const override {
265 cout << ", value " << this->value() << (m_linesearch ? ", line-searching" : ", quasi-Newton step");
266 if (endl)
267 cout << std::endl;
268 }
269
270protected:
271 std::vector<value_type> m_BFGS_update_alpha;
274
275protected:
276 // for non-linear problems, actions already contains the residual
277 void construct_residual(const std::vector<int>& roots, const CVecRef<R>& params, const VecRef<R>& actions) override {}
278
280 bool m_strong_Wolfe = true;
281 value_type_abs m_Wolfe_1 = 1e-4;
282 value_type_abs m_Wolfe_2 = 0.9;
283 value_type_abs m_linesearch_tolerance = .2;
287 2;
288 value_type_abs m_quasinewton_maximum_step = std::numeric_limits<value_type_abs>::max();
289};
290
291} // namespace molpro::linalg::itsolv
292#endif // LINEARALGEBRA_SRC_MOLPRO_LINALG_ITSOLV_OPTIMIZEBFGS_H
Class, containing a collection of array handlers used in IterativeSolver Provides a Builder sub-class...
Definition ArrayHandlers.h:25
The interpolant, in the precision of the problem it is used for.
Definition Interpolate.h:31
point minimize(value_type xa, value_type xb, size_t bracket_grid=100, size_t max_bracket_grid=100000, bool analytic=true) const
Find the minimum of the interpolant within a range.
Definition Interpolate-implementation.h:142
Implements IterativeSolver interface that is common to all solvers.
Definition IterativeSolverTemplate.h:145
std::vector< value_type_abs > m_value_errors
value errors from the most recent solution
Definition IterativeSolverTemplate.h:736
void solution_params(const std::vector< int > &roots, std::vector< R > &parameters) override
Definition IterativeSolverTemplate.h:247
std::vector< int > m_working_set
indices of roots in the working set
Definition IterativeSolverTemplate.h:737
scalar_type value() const override
Definition IterativeSolverTemplate.h:369
std::shared_ptr< subspace::IXSpace< R, Q, P > > m_xspace
manages the subspace and associated data
Definition IterativeSolverTemplate.h:733
std::shared_ptr< ArrayHandlers< R, Q, P > > m_handlers
Array handlers.
Definition IterativeSolverTemplate.h:732
std::vector< value_type_abs > m_errors
errors from the most recent solution
Definition IterativeSolverTemplate.h:735
std::shared_ptr< Options > get_options() const override
Definition IterativeSolverTemplate.h:291
const std::shared_ptr< molpro::profiler::Profiler > & profiler() const override
Definition IterativeSolverTemplate.h:382
const std::vector< value_type_abs > & errors() const override
Definition IterativeSolverTemplate.h:302
bool m_end_iteration_needed
whether end_iteration should be called after any preconditioner
Definition IterativeSolverTemplate.h:753
int add_vector(const VecRef< R > &parameters, const VecRef< R > &actions) override
Definition IterativeSolverTemplate.h:168
void report() const override
Definition IterativeSolverTemplate.h:332
std::shared_ptr< Logger > m_logger
logger
Definition IterativeSolverTemplate.h:743
void set_options(const Options &options) override
Definition IterativeSolverTemplate.h:276
std::shared_ptr< Statistics > m_stats
accumulates statistics of operations performed by the solver
Definition IterativeSolverTemplate.h:742
value_type_abs m_convergence_threshold
residual norms less than this mark a converged solution
Definition IterativeSolverTemplate.h:739
A class that optimises a function using a Quasi-Newton or other method.
Definition OptimizeBFGS.h:26
int add_vector(R &parameters, R &residual, value_type value) override
Definition OptimizeBFGS.h:44
bool m_strong_Wolfe
Whether to use strong or weak Wolfe conditions.
Definition OptimizeBFGS.h:280
size_t end_iteration(R &parameters, R &actions) override
Definition OptimizeBFGS.h:211
void report(std::ostream &cout, bool endl=true) const override
Definition OptimizeBFGS.h:263
std::shared_ptr< Options > get_options() const override
Definition OptimizeBFGS.h:250
bool nonlinear() const override
Definition OptimizeBFGS.h:42
void BFGS_update_1(R &residual, std::shared_ptr< const subspace::IXSpace< R, Q, P > > xspace, const subspace::Matrix< value_type > &H)
Definition OptimizeBFGS.h:148
bool m_linesearch
Definition OptimizeBFGS.h:272
int m_max_size_qspace
maximum size of Q space
Definition OptimizeBFGS.h:279
size_t end_iteration(std::vector< R > &parameters, std::vector< R > &action) override
Definition OptimizeBFGS.h:206
void set_options(const Options &options) override
Definition OptimizeBFGS.h:229
std::vector< value_type > m_BFGS_update_alpha
Definition OptimizeBFGS.h:271
value_type_abs m_linesearch_tolerance
Definition OptimizeBFGS.h:283
value_type_abs m_Wolfe_1
Acceptance parameter for function value; recommended value Nocedal and Wright p142.
Definition OptimizeBFGS.h:281
void set_value_errors() override
Implementation class should overload this to set errors in the current values (e.g....
Definition OptimizeBFGS.h:217
value_type_abs m_linesearch_grow_factor
If the predicted line search step is extrapolation, limit the step to this factor times the current s...
Definition OptimizeBFGS.h:286
value_type_abs m_Wolfe_2
Acceptance parameter for function gradient; recommended value Nocedal and Wright p142.
Definition OptimizeBFGS.h:282
void set_max_size_qspace(int n)
Definition OptimizeBFGS.h:226
void BFGS_update_2(R &z, std::shared_ptr< const subspace::IXSpace< R, Q, P > > xspace, const subspace::Matrix< value_type > &H)
Definition OptimizeBFGS.h:162
size_t end_iteration(const VecRef< R > &parameters, const VecRef< R > &action) override
Definition OptimizeBFGS.h:174
int get_max_size_qspace() const
Definition OptimizeBFGS.h:227
void construct_residual(const std::vector< int > &roots, const CVecRef< R > &params, const VecRef< R > &actions) override
Constructs residual for given roots provided their parameters and actions.
Definition OptimizeBFGS.h:277
bool m_last_iteration_linesearching
Definition OptimizeBFGS.h:273
OptimizeBFGS(const std::shared_ptr< ArrayHandlers< R, Q, P > > &handlers, const std::shared_ptr< Logger > &logger_=std::make_shared< Logger >())
Definition OptimizeBFGS.h:35
value_type_abs m_quasinewton_maximum_step
Definition OptimizeBFGS.h:288
Full subspace.
Definition IXSpace.h:19
Matrix container that allows simple data access, slicing, copying and resizing without loosing data.
Definition Matrix.h:32
Solves subspace problem for minimisation using the Steepest Descent algorithm.
Definition SubspaceSolverOptBFGS.h:16
4-parameter interpolation of a 1-dimensional function given two points for which function values and ...
Definition helper.h:14
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
std::vector< std::reference_wrapper< A > > VecRef
Definition wrap.h:11
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
const std::shared_ptr< const molpro::Options > options()
Get the Options object associated with iterative-solver.
Definition linalg_options.cpp:4
static std::shared_ptr< OptimizeBFGSOptions > OptimizeBFGS(const std::shared_ptr< Options > &options)
Definition CastOptions.h:79
Allows setting and getting of options for OptimizeBFGS instance via IterativeSolver base class.
Definition OptimizeBFGSOptions.h:9
Access point for different options in iterative solvers.
Definition Options.h:20
Information about performance of IterativeSolver instance.
Definition Statistics.h:10