QCOR
gradient_function.hpp
1 #pragma once
2 #include "Identifiable.hpp"
3 #include "heterogeneous.hpp"
4 #include "qcor_ir.hpp"
5 #include "qcor_observable.hpp"
6 #include <functional>
7 #include <memory>
8 #include <vector>
9 
10 namespace qcor {
11 class ObjectiveFunction;
12 // Gradient function type:
13 // Input: set of current parameters (std::vector<double>) and the current
14 // objective (cost) function value. Output: gradients (std::vector<double>)
15 // Requirements: size(parameters) == size (gradients)
16 using GradientFunctionType =
17  std::function<std::vector<double>(const std::vector<double> &, double)>;
19 protected:
20  GradientFunctionType gradient_func;
21 
22 public:
23  GradientFunction() {}
24  GradientFunction(GradientFunctionType func) : gradient_func(func) {}
25  std::vector<double> operator()(const std::vector<double> &x,
26  double current_val) {
27  return gradient_func(x, current_val);
28  }
29 };
30 
31 namespace __internal__ {
32 extern std::string DEFAULT_GRADIENT_METHOD;
33 std::shared_ptr<GradientFunction>
34 get_gradient_method(const std::string &type,
35  std::shared_ptr<ObjectiveFunction> obj_func,
36  xacc::HeterogeneousMap options = {});
37 
38 std::shared_ptr<GradientFunction>
39 get_gradient_method(const std::string &type,
40  std::function<std::shared_ptr<CompositeInstruction>(
41  std::vector<double>)>
42  kernel_eval,
43  Operator &obs);
44 } // namespace __internal__
45 
46 // Interface for gradient calculation services.
47 // Note: we keep the base GradientFunction API as simple as possible (just a
48 // thin wrapper around std::function, i.e. C++ lambda) so that users can define
49 // it in-place if need be. We also provide a set of registered gradient
50 // services implementing this interface.
52  public xacc::Identifiable {
53 public:
54  virtual void initialize(std::shared_ptr<ObjectiveFunction> obj_func,
55  xacc::HeterogeneousMap &&options = {}) = 0;
56  virtual void
57  initialize(std::function<std::shared_ptr<CompositeInstruction>(
58  std::vector<double>)>
59  kernel_eval,
60  Operator &obs, xacc::HeterogeneousMap &&options = {}) = 0;
61 };
62 } // namespace qcor
qcor::Operator
Definition: qcor_observable.hpp:24
qcor::GradientFunction
Definition: gradient_function.hpp:18
qcor::KernelGradientService
Definition: gradient_function.hpp:51
qcor
Definition: qcor_syntax_handler.cpp:15