Debian Codegraph @

src/dr/oldevomodel/indel/HomologyRecursion.java

raw symbols SCIP
1 /*
2 * HomologyRecursion.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.oldevomodel.indel;
27
28
29 import dr.evolution.alignment.Alignment;
30 import dr.evolution.datatype.DataType;
31 import dr.evolution.tree.NodeRef;
32 import dr.evolution.tree.Tree;
33 import dr.oldevomodel.substmodel.SubstitutionModel;
34 import dr.math.BFloat;
35
36 import java.util.HashMap;
37
38 public class HomologyRecursion {
39
40 /** Array of 0-1 vectors, encoding the alignment as columns */
41 IntMathVec[] iAlignment;
42
43 /** Array of arrays, encoding the sequences (in rows). No gaps. Range [0,iNumNucs). */
44 int[][] iSequences;
45
46 /**
47 * Array encoding the tree.
48 * iParent[iChild] is the parent of iChild, except -1 = root's parent.
49 * Parent must be > child, and leaf indices must correspond to indices into alignment vectors
50 */
51 private int[] iParent;
52
53 /** Length of incoming branches to each tree node. Root is assumed to be infinity */
54 private double[] iTau;
55
56 /** Parameters of the TKF91 model */
57 double iLambda;
58 double iMu;
59
60 /** Number of nucleotides */
61 int iNumNucs;
62
63 /** Transition probability matrices, iTrans[node][from][to], for each tree node except root */
64 double[][][] iTrans;
65
66 /** Equilibrium probabilities for nucleotides. */
67 double[] iEquil;
68
69 /** Intermediate results for TKF91 model, initialised in recursion(), used in treeRecursion() */
70 private double iH[], iN[], iB[], iE[];
71
72 /** TKF91-related result for initialising the DP table */
73 private double iInitial;
74
75 /** Class that implements a fast version of treeLikelihood */
76 private NativeTreeLikelihood iNativeMethod;
77
78 /** Labels used in local array iState[] */
79 static private final int eFree = 0, ePossible = 1, eEdgeUsed = 2, eUsed = 3;
80
81 /** Max dimension of unalignable region */
82 static private final int cMaxUnalignDimension = 10;
83
84 /** Minimum edge length */
85 static private final double MIN_EDGE_LENGTH = 1e-3;
86
87 /** Error count */
88 static int sBigUnalignableRegion = 0;
89
90 String PrintDouble(double[] d) {
91 String str = "";
92 for(double aD : d) {
93 str = str + aD + " ";
94 }
95 return str;
96 }
97
98 void checkConsistency() {
99 // Checks whether variables are init'ed properly
100 int iCols = iAlignment.length;
101 int iRows = iAlignment[0].iV.length;
102 String iErr = "";
103 IntMathVec iPos = new IntMathVec( iRows );
104 for (int i=0; i<iCols; i++) {
105 for (int j=0; j<iRows; j++) {
106 if (iAlignment[i].iV[j] != 0 && iAlignment[i].iV[j] != 1) {
107 iErr = "Non-0/1 emissions.";
108 }
109 }
110 iPos.add( iAlignment[i] );
111 }
112 for (int j=0; j<iRows; j++) {
113 if (iSequences[j].length != iPos.iV[j]) {
114 iErr = "Bad sequences length";
115 }
116 for (int i=0; i<iPos.iV[j]; i++) {
117 if ((iSequences[j][i]<0)||(iSequences[j][i]>=iNumNucs)) {
118 iErr = "Nucleotide codes in iSequences not in range, " + iSequences[j][i] + "not in [0,"+(iNumNucs-1)+"]";
119 }
120 }
121 }
122 int[] iChildren = new int[ iParent.length ];
123 for (int i=0; i<iParent.length-1; i++)
124 iChildren[ iParent[i] ]++;
125 for (int i=0; i<iRows; i++)
126 if (iChildren[i] != 0) {
127 iErr = "Num tips does not correspond to num sequences, or bad tree";
128 }
129 for (int i=iRows; i<iParent.length; i++)
130 if (iChildren[i] != 2) {
131 iErr = "Bad tree - not binary? Or too many tips?";
132 }
133 if (iParent[iParent.length-1] != -1) {
134 iErr = "Bad tree - root not in final position, or not labeled -1";
135 }
136 for (int i=0; i<iParent.length-1; i++) {
137 if (iTau[i] < MIN_EDGE_LENGTH) {
138 iErr = "";//Bad tree - edge lengths below threshold (edge " + i + ", len " + iTau[i] + ")";
139 iTau[i] = MIN_EDGE_LENGTH;
140 }
141 }
142
143 //for (int i=0; i < iAlignment.length; i++) {
144 // System.out.println(iAlignment[i]);
145 //}
146
147 if ( !iErr.equals("") )
148 System.out.println(iErr);
149 }
150
151
152
153 public HomologyRecursion() {
154 // Nothing? Initialisation is done manually through init() below.
155 }
156
157 public void init(Tree tree, Alignment alignment, SubstitutionModel substModel,
158 double mutationRate, double lengthDistr, double deathRate) {
159
160 // initialize the iParent and iTau arrays based on the given tree.
161 initTree(tree, mutationRate);
162
163 int[] treeIndex = new int[tree.getTaxonCount()];
164 for (int i =0; i < treeIndex.length; i++) {
165 treeIndex[i] = tree.getTaxonIndex(alignment.getTaxonId(i));
166 //System.out.println("alignment[" + i + "] = tree[" + treeIndex[i] + "]");
167 }
168
169 // initialize the iAlignment array from the given alignment.
170 initAlignment(alignment, treeIndex);
171
172 // initialize the iSequences array from the given alignment.
173 initSequences(alignment, treeIndex);
174
175 // initialize the iTrans array from the substitution model -- must be called after populating tree!
176 initSubstitutionModel(substModel);
177
178 // iLambda, iMu
179 iLambda = deathRate*lengthDistr;
180 iMu = deathRate;
181
182 // iNumNucs - alphabet size
183 DataType dataType = substModel.getDataType();
184 iNumNucs = dataType.getStateCount();
185
186 // Initialise TKF91 coefficients in iB, iH, iN, iE, and iInitial
187 initTKF91();
188
189 // Check
190 checkConsistency();
191
192 // Initialise native method
193 iNativeMethod = new NativeTreeLikelihood();
194 iNativeMethod.init(iNumNucs, cMaxUnalignDimension, iParent, iEquil, iTrans, iSequences, iN, iH, iE, iB);
195
196 }
197
198 private void initTree(Tree tree, double mutationRate) {
199 iParent = new int[tree.getNodeCount()];
200 iTau = new double[tree.getNodeCount()-1];
201 populate(tree, tree.getRoot(), new int[] {tree.getExternalNodeCount()}, mutationRate);
202 iParent[tree.getNodeCount()-1] = -1;
203
204 }
205
206 /**
207 * initialize the iTrans array from the substitution model -- must be called after populating tree!
208 */
209 private void initSubstitutionModel(SubstitutionModel model) {
210
211 DataType dataType = model.getDataType();
212 int stateCount = dataType.getStateCount();
213
214 iTrans = new double[iTau.length][stateCount][stateCount];
215
216 double[] transProb = new double[stateCount*stateCount];
217 int count;
218 for (int i =0; i < iTau.length; i++) {
219 model.getTransitionProbabilities(iTau[i], transProb);
220 count = 0;
221 for (int j = 0; j < stateCount; j++) {
222 for (int k = 0; k < stateCount; k++) {
223 iTrans[i][j][k] = transProb[count];
224 count += 1;
225 }
226 }
227 }
228
229 // initialize equlibrium distribution
230 iEquil = new double[stateCount];
231 for (int k = 0; k < stateCount; k++) {
232 iEquil[k] = model.getFrequencyModel().getFrequency(k);
233 }
234 }
235
236 /**
237 * Initializes the iAlignment array from the given alignment.
238 */
239 private void initAlignment(Alignment alignment, int[] treeIndex) {
240
241 int numSeqs = alignment.getSequenceCount();
242 int numSites = alignment.getSiteCount();
243 DataType dataType = alignment.getDataType();
244 int numStates = dataType.getStateCount();
245
246 iAlignment = new IntMathVec[numSites];
247
248 int[] column = new int[numSeqs];
249 for (int i =0; i < numSites; i++) {
250 for (int j = 0; j < numSeqs; j++) {
251 column[treeIndex[j]] = ((alignment.getState(j, i) >= numStates) ? 0 : 1);
252 }
253 iAlignment[i] = new IntMathVec(column);
254 }
255 }
256
257 /**
258 * Initializes the iSequence array from the given alignment.
259 */
260 private void initSequences(Alignment alignment, int[] treeIndex) {
261
262 int numSeqs = alignment.getSequenceCount();
263 DataType dataType = alignment.getDataType();
264 int numStates = dataType.getStateCount();
265
266 iSequences = new int[numSeqs][];
267
268 for (int i = 0; i < numSeqs; i++) {
269
270 int seqLength = 0;
271 for (int j =0; j < alignment.getSiteCount(); j++) {
272 int state = alignment.getState(i, j);
273 if (state>=0 && state<numStates) { seqLength += 1;}
274
275 }
276 iSequences[treeIndex[i]] = new int[seqLength];
277 int count = 0;
278 for (int j =0; j < alignment.getSiteCount(); j++) {
279 int state = alignment.getState(i, j);
280 if (state>=0 && state<numStates) {
281 iSequences[treeIndex[i]][count] = state;
282 count += 1;
283 }
284 }
285 }
286 }
287
288 /**
289 * Populates the iParent and iTau arrays.
290 * @return the node number of the given node.
291 */
292 private int populate(Tree tree, NodeRef node, int[] current, double mutationRate) {
293
294 int nodeNumber = node.getNumber();
295
296 // if its an external node just return the number
297 if (tree.isExternal(node)) {
298 iTau[nodeNumber] =
299 (tree.getNodeHeight(tree.getParent(node)) - tree.getNodeHeight(node)) * mutationRate;
300 return nodeNumber;
301 }
302
303 // if internal node, first let your children be assigned numbers
304 int[] childNumbers = new int[tree.getChildCount(node)];
305 for (int i = 0; i < tree.getChildCount(node); i++) {
306 childNumbers[i] = populate(tree, tree.getChild(node, i), current, mutationRate);
307 }
308
309 // now, pick the next available number
310 nodeNumber = current[0];
311 // if you are not the root, then record the branch length above you.
312 if (!tree.isRoot(node)) {
313 //iTau[nodeNumber] = tree.getBranchLength(node) * mutationRate;
314 iTau[nodeNumber] =
315 (tree.getNodeHeight(tree.getParent(node)) - tree.getNodeHeight(node)) * mutationRate;
316 }
317 // increment the next available number
318 current[0] += 1;
319
320 // now that you have your number, populate the iParent entries of your children.
321 for (int i = 0; i < tree.getChildCount(node); i++) {
322 iParent[childNumbers[i]] = nodeNumber;
323 }
324
325 // finally return your number so your parent can do the same.
326 return nodeNumber;
327 }
328
329
330 /**
331 * Populates the iB, iE, iH and iN arrays, and iInitial value
332 * @return void
333 */
334 public void initTKF91() {
335
336 int iNumNodes = iParent.length;
337 double iBeta[] = new double[iNumNodes];
338 iB = new double[iNumNodes];
339 iE = new double[iNumNodes];
340 iH = new double[iNumNodes];
341 iN = new double[iNumNodes];
342 iInitial = 1.0;
343 for (int i=0; i<iNumNodes; i++) {
344 if (i==iNumNodes-1) {
345 // root
346 iBeta[ i ] = 1.0/iMu;
347 iH[i] = 0.0;
348 } else {
349 // internal node or tip
350 iBeta[ i ] = Math.exp((iLambda-iMu)*iTau[i]);
351 iBeta[ i ] = (1.0-iBeta[i])/(iMu-iLambda*iBeta[i]);
352 iH[i] = Math.exp(-iMu*iTau[i])*(1.0-iLambda*iBeta[i]);
353 }
354 iB[i] = iLambda*iBeta[i];
355 iE[i] = iMu*iBeta[i];
356 iN[i] = (1.0-iMu*iBeta[i])*(1.0-iB[i]) - iH[i];
357 iInitial *= (1.0 - iB[i]);
358 }
359 }
360
361
362 /**
363 * Calculates 'conditional factor' associated to emission encoded by iSignature, at position iPos.
364 * Nulls in iSignature represent no-emissions, others indicate homology family (1,2,...,cMaxUnalignDimension, inclusive)
365 */
366 private double treeRecursion(IntMathVec iSignature, IntMathVec iPos) {
367
368 // See if we can use C code
369 if (iNativeMethod.isAvailable()) {
370 return iNativeMethod.treeRecursion(iSignature, iPos);
371 }
372
373 int iLeaves = iSignature.iV.length; // Dimension of alignment columns, i.e. number of leaves
374 int iNumNodes = iParent.length; // Number of internal nodes
375 int[] iHom = new int[ iNumNodes ]; // Homology for every node; 0 if node need not be homologous to an emitted nucleotide
376 int[] iHomNum = new int[ iNumNodes ]; // Number of homologous emissions accounted for by homologous nucleotide @ this node
377 int[] iHomMultiplicity = new int[ cMaxUnalignDimension+1 ]; // Number of emissions for each class of homologous nucleotides
378 int[] iChild1 = new int[ iNumNodes ], iChild2 = new int[ iNumNodes ]; // Left and right children
379 double[][] iFh = new double[ iNumNodes ][], iFi = new double[ iNumNodes ][]; // Fhomolgous and Finhomologous arrays
380
381 // Initialise stuff
382 for (int i=0; i<iNumNodes; i++) {
383 iFh[i] = new double[ iNumNucs ];
384 iFi[i] = new double[ iNumNucs + 1]; // Extra position for 'gap' entry
385 }
386 for (int i=0; i<iLeaves; i++) {
387 iHomMultiplicity[ iSignature.iV[ i ] ]++;
388 iHom[ i ] = iSignature.iV[ i ];
389 if (iSignature.iV[i] == 0)
390 iHomNum[ i ] = 0;
391 else
392 iHomNum[ i ] = 1;
393 }
394
395 // Loop over all nodes except root, and find out which nodes need carry nucleotides of what
396 // homology class. Also fill iChild* arrays, which point to the two children of every parent.
397 boolean iClashingHomology = false;
398 for (int i=0; i<iNumNodes-1; i++) {
399 if ((iHomNum[i] == iHomMultiplicity[ iHom[i] ]) || (iHom[i] == 0)) {
400 // This node is the MRCA of the homologous nucleotides iHom[i], or a gap - do nothing
401 } else {
402 if (iHom[ iParent[ i ]] == 0 || iHom[ iParent[ i ]] == iHom[i]) {
403 // This node is not yet MRCA, so node above must be homologous
404 iHom[iParent[i]] = iHom[i];
405 // If iHom[i]==0, iHomNum[i]==0.
406 iHomNum[iParent[i]] += iHomNum[i];
407 } else {
408 // Clashing homology; signal
409 iClashingHomology = true;
410 }
411 }
412 if (iChild1[ iParent[ i ] ] == 0)
413 iChild1[ iParent[ i ] ] = i;
414 else
415 iChild2[ iParent[ i ] ] = i;
416 }
417
418 // Bail out - cheaper than do this implicitly in the recursion below
419 if (iClashingHomology) {
420 return 0.0;
421 }
422
423 // Start recursion. First initialise the leaves
424 for (int i=0; i<iLeaves; i++) {
425 if (iSignature.iV[i] == 0) {
426 // gap
427 iFi[i][iNumNucs] = 1.0;
428 } else {
429 // nucleotide
430 iFh[i][ iSequences[i][iPos.iV[i]] ] = 1.0;
431 }
432 //System.out.println("Fi" + i +" = " + PrintDouble(iFi[i]));
433 //System.out.println("Fh" + i +" = " + PrintDouble(iFh[i]));
434 }
435
436 // Now do the recursion, bottom-up, on all internal nodes
437 for (int i=iLeaves; i<iNumNodes; i++) {
438 // Find out whether:
439 // 1- One homology family spanning tree intersects both child edges, i.e.
440 // a 'homologous' nucleotide should travel down both edges,
441 // 2- One homology family Spanning tree intersects one of the child edges, i.e.
442 // 'homologous' nucleotide must travel down a specific edge
443 // 3- No homology family's spanning tree intersect either child edge, i.e.
444 // a 'homologous' nucleotide may travel down either edge and pop out at a leaf,
445 // or may travel down both edges but has to die in at least one subtree, or
446 // an 'inhomologous' nucleotide may do whatever it likes here.
447 if ((iHom[i] != 0) && (iHom[i] == iHom[iChild1[i]]) && (iHom[i] == iHom[iChild2[i]])) {
448 // case 1
449
450 for (int j=0; j<iNumNucs; j++) {
451 double iL = 0.0;
452 double iR = 0.0;
453 for (int k=0; k<iNumNucs; k++) {
454 iL += iFh[iChild1[i]][k] * iH[iChild1[i]] * iTrans[iChild1[i]][j][k];
455 iR += iFh[iChild2[i]][k] * iH[iChild2[i]] * iTrans[iChild2[i]][j][k];
456 }
457 iFh[i][j] = iL*iR;
458 }
459 // Others: 0.0
460 } else if (iHom[i] != 0) {
461 // case 2. Figure out which is the homologous child, and which the inhomologous one.
462
463 int iChildH, iChildI;
464 if (iHom[i] == iHom[iChild1[i]]) {
465 iChildH = iChild1[i];
466 iChildI = iChild2[i];
467 } else {
468 iChildH = iChild2[i];
469 iChildI = iChild1[i];
470 }
471
472 for (int j=0; j<iNumNucs; j++) {
473 double iL = 0.0;
474 double iR = iE[iChildI] * iFi[iChildI][iNumNucs];
475 for (int k=0; k<iNumNucs; k++) {
476
477 iL += iFh[iChildH][k] * iH[iChildH] * iTrans[iChildH][j][k];
478 iR +=
479 (iFh[iChildI][k] + iFi[iChildI][k]) * (iN[iChildI] - iE[iChildI]*iB[iChildI]) * iEquil[k] +
480 iFi[iChildI][k] * iH[iChildI] * iTrans[iChildI][j][k];
481
482 }
483
484 iFh[i][j] = iL*iR;
485
486 }
487 // Others: 0.0
488
489 } else {
490 // case 3
491 int iC1 = iChild1[i];
492 int iC2 = iChild2[i];
493 //System.out.println(iC1);
494 //System.out.println(iC2);
495 for (int j=0; j<iNumNucs; j++) {
496 double iL1 = 0.0, iL2 = 0.0;
497 double iR1 = iE[iC1] * iFi[iC1][iNumNucs];
498 double iR2 = iE[iC2] * iFi[iC2][iNumNucs];
499 //System.out.println(iR1);
500 //System.out.println(iR2);
501 for (int k=0; k<iNumNucs; k++) {
502 iL1 += iFh[iC1][k] * iH[iC1] * iTrans[iC1][j][k];
503 iL2 += iFh[iC2][k] * iH[iC2] * iTrans[iC2][j][k];
504 iR1 +=
505 (iFh[iC1][k] + iFi[iC1][k]) * (iN[iC1] - iE[iC1]*iB[iC1]) * iEquil[k] +
506 iFi[iC1][k] * iH[iC1] * iTrans[iC1][j][k];
507 iR2 +=
508 (iFh[iC2][k] + iFi[iC2][k]) * (iN[iC2] - iE[iC2]*iB[iC2]) * iEquil[k] +
509 iFi[iC2][k] * iH[iC2] * iTrans[iC2][j][k];
510 }
511 iFh[i][j] = iL1*iR2 + iL2*iR1; // homology pops out below iC1 + homology pops out below iC2
512 iFi[i][j] = iR1*iR2; // no homology with j below i.
513 }
514
515 double iL = iFi[iC1][iNumNucs];
516 double iR = iFi[iC2][iNumNucs];
517 for (int j=0; j<iNumNucs; j++) {
518
519 iL -= iB[iC1] * (iFi[iC1][j] + iFh[iC1][j]) * iEquil[j];
520 iR -= iB[iC2] * (iFi[iC2][j] + iFh[iC2][j]) * iEquil[j];
521
522 }
523 iFi[i][iNumNucs] = iL*iR;
524 }
525
526 } // recursion over the internal nodes
527
528 // Now calculate the final result
529
530 int iRoot = iNumNodes-1;
531 double iResult = iFi[iRoot][iNumNucs];
532 for (int i=0; i<iNumNucs; i++)
533 iResult -= (iFi[iRoot][i] + iFh[iRoot][i]) * iB[iRoot] * iEquil[i];
534
535 return iResult;
536
537 } // treeRecursion
538
539
540 /**
541 * @return the logLikelihood of the alignment given tree, substitution model, et cetera
542 */
543
544 public double recursion() {
545
546 // Initialise
547
548 int iLen = iAlignment.length;
549 int iLeaves = iAlignment[0].iV.length;
550 int iFirstNotUsed = 0; // First not-'used' alignment vector (for efficiency)
551 int iState[] = new int[ iLen ]; // Helper array, to traverse the region in the DP table corresp. to the alignment
552 IntMathVec iPos = new IntMathVec( iLeaves ); // Current position; sum of all used vectors
553 HashMap<IntMathVec, BFloat> iTable = new HashMap<IntMathVec, BFloat>();
554
555 // Calculate correction factor for null emissions ("wing folding", or linear equation solving.)
556
557 double iNullEmissionFac = treeRecursion( iPos, iPos );
558 //System.out.println("Null emisison: " + iNullEmissionFac);
559
560 // Enter first probability into DP table
561 iTable.put( iPos, new BFloat(iInitial / iNullEmissionFac) );
562
563 // Array of possible vector indices, used in inner loop
564 int[] iPossibles = new int[cMaxUnalignDimension];
565
566 do {
567
568 // Find all possible vectors from current position, iPos
569 IntMathVec iMask = new IntMathVec( iLeaves );
570 int iPtr;
571 int iNumPossible = 0;
572 for (iPtr = iFirstNotUsed; iMask.zeroEntry() && iPtr<iLen; iPtr++) {
573 if (iState[ iPtr ] != eUsed) {
574 if (iMask.innerProduct( iAlignment[iPtr] ) == 0) {
575 iState[ iPtr ] = ePossible;
576 //System.out.println("Accepting column " + iAlignment[iPtr] + " as number " + iNumPossible);
577 if (iNumPossible == cMaxUnalignDimension) {
578 // This gets too hairy - bail out.
579 sBigUnalignableRegion++;
580 System.err.println("We bailed out cause it was hairy: iNumPossible=" + iNumPossible);
581 return Double.NEGATIVE_INFINITY;
582 }
583 iPossibles[iNumPossible++] = iPtr;
584 }
585 iMask.add( iAlignment[iPtr] );
586 }
587 }
588
589 // Loop over all combinations of possible vectors, which define edges from
590 // iPos to another possible position, by ordinary binary counting.
591
592 IntMathVec iNewPos = new IntMathVec( iPos );
593 IntMathVec iSignature = new IntMathVec( iPos.iV.length );
594 int iPosPtr;
595 boolean iUnusedPos;
596 boolean iFoundNonZero;
597
598 do {
599
600 // Find next combination
601 iFoundNonZero = false;
602 for (iPosPtr = iNumPossible - 1; iPosPtr >= 0; --iPosPtr) {
603 int iCurPtr = iPossibles[ iPosPtr ];
604 if (iState[ iCurPtr ] == ePossible) {
605 iState[ iCurPtr ] = eEdgeUsed;
606 iNewPos.add( iAlignment[ iCurPtr ] );
607 // Compute signature vector
608 iSignature.addMultiple( iAlignment[ iCurPtr ], iPosPtr+1 );
609 // Signal: non-zero combination found, and stop
610 iFoundNonZero = true;
611 iPosPtr = 0;
612 } else {
613 // It was eEdgeUsed (i.e., digit == 1), so reset digit and continue
614 iState[ iCurPtr ] = ePossible;
615 iNewPos.subtract( iAlignment[ iCurPtr ] );
616 iSignature.addMultiple( iAlignment[ iCurPtr ], -iPosPtr-1 );
617 }
618 }
619
620 if (iFoundNonZero) {
621 //System.out.print("Reading from pos " + iPos);
622 BFloat iLeft = (BFloat)(iTable.get( iPos )).clone();
623 //System.out.print(" left=" + iLeft);
624 BFloat iRightObj = iTable.get( iNewPos );
625 BFloat iRight;
626 if (iRightObj == null) {
627 iUnusedPos = true;
628 iRight = new BFloat(0);
629 } else {
630 iRight = iRightObj;
631 iUnusedPos = false;
632 }
633 double iTransFac = (-treeRecursion( iSignature, iPos )) / iNullEmissionFac;
634 //System.out.print(" fac=" + iTransFac);
635 iLeft.multiply( iTransFac );
636 iRight.add( iLeft );
637 //System.out.print(" sig=" + iSignature);
638 // And store
639 //System.out.println(" Storing pos " + iNewPos+ " val=" + iRight);
640 // If we are storing a value at a previously unused position, make sure we use a fresh key object
641 if (iUnusedPos) {
642 iTable.put( iNewPos.clone(), iRight );
643 } else {
644 iTable.put( iNewPos, iRight );
645 }
646 }
647
648 } while (iFoundNonZero);
649
650 // Now find next entry in DP table. Use farthest unused vector
651 --iPtr;
652 while (iPtr >= 0 && iState[iPtr] != ePossible) {
653 // Undo any possible used vector that we encounter
654 if (iState[iPtr] == eUsed) {
655 iPos.subtract( iAlignment[iPtr] );
656 iState[iPtr] = eFree;
657 }
658 --iPtr;
659 }
660
661 if (iPtr == -1) {
662 // No more unused vectors, so we also fell through the edge loop above,
663 // hence iNewPos contains the final position
664 //System.out.println("Returning " + (BFloat)iTable.get( iNewPos ) + " = " + ((BFloat)iTable.get( iNewPos ) ).log());
665 return (iTable.get( iNewPos )).log();
666 }
667
668 // Now use this farthest-out possible vector
669 iState[iPtr] = eUsed;
670 iPos.add( iAlignment[iPtr] );
671 if (iPtr <= iFirstNotUsed)
672 iFirstNotUsed++;
673
674 } while (true);
675
676 } // recursion
677 }
678