summaryrefslogtreecommitdiff
path: root/gi/posterior-regularisation/prjava/src/optimization/gradientBasedMethods/LBFGS.java
blob: dedbc94244c91e3faaeeeb91fc5ae71ab5cea61f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package optimization.gradientBasedMethods;


import optimization.gradientBasedMethods.stats.OptimizerStats;
import optimization.linesearch.DifferentiableLineSearchObjective;
import optimization.linesearch.LineSearchMethod;
import optimization.stopCriteria.StopingCriteria;
import optimization.util.MathUtils;

public class LBFGS extends AbstractGradientBaseMethod{

	//How many previous values are being saved
	int history;
	double[][] skList;
	double[][] ykList;
	double initialHessianParameters;
	double[] previousGradient;
	double[] previousParameters;
	
	//auxiliar structures
	double q[];
	double[] roi;
	double[] alphai;
	
	public LBFGS(LineSearchMethod ls, int history) {
		lineSearch = ls;
		this.history = history;
		skList = new double[history][];
		ykList = new double[history][];

	}
	
	public void reset(){
		super.reset();
		initialHessianParameters = 0;
		previousParameters = null;
		previousGradient = null;
		skList = new double[history][];
		ykList = new double[history][];
		q = null;
		roi = null;
		alphai = null;
	}
	
	public double[] LBFGSTwoLoopRecursion(double hessianConst){
		//Only create array once
		if(q == null){
			 q = new double[gradient.length];
		}
		System.arraycopy(gradient, 0, q, 0, gradient.length);
		//Only create array once
		if(roi == null){
			roi = new double[history]; 
		}
		//Only create array once
		if(alphai == null){
			alphai = new double[history];
		}
		
		for(int i = history-1; i >=0 && skList[i]!= null && ykList[i]!=null; i-- ){			
		//	System.out.println("New to Old proj " + currentProjectionIteration + " history "+history + " index " + i);
			double[] si =  skList[i];
			double[] yi = ykList[i];
			roi[i]= 1.0/MathUtils.dotProduct(yi,si);
			alphai[i] = MathUtils.dotProduct(si, q)*roi[i];
			MathUtils.plusEquals(q, yi, -alphai[i]);
		}
		//Initial Hessian is just a constant
		MathUtils.scalarMultiplication(q, hessianConst);
		for(int i = 0; i <history && skList[i]!= null && ykList[i]!=null; i++ ){
		//	System.out.println("Old to New proj " + currentProjectionIteration + " history "+history + " index " + i);
			double beta = MathUtils.dotProduct(ykList[i], q)*roi[i];
			MathUtils.plusEquals(q, skList[i], (alphai[i]-beta));
		}
		return q;
	}
	
	
	
	
	@Override
	public double[] getDirection() {
		
		calculateInitialHessianParameter();
//		System.out.println("Initial hessian " + initialHessianParameters);
		return direction = MathUtils.negation(LBFGSTwoLoopRecursion(initialHessianParameters));		
	}
	
	public void calculateInitialHessianParameter(){
		if(currentProjectionIteration == 1){
			//Use gradient
			initialHessianParameters = 1;
		}else if(currentProjectionIteration <= history){
			double[] sk = skList[currentProjectionIteration-2];
			double[] yk = ykList[currentProjectionIteration-2];
			initialHessianParameters = MathUtils.dotProduct(sk, yk)/MathUtils.dotProduct(yk, yk);
		}else{
			//get the last one
			double[] sk = skList[history-1];
			double[] yk = ykList[history-1];
			initialHessianParameters = MathUtils.dotProduct(sk, yk)/MathUtils.dotProduct(yk, yk);
		}
	}
	
	//TODO if structures exit just reset them to zero
	public void initializeStructures(Objective o,OptimizerStats stats, StopingCriteria stop){
		super.initializeStructures(o, stats, stop);
		previousParameters = new double[o.getNumParameters()];
		previousGradient = new double[o.getNumParameters()];
	}
	public void updateStructuresBeforeStep(Objective o,OptimizerStats stats, StopingCriteria stop){	
		super.initializeStructures(o, stats, stop);
		System.arraycopy(o.getParameters(), 0, previousParameters, 0, previousParameters.length);
		System.arraycopy(gradient, 0, previousGradient, 0, gradient.length);
	}

	public void 	updateStructuresAfterStep( Objective o,OptimizerStats stats, StopingCriteria stop){
		double[] diffX = MathUtils.arrayMinus(o.getParameters(), previousParameters);
		double[] diffGrad = MathUtils.arrayMinus(gradient, previousGradient);
		//Save new values and discard new ones
		if(currentProjectionIteration > history){
			for(int i = 0; i < history-1;i++){
				skList[i]=skList[i+1];
				ykList[i]=ykList[i+1];
			}
			skList[history-1]=diffX;
			ykList[history-1]=diffGrad;
		}else{
			skList[currentProjectionIteration-1]=diffX;
			ykList[currentProjectionIteration-1]=diffGrad;
		}	
	}
	
//	public boolean optimize(Objective o, OptimizerStats stats, StopingCriteria stop) {		
//		DifferentiableLineSearchObjective lso = new DifferentiableLineSearchObjective(o);		
//		gradient = o.getGradient();
//		direction = new double[o.getNumParameters()];
//		previousGradient = new double[o.getNumParameters()];
//		
//		previousParameters = new double[o.getNumParameters()];
//	
//		stats.collectInitStats(this, o);
//		previousValue = Double.MAX_VALUE;
//		currValue= o.getValue();
//		//Used for stopping criteria
//		double[] originalGradient = o.getGradient();
//		
//		originalGradientL2Norm = MathUtils.L2Norm(originalGradient);
//		if(stop.stopOptimization(originalGradient)){
//			stats.collectFinalStats(this, o);
//			return true;
//		}
//		for (currentProjectionIteration = 1; currentProjectionIteration < maxNumberOfIterations; currentProjectionIteration++){
//			
//			
//			currValue = o.getValue();
//			gradient  = o.getGradient();
//			currParameters = o.getParameters();
//			
//			
//			if(currentProjectionIteration == 1){
//				//Use gradient
//				initialHessianParameters = 1;
//			}else if(currentProjectionIteration <= history){
//				double[] sk = skList[currentProjectionIteration-2];
//				double[] yk = ykList[currentProjectionIteration-2];
//				initialHessianParameters = MathUtils.dotProduct(sk, yk)/MathUtils.dotProduct(yk, yk);
//			}else{
//				//get the last one
//				double[] sk = skList[history-1];
//				double[] yk = ykList[history-1];
//				initialHessianParameters = MathUtils.dotProduct(sk, yk)/MathUtils.dotProduct(yk, yk);
//			}
//			
//			getDirection();
//			
//			//MatrixOutput.printDoubleArray(direction, "direction");
//			double dot = MathUtils.dotProduct(direction, gradient);
//			if(dot > 0){				
//				throw new RuntimeException("Not a descent direction");
//			} if (Double.isNaN(dot)){
//				throw new RuntimeException("dot is not a number!!");
//			}
//			System.arraycopy(currParameters, 0, previousParameters, 0, currParameters.length);
//			System.arraycopy(gradient, 0, previousGradient, 0, gradient.length);
//			lso.reset(direction);
//			step = lineSearch.getStepSize(lso);
//			if(step==-1){
//				System.out.println("Failed to find a step size");
////				lso.printLineSearchSteps();
////				System.out.println(stats.prettyPrint(1));
//				stats.collectFinalStats(this, o);
//				return false;	
//			}
//			stats.collectIterationStats(this, o);
//			
//			//We are not updating the alpha since it is done in line search already
//			currParameters = o.getParameters();
//			gradient = o.getGradient();
//			
//			if(stop.stopOptimization(gradient)){
//				stats.collectFinalStats(this, o);
//				return true;
//			}
//			double[] diffX = MathUtils.arrayMinus(currParameters, previousParameters);
//			double[] diffGrad = MathUtils.arrayMinus(gradient, previousGradient);
//			//Save new values and discard new ones
//			if(currentProjectionIteration > history){
//				for(int i = 0; i < history-1;i++){
//					skList[i]=skList[i+1];
//					ykList[i]=ykList[i+1];
//				}
//				skList[history-1]=diffX;
//				ykList[history-1]=diffGrad;
//			}else{
//				skList[currentProjectionIteration-1]=diffX;
//				ykList[currentProjectionIteration-1]=diffGrad;
//			}		
//			previousValue = currValue;
//		}
//		stats.collectFinalStats(this, o);
//		return false;	
//	}
	


	

	

	
	

}