1 |
#include "NLModel.hpp"
|
2 |
//calculate hessian using finite difference
|
3 |
SymMatrix NLModel1::FiniteHessian(vector<double>& x, vector<double>& h){
|
4 |
|
5 |
SymMatrix hessian(ndim);
|
6 |
vector<double> gplus;
|
7 |
vector<double> tempX;
|
8 |
double hi;
|
9 |
|
10 |
#ifdef IS_MPI
|
11 |
vector<double> gplusAll;
|
12 |
vector<double> tempGradAll;
|
13 |
|
14 |
tempGradAll = getAllGrad();
|
15 |
#endif
|
16 |
|
17 |
tempX = x;
|
18 |
|
19 |
for(int i = 0; i < ndim; i++){
|
20 |
|
21 |
#ifndef IS_MPI
|
22 |
hi = copysign(h[i], tempX[i]);
|
23 |
|
24 |
tempX[i] += hi;
|
25 |
|
26 |
gplus = calcGrad(tempX);
|
27 |
|
28 |
//hessian.Colume(i) = (gplus - currentGrad) / hi;
|
29 |
|
30 |
//restore tempX to its original value
|
31 |
tempX[i] -= hi;
|
32 |
#else
|
33 |
if(procMappingArray[i] == myRank){
|
34 |
|
35 |
hi = copysign(h[i], tempX[i]);
|
36 |
tempX[i] += hi;
|
37 |
|
38 |
}
|
39 |
|
40 |
gplus = calcGrad(tempX);
|
41 |
|
42 |
gplusAll.clear();
|
43 |
|
44 |
//very inefficient, need to change
|
45 |
for(int j = 0; j , numOfProc; j++){
|
46 |
brocastVector(gplus, j);
|
47 |
gplusAll.insert(gplus);
|
48 |
}
|
49 |
|
50 |
if(procMappingArray[i] == myRank){
|
51 |
|
52 |
hi = copysign(h[i], tempX[i]);
|
53 |
tempX[i] += hi;
|
54 |
|
55 |
}
|
56 |
|
57 |
hessian.Cloume(i) = (gplusAll - tempGradAll) / hi;
|
58 |
#endif
|
59 |
|
60 |
}
|
61 |
|
62 |
return hessian;
|
63 |
|
64 |
}
|
65 |
|
66 |
double ConcreteNLMode1::calcF(){
|
67 |
|
68 |
currentF = (*objfunc)(currentX, currentGrad);
|
69 |
numOfFunEval ++;
|
70 |
|
71 |
return currentF;
|
72 |
}
|
73 |
|
74 |
double ConcreteNLMode1::calcF(const vector<double>& x){
|
75 |
|
76 |
vector<double> tempGrad(x.size());
|
77 |
|
78 |
double tempF;
|
79 |
|
80 |
//tempF = (*objfunc)(x, tempGrad);
|
81 |
numOfFunEval ++;
|
82 |
|
83 |
return tempF;
|
84 |
}
|
85 |
|
86 |
vector<double> ConcreteNLMode1::calcGrad(){
|
87 |
|
88 |
currentF = (*objfunc)(currentX, currentGrad);
|
89 |
|
90 |
return currentGrad;
|
91 |
|
92 |
}
|
93 |
|
94 |
vector<double> ConcreteNLMode1::calcGrad(const vector<double>& x){
|
95 |
vector<double> tempGrad;
|
96 |
//vector<double> tempGrad(x.szie());
|
97 |
|
98 |
double tempF;
|
99 |
|
100 |
//tempF = (*objfunc)(x, tempGrad);
|
101 |
|
102 |
return tempGrad;
|
103 |
}
|
104 |
|
105 |
/*
|
106 |
SymMatrix ConcreteNLMode1::calcHessian(){
|
107 |
calcGrad(currentX);
|
108 |
return FiniteHessian(currentX);
|
109 |
}
|
110 |
|
111 |
SymMatrix ConcreteNLMode1::calcHessian(vector<double>& x){
|
112 |
return FiniteHessian(x);
|
113 |
}
|
114 |
*/
|