Debian Codegraph @

src/dr/evoxml/UncertainAttributePatternsParser.java

raw symbols SCIP
1 /*
2 * AttributeUncertainPatternsParser.java
3 *
4 * Copyright (c) 2002-2016 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.evoxml;
27
28 import dr.evolution.alignment.PatternList;
29 import dr.evolution.alignment.SimpleSiteList;
30 import dr.evolution.alignment.UncertainSiteList;
31 import dr.evolution.datatype.DataType;
32 import dr.evolution.util.Taxon;
33 import dr.evolution.util.TaxonList;
34 import dr.evoxml.util.DataTypeUtils;
35 import dr.util.Citable;
36 import dr.util.Citation;
37 import dr.xml.*;
38
39 import java.util.ArrayList;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.logging.Logger;
44
45 /**
46 * @author Marc A. Suchard
47 */
48 public class UncertainAttributePatternsParser extends AbstractXMLObjectParser {
49
50 public static final String ATTRIBUTE = AttributePatternsParser.ATTRIBUTE;
51 public static final String NAME = "uncertainAttributePatterns";
52 public static final String LOCATION_TOKEN = "\\s";
53 public static final String PROBABILITY_TOKEN = ":";
54 public static final String NORMALIZE = "normalize";
55
56 public String getParserName() { return NAME; }
57
58 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
59
60 String attributeName = xo.getStringAttribute(ATTRIBUTE);
61 TaxonList taxa = (TaxonList) xo.getChild(TaxonList.class);
62 DataType dataType = DataTypeUtils.getDataType(xo);
63
64 if (dataType == null) {
65 throw new XMLParseException("dataType expected for attributePatterns element");
66 }
67
68 // using a SimpleSiteList rather than Patterns to allow ancestral reconstruction
69 UncertainSiteList patterns = new UncertainSiteList(dataType, taxa);
70
71 boolean normalize = xo.getAttribute(NORMALIZE, true);
72
73 if (dataType == null) { // TODO Is this necessary given XMLSyntaxRules?
74 throw new XMLParseException("dataType expected for attributePatterns element");
75 }
76
77 double[][] uncertainPattern = new double[taxa.getTaxonCount()][];
78
79 // Parse attributes
80 boolean attributeFound = false;
81
82 for (int i = 0; i < taxa.getTaxonCount(); i++) {
83 Taxon taxon = taxa.getTaxon(i);
84
85 Object value = taxon.getAttribute(attributeName);
86
87 if (value != null) {
88 attributeFound = true;
89 List<StateProbability> stateProbabilities;
90
91 try {
92 stateProbabilities = parseStates(value.toString(), dataType);
93 } catch (StateParseException e) {
94 throw new XMLParseException("State or probability for attribute (" + attributeName + ") in taxon "
95 + taxon.getId() + " is invalid; state = \"" + e.getState() + "\" and probability =\""
96 + e.getProbability() + "\"");
97 }
98
99 uncertainPattern[i] = convertToPartials(stateProbabilities, dataType, normalize);
100 } else {
101 throw new XMLParseException("State for attribute (" + attributeName + ") in taxon "
102 + taxon.getId() + " is unknown.");
103 }
104 }
105
106 if (!attributeFound) {
107 throw new XMLParseException("The attribute (" + attributeName + ") was missing in all taxa. Check the name of the attribute.");
108 }
109
110 patterns.addPattern(uncertainPattern);
111
112 Logger.getLogger("dr.evolution").info("\n ---------------------------------\nCreating an uncertain attribute model for attribute \""
113 + attributeName + "\"");
114 Logger.getLogger("dr.evolution").info("\tIf you publish results using this model, please reference:");
115 Logger.getLogger("dr.evolution").info("\t" + Citable.Utils.getCitationString(patterns));
116 Logger.getLogger("dr.evolution").info("\n");
117
118 return patterns;
119 }
120
121
122 class StateProbability {
123 int state;
124 double probability;
125
126 public StateProbability(int state, double probability) {
127 this.state = state;
128 this.probability = probability;
129 }
130
131 public int getState() { return state; }
132
133 public double getProbability() { return probability; }
134 }
135
136 class StateParseException extends Exception {
137 String state;
138 String probability;
139
140 public StateParseException(String state, String probability) {
141 this.state = state;
142 this.probability = probability;
143 }
144
145 public String getState() { return state; }
146
147 public String getProbability() { return probability; }
148 }
149
150 private List<StateProbability> parseStates(String string, DataType dataType)
151 throws StateParseException {
152
153 List<StateProbability> stateProbabilities = new ArrayList<StateProbability>();
154
155 String[] tokens = string.split(LOCATION_TOKEN);
156 for (String token : tokens) {
157 String[] component = token.split(PROBABILITY_TOKEN);
158
159 int state = dataType.getState(component[0]);
160
161 double probability = 1.0;
162
163 if (component.length > 1) {
164 try {
165 probability = Double.valueOf(component[1]);
166 } catch (NumberFormatException e) {
167 probability = Double.NaN;
168 }
169 }
170
171 if (state < 0 || Double.isNaN(probability) || probability <= 0.0 || probability > 1.0) {
172 throw new StateParseException(component[0], (component.length == 1 ? "" : component[1]));
173 }
174
175 stateProbabilities.add(new StateProbability(state, probability));
176 }
177
178 return stateProbabilities;
179 }
180
181 private void normalize(double[] vec) {
182 double sum = 0.0;
183 for (double x : vec) {
184 sum += x;
185 }
186 for (int i = 0; i < vec.length; ++i) {
187 vec[i] /= sum;
188 }
189 }
190
191 private double[] convertToPartials(List<StateProbability> stateProbabilities, DataType dataType,
192 boolean normalize) {
193 double[] partials = new double[dataType.getStateCount()];
194
195 for (StateProbability state : stateProbabilities) {
196 partials[state.getState()] = state.getProbability();
197 }
198
199 if (normalize) {
200 normalize(partials);
201 }
202 return partials;
203 }
204
205 //************************************************************************
206 // AbstractXMLObjectParser implementation
207 //************************************************************************
208
209 public XMLSyntaxRule[] getSyntaxRules() { return rules; }
210
211 private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
212 new XORRule(
213 new StringAttributeRule(
214 DataType.DATA_TYPE,
215 "The data type",
216 DataType.getRegisteredDataTypeNames(), false),
217 new ElementRule(DataType.class)
218 ),
219 AttributeRule.newStringRule(ATTRIBUTE),
220 AttributeRule.newBooleanRule(NORMALIZE, true),
221 new ElementRule(TaxonList.class, "The taxon set")
222 };
223
224 public String getParserDescription() {
225 return "A site pattern defined by an attribute in a set of taxa.";
226 }
227
228 public Class getReturnType() { return PatternList.class; }
229
230 }