| 1 |
/****************************************************************************** |
| 2 |
This source file is part of the Avogadro project. |
| 3 |
This source code is released under the 3-Clause BSD License, (see "LICENSE"). |
| 4 |
******************************************************************************/ |
| 5 |
|
| 6 |
#include "energyoptimizer.h" |
| 7 |
|
| 8 |
#include "energycalculator.h" |
| 9 |
|
| 10 |
#include <cppoptlib/function.h> |
| 11 |
#include <cppoptlib/solver/lbfgs.h> |
| 12 |
#include <cppoptlib/solver/progress.h> |
| 13 |
|
| 14 |
namespace Avogadro::Calc { |
| 15 |
|
| 16 |
namespace { |
| 17 |
class EnergyObjective : public cppoptlib::function::FunctionCRTP< |
| 18 |
EnergyObjective, double, |
| 19 |
cppoptlib::function::DifferentiabilityMode::First> |
| 20 |
{ |
| 21 |
public: |
| 22 |
explicit EnergyObjective(EnergyCalculator& method_) : method(method_) {} |
| 23 |
|
| 24 |
ScalarType operator()(const VectorType& x, VectorType* grad) const |
| 25 |
{ |
| 26 |
return method.evaluate(x, grad); |
| 27 |
} |
| 28 |
|
| 29 |
private: |
| 30 |
EnergyCalculator& method; |
| 31 |
}; |
| 32 |
|
| 33 |
bool optimizeLbfgs(EnergyCalculator& method, Eigen::VectorXd& positions, |
| 34 |
size_t chunkIterations) |
| 35 |
{ |
| 36 |
EnergyObjective objective(method); |
| 37 |
cppoptlib::solver::Lbfgs<EnergyObjective> solver; |
| 38 |
|
| 39 |
auto initialState = cppoptlib::function::FunctionState(positions); |
| 40 |
using StateType = decltype(initialState); |
| 41 |
auto stopProgress = |
| 42 |
cppoptlib::solver::DefaultStoppingSolverProgress<EnergyObjective, |
| 43 |
StateType>(); |
| 44 |
|
| 45 |
stopProgress.num_iterations = chunkIterations; |
| 46 |
stopProgress.x_delta = 0.0; |
| 47 |
stopProgress.f_delta = 0.0; |
| 48 |
stopProgress.gradient_norm = 0.0; |
| 49 |
stopProgress.condition_hessian = 0.0; |
| 50 |
solver.stopping_progress = stopProgress; |
| 51 |
|
| 52 |
auto [solution, solverProgress] = solver.Minimize(objective, initialState); |
| 53 |
(void)solverProgress; |
| 54 |
positions = solution.x; |
| 55 |
return true; |
| 56 |
} |
| 57 |
} // namespace |
| 58 |
|
| 59 |
bool optimizeSteps(EnergyCalculator& method, Eigen::VectorXd& positions, |
| 60 |
const OptimizationOptions& options) |
| 61 |
{ |
| 62 |
if (options.chunkIterations == 0) |
| 63 |
return false; |
| 64 |
|
| 65 |
switch (options.algorithm) { |
| 66 |
case OptimizationAlgorithm::Lbfgs: |
| 67 |
return optimizeLbfgs(method, positions, options.chunkIterations); |
| 68 |
default: |
| 69 |
return false; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
} // namespace Avogadro::Calc |