vnl_cost_function.cxx
Go to the documentation of this file.
1 // This is core/vnl/vnl_cost_function.cxx
2 //:
3 // \file
4 // \author Andrew W. Fitzgibbon, Oxford RRG
5 // \date 23 Oct 1997
6 //
7 //-----------------------------------------------------------------------------
8 
9 #include "vnl_cost_function.h"
10 #include <cassert>
11 
12 static bool f_calling_compute;
13 
15 {
16  if (val) *val = this->f(x);
17  if (g) this->gradf(x, *g);
18 }
19 
20 //: Default implementation of f is compute...
22 {
23  // if we get back here from compute, neither vf was implemented.
24  if (f_calling_compute)
25  assert(!"vnl_cost_function: RECURSION");
26  double val;
27  f_calling_compute = true;
28  this->compute(x, &val, nullptr);
29  f_calling_compute = false;
30  return val;
31 }
32 
33 //: Default implementation of gradf is to call compute
35 {
36  if (f_calling_compute)
37  assert(!"vnl_cost_function: RECURSION");
38  f_calling_compute = true;
39  this->compute(x, nullptr, &g);
40  f_calling_compute = false;
41 }
42 
43 //: Compute fd gradient
45  vnl_vector<double> & gradient,
46  double stepsize )
47 {
48  vnl_vector<double> tx = x;
49  double h = stepsize;
50  for (int i = 0; i < dim; ++i) {
51  double tplus = x[i] + h;
52  tx[i] = tplus;
53  double fplus = this->f(tx);
54 
55  double tminus = x[i] - h;
56  tx[i] = tminus;
57  double fminus = this->f(tx);
58 
59  gradient[i] = (fplus - fminus) / (tplus - tminus);
60  tx[i] = x[i];
61  }
62 }
63 
65 {
67  this->gradf(x, g);
68  return g;
69 }
70 
72 {
74  this->fdgradf(x, g);
75  return g;
76 }
virtual void gradf(vnl_vector< double > const &x, vnl_vector< double > &gradient)
Calculate the gradient of f at parameter vector x.
Vector->Real function.
double f(vnl_vector< double > const &x) override
The main function. Given the parameter vector x, compute the value of f(x).
void fdgradf(vnl_vector< double > const &x, vnl_vector< double > &gradient, double stepsize=1e-5)
Compute finite-difference gradient.
virtual void compute(vnl_vector< double > const &x, double *f, vnl_vector< double > *g)
Compute one or both of f and g.