EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
SquareGradient.cpp
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file SquareGradient.cpp
1 #include "SquareGradient.h"
2 
3 #include <vector>
4 
5 using namespace std;
6 using namespace Eigen;
7 
8 
9 namespace FitNewton
10 {
11  SquareGradient::SquareGradient(FunctionGradHessian* func) : FunctionGradHessian(func->nPars(), func->nFixedPars()), verbose(true), function(func)
12  {
13  fixedpars = func->getFixedPars();
14  }
15 
16 
18  {
19 
20  }
21 
22 
24  {
25  SquareGradient* clone = new SquareGradient(function);
26  return clone;
27  }
28 
29 
30  bool SquareGradient::calcValGrad(const VectorXd& x, double& val, VectorXd& grad)
31  {
32  // this class is the square of the gradient of function
33  // val = sum_i fgrad(i)^2
34  // grad(j) = sum_i 2*fgrad(i)*fhessian(i,j)
35 
36  double fval=0.;
37  VectorXd fgrad = VectorXd::Zero(npars);
38  MatrixXd fhessian = MatrixXd::Zero(npars,npars);
39  function->calcValGradHessian(x, fval, fgrad, fhessian);
40 
41  val = 0.;
42  grad = VectorXd::Zero(npars);
43 
44  for(unsigned int i=0;i<npars;++i)
45  {
46  val += fgrad(i)*fgrad(i);
47  }
48 
49  for(unsigned int j=0;j<npars;++j)
50  {
51  for(unsigned int i=0;i<npars;++i)
52  {
53  grad(j) += fgrad(i)*fhessian(i,j);
54  }
55  grad(j) *= 2.;
56  }
57 
58 // if(verbose == true)
59 // {
60 // for(unsigned int i=0;i<npars;++i)
61 // {
62 // VectorXd xtemp = x;
63 // xtemp(i) += 1.0e-6;
64 //
65 // double fval=0.;
66 // VectorXd fgrad = VectorXd::Zero(npars);
67 // double tempval = 0.;
68 // function->calcValGrad(xtemp, fval, fgrad);
69 //
70 // for(unsigned int j=0;j<npars;++j)
71 // {
72 // tempval += fgrad(j)*fgrad(j);
73 // }
74 //
75 // cout<<"grad test "<<i<<" "<<(tempval-val)*1.0e6<<" "<<grad(i)<<endl;
76 // }
77 // cout<<endl;
78 // }
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89  return true;
90  }
91 
92 
93  bool SquareGradient::calcValGradHessian(const VectorXd& x, double& val, VectorXd& grad, MatrixXd& /*hessian*/)
94  {
95 // verbose = false;
96 //
97 // this->calcValGrad(x, val, grad);
98 //
99 // hessian = MatrixXd::Zero(npars,npars);
100 // for(unsigned int j=0;j<npars;++j)
101 // {
102 // VectorXd xtemp = x;
103 // xtemp(j) += 1.0e-8;
104 // VectorXd gradtemp = VectorXd::Zero(npars);
105 // double valtemp=0.;
106 //
107 // this->calcValGrad(xtemp, valtemp, gradtemp);
108 //
109 // for(unsigned int i=0;i<npars;++i)
110 // {
111 // hessian(i,j) = (gradtemp(i) - grad(i))/(1.0e-8);
112 // }
113 // }
114 //
115 // verbose = true;
116 //
117 // return true;
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129  return calcValGrad(x,val,grad);
130  }
131 
132 
133 
134 }