Debian Codegraph @

src/dr/evomodel/coalescent/operators/GaussianProcessSkytrackBlockUpdateOperator.java

raw symbols SCIP
1 /*
2 * GaussianProcessSkytrackBlockUpdateOperator.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evomodel.coalescent.operators;
27
28
29 //import com.sun.servicetag.SystemEnvironment;
30 import dr.evomodel.coalescent.GaussianProcessSkytrackLikelihood;
31
32 import dr.evomodelxml.coalescent.operators.GaussianProcessSkytrackBlockUpdateOperatorParser;
33 //import dr.inference.mcmc.MCMCOptions;
34 import dr.inference.model.Parameter;
35 import dr.inference.operators.*;
36 import dr.math.MathUtils;
37 //import dr.math.matrixAlgebra.SymmetricMatrix;
38 import no.uib.cipr.matrix.*;
39
40 import java.io.BufferedWriter;
41 //import java.io.FileNotFoundException;
42 import java.io.FileWriter;
43
44 /* A Metropolis-Hastings/Gibbs operator to update the log population sizes and precision parameter jointly under a GP prior
45 *
46 * @author Julia Palacios
47 * @author Vladimir Minin
48 * @author Marc Suchard
49 * @version $Id: GMRFSkylineBlockUpdateOperator.java,v 1.5 2007/03/20 11:26:49 msuchard Exp $
50 */
51
52 //public class GaussianProcessSkytrackBlockUpdateOperator extends AbstractAdaptableOperator{
53
54 public class GaussianProcessSkytrackBlockUpdateOperator extends SimpleMCMCOperator implements GibbsOperator {
55 private double scaleFactor;
56 // private double lambdaScaleFactor;
57 // private int fieldLength;
58
59 // private int maxIterations;
60 // private double stopValue;
61 public static final double TWO_TIMES_PI =6.283185;
62 private Parameter popSizeParameter;
63 private Parameter precisionParameter;
64 private Parameter lambdaParameter;
65 private Parameter lambdaBoundParameter;
66 private Parameter changePoints;
67 private Parameter GPcounts;
68 private Parameter GPtype;
69 // private Parameter popValue; //This will actually have the Effective Pop. Size for the grid
70 private Parameter CoalCounts;
71 private Parameter numPoints;
72 // private double [] intervals;
73 private double [] GPcoalfactor;
74 private Parameter coalfactor;
75 private double alphaprior;
76 private double betaprior;
77 private SymmTridiagMatrix currentQ;
78 private int numberPoints; //Number of coalescent points
79 // private double [] addPoints;
80 // private int [] add;
81 // private int fixedNumberPoints; //Number of coalescent or sampling points
82 private int [] CoalPosIndicator;
83 private double [] CoalTime;
84
85
86
87 GaussianProcessSkytrackLikelihood GPvalue;
88 // GMRFSkyrideLikelihood gmrfField;
89
90 // private double[] zeros;
91
92 public GaussianProcessSkytrackBlockUpdateOperator(GaussianProcessSkytrackLikelihood GPLikelihood,
93 double weight, AdaptationMode mode, double scaleFactor,
94 int maxIterations, double stopValue) {
95 // super(mode);
96 GPvalue = GPLikelihood; //before gmrfField
97 popSizeParameter = GPLikelihood.getPopSizeParameter();
98
99 // popValue=GPLikelihood.getPopValue();
100 changePoints=GPLikelihood.getChangePoints();
101 GPcoalfactor=GPLikelihood.getGPcoalfactor();
102 coalfactor=GPLikelihood.getcoalfactor();
103 GPtype=GPLikelihood.getGPtype();
104 GPcounts=GPLikelihood.getGPcounts();
105 precisionParameter = GPLikelihood.getPrecisionParameter();
106 lambdaParameter = GPLikelihood.getLambdaParameter();
107 alphaprior=GPLikelihood.getAlphaParameter();
108 betaprior=GPLikelihood.getBetaParameter();
109 lambdaBoundParameter=GPLikelihood.getLambdaBoundParameter();
110 currentQ=GPLikelihood.getWeightMatrix();
111
112 CoalPosIndicator=GPLikelihood.getCoalPosIndicator();
113 CoalTime=GPLikelihood.getCoalTime();
114 // fixedNumberPoints=GPcounts.getSize();
115 CoalCounts=GPLikelihood.getCoalCounts();
116 numberPoints=CoalCounts.getSize();
117 numPoints=GPLikelihood.getNumPoints();
118 // int [] add = new int[fixedNumberPoints];
119 // double [] addPoints = new double[fixedNumberPoints];
120
121 this.scaleFactor = scaleFactor;
122 // lambdaScaleFactor = 0.0;
123 // fieldLength = popSizeParameter.getDimension();
124
125 // this.maxIterations = maxIterations;
126
127 // this.stopValue = stopValue;
128 setWeight(weight);
129
130 // zeros = new double[numberPoints];
131
132
133
134
135
136 }
137
138
139 public GaussianProcessSkytrackBlockUpdateOperator() {
140
141 }
142 //change the 0.0005 to a parameter in BlockUpdate Parser
143 private double getProposalLambda(double currentValue) {
144 double proposal= MathUtils.uniform(currentValue-0.00001,currentValue+0.00001);
145 //Symmetric proposal
146 if (proposal<0){
147 proposal=-proposal;
148 }
149 return proposal;
150 }
151
152 //change mixing values to parameters - see Eq. 7
153 private double getPriorLambda(double lambdaMean, double epsilon, double lambdaValue) {
154 double res;
155 if (lambdaValue < lambdaMean) {
156 res=epsilon*(1/lambdaMean);
157 } else {
158 res=(1-epsilon)*(1/lambdaMean)*Math.exp(-(1/lambdaMean)*(lambdaValue-lambdaMean));
159 }
160 return res;
161 }
162
163
164 private void getNewUpperBound(double currentValue) {
165 double newLambda, lambdaMean;
166
167 newLambda = getProposalLambda(currentValue);
168 lambdaMean = lambdaParameter.getParameterValue(0);
169
170 double a = getPriorLambda(lambdaMean, 0.01, newLambda) * (Math.pow(newLambda/currentValue,popSizeParameter.getSize())) *
171 Math.exp((currentValue-newLambda) * GPvalue.getConstlik()) / getPriorLambda(lambdaMean,0.01,currentValue);
172
173 if (a>MathUtils.nextDouble()) {
174 this.lambdaBoundParameter.setParameterValue(0, newLambda);
175 }
176 }
177
178 // private int getNumberPoints(){
179 // return numberPoints;
180 // }
181
182 private double getQuadraticForm(SymmTridiagMatrix currentQ, DenseVector x){
183 DenseVector diagonal1 = new DenseVector(x.size());
184 currentQ.mult(x, diagonal1);
185 return x.dot(diagonal1);
186 }
187
188 // Assumes the input vector x is ordered
189 protected SymmTridiagMatrix getQmatrix(double precision, DenseVector x) {
190 SymmTridiagMatrix res;
191 double trick = 0;
192 double[] offdiag = new double[x.size() - 1];
193 double[] diag = new double[x.size()];
194
195 for (int i = 0; i < x.size() - 1; i++) {
196 offdiag[i] = precision*(-1.0 / (x.get(i+1)-x.get(i)));
197 if (i< x.size()-2){
198 diag[i+1]= -offdiag[i]+precision*(1.0/(x.get(i+2)-x.get(i+1))+trick);
199 }
200 }
201 // Diffuse prior correction - intrinsic
202 // Take care of the endpoints
203 diag[0] = -offdiag[0]+precision*trick;
204
205 diag[x.size() - 1] = -offdiag[x.size() - 2]+precision*(trick);
206 res = new SymmTridiagMatrix(diag, offdiag);
207 return res;
208 }
209
210 protected SymmTridiagMatrix getQmatrix(double precision, double[] x) {
211 SymmTridiagMatrix res;
212 double trick = 0.00000000001;
213 double[] offdiag = new double[x.length - 1];
214 double[] diag = new double[x.length];
215
216 for (int i = 0; i < x.length - 1; i++) {
217 offdiag[i] = precision*(-1.0 / (x[i+1]-x[i]));
218
219 if (i< x.length-2){
220 diag[i+1]= -offdiag[i]+precision*(1.0/(x[i+2]-x[i+1])+trick);
221 }
222 }
223 // Diffuse prior correction - intrinsic
224 // Take care of the endpoints
225 diag[0] = -offdiag[0]+precision*trick;
226
227 diag[x.length - 1] = -offdiag[x.length - 2]+precision*(trick);
228 res = new SymmTridiagMatrix(diag, offdiag);
229 return res;
230 }
231
232 protected QuadupleGP sortUpdate(double [] sortedData, double [] newData){
233 // note that sortedData and newData are already ordered (minimum to maximum)
234 // and last(sortedData) > last(newData)
235 int newLength = sortedData.length + newData.length;
236 double [] newList = new double [newLength];
237 int [] newOrder = new int [newLength];
238
239 // indexNew contains the index where the newData is stored (index ordered) in newList
240 // indexOld contains the index where OldData is stored (index ordered) index newList
241 int [] indexNew =new int[newData.length];
242 int [] indexOld =new int[sortedData.length];
243
244 int index2=sortedData.length;
245 double pivot2=newData[0];
246 double pivot1=sortedData[0];
247 int k1 = 0;
248
249 for (int j = 0; j < newLength; j++){
250 if (index2<newLength) {
251 if (pivot1<pivot2) {
252 newList[j]=pivot1;
253 newOrder[j]=k1;
254 indexOld[k1]=j;
255 k1++;
256 pivot1=sortedData[k1];
257 } else {
258 newList[j]=pivot2;
259
260 newOrder[j]=index2;
261
262 indexNew[index2-sortedData.length]=j;
263
264 index2++;
265 if (index2<newLength){
266 pivot2=newData[index2-sortedData.length];
267 }
268 }
269
270 } else {
271 newList[j]=sortedData[k1];
272 newOrder[j]=k1;
273 indexOld[k1]=j;
274 k1++;
275 }
276 }
277
278 return new QuadupleGP(newList,newOrder,indexNew,indexOld);
279 }
280
281 protected Quaduple1GP sortUpdate(double [] sortedData, double newData){
282 // note that sortedData and newData are already ordered (minimum to maximum)
283 // and last(sortedData) > last(newData)
284 int newLength = sortedData.length + 1;
285 double [] newList = new double [newLength];
286 int [] newOrder = new int [newLength];
287
288 // indexNew contains the index where the newData is stored (index ordered) in newList
289 // indexOld contains the index where OldData is stored (index ordered) index newList
290
291 int indexNew=0;
292 int [] indexOld =new int[sortedData.length];
293
294 int index2=sortedData.length;
295 double pivot2=newData;
296 double pivot1=sortedData[0];
297 int k1 = 0;
298
299 for (int j = 0; j < newLength; j++){
300 if (index2<newLength) {
301 if (pivot1<pivot2) {
302 newList[j]=pivot1;
303 newOrder[j]=k1;
304 indexOld[k1]=j;
305 k1++;
306 pivot1=sortedData[k1];
307 } else {
308 newList[j]=pivot2;
309
310 newOrder[j]=index2;
311
312 indexNew=j;
313
314 index2++;
315 if (index2<newLength){
316 pivot2=newData;
317 }
318 }
319
320 } else {
321 newList[j]=sortedData[k1];
322 newOrder[j]=k1;
323 indexOld[k1]=j;
324 k1++;
325 }
326 }
327
328
329 return new Quaduple1GP(newList,newOrder,indexNew,indexOld);
330 }
331
332 //Returns the index (position) of newData + Neighbors in the Ordered List
333 protected int [] Neighbors(int [] indexNew, int numberTotalData){
334 int [] Neighbors = new int[numberTotalData];
335 int k=0;
336
337 for (int j=0; j<indexNew.length-1;j++){
338
339 if (indexNew[j]==0) {
340 if (indexNew[j+1]>2){
341 Neighbors[k]=0;
342 Neighbors[k+1]=1;
343 k+=2;
344 }
345 if (indexNew[j+1]==2){
346 Neighbors[k]=0;
347 k++;
348 }
349 } else {
350 if ((indexNew[j+1]-indexNew[j])>2){
351 Neighbors[k]=indexNew[j]-1;
352 Neighbors[k+1]=indexNew[j];
353 Neighbors[k+2]=indexNew[j]+1;
354 k+=3;
355 }
356 if ((indexNew[j+1]-indexNew[j])==2){
357 Neighbors[k]=indexNew[j]-1;
358 Neighbors[k+1]=indexNew[j];
359 k+=2;
360 }
361 if ((indexNew[j+1]-indexNew[j])==1){
362 Neighbors[k]=indexNew[j]-1;
363 k++;
364 }
365 }
366 }
367 Neighbors[k]=indexNew[indexNew.length-1]-1;
368 Neighbors[k+1]=indexNew[indexNew.length-1];
369 Neighbors[k+2]=indexNew[indexNew.length-1]+1;
370 k+=3;
371
372 int [] FinalNeighbors = new int[k];
373 System.arraycopy(Neighbors,0,FinalNeighbors,0,k);
374 return FinalNeighbors;
375 }
376
377 protected int [] Neighbors(int indexNew) {
378 int [] Neighbors = new int[3];
379 int k=3;
380 if (indexNew>0) {
381 Neighbors[0]=indexNew-1;
382 Neighbors[1]=indexNew;
383 Neighbors[2]=indexNew+1;
384
385 } else {
386 Neighbors[0]=0;
387 Neighbors[1]=1;
388 k=2;
389 }
390
391
392 int [] FinalNeighbors = new int[k];
393 System.arraycopy(Neighbors,0,FinalNeighbors,0,k);
394 return FinalNeighbors;
395 }
396
397
398 // Returns an array with the positions indicated in Index
399 protected double [] SubsetData(double [] Data, int [] Index) {
400 double [] Res= new double [Index.length];
401 for (int j=0;j<Index.length;j++){
402 Res[j]=Data[Index[j]];
403 }
404 return Res;
405 }
406
407 protected double [] SubsetData(DenseVector Data, int [] Index) {
408 double [] Res= new double [Index.length];
409 for (int j=0;j<Index.length;j++){
410 Res[j]= Data.get(Index[j]);
411 }
412 return Res;
413 }
414 protected int [] SubsetData(int [] Data, int [] Index) {
415 int [] Res= new int [Index.length];
416 for (int j=0;j<Index.length;j++){
417 Res[j]=Data[Index[j]];
418 }
419 return Res;
420 }
421
422 // Returns the index in the Neighbors data that contain new data
423 protected PairIndex SubIndex (int [] Index, int numberOldData, int numberNewData) {
424 int [] newArray =new int[numberNewData];
425 int [] oldArray =new int[numberOldData];
426 int k=0;
427 int k2=0;
428 for (int j=0;j<Index.length;j++){
429 if (Index[j]>=numberOldData){
430 newArray[k]=j;
431 k+=1;
432 } else {
433 oldArray[k2]=j;
434 k2+=1;
435 }
436 }
437 int [] oldArray2 = new int[k2];
438 System.arraycopy(oldArray,0,oldArray2,0,k2);
439 return new PairIndex(newArray,oldArray2);
440 }
441
442 private class PairGP {
443 private double[] array1;
444 private int[] array2;
445
446 public PairGP (double [] array1, int [] array2){
447 this.array1=array1;
448 this.array2=array2;
449
450 }
451
452 public double[] getData() {
453 return array1;
454 }
455
456 public int[] getOrder() {
457 return array2;
458 }
459 }
460
461
462 public class Pair1GP {
463 private double array1;
464 private int[] array2;
465
466 public Pair1GP (double array1, int [] array2){
467 this.array1=array1;
468 this.array2=array2;
469 }
470
471 public double getData() {
472 return array1;
473 }
474
475 public int[] getOrder() {
476 return array2;
477 }
478 }
479
480 public class TripGP{
481 private double [] array1;
482 private int[] array2;
483 private int[] array3;
484
485 public TripGP (double [] array1, int [] array2, int[] array3){
486 this.array1=array1;
487 this.array2=array2;
488 this.array3=array3;
489 }
490
491 public double [] getData() {
492 return array1;
493 }
494
495 public int[] getOrder() {
496 return array2;
497 }
498
499 public int[] getNewOrder() {
500 return array3;
501 }
502 }
503
504 private class Trip1GP{
505 private double array1;
506 private int[] array2;
507 private int array3;
508
509 public Trip1GP (double array1, int [] array2, int array3){
510 this.array1=array1;
511 this.array2=array2;
512 this.array3=array3;
513
514 }
515 public double getData() {return array1;}
516 public int[] getOrder() {return array2;}
517 public int getNewOrder() {return array3;}
518 }
519
520 public class PairIndex{
521 private int[] array1;
522 private int[] array2;
523
524 public PairIndex (int [] array1, int [] array2){
525 this.array1=array1;
526 this.array2=array2;
527
528 }
529 public int[] getOrderNew() {return array1;}
530 public int[] getOrderOld() {return array2;}
531 }
532
533 public class QuadupleGP{
534 private double[] array1;
535 private int[] array2;
536 private int[] array3;
537 private int[] array4;
538
539 public QuadupleGP (double [] array1, int [] array2, int [] array3, int[] array4){
540 this.array1=array1;
541 this.array2=array2;
542 this.array3=array3;
543 this.array4=array4;
544
545 }
546 public double[] getData() {return array1;}
547 public int[] getOrder() {return array2;}
548 public int [] getPositionNew() {return array3;}
549 public int [] getPositionOld() {return array4;}
550 }
551
552
553 public class Quaduple1GP{
554 private double[] array1;
555 private int[] array2;
556 private int array3;
557 private int[] array4;
558
559 public Quaduple1GP (double [] array1, int [] array2, int array3, int[] array4){
560 this.array1=array1;
561 this.array2=array2;
562 this.array3=array3;
563 this.array4=array4;
564
565 }
566 public double[] getData() {return array1;}
567 public int[] getOrder() {return array2;}
568 public int getPositionNew() {return array3;}
569 public int [] getPositionOld() {return array4;}
570 }
571
572 private double getNewPrecision(double currentValue, double quadraticTerm) {
573 double alphaPost = alphaprior + popSizeParameter.getSize() * 0.5;
574 double betaPost = betaprior + 0.5 * (1 / currentValue) * quadraticTerm;
575
576 return MathUtils.nextGamma(alphaPost,betaPost);
577 }
578
579 public DenseVector getMultiNormalMean(DenseVector CanonVector, UpperTriangBandMatrix CholeskyUpper) {
580 DenseVector tempValue = new DenseVector(CanonVector.size());
581 DenseVector Mean = new DenseVector(CanonVector.size());
582
583 // UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
584
585 // Assume Cholesky factorization of the precision matrix Q = LL^T
586 // 1. Solve L\omega = b
587 // System.err.println(CanonVector.size()+"and"+tempValue.size());
588 CholeskyUpper.transSolve(CanonVector, tempValue);
589
590 // 2. Solve L^T \mu = \omega
591 CholeskyUpper.solve(tempValue, Mean);
592
593 return Mean;
594 }
595
596 public DenseVector getMultiNormal(DenseVector Mean, UpperTriangBandMatrix CholeskyUpper) {
597 int length = Mean.size();
598 DenseVector tempValue = new DenseVector(length);
599
600 for (int i = 0; i < length; i++)
601 tempValue.set(i, MathUtils.nextGaussian());
602
603 DenseVector returnValue = new DenseVector(Mean.size());
604
605 // UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
606 // 3. Solve L^T v = z
607 CholeskyUpper.solve(tempValue, returnValue);
608 // 4. Return x = \mu + v
609 returnValue.add(Mean);
610 return returnValue;
611 }
612
613 public TripGP getGPvalues(double [] currentChangePoints, DenseVector currentGPvalues, double[] newChangePoints, double precision){
614 int currentLength=currentChangePoints.length;
615 int addLength=newChangePoints.length;
616 int newLength = currentLength+addLength;
617
618 // Takes the currentChangePoints and the newChangePoints into getData() but ordered and the order in getOrder()
619 // assumes that order numbers 0..currentLength are the positions of currentChangePoints
620 // and currentLength..newLength - currentLentgth are the positions of newChangePoints
621
622 QuadupleGP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
623 // index=tempPair.getOrder();
624 // totalChangePoints=tempPair.getData();
625 // This is a silly thing to only compute the Q.matrix for the neighbors of the newChangePoints
626 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
627
628
629
630 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
631 int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew(), newLength);
632
633 // Retrieves the positions indicated in NeigborsIndex from the complete sorted data
634 DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
635
636 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
637
638
639
640 // Retrieves the positions indicated in NeighborsIndex from the getOrder
641 int [] NeighborsOriginal= SubsetData(tempQuad.getOrder(),NeighborsIndex);
642 // Generates two arrays: one with the positions of newData and other with the positions of OldData in the Neighbors data TempData
643 PairIndex Indicators = SubIndex(NeighborsOriginal,currentLength,addLength);
644
645 UpperSPDBandMatrix varf = new UpperSPDBandMatrix(Matrices.getSubMatrix(Q,Indicators.getOrderNew(),Indicators.getOrderNew()),1);
646 BandCholesky U1 = new BandCholesky(addLength,1,true);
647
648 U1.factor(varf);
649
650
651 DenseVector part = new DenseVector(addLength);
652 int [] GPpositions =SubsetData(NeighborsOriginal,Indicators.getOrderOld());
653 DenseVector currentGPneighbors = new DenseVector(SubsetData(currentGPvalues,GPpositions));
654
655 Matrix first = Matrices.getSubMatrix(Q,Indicators.getOrderNew(),Indicators.getOrderOld());
656
657 first.mult(-1,currentGPneighbors,part);
658
659 DenseVector mean = new DenseVector(getMultiNormalMean(part, U1.getU()));
660
661 double [] addGPvalues = getMultiNormal(mean,U1.getU()).getData();
662
663
664 return new TripGP(addGPvalues,tempQuad.getOrder(),tempQuad.getPositionNew());
665
666 }
667
668
669 public double[] getGPvaluesS(double[] currentChangePoints, double[] currentGPvalues1, double[] newChangePoints, double precision){
670 int currentLength=currentChangePoints.length;
671 int addLength=newChangePoints.length;
672 int newLength = currentLength+addLength;
673
674 // Takes the currentChangePoints and the newChangePoints into getData() but ordered and the order in getOrder()
675 // assumes that order numbers 0..currentLength are the positions of currentChangePoints
676 // and currentLength..newLength - currentLentgth are the positions of newChangePoints
677
678 QuadupleGP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
679 // index=tempPair.getOrder();
680 // totalChangePoints=tempPair.getData();
681 // This is a silly thing to only compute the Q.matrix for the neighbors of the newChangePoints
682 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
683
684
685 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
686 int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew(), newLength);
687
688 // Retrieves the positions indicated in NeigborsIndex from the complete sorted data
689 no.uib.cipr.matrix.DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
690
691 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
692
693
694
695 // Retrieves the positions indicated in NeighborsIndex from the getOrder
696 int [] NeighborsOriginal= SubsetData(tempQuad.getOrder(),NeighborsIndex);
697 // Generates two arrays: one with the positions of newData and other with the positions of OldData in the Neighbors data TempData
698 PairIndex Indicators = SubIndex(NeighborsOriginal,currentLength,addLength);
699
700 UpperSPDBandMatrix varf = new UpperSPDBandMatrix(Matrices.getSubMatrix(Q, Indicators.getOrderNew(), Indicators.getOrderNew()),1);
701 BandCholesky U1 = new BandCholesky(addLength,1,true);
702
703 U1.factor(varf);
704
705
706
707 DenseVector part = new DenseVector(addLength);
708 int [] GPpositions =SubsetData(NeighborsOriginal,Indicators.getOrderOld());
709 DenseVector currentGPvalues= new DenseVector(currentGPvalues1);
710 DenseVector currentGPneighbors = new DenseVector(SubsetData(currentGPvalues,GPpositions));
711
712
713 Matrix first = Matrices.getSubMatrix(Q,Indicators.getOrderNew(),Indicators.getOrderOld());
714
715 first.mult(-1,currentGPneighbors,part);
716
717 DenseVector mean = new DenseVector(getMultiNormalMean(part, U1.getU()));
718
719 double [] addGPvalues = getMultiNormal(mean,U1.getU()).getData();
720
721 return addGPvalues;
722
723 }
724
725 // public PairGP sortNew(double [] newPoints){
726 // double [] newPoints2= new double[newPoints.length];
727 // int [] newOrder=new int[newPoints.length];
728
729 //
730 // double pivot=newPoints[0];
731 // for (int j=0; j<newPoints.length;j++){
732 //
733 // }
734 // newPoints2;
735 //
736 //
737 // return new PairGP(newPoints2,newOrder);
738 // }
739
740 public Trip1GP getGPvalues(double [] currentChangePoints, DenseVector currentGPvalues, double newChangePoints, double precision){
741 int currentLength=currentChangePoints.length;
742 int addLength=1;
743 int newLength = currentLength+addLength;
744 // Takes the currentChangePoints and the newChangePoints into getData() but ordered and the order in getOrder()
745 // assumes that order numbers 0..currentLength are the positions of currentChangePoints
746 // and currentLength..newLength - currentLentgth are the positions of newChangePoints
747 Quaduple1GP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
748
749 // index=tempPair.getOrder();
750 // totalChangePoints=tempPair.getData();
751 // This is a silly thing to only compute the Q.matrix for the neighbors of the newChangePoints
752 // Takes the positions of the newData in the new complete sorted data and adds the positions of neighbors
753
754
755 int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew());
756
757
758 // Retrieves the positions indicated in NeigborsIndex from the complete sorted data
759 DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
760
761 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
762
763
764 // Retrieves the positions indicated in NeighborsIndex from the getOrder
765 // int [] NeighborsOriginal= SubsetData(tempQuad.getOrder(),NeighborsIndex);
766
767 // System.err.println("neighborsOriginal"+NeighborsOriginal[0]+"b:"+NeighborsOriginal[1]+"c"+NeighborsOriginal[2]);
768 //
769
770 double part=0.0;
771 double varf=1.0;
772 if (NeighborsIndex.length==3){
773 varf = Q.get(1,1);
774
775
776 part = -currentGPvalues.get(NeighborsIndex[0])*Q.get(1,0)-currentGPvalues.get(NeighborsIndex[1])*Q.get(1,2);
777
778 }
779 if (NeighborsIndex.length==2){
780 varf = Q.get(0,0);
781 part = -currentGPvalues.get(NeighborsIndex[0])*Q.get(0,1);
782 }
783 double res =(part/varf)+(MathUtils.nextGaussian()/Math.sqrt(varf));
784
785 return new Trip1GP(res,tempQuad.getOrder(),tempQuad.getPositionNew());
786 }
787
788 public double[] getGPvalue(double [] currentChangePoints, DenseVector currentGPvalues, double newChangePoints, double precision){
789
790 int currentLength=currentChangePoints.length;
791 int addLength=1;
792 // int newLength = currentLength+addLength;
793 Quaduple1GP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
794 int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew());
795 DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
796
797
798 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
799
800 double part=0.0;
801 double varf=1.0;
802 if (NeighborsIndex.length==3){
803 varf = Q.get(1,1);
804
805 part = -currentGPvalues.get(NeighborsIndex[0])*Q.get(1,0)-currentGPvalues.get(NeighborsIndex[1])*Q.get(1,2);
806
807 }
808 if (NeighborsIndex.length==2){
809 varf = Q.get(0,0);
810 part = -currentGPvalues.get(NeighborsIndex[0])*Q.get(0,1);
811 }
812 double res =(part/varf)+(MathUtils.nextGaussian()/Math.sqrt(varf));
813 double logpr=0.5*Math.log(varf)-0.5*varf*Math.pow(res-(part/varf),2);
814 double [] end=new double[3];
815 end[0]=res;
816 end[1]=logpr;
817 end[2]=tempQuad.getPositionNew();
818 // System.err.println("here"+end[2]);
819 return end;
820 }
821
822 public double[] getGPvalueroot(double [] currentChangePoints, DenseVector currentGPvalues, double newChangePoints, double precision){
823 //Here, we know that the newChangePoint is larger than all the currentChangePoints, so we only need one currentChangePoint
824 // and one currentGPvalues (the last one)
825
826 // int currentLength=currentChangePoints.length;
827 // int addLength=1;
828 // int newLength = currentLength+addLength;
829 // Quaduple1GP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
830 // int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew());
831 // DenseVector tempData = new DenseVector(SubsetData(tempQuad.getData(),NeighborsIndex));
832 double [] tempD=new double[2];
833 double part=0.0;
834 double varf=1.0;
835 if (currentChangePoints[currentChangePoints.length-1]<newChangePoints){
836 tempD[0]=currentChangePoints[currentChangePoints.length-1];
837 tempD[1]=newChangePoints;
838 DenseVector tempData=new DenseVector(tempD);
839 // System.err.println(tempData);
840 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
841
842
843 varf = Q.get(1,1);
844 part = -currentGPvalues.get(currentGPvalues.size()-1)*Q.get(0,1);
845 }
846 else {
847 tempD[1]=currentChangePoints[currentChangePoints.length-1];
848 tempD[0]=newChangePoints;
849 DenseVector tempData=new DenseVector(tempD);
850 // System.err.println(tempData);
851 SymmTridiagMatrix Q = getQmatrix(precision, tempData);
852
853
854 varf = Q.get(0,0);
855 part = -currentGPvalues.get(currentGPvalues.size()-1)*Q.get(0,1);
856
857
858 }
859
860 double res =(part/varf)+(MathUtils.nextGaussian()/Math.sqrt(varf));
861 double logpr=0.5*Math.log(varf)-0.5*varf*Math.pow(res-(part/varf),2);
862 double [] end=new double[2];
863 end[0]=res;
864 end[1]=logpr;
865 return end;
866 }
867
868 public double getDensity(double [] currentChangePoints, DenseVector currentGPvalues, double newChangePoints, double precision,int who){
869 double [] temp;
870 SymmTridiagMatrix Q;
871 double part=0.0;
872 double varf=1.0;
873 // System.err.println("who"+who);
874
875 if (who==0){
876 temp=new double[2];
877 temp[0]=newChangePoints;
878 temp[1]=currentChangePoints[1];
879 DenseVector tempData = new DenseVector(temp);
880
881
882 Q = getQmatrix(precision, tempData);
883 varf = Q.get(0,0);
884 part = -currentGPvalues.get(1)*Q.get(0,1);
885 }
886
887 if (who==currentChangePoints.length-1){
888 temp=new double[2];
889 temp[0]=currentChangePoints[who-1];
890 temp[1]=newChangePoints;
891 DenseVector tempData = new DenseVector(temp);
892 Q = getQmatrix(precision, tempData);
893 varf = Q.get(1,1);
894 part = -currentGPvalues.get(0)*Q.get(0,1);
895 }
896 if (who>0 & who<currentChangePoints.length-1){
897 // System.err.println("whooo");
898 temp=new double[3];
899 temp[0]=currentChangePoints[who-1];
900 temp[1]=newChangePoints;
901 temp[2]=currentChangePoints[who+1];
902 DenseVector tempData = new DenseVector(temp);
903 Q = getQmatrix(precision, tempData);
904 varf = Q.get(1,1);
905 part = -currentGPvalues.get(who-1)*Q.get(1,0)-currentGPvalues.get(who+1)*Q.get(1,2);
906
907
908 }
909 // Quaduple1GP tempQuad= sortUpdate(currentChangePoints, newChangePoints);
910 // int [] NeighborsIndex =Neighbors(tempQuad.getPositionNew());
911 double res =currentGPvalues.get(who);
912 double logpr=0.5*Math.log(varf)-0.5*varf*Math.pow(res-(part/varf),2);
913 return logpr;
914 }
915
916 public double sigmoidal (double x){
917 return 1/(1+Math.exp(-x));
918 }
919
920 public void addOnePoint(double gpval, double location, int positions, int where){
921 GPcounts.setParameterValue(where,GPcounts.getParameterValue(where)+1.0);
922 popSizeParameter.addDimension(positions,gpval);
923 changePoints.addDimension(positions, location);
924 GPtype.addDimension(positions,-1.0);
925 coalfactor.addDimension(positions,GPcoalfactor[where]);
926 }
927
928 public void delOnePoint(int positions, int locIntervals){
929 popSizeParameter.removeDimension(positions);
930 changePoints.removeDimension(positions);
931 GPtype.removeDimension(positions);
932 coalfactor.removeDimension(positions);
933 GPcounts.setParameterValue(locIntervals,GPcounts.getParameterValue(locIntervals)-1.0);
934 }
935
936 public int wherePoint(double point, int x, double lower) {
937 int z=0;
938 int found=0;
939 if (x==-1){
940 z=0;
941 }
942 if (x>=0){
943 z=CoalPosIndicator[x]+1;
944 }
945 while (found==0){
946 if (point<=lower+GPvalue.getInterval(z)){
947 found=1;
948 } else {
949 lower+=GPvalue.getInterval(z);
950 z++;
951 }
952 }
953
954 return z;
955 }
956
957 public int searchPos(double[] dataFind, double oldValue, double newValue, int currentPosition){
958 boolean found=false;
959 if (oldValue<newValue){
960 // look back
961 while (found==false){
962 currentPosition--;
963 if (dataFind[currentPosition]<=oldValue){
964 found=true;
965 }
966 }
967 } else {
968 while (found==false){
969 currentPosition++;
970 if(dataFind[currentPosition]>=oldValue){
971 found=true;
972 }
973 }
974 }
975 return currentPosition;
976 }
977
978 public void writeChain(double [] current,String fileName){
979 try {
980 BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true));
981 for (int i=0;i<current.length;i++){
982 writer.write(current[i]+" ");
983 }
984 writer.newLine();
985 writer.close();
986 }
987 catch(java.io.IOException ioe){
988 System.err.println("IOException:"+ ioe.getMessage());
989 }
990 }
991
992
993 public void numberThinned(double [] currentChangePoints, DenseVector currentPopSize, double currentPrecision) {
994 numberPoints=CoalCounts.getSize();
995 double [] addPoints=new double[numberPoints];
996 int [] indAPoint = new int[numberPoints];
997 int [] indicator =new int[numberPoints];
998 double lowL = 0.0;
999 double uppL =0.0;
1000 TripGP tempG;
1001 double accept=0.0;
1002 double ltime=0.0;
1003 int where=0;
1004 int who=0;
1005 int k=0;
1006 int k1=0;
1007 int fix=0;
1008
1009
1010 // Proposes to add/delete and proposes location uniformly in each intercoalescent interval
1011 for (int j=0; j<numberPoints; j++){
1012 uppL+=GPvalue.getGPCoalInterval(j);
1013
1014
1015 if (MathUtils.nextDouble()<0.5) {
1016 indicator[j]=1;
1017 addPoints[k]=MathUtils.uniform(lowL,uppL);
1018 indAPoint[k]=wherePoint(addPoints[k],j-1,lowL);
1019 k++;
1020 }
1021 lowL=uppL;
1022 }
1023
1024 double [] addPoints2 = new double[k];
1025
1026 System.arraycopy(addPoints,0,addPoints2,0,k);
1027 tempG = getGPvalues(currentChangePoints, currentPopSize, addPoints2,currentPrecision);
1028 for (int i=0; i<numberPoints;i++){
1029 if (indicator[i]==1){
1030 accept=lambdaBoundParameter.getParameterValue(0)*GPvalue.getGPCoalInterval(i)*GPcoalfactor[indAPoint[k1]]*sigmoidal(-tempG.getData()[k1])/(CoalCounts.getParameterValue(i)+1);
1031 if (MathUtils.nextDouble()<accept) {
1032 addOnePoint(tempG.getData()[k1], addPoints2[k1], tempG.getNewOrder()[k1] + fix, indAPoint[k1]);
1033 CoalCounts.setParameterValue(i,CoalCounts.getParameterValue(i)+1);
1034 } else {
1035 fix--;}
1036 k1++;
1037
1038 } else {
1039 double temp=CoalCounts.getParameterValue(i);
1040 if (temp>1){
1041 // it's 0 inclusive, no need to -1
1042 int rdm = MathUtils.nextInt((int) temp-1);
1043 who=where+rdm;
1044 accept=temp/(lambdaBoundParameter.getParameterValue(0)*GPvalue.getGPCoalInterval(i)*sigmoidal(-popSizeParameter.getParameterValue(who))*coalfactor.getParameterValue(who));
1045 if (MathUtils.nextDouble()<accept){
1046 if (i>0) {ltime=CoalTime[i-1];} else {ltime=0.0;}
1047 int locationIntervals=wherePoint(changePoints.getParameterValue(who),i-1, ltime);
1048 delOnePoint(who+1,locationIntervals);
1049 CoalCounts.setParameterValue(i,CoalCounts.getParameterValue(i)-1);
1050 fix--;
1051
1052 }
1053 }
1054 if (temp==1){
1055 if (i>0) {ltime=CoalTime[i-1];} else {ltime=0.0;}
1056 int locationIntervals=wherePoint(changePoints.getParameterValue(where), i - 1, ltime);
1057 delOnePoint(where+1,locationIntervals);
1058 CoalCounts.setParameterValue(i,0);
1059 fix--;
1060 }
1061 }
1062 where+=CoalCounts.getParameterValue(i)+1;
1063 }
1064
1065 }
1066
1067
1068 public void locationThinned(double [] currentChangePoints, DenseVector currentPopSize, double currentPrecision) {
1069 // Sample the interval
1070 double where;
1071 double lowL = 0.0;
1072 double [] toAdd;
1073 double [] toDel;
1074 double uppL =0.0;
1075 double cum=0.0;
1076 boolean got=false;
1077 double Tlen=0.0;
1078 double numberPoints=CoalCounts.getSize();
1079 for (int j=0; j<numberPoints; j++){
1080 if (CoalCounts.getParameterValue(j)>0) {
1081 Tlen+=GPvalue.getGPCoalInterval(j);
1082 }
1083 }
1084 // Need to only consider the intevals with latent points
1085 int j=0;
1086 int [] ind;
1087 int [] ind2;
1088 double [] toDelG;
1089 int position =0;
1090 int oldPos=0;
1091 double accept;
1092 if (Tlen>0){
1093 where= MathUtils.uniform(0,Tlen);
1094 while (!got) {
1095 cum+=GPvalue.getGPCoalInterval(j);
1096 if (CoalCounts.getParameterValue(j)>0){
1097 uppL+=GPvalue.getGPCoalInterval(j);
1098 if (where>lowL & where<=uppL){
1099 got=true;
1100 }
1101
1102 lowL=uppL;
1103 }
1104 position+=CoalCounts.getParameterValue(j)+1;
1105 j++;
1106 }
1107 j--;
1108 position-=CoalCounts.getParameterValue(j)+1;
1109 Trip1GP tempG;
1110 int m=(int) CoalCounts.getParameterValue(j);
1111 toAdd=new double[m];
1112 toDelG=new double[m];
1113 ind= new int[m];
1114 toDel= new double[m];
1115 ind2= new int[m];
1116
1117 for (int i=0; i<m; i++){
1118 toAdd[i]=MathUtils.uniform(cum-GPvalue.getGPCoalInterval(j),cum);
1119 // System.err.println("add"+toAdd[i]+"from:"+(cum-GPvalue.getGPCoalInterval(j))+"check"+CoalTime[j]);
1120 ind[i]=wherePoint(toAdd[i],j-1,cum-GPvalue.getGPCoalInterval(j));
1121 toDel[i]=currentChangePoints[position+i];
1122 toDelG[i]=currentPopSize.get(position+i);
1123 // System.err.println("verify:"+toDel[i]+"be replaced by"+toAdd[i]+"in?"+ind[i]+"interval:"+(cum-GPvalue.getGPCoalInterval(j))+"and"+cum);
1124 ind2[i]=wherePoint(changePoints.getParameterValue(position+i),j-1,cum-GPvalue.getGPCoalInterval(j));
1125 // System.err.println(i+": to add:"+toAdd[i]+"and pos"+position);
1126 }
1127
1128 //
1129
1130
1131 // Arrays.sort(index,toAdd);
1132 for (int i=0; i<m; i++){
1133 tempG = getGPvalues(currentChangePoints, currentPopSize, toAdd[i],currentPrecision);
1134
1135
1136 // tempG=getGPvalues(currentChangePoints,currentPopSize,toAdd[i],currentPrecision);
1137 // System.err.println(tempG.getNewOrder()+" as new order");
1138 // System.err.println("gp fac old:"+GPcoalfactor[ind2[i]]+" gp factor new"+GPcoalfactor[ind[i]]);
1139 // System.err.println("gp val old:"+toDelG[i]+" gp val new:"+tempG.getData());
1140 //
1141 accept=(GPcoalfactor[ind[i]]*sigmoidal(-tempG.getData()))/(GPcoalfactor[ind2[i]]*(sigmoidal(-toDelG[i])));
1142
1143 if (MathUtils.nextDouble()<accept){
1144 // System.err.println("here2");
1145 addOnePoint(tempG.getData(),toAdd[i],tempG.getNewOrder(),ind[i]);
1146 currentChangePoints=(double []) changePoints.getParameterValues();
1147 currentPopSize=new DenseVector(popSizeParameter.getParameterValues());
1148
1149 oldPos=searchPos(currentChangePoints,toDel[i],toAdd[i],tempG.getNewOrder());
1150 //
1151 // System.err.println("removes in location"+toDel[i]+"pos"+oldPos+"value?"+changePoints.getParameterValue(oldPos)+"from"+ind2[i]);
1152 delOnePoint(oldPos+1,ind2[i]);
1153 currentChangePoints = (double []) changePoints.getParameterValues();
1154 currentPopSize=new DenseVector(popSizeParameter.getParameterValues());
1155 }
1156 }
1157 }
1158 }
1159
1160 public double forLikelihood(double [] Gvalues, Parameter Gtype){
1161 double loglik=0.0;
1162 for (int j=0;j<Gvalues.length;j++){
1163
1164 loglik-=Math.log(1+Math.exp(-Gtype.getParameterValue(j)*Gvalues[j]));
1165 }
1166 return loglik;
1167 }
1168
1169 public void sliceSampling(double [] currentChangePoints, DenseVector currentPopSize, double currentPrecision){
1170 double theta;
1171 double thetaPrime=0.0;
1172 int keep = 1;
1173 double [] zeross = new double[currentPopSize.size()];
1174 DenseVector v= new DenseVector(zeross);
1175 DenseVector v1 = new DenseVector(zeross);
1176 DenseVector v2 = new DenseVector(zeross);
1177 DenseVector proposal = new DenseVector(zeross);
1178 currentQ=getQmatrix(currentPrecision,currentChangePoints);
1179
1180 UpperSPDBandMatrix U = new UpperSPDBandMatrix(currentQ,1);
1181 BandCholesky U1 = new BandCholesky(zeross.length,1,true);
1182 U1.factor(U);
1183
1184 v= getMultiNormal(v1,U1.getU());
1185
1186 theta=MathUtils.uniform(0,TWO_TIMES_PI);
1187 v1.add(Math.sin(theta),currentPopSize);
1188
1189 v1.add(Math.cos(theta),v);
1190 v2.add(Math.cos(theta),currentPopSize);
1191 v2.add(-Math.sin(theta),v);
1192
1193 double thetaMin=0.0;
1194 double thetaMax=TWO_TIMES_PI;
1195 double [] popSize = currentPopSize.getData();
1196 double loglik=Math.log(MathUtils.nextDouble())+forLikelihood(popSize,GPtype);
1197 // System.err.println("loglik"+loglik);
1198 double loglik2=0.0;
1199
1200 while (keep==1){
1201 thetaPrime=MathUtils.uniform(thetaMin,thetaMax);
1202 // System.err.println("theta Prime"+thetaPrime+"theta"+theta+"thetaMin"+thetaMin+"thetaMax"+thetaMax);
1203 proposal.zero();
1204 proposal.add(Math.sin(thetaPrime),v1);
1205 proposal.add(Math.cos(thetaPrime),v2);
1206 double [] popSize2 = proposal.getData();
1207 loglik2=forLikelihood(popSize2,GPtype);
1208 // System.err.println("loglik2"+loglik2);
1209
1210 if (loglik2>loglik) {keep=2;}
1211 else {
1212 if (thetaPrime<theta) {thetaMin=thetaPrime;} else {thetaMax=thetaPrime;}
1213 }
1214 }
1215 for (int j=0; j<popSizeParameter.getSize();j++)
1216 popSizeParameter.setParameterValue(j, proposal.get(j));
1217 // popSizeParameter.setParameterValueQuietly(j,proposal.get(j));
1218
1219 // ((Parameter.Abstract) popSizeParameter).fireParameterChangedEvent();
1220
1221 }
1222
1223 // public DenseVector getMultiNormal(DenseVector StandNorm, DenseVector Mean, BandCholesky Cholesky) {
1224 //
1225 // DenseVector returnValue = new DenseVector(zeros);
1226 //
1227 // UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
1228 //
1229 // // 3. Solve L^T v = z
1230 //
1231 // CholeskyUpper.solve(StandNorm, returnValue);
1232 //
1233 // // 4. Return x = \mu + v
1234 //
1235 // returnValue.add(Mean);
1236 //
1237 // return returnValue;
1238 // }
1239 //
1240
1241 // public static DenseVector getMultiNormal(DenseVector Mean, UpperSPDDenseMatrix Variance) {
1242 // int length = Mean.size();
1243 // DenseVector tempValue = new DenseVector(length);
1244 // DenseVector returnValue = new DenseVector(length);
1245 // UpperSPDDenseMatrix ab = Variance.copy();
1246 //
1247 // for (int i = 0; i < returnValue.size(); i++)
1248 // tempValue.set(i, MathUtils.nextGaussian());
1249 //
1250 // DenseCholesky chol = new DenseCholesky(length, true);
1251 // chol.factor(ab);
1252 //
1253 // UpperTriangDenseMatrix x = chol.getU();
1254 //
1255 // x.transMult(tempValue, returnValue);
1256 // returnValue.add(Mean);
1257 // return returnValue;
1258 // }
1259
1260
1261 public static double logGeneralizedDeterminant(UpperTriangBandMatrix Matrix) {
1262 double returnValue = 0;
1263
1264 for (int i = 0; i < Matrix.numColumns(); i++) {
1265 if (Matrix.get(i, i) > 0.0000001) {
1266 returnValue += Math.log(Matrix.get(i, i));
1267 }
1268 }
1269
1270 return returnValue;
1271 }
1272
1273 // public DenseVector newtonRaphson(double[] data, DenseVector currentGamma, SymmTridiagMatrix proposedQ) throws OperatorFailedException {
1274 // return newNewtonRaphson(data, currentGamma, proposedQ, maxIterations, stopValue);
1275 // }
1276
1277 // public static DenseVector newNewtonRaphson(double[] data, DenseVector currentGamma, SymmTridiagMatrix proposedQ,
1278 // int maxIterations, double stopValue) throws OperatorFailedException {
1279 // DenseVector iterateGamma = currentGamma.copy();
1280 // DenseVector tempValue = currentGamma.copy();
1281 //
1282 // int numberIterations = 0;
1283 //
1284 //
1285 // while (gradient(data, iterateGamma, proposedQ).norm(Vector.Norm.Two) > stopValue) {
1286 // try {
1287 // jacobian(data, iterateGamma, proposedQ).solve(gradient(data, iterateGamma, proposedQ), tempValue);
1288 // } catch (MatrixNotSPDException e) {
1289 // Logger.getLogger("dr.evomodel.coalescent.operators.GMRFSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
1290 // throw new OperatorFailedException("");
1291 // } catch (MatrixSingularException e) {
1292 // Logger.getLogger("dr.evomodel.coalescent.operators.GMRFSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
1293 //
1294 // throw new OperatorFailedException("");
1295 // }
1296 // iterateGamma.add(tempValue);
1297 // numberIterations++;
1298 //
1299 // if (numberIterations > maxIterations) {
1300 // Logger.getLogger("dr.evomodel.coalescent.operators.GMRFSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
1301 // throw new OperatorFailedException("Newton Raphson algorithm did not converge within " + maxIterations + " step to a norm less than " + stopValue + "\n" +
1302 // "Try starting BEAST with a more accurate initial tree.");
1303 // }
1304 // }
1305 //
1306 // Logger.getLogger("dr.evomodel.coalescent.operators.GMRFSkyrideBlockUpdateOperator").fine("Newton-Raphson S");
1307 // return iterateGamma;
1308 //
1309 // }
1310
1311 // private static DenseVector gradient(double[] data, DenseVector value, SymmTridiagMatrix Q) {
1312 //
1313 // DenseVector returnValue = new DenseVector(value.size());
1314 // Q.mult(value, returnValue);
1315 // for (int i = 0; i < value.size(); i++) {
1316 // returnValue.set(i, -returnValue.get(i) - 1 + data[i] * Math.exp(-value.get(i)));
1317 // }
1318 // return returnValue;
1319 // }
1320 //
1321 //
1322 // private static SPDTridiagMatrix jacobian(double[] data, DenseVector value, SymmTridiagMatrix Q) {
1323 // SPDTridiagMatrix jacobian = new SPDTridiagMatrix(Q, true);
1324 // for (int i = 0, n = value.size(); i < n; i++) {
1325 // jacobian.set(i, i, jacobian.get(i, i) + Math.exp(-value.get(i)) * data[i]);
1326 // }
1327 // return jacobian;
1328 // }
1329
1330
1331 //In GMRF there is only one MH block proposing precision + GMRF jointly. Here we have : numberThinned,
1332 // locationThinned, the GMRF (GP values), Gibbs sampling precision and the upper bound lambda
1333 public double doOperation() {
1334
1335 System.err.println("Runs my operator");
1336
1337 double currentPrecision = this.precisionParameter.getParameterValue(0);
1338 DenseVector currentPopSize = new DenseVector(popSizeParameter.getParameterValues());
1339 double [] currentChangePoints = this.changePoints.getParameterValues();
1340
1341 currentQ=getQmatrix(currentPrecision,currentChangePoints);
1342 double currentQuadratic = getQuadraticForm(currentQ, currentPopSize);
1343 double newprecision=getNewPrecision(currentPrecision,currentQuadratic);
1344 // Gibbs sample new precision
1345 precisionParameter.setParameterValue(0,newprecision);
1346 currentPrecision=this.precisionParameter.getParameterValue(0);
1347
1348
1349 double currentLambda = this.lambdaBoundParameter.getParameterValue(0);
1350 getNewUpperBound(currentLambda);
1351 currentLambda=this.lambdaBoundParameter.getParameterValue(0);
1352 // System.err.println("before thinned:"+changePoints.getParameterValue(75));
1353 //
1354 numberThinned(currentChangePoints, currentPopSize, currentPrecision);
1355 // System.err.println("after thinned:"+changePoints.getParameterValue(75));
1356 //
1357 DenseVector currentPopSize1 = new DenseVector(popSizeParameter.getParameterValues());
1358 double [] currentChangePoints1 = this.changePoints.getParameterValues();
1359 // System.err.println("finished number"+popSizeParameter.getSize());
1360
1361 locationThinned(currentChangePoints1,currentPopSize1,currentPrecision);
1362
1363 // System.err.println("finished location"+popSizeParameter.getSize());
1364
1365 DenseVector currentPopSize2 = new DenseVector(popSizeParameter.getParameterValues());
1366 // System.err.println("2:"+currentPopSize2);
1367
1368 double [] currentChangePoints2 = this.changePoints.getParameterValues();
1369 // System.exit(-1);
1370
1371 sliceSampling(currentChangePoints2, currentPopSize2, currentPrecision);
1372 numPoints.setParameterValue(0,popSizeParameter.getSize());
1373
1374 double [] currentPopSize3 = this.popSizeParameter.getParameterValues();
1375
1376 int sumcoal=0;
1377 int sumlat=0;
1378
1379 for (int j=0;j<changePoints.getSize();j++){
1380 if( GPtype.getParameterValue(j)==1) {sumcoal++;}
1381
1382 }
1383 for (int j=0;j<CoalCounts.getSize();j++){
1384 sumlat+=CoalCounts.getParameterValue(j);
1385 }
1386 if (sumcoal!=CoalCounts.getSize()){ System.err.println("WARNING CONSISTENCY 1"); }
1387 if (sumlat!=(changePoints.getSize()-CoalCounts.getSize())){ System.err.println("WARNING CONSISTENCY 2"+sumlat+"and changePts size"+changePoints.getSize()); }
1388
1389 // System.err.println("check values 72:"+changePoints.getParameterValue(72)+"type"+GPtype.getParameterValue(72));
1390 // System.err.println("check values 73:"+changePoints.getParameterValue(73)+"type"+GPtype.getParameterValue(73));
1391
1392 // System.err.println("check values 74:"+changePoints.getParameterValue(74)+"type"+GPtype.getParameterValue(74)+"counts"+GPcounts.getParameterValue(114));
1393 // System.err.println("check values 75:"+changePoints.getParameterValue(75)+"type"+GPtype.getParameterValue(75)+"counts"+GPcounts.getParameterValue(115));
1394 // System.err.println("check values 76:"+changePoints.getParameterValue(76)+"type"+GPtype.getParameterValue(76)+"counts"+GPcounts.getParameterValue(116));
1395 // System.err.println("check values 3:"+changePoints.getParameterValue(3)+"type"+GPtype.getParameterValue(3)+"counts"+GPcounts.getParameterValue(16));
1396 // System.err.println("check values 4:"+changePoints.getParameterValue(4)+"type"+GPtype.getParameterValue(4)+"counts"+GPcounts.getParameterValue(18));
1397 // System.err.println("check values 5:"+changePoints.getParameterValue(5)+"type"+GPtype.getParameterValue(5)+"counts"+GPcounts.getParameterValue(19));
1398 //
1399 // writeChain(currentChangePoints2,"locations.txt");
1400 // writeChain(currentPopSize3,"gvalues.txt");
1401
1402
1403
1404 //
1405 ////
1406 // System.err.println("type after"+GPtype.getSize());
1407
1408 //
1409 //
1410 //// ArrayList<ComparableDouble> times = new ArrayList<ComparableDouble>();
1411 //// ArrayList<Integer> childs = new ArrayList<Integer>();
1412 //// collectAllTimes(tree, root, exclude, times, childs);
1413 //// int[] indices = new int[times.size()];
1414 //
1415 //
1416 //
1417 //// double currentPrecision = precisionParameter.getParameterValue(0);
1418 // double proposedPrecision = this.getNewPrecision(currentPrecision, scaleFactor);
1419 //
1420 //// double currentLambda = this.lambdaParameter.getParameterValue(0);
1421 // double proposedLambda = currentLambda;
1422 //
1423 // precisionParameter.setParameterValue(0, proposedPrecision);
1424 // lambdaParameter.setParameterValue(0, proposedLambda);
1425 //
1426 // DenseVector currentGamma = new DenseVector(GPvalue.getPopSizeParameter().getParameterValues());
1427 // DenseVector proposedGamma;
1428 //
1429 //// SymmTridiagMatrix currentQ = GPvalue.getStoredScaledWeightMatrix(currentPrecision, currentLambda);
1430 //// SymmTridiagMatrix proposedQ = GPvalue.getScaledWeightMatrix(proposedPrecision, proposedLambda);
1431 //
1432 //
1433 //
1434 //
1435 //// double[] wNative = gmrfField.getSufficientStatistics();
1436 //
1437 //// UpperSPDBandMatrix forwardQW = new UpperSPDBandMatrix(proposedQ, 1);
1438 //// UpperSPDBandMatrix backwardQW = new UpperSPDBandMatrix(currentQ, 1);
1439 ////
1440 //// BandCholesky forwardCholesky = new BandCholesky(wNative.length, 1, true);
1441 //// BandCholesky backwardCholesky = new BandCholesky(wNative.length, 1, true);
1442 ////
1443 //// DenseVector diagonal1 = new DenseVector(fieldLength);
1444 //// DenseVector diagonal2 = new DenseVector(fieldLength);
1445 //// DenseVector diagonal3 = new DenseVector(fieldLength);
1446 ////
1447 //// DenseVector modeForward = newtonRaphson(wNative, currentGamma, proposedQ.copy());
1448 ////
1449 //// for (int i = 0; i < fieldLength; i++) {
1450 //// diagonal1.set(i, wNative[i] * Math.exp(-modeForward.get(i)));
1451 //// diagonal2.set(i, modeForward.get(i) + 1);
1452 ////
1453 //// forwardQW.set(i, i, diagonal1.get(i) + forwardQW.get(i, i));
1454 //// diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
1455 //// }
1456 ////
1457 //// forwardCholesky.factor(forwardQW.copy());
1458 ////
1459 //// DenseVector forwardMean = getMultiNormalMean(diagonal1, forwardCholesky);
1460 ////
1461 //// DenseVector stand_norm = new DenseVector(zeros);
1462 ////
1463 //// for (int i = 0; i < zeros.length; i++)
1464 //// stand_norm.set(i, MathUtils.nextGaussian());
1465 ////
1466 //// proposedGamma = getMultiNormal(stand_norm, forwardMean, forwardCholesky);
1467 ////
1468 ////
1469 //// for (int i = 0; i < fieldLength; i++)
1470 //// popSizeParameter.setParameterValueQuietly(i, proposedGamma.get(i));
1471 ////
1472 //// ((Parameter.Abstract) popSizeParameter).fireParameterChangedEvent();
1473 ////
1474 //
1475 // double hRatio = 0;
1476 //
1477 //// diagonal1.zero();
1478 //// diagonal2.zero();
1479 //// diagonal3.zero();
1480 ////
1481 //// DenseVector modeBackward = newtonRaphson(wNative, proposedGamma, currentQ.copy());
1482 ////
1483 //// for (int i = 0; i < fieldLength; i++) {
1484 //// diagonal1.set(i, wNative[i] * Math.exp(-modeBackward.get(i)));
1485 //// diagonal2.set(i, modeBackward.get(i) + 1);
1486 ////
1487 //// backwardQW.set(i, i, diagonal1.get(i) + backwardQW.get(i, i));
1488 //// diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
1489 //// }
1490 ////
1491 //// backwardCholesky.factor(backwardQW.copy());
1492 ////
1493 //// DenseVector backwardMean = getMultiNormalMean(diagonal1, backwardCholesky);
1494 ////
1495 //// for (int i = 0; i < fieldLength; i++) {
1496 //// diagonal1.set(i, currentGamma.get(i) - backwardMean.get(i));
1497 //// }
1498 ////
1499 //// backwardQW.mult(diagonal1, diagonal3);
1500 ////
1501 //// // Removed 0.5 * 2
1502 //// hRatio += logGeneralizedDeterminant(backwardCholesky.getU()) - 0.5 * diagonal1.dot(diagonal3);
1503 //// hRatio -= logGeneralizedDeterminant(forwardCholesky.getU() ) - 0.5 * stand_norm.dot(stand_norm);
1504 //
1505 //
1506 //// return hRatio;
1507 //// System.err.println("Prueba");
1508 //// System.exit(-1);
1509 return 0.0;
1510 }
1511
1512 //MCMCOperator INTERFACE
1513 // This is the only part where GPSBUOperateroParser is used
1514 public final String getOperatorName() {
1515 return GaussianProcessSkytrackBlockUpdateOperatorParser.BLOCK_UPDATE_OPERATOR;
1516 }
1517
1518
1519 public double getTemperature() {
1520 return 0.0;
1521 }
1522
1523 /* This is not a coercable operator so shouldn't have these
1524 public double getCoercableParameter() {
1525 // return Math.log(scaleFactor);
1526 return Math.sqrt(scaleFactor - 1);
1527 }
1528
1529 public void setCoercableParameter(double value) {
1530 // scaleFactor = Math.exp(value);
1531 scaleFactor = 1 + value * value;
1532 }
1533 */
1534
1535 public int getStepCount() {
1536 return 1;
1537 }
1538
1539 public double getRawParameter() {
1540 return scaleFactor;
1541 }
1542
1543 public double getScaleFactor() {
1544 return scaleFactor;
1545 }
1546
1547 public double getTargetAcceptanceProbability() {
1548 return 0.234;
1549 }
1550
1551 public double getMinimumAcceptanceLevel() {
1552 return 0.1;
1553 }
1554
1555
1556 public double getMaximumAcceptanceLevel() {
1557 return 0.4;
1558 }
1559
1560 public double getMinimumGoodAcceptanceLevel() {
1561 return 0.20;
1562 }
1563
1564 public double getMaximumGoodAcceptanceLevel() {
1565 return 0.30;
1566 }
1567
1568 public final String getPerformanceSuggestion() {
1569
1570 double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
1571
1572 // double prob = Utils.getAcceptanceProbability(this);
1573 double targetProb = getTargetAcceptanceProbability();
1574 dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
1575
1576 double sf = OperatorUtils.optimizeWindowSize(scaleFactor, prob, targetProb);
1577
1578 if (prob < getMinimumGoodAcceptanceLevel()) {
1579 return "Try setting scaleFactor to about " + formatter.format(sf);
1580 } else if (prob > getMaximumGoodAcceptanceLevel()) {
1581 return "Try setting scaleFactor to about " + formatter.format(sf);
1582 } else return "";
1583 }
1584
1585
1586 // public DenseVector oldNewtonRaphson(double[] data, DenseVector currentGamma, SymmTridiagMatrix proposedQ) throws OperatorFailedException{
1587 // return newNewtonRaphson(data, currentGamma, proposedQ, maxIterations, stopValue);
1588 //
1589 //}
1590 //
1591 //public static DenseVector newtonRaphson(double[] data, DenseVector currentGamma, SymmTridiagMatrix proposedQ,
1592 //int maxIterations, double stopValue) {
1593 //
1594 //DenseVector iterateGamma = currentGamma.copy();
1595 //int numberIterations = 0;
1596 //while (gradient(data, iterateGamma, proposedQ).norm(Vector.Norm.Two) > stopValue) {
1597 //inverseJacobian(data, iterateGamma, proposedQ).multAdd(gradient(data, iterateGamma, proposedQ), iterateGamma);
1598 //numberIterations++;
1599 //}
1600 //
1601 //if (numberIterations > maxIterations)
1602 //throw new RuntimeException("Newton Raphson algorithm did not converge within " + maxIterations + " step to a norm less than " + stopValue);
1603 //
1604 //return iterateGamma;
1605 //}
1606 //
1607 //private static DenseMatrix inverseJacobian(double[] data, DenseVector value, SymmTridiagMatrix Q) {
1608 //
1609 // SPDTridiagMatrix jacobian = new SPDTridiagMatrix(Q, true);
1610 // for (int i = 0; i < value.size(); i++) {
1611 // jacobian.set(i, i, jacobian.get(i, i) + Math.exp(-value.get(i)) * data[i]);
1612 // }
1613 //
1614 // DenseMatrix inverseJacobian = Matrices.identity(jacobian.numRows());
1615 // jacobian.solve(Matrices.identity(value.size()), inverseJacobian);
1616 //
1617 // return inverseJacobian;
1618 // }
1619 }