Debian Codegraph @

src/dr/evomodel/operators/ImportanceNarrowExchange.java

raw symbols SCIP
1 /*
2 * ImportanceNarrowExchange.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 /**
27 *
28 */
29 package dr.evomodel.operators;
30
31 import dr.evolution.alignment.PatternList;
32 import dr.evolution.datatype.DataType;
33 import dr.evolution.tree.NodeRef;
34 import dr.evolution.tree.TreeUtils;
35 import dr.evolution.util.Taxon;
36 import dr.evomodel.tree.TreeLogger;
37 import dr.evomodel.tree.TreeModel;
38 import dr.math.MathUtils;
39
40 import java.util.HashMap;
41 import java.util.Map;
42
43 /**
44 * @author Joseph Heled
45 * @version 1.0
46 */
47 @SuppressWarnings({"ConstantConditions"})
48 // Cleaning out untouched stuff. Can be resurrected if needed
49 @Deprecated
50 public class ImportanceNarrowExchange extends AbstractTreeOperator implements TreeLogger.LogUpon {
51
52 private TreeModel tree = null;
53
54 private final double epsilon;
55
56 private int[] nodeCounts;
57 private boolean justAccepted;
58
59 private final double[] weights;
60 private double totalWeight;
61
62 public ImportanceNarrowExchange(TreeModel tree, PatternList patterns, double epsilon, double weight) throws Exception {
63 this.tree = tree;
64 setWeight(weight);
65
66 justAccepted = false;
67 this.epsilon = epsilon;
68
69 weights = new double[tree.getNodeCount()];
70 setTaxaWeights(patterns);
71 }
72
73 private void setTaxaWeights(PatternList patterns) throws Exception {
74 final DataType type = patterns.getDataType();
75 Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
76
77 int[] taxaCounts = new int[patterns.getPatternLength()];
78
79 for(int nPat = 0; nPat < patterns.getPatternCount(); ++nPat) {
80 final int[] pattern = patterns.getPattern(nPat);
81
82 counts.clear();
83 for( int s : pattern ) {
84 if( type.isGapState(s) || type.isAmbiguousState(s) || type.isUnknownState(s) ) {
85 continue;
86 }
87 if( ! counts.containsKey(s) ) {
88 counts.put(s, 0);
89 }
90 counts.put(s, counts.get(s)+1);
91 }
92
93 if( counts.size() <= 1 ) {
94 continue;
95 }
96
97 Map.Entry<Integer, Integer> m = null;
98 for( Map.Entry<Integer, Integer> e : counts.entrySet()) {
99 if( m == null || e.getValue() > m.getValue() ) {
100 m = e;
101 }
102 }
103 assert m != null;
104
105 for(int i = 0; i < pattern.length; ++i) {
106 final int s = pattern[i];
107 if( ! (type.isGapState(s) || type.isAmbiguousState(s) || type.isUnknownState(s) ) ) {
108 if( s != m.getKey() ) {
109 taxaCounts[i] += patterns.getPatternWeight(nPat);
110 }
111 }
112 }
113 }
114
115 nodeCounts = new int[tree.getNodeCount()];
116 Map<Taxon, Integer> taxaWeights = new HashMap<Taxon, Integer>();
117 for(int i = 0; i < taxaCounts.length; ++i) {
118 taxaWeights.put(patterns.getTaxon(i), taxaCounts[i]);
119 }
120
121 for(int i = 0; i < tree.getExternalNodeCount(); ++i) {
122 final NodeRef leaf = tree.getExternalNode(i);
123 final Taxon nodeTaxon = tree.getNodeTaxon(leaf);
124
125 // assert taxaWeights.containsKey(nodeTaxon) : nodeTaxon;
126 if( ! taxaWeights.containsKey(nodeTaxon) ) {
127 throw new Exception("" + nodeTaxon + " in tree " + tree.getId() +
128 " not in patterns" + patterns.getId() + ".");
129 }
130 nodeCounts[leaf.getNumber()] = taxaWeights.get(nodeTaxon) ;
131 }
132 }
133
134
135 private int traverseTree(NodeRef n) {
136 final int k = n.getNumber();
137 if( ! tree.isExternal(n) ) {
138 int w = 0;
139 for(int nc = 0; nc < tree.getChildCount(n); ++nc ) {
140 w += traverseTree(tree.getChild(n, nc));
141 }
142 nodeCounts[k] = w;
143 }
144
145 return nodeCounts[k];
146 }
147
148 final private int DEBUG = 0;
149
150 private double nodeWeight(final NodeRef node ) {
151 final NodeRef ch0 = tree.getChild(node, 0);
152 final NodeRef ch1 = tree.getChild(node, 1);
153
154 if( tree.isExternal(ch0) && tree.isExternal(ch1) ) {
155 return 0;
156 }
157
158 final boolean leftSubtree = tree.getNodeHeight(ch0) < tree.getNodeHeight(ch1);
159 final int st0 = nodeCounts[(leftSubtree ? ch0 : ch1).getNumber()];
160 final int st1 = nodeCounts[tree.getChild(leftSubtree ? ch1 : ch0, 0).getNumber()];
161 final int st2 = nodeCounts[tree.getChild(leftSubtree ? ch1 : ch0, 1).getNumber()];
162 final double w = (epsilon + st0)*(epsilon + st1) + (epsilon + st0)*(epsilon + st2) + (epsilon + st1)*(epsilon + st2)
163 - 3*epsilon*epsilon;
164 return w;
165 }
166
167 private int getNode() {
168 traverseTree(tree.getRoot());
169
170 totalWeight = 0;
171
172 for(int k = 0; k < tree.getInternalNodeCount(); ++k) {
173 final NodeRef node = tree.getInternalNode(k);
174 final double w = nodeWeight(node);
175
176 weights[node.getNumber()] = w;
177 if( DEBUG > 5 && w > 0 ) {
178 System.out.println("" + w + " " + TreeUtils.uniqueNewick(tree, node));
179 }
180 totalWeight += w;
181 }
182
183 double r = MathUtils.nextDouble() * totalWeight;
184 for(int k = 0; k < tree.getInternalNodeCount(); ++k) {
185 final NodeRef node = tree.getInternalNode(k);
186 final int nodeIndex = node.getNumber();
187 r -= weights[nodeIndex];
188 if( r < 0 ) {
189 if( DEBUG > 0 ) {
190 System.out.println("" + weights[nodeIndex] + "/" + totalWeight + " " + TreeUtils.uniqueNewick(tree, node));
191 }
192 return k;
193 }
194 }
195 //assert false;
196 return -1;
197 }
198
199 /*
200 * (non-Javadoc)
201 *
202 * @see dr.inference.operators.SimpleMCMCOperator#doOperation()
203 */
204 @Override
205 public double doOperation() {
206 int k = getNode();
207 if( k < 0 ) {
208 throw new RuntimeException("no node found");
209 }
210
211 final NodeRef p = tree.getInternalNode(k);
212 if( DEBUG > 0 ) {
213 System.out.println(TreeUtils.newick(tree));
214 System.out.println("" + getAcceptCount() + " - " + getRejectCount());
215 }
216 assert tree.getChildCount(p) == 2;
217 final NodeRef ch0 = tree.getChild(p, 0);
218 final NodeRef ch1 = tree.getChild(p, 1);
219
220 final boolean side = tree.getNodeHeight(ch0) < tree.getNodeHeight(ch1);
221 final NodeRef iUncle = side ? ch0 : ch1;
222 final NodeRef jP = side ? ch1 : ch0;
223 final NodeRef j = tree.getChild(jP, MathUtils.nextInt(2));
224 exchangeNodes(tree, iUncle, j, p, jP);
225
226 final int jPindex = jP.getNumber();
227 nodeCounts[jPindex] += -nodeCounts[j.getNumber()] + nodeCounts[iUncle.getNumber()]; // debug
228
229 // the weights function is symmetric with respect to counts of the three sub-trees involved in the exchange,
230 // so the weight of the root node (p) does not change, but the weight of jP has changed
231
232 final double prev = weights[jPindex];
233 // The counts below jP are still valid
234 final double now = nodeWeight(jP);
235 double newTot = totalWeight + (now - prev);
236
237 weights[jPindex] = now; // debug
238 final NodeRef pP = tree.getParent(p);
239 if( pP != null ) {
240 final int pPindex = pP.getNumber();
241 final double prev1 = weights[pPindex];
242 final double now1 = nodeWeight(pP);
243 weights[pPindex] = now1; // debug
244 newTot += + (now1 - prev1);
245 }
246
247 // pr(node before operation) = w/tot. pr(node after operation) = w/newTot
248 // log(back/forward) = w/newTot / w/tot = log(tot/newTot)
249
250 double saveTotalWeight = totalWeight; // debug
251 double[] w = new double[weights.length]; // debug
252
253 System.arraycopy(weights, 0, w, 0, w.length); // debug
254 int[] c = new int[nodeCounts.length]; // debug
255 System.arraycopy(nodeCounts, 0, c, 0, c.length); // debug
256 getNode(); // debug
257
258 for(int l = 0; l < c.length; ++l) { // debug
259 if( c[l] != nodeCounts[l] ) { // debug
260 assert false; // debug
261 } // debug
262 } // debug
263 for(int l = 0; l < w.length; ++l) { // debug
264 if( Math.abs(weights[l]/w[l] - 1) > 1e-12 ) { // debug
265 assert false; // debug
266 } // debug
267 } // debug
268 assert Math.abs(newTot/totalWeight - 1) < 1e-10; // debug
269
270 return Math.log(saveTotalWeight / newTot);
271 }
272
273 public void reject() {
274 super.reject();
275 justAccepted = false;
276 }
277
278 public void accept(double deviation) {
279 super.accept(deviation);
280 justAccepted = true;
281 }
282
283 private final long lFreq = 1000;
284 private long lastLog = -lFreq-1;
285
286 public boolean logNow(long state) {
287
288 boolean r = justAccepted;
289 if( lastLog + lFreq >= state ) {
290 r = false;
291 } else if( r ) {
292 lastLog = state;
293 }
294 justAccepted = false;
295 return r;
296 }
297
298 /*
299 * (non-Javadoc)
300 *
301 * @see dr.inference.operators.SimpleMCMCOperator#getOperatorName()
302 */
303 @Override
304
305 public String getOperatorName() {
306 return "Importance Narrow Exchange" + "(" + tree.getId() + ")";
307 }
308
309 public double getMinimumAcceptanceLevel() {
310 return 0.025;
311 }
312
313 public double getMinimumGoodAcceptanceLevel() {
314 return 0.05;
315 }
316
317 /*
318 * (non-Javadoc)
319 *
320 * @see dr.inference.operators.MCMCOperator#getPerformanceSuggestion()
321 */
322 public String getPerformanceSuggestion() {
323 return "";
324 }
325
326 }