Debian Codegraph @

src/dr/evomodel/coalescent/GaussianProcessSkytrackParser.java

raw symbols SCIP
1 package dr.evomodel.coalescent;
2
3 import dr.math.MathUtils;
4 import dr.stats.DiscreteStatistics;
5 import no.uib.cipr.matrix.*;
6
7 import java.io.BufferedReader;
8 import java.io.FileReader;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11
12 /**
13 * Created by mkarcher on 6/22/16.
14 */
15 public class GaussianProcessSkytrackParser {
16 private static final int changepointsIndex = 5;
17 private static final int GvaluesIndex = 6;
18 private static final int lambdaBoundIndex = 7;
19 private static final int precisionIndex = 8;
20 private static final int tmrcaIndex = 10;
21
22 public static void main(String[] args) {
23 // int [] indices = {0, 5, 9};
24 // int total = 10;
25 // int [] neighbs = neighbors(indices, total);
26 // System.out.println(Arrays.toString(neighbs));
27
28 // double [] oldData = {1.0, 2.0, 3.0};
29 // double [] newData = {1.5, 3.5};
30 //
31 // QuadupleGP result = sortUpdate(oldData, newData);
32 //
33 // System.out.println("Data: " + Arrays.toString(result.getData()));
34 // System.out.println("Order: " + Arrays.toString(result.getOrder()));
35 // System.out.println("New Positions: " + Arrays.toString(result.getPositionNew()));
36 // System.out.println("Old Positions: " + Arrays.toString(result.getPositionOld()));
37
38 int NGRID = 101;
39 double quantile = 0.5;
40 String filePathName = "examples/hcvNew2small.log";
41 CSVstats stats = parseCSV(filePathName, 3);
42 //System.out.println(Arrays.toString(stats.precisions));
43 double tmrca = DiscreteStatistics.quantile(quantile, stats.tmrcas);
44 System.out.println(tmrca);
45
46 double[] grid = new double[NGRID];
47 double step = tmrca / (NGRID-1);
48 grid[0] = 0.001;
49 for (int i = 1; i < grid.length; i++) {
50 grid[i] = grid[i-1] + step;
51 }
52
53 double[] result = gpPosterior(stats, grid, stats.getSize() - 1);
54
55 double[] result2 = new double[result.length];
56 for (int i = 0; i < result.length; i++) {
57 result2[i] = 1/result[i];
58 }
59
60 System.out.println(Arrays.toString(grid));
61 System.out.println(Arrays.toString(result2));
62 }
63
64 public static CSVstats parseCSV(String filename, int skip) {
65 CSVstats result = null;
66
67 try {
68 BufferedReader br = new BufferedReader(new FileReader(filename));
69
70 String line;
71 String[] fieldsArray;
72 int lineNum = 0;
73
74 ArrayList<ArrayList<Double>> changepoints = new ArrayList<ArrayList<Double>>();
75 ArrayList<ArrayList<Double>> Gvalues = new ArrayList<ArrayList<Double>>();
76 ArrayList<Double> lambdas = new ArrayList<Double>();
77 ArrayList<Double> precisions = new ArrayList<Double>();
78 ArrayList<Double> tmrcas = new ArrayList<Double>();
79
80 while ((line = br.readLine()) != null) {
81 if (lineNum >= skip) {
82 fieldsArray = line.split("\t");
83
84 changepoints.add(parseListStr(fieldsArray[changepointsIndex]));
85 Gvalues.add(parseListStr(fieldsArray[GvaluesIndex]));
86 lambdas.add(new Double(fieldsArray[lambdaBoundIndex]));
87 precisions.add(new Double(fieldsArray[precisionIndex]));
88 tmrcas.add(new Double(fieldsArray[tmrcaIndex]));
89 }
90 lineNum += 1;
91 }
92
93 result = new CSVstats(changepoints, Gvalues, lambdas, precisions, tmrcas);
94 } catch (Exception e) {
95 e.printStackTrace();
96 }
97
98 return result;
99 }
100
101 public static double[] gpPosterior(CSVstats stats, double[] grid, int iter) {
102 double[] changePoints = stats.changepoints.get(iter);
103 DenseVector values = new DenseVector(stats.Gvalues.get(iter));
104 double precision = stats.precisions[iter];
105
106 TripGP res1 = getGPvalues(changePoints, values, grid, precision);
107
108 double[] result1 = sigmoidal(res1.getData());
109
110 double[] result = new double[result1.length];
111 for (int i = 0; i < result1.length; i++) {
112 result[i] = result1[i] * stats.lambdas[iter];
113 }
114
115 return result;
116 }
117
118 public static TripGP getGPvalues(double[] currentChangePoints, DenseVector currentGPvalues,
119 double[] newChangePoints, double precision) {
120 int currentLength=currentChangePoints.length;
121 int addLength=newChangePoints.length;
122 int newLength = currentLength+addLength;
123
124 // Takes the currentChangePoints and the newChangePoints into getData() but ordered and the order in getOrder()
125 // assumes that order numbers 0..currentLength are the positions of currentChangePoints
126 // and currentLength..newLength - currentLentgth are the positions of newChangePoints
127
128 QuadupleGP tempQuad = sortUpdate(currentChangePoints, newChangePoints);
129 // index=tempPair.getOrder();
130 // totalChangePoints=tempPair.getData();
131 // This is a silly thing to only compute the Q.matrix for the neighbors of the newChangePoints
132 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
133
134
135
136 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
137 int [] NeighborsIndex = neighbors(tempQuad.getPositionNew(), newLength);
138
139 // Retrieves the positions indicated in NeigborsIndex from the complete sorted data
140 DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
141
142 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
143
144
145
146 // Retrieves the positions indicated in NeighborsIndex from the getOrder
147 int [] NeighborsOriginal= SubsetData(tempQuad.getOrder(),NeighborsIndex);
148 // Generates two arrays: one with the positions of newData and other with the positions of OldData in the Neighbors data TempData
149 PairIndex Indicators = SubIndex(NeighborsOriginal,currentLength,addLength);
150
151 UpperSPDBandMatrix varf = new UpperSPDBandMatrix(Matrices.getSubMatrix(Q, Indicators.getOrderNew(), Indicators.getOrderNew()),1);
152 BandCholesky U1 = new BandCholesky(addLength,1,true);
153
154 U1.factor(varf);
155
156
157 DenseVector part = new DenseVector(addLength);
158 int [] GPpositions =SubsetData(NeighborsOriginal,Indicators.getOrderOld());
159 DenseVector currentGPneighbors = new DenseVector(SubsetData(currentGPvalues,GPpositions));
160
161 Matrix first = Matrices.getSubMatrix(Q,Indicators.getOrderNew(),Indicators.getOrderOld());
162
163 first.mult(-1,currentGPneighbors,part);
164
165 DenseVector mean = new DenseVector(getMultiNormalMean(part, U1.getU()));
166
167 double [] addGPvalues = getMultiNormal(mean,U1.getU()).getData();
168
169 return new TripGP(addGPvalues,tempQuad.getOrder(),tempQuad.getPositionNew());
170 }
171
172 private static DenseVector getMultiNormalMean(DenseVector CanonVector, UpperTriangBandMatrix CholeskyUpper) {
173 DenseVector tempValue = new DenseVector(CanonVector.size());
174 DenseVector Mean = new DenseVector(CanonVector.size());
175
176 // UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
177
178 // Assume Cholesky factorization of the precision matrix Q = LL^T
179 // 1. Solve L\omega = b
180 // System.err.println(CanonVector.size()+"and"+tempValue.size());
181 CholeskyUpper.transSolve(CanonVector, tempValue);
182
183 // 2. Solve L^T \mu = \omega
184 CholeskyUpper.solve(tempValue, Mean);
185
186 return Mean;
187 }
188
189 private static DenseVector getMultiNormal(DenseVector Mean, UpperTriangBandMatrix CholeskyUpper) {
190 int length = Mean.size();
191 DenseVector tempValue = new DenseVector(length);
192
193 for (int i = 0; i < length; i++)
194 tempValue.set(i, MathUtils.nextGaussian());
195
196 DenseVector returnValue = new DenseVector(Mean.size());
197
198 // UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
199 // 3. Solve L^T v = z
200 CholeskyUpper.solve(tempValue, returnValue);
201 // 4. Return x = \mu + v
202 returnValue.add(Mean);
203 return returnValue;
204 }
205
206 // Returns an array with the positions indicated in Index
207 private static double [] SubsetData(double [] Data, int [] Index) {
208 double [] Res= new double [Index.length];
209 for (int j=0;j<Index.length;j++){
210 Res[j]=Data[Index[j]];
211 }
212 return Res;
213 }
214
215 private static double [] SubsetData(DenseVector Data, int [] Index) {
216 double [] Res= new double [Index.length];
217 for (int j=0;j<Index.length;j++){
218 Res[j]= Data.get(Index[j]);
219 }
220 return Res;
221 }
222 private static int [] SubsetData(int [] Data, int [] Index) {
223 int [] Res= new int [Index.length];
224 for (int j=0;j<Index.length;j++){
225 Res[j]=Data[Index[j]];
226 }
227 return Res;
228 }
229
230 private static ArrayList<Double> parseListStr(String arg) {
231 ArrayList<Double> vals = new ArrayList<Double>();
232
233 String[] valStrs = arg.replaceAll("\\{|}", "").split(",");
234 for (String valStr : valStrs) {
235 vals.add(new Double(valStr));
236 }
237
238 return vals;
239 }
240
241 private static double sigmoidal(double x) {
242 return 1/(1+Math.exp(-x));
243 }
244
245 private static double[] sigmoidal(double[] xs) {
246 double[] result = new double[xs.length];
247 for (int i = 0; i < result.length; i++) {
248 result[i] = sigmoidal(xs[i]);
249 }
250 return result;
251 }
252
253 //Returns the index (position) of newData + Neighbors in the Ordered List
254 /*private static int [] neighbors(int [] indexNew, int numberTotalData){
255 int [] Neighbors = new int[numberTotalData];
256 int k=0;
257
258 for (int j=0; j<indexNew.length-1;j++){
259
260 if (indexNew[j]==0) {
261 if (indexNew[j+1]>2){
262 Neighbors[k]=0;
263 Neighbors[k+1]=1;
264 k+=2;
265 }
266 if (indexNew[j+1]==2){
267 Neighbors[k]=0;
268 k++;
269 }
270 } else {
271 if ((indexNew[j+1]-indexNew[j])>2){
272 Neighbors[k]=indexNew[j]-1;
273 Neighbors[k+1]=indexNew[j];
274 Neighbors[k+2]=indexNew[j]+1;
275 k+=3;
276 }
277 if ((indexNew[j+1]-indexNew[j])==2){
278 Neighbors[k]=indexNew[j]-1;
279 Neighbors[k+1]=indexNew[j];
280 k+=2;
281 }
282 if ((indexNew[j+1]-indexNew[j])==1){
283 Neighbors[k]=indexNew[j]-1;
284 k++;
285 }
286 }
287 }
288 Neighbors[k]=indexNew[indexNew.length-1]-1;
289 Neighbors[k+1]=indexNew[indexNew.length-1];
290 Neighbors[k+2]=indexNew[indexNew.length-1]+1;
291 k+=3;
292
293 int [] FinalNeighbors = new int[k];
294 System.arraycopy(Neighbors,0,FinalNeighbors,0,k);
295 return FinalNeighbors;
296 }*/
297
298 private static int [] neighbors(int [] indexNew, int numberTotalData) {
299 int [] ns = new int[numberTotalData];
300 int index, k = 0;
301 int [] result1 = new int[numberTotalData];
302 int [] result;
303
304 for (int i = 0; i < indexNew.length; i++) {
305 index = indexNew[i];
306
307 if (index-1 > 0) {
308 ns[index-1]++;
309 }
310
311 ns[index]++;
312
313 if (index+1 < numberTotalData) {
314 ns[index+1]++;
315 }
316 }
317
318 for (int i = 0; i < numberTotalData; i++) {
319 if (ns[i] > 0) {
320 result1[k] = i;
321 k++;
322 }
323 }
324
325 result = new int[k];
326 System.arraycopy(result1, 0, result, 0, k);
327
328 return result;
329 }
330
331 // Assumes the input vector x is ordered
332 private static SymmTridiagMatrix getQmatrix(double precision, DenseVector x) {
333 SymmTridiagMatrix res;
334 double trick = 0;
335 double[] offdiag = new double[x.size() - 1];
336 double[] diag = new double[x.size()];
337
338 for (int i = 0; i < x.size() - 1; i++) {
339 offdiag[i] = precision*(-1.0 / (x.get(i+1)-x.get(i)));
340 if (i< x.size()-2){
341 diag[i+1]= -offdiag[i]+precision*(1.0/(x.get(i+2)-x.get(i+1))+trick);
342 }
343 }
344 // Diffuse prior correction - intrinsic
345 // Take care of the endpoints
346 diag[0] = -offdiag[0]+precision*trick;
347
348 diag[x.size() - 1] = -offdiag[x.size() - 2]+precision*(trick);
349 res = new SymmTridiagMatrix(diag, offdiag);
350 return res;
351 }
352
353 private static SymmTridiagMatrix getQmatrix(double precision, double[] x) {
354 SymmTridiagMatrix res;
355 double trick = 0.00000000001;
356 double[] offdiag = new double[x.length - 1];
357 double[] diag = new double[x.length];
358
359 for (int i = 0; i < x.length - 1; i++) {
360 offdiag[i] = precision*(-1.0 / (x[i+1]-x[i]));
361
362 if (i< x.length-2){
363 diag[i+1]= -offdiag[i]+precision*(1.0/(x[i+2]-x[i+1])+trick);
364 }
365 }
366 // Diffuse prior correction - intrinsic
367 // Take care of the endpoints
368 diag[0] = -offdiag[0]+precision*trick;
369
370 diag[x.length - 1] = -offdiag[x.length - 2]+precision*(trick);
371 res = new SymmTridiagMatrix(diag, offdiag);
372 return res;
373 }
374
375 private static QuadupleGP sortUpdate(double [] sortedData, double [] newData){
376 // note that sortedData and newData are already ordered (minimum to maximum)
377 // and last(sortedData) > last(newData)
378 int newLength = sortedData.length + newData.length;
379 double [] newList = new double [newLength];
380 int [] newOrder = new int [newLength];
381
382 // indexNew contains the index where the newData is stored (index ordered) in newList
383 // indexOld contains the index where OldData is stored (index ordered) index newList
384 int [] indexNew =new int[newData.length];
385 int [] indexOld =new int[sortedData.length];
386
387 int index2=sortedData.length;
388 double pivot2=newData[0];
389 double pivot1=sortedData[0];
390 int k1 = 0;
391
392 for (int j = 0; j < newLength; j++){
393 if (index2<newLength && k1<sortedData.length) {
394 pivot1=sortedData[k1];
395 pivot2=newData[index2-sortedData.length];
396
397 if (pivot1<pivot2) {
398 newList[j]=pivot1;
399 newOrder[j]=k1;
400 indexOld[k1]=j;
401 k1++;
402 } else {
403 newList[j]=pivot2;
404 newOrder[j]=index2;
405 indexNew[index2-sortedData.length]=j;
406 index2++;
407 }
408
409 } else if (index2<newLength) {
410 newList[j]=newData[index2-sortedData.length];
411 newOrder[j]=index2;
412 indexNew[index2-sortedData.length]=j;
413 index2++;
414 } else {
415 newList[j]=sortedData[k1];
416 newOrder[j]=k1;
417 indexOld[k1]=j;
418 k1++;
419 }
420 }
421
422 return new QuadupleGP(newList,newOrder,indexNew,indexOld);
423 }
424
425 // Returns the index in the Neighbors data that contain new data
426 private static PairIndex SubIndex (int [] Index, int numberOldData, int numberNewData) {
427 int [] newArray =new int[numberNewData];
428 int [] oldArray =new int[numberOldData];
429 int k=0;
430 int k2=0;
431 for (int j=0;j<Index.length;j++){
432 if (Index[j]>=numberOldData){
433 newArray[k]=j;
434 k+=1;
435 } else {
436 oldArray[k2]=j;
437 k2+=1;
438 }
439 }
440 int [] oldArray2 = new int[k2];
441 System.arraycopy(oldArray,0,oldArray2,0,k2);
442 return new PairIndex(newArray,oldArray2);
443 }
444
445 private static class CSVstats {
446 public ArrayList<double[]> changepoints, Gvalues;
447 public double[] lambdas, precisions, tmrcas;
448
449 public CSVstats(ArrayList<ArrayList<Double>> changepoints,
450 ArrayList<ArrayList<Double>> Gvalues,
451 ArrayList<Double> lambdas,
452 ArrayList<Double> precisions,
453 ArrayList<Double> tmrcas) {
454 this.changepoints = new ArrayList<double[]>();
455 for (ArrayList<Double> al : changepoints) {
456 double[] arr = new double[al.size()];
457 for (int i = 0; i < al.size(); i++) {
458 arr[i] = al.get(i);
459 }
460 this.changepoints.add(arr);
461 }
462
463 this.Gvalues = new ArrayList<double[]>();
464 for (ArrayList<Double> al : Gvalues) {
465 double[] arr = new double[al.size()];
466 for (int i = 0; i < al.size(); i++) {
467 arr[i] = al.get(i);
468 }
469 this.Gvalues.add(arr);
470 }
471
472 this.lambdas = new double[lambdas.size()];
473 for (int i = 0; i < lambdas.size(); i++) {
474 this.lambdas[i] = lambdas.get(i);
475 }
476
477 this.precisions = new double[precisions.size()];
478 for (int i = 0; i < precisions.size(); i++) {
479 this.precisions[i] = precisions.get(i);
480 }
481
482 this.tmrcas = new double[tmrcas.size()];
483 for (int i = 0; i < tmrcas.size(); i++) {
484 this.tmrcas[i] = tmrcas.get(i);
485 }
486 }
487
488 public int getSize() {
489 int result = -1;
490 if (changepoints.size() == Gvalues.size() && changepoints.size() == precisions.length &&
491 changepoints.size() == tmrcas.length) {
492 result = changepoints.size();
493 }
494 return result;
495 }
496 }
497
498 private static class TripGP {
499 private double [] data;
500 private int[] order;
501 private int[] newOrder;
502
503 public TripGP (double [] data, int [] order, int[] newOrder){
504 this.data = data;
505 this.order = order;
506 this.newOrder = newOrder;
507 }
508
509 public double [] getData() {
510 return data;
511 }
512
513 public int[] getOrder() {
514 return order;
515 }
516
517 public int[] getNewOrder() {
518 return newOrder;
519 }
520 }
521
522 private static class QuadupleGP{
523 private double[] data;
524 private int[] order;
525 private int[] positionNew;
526 private int[] positionOld;
527
528 public QuadupleGP (double [] data, int [] order, int [] positionNew, int[] positionOld){
529 this.data = data;
530 this.order = order;
531 this.positionNew = positionNew;
532 this.positionOld = positionOld;
533
534 }
535 public double[] getData() {return data;}
536 public int[] getOrder() {return order;}
537 public int [] getPositionNew() {return positionNew;}
538 public int [] getPositionOld() {return positionOld;}
539 }
540
541 private static class PairIndex{
542 private int[] orderNew;
543 private int[] orderOld;
544
545 public PairIndex (int [] orderNew, int [] orderOld){
546 this.orderNew = orderNew;
547 this.orderOld = orderOld;
548
549 }
550 public int[] getOrderNew() {return orderNew;}
551 public int[] getOrderOld() {return orderOld;}
552 }
553 }