Debian Codegraph @

src/dr/evomodel/continuous/plink/PlinkImporter.java

raw symbols SCIP
1 /*
2 * PlinkImporter.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.continuous.plink;
27
28 import dr.evolution.util.Taxa;
29 import dr.evolution.util.Taxon;
30 import dr.evolution.util.TaxonList;
31 import dr.util.*;
32 import dr.xml.*;
33
34 import java.io.BufferedReader;
35 import java.io.FileReader;
36 import java.io.IOException;
37 import java.io.Reader;
38 import java.util.*;
39 import java.util.logging.Logger;
40
41 /**
42 * @author Marc A. Suchard
43 */
44 public class PlinkImporter implements Citable {
45
46 private TaxonList taxonList = null;
47 private Map<String, List<Double>> taxonHash;
48 private Map<String, Integer> taxonCounts;
49 private List<Integer> remove;
50
51 public PlinkImporter(Reader reader) throws IOException {
52 taxonHash = new HashMap<String, List<Double>>();
53 taxonCounts = new HashMap<String, Integer>();
54 remove = new ArrayList<Integer>();
55 parse(reader);
56 }
57
58 @Override
59 public Citation.Category getCategory() {
60 return Citation.Category.DATA_MODELS;
61 }
62
63 @Override
64 public String getDescription() {
65 return "PLink";
66 }
67
68 public List<Citation> getCitations() {
69 return Arrays.asList(new Citation(
70 new Author[]{
71 new Author("MA", "Suchard"),
72 new Author("A", "Boyko"),
73 },
74 Citation.Status.IN_PREPARATION)
75 );
76 }
77
78 private String formatTransformedValue(double value) {
79 return String.format("%+4.3e", value);
80 }
81
82 private String makeStringAttribute(List<Double> valueList) {
83 StringBuffer sb = new StringBuffer();
84 // sb.append(formatTransformedValue(valueList.get(0)));
85 boolean first = true;
86 for (int i = 0; i < valueList.size(); i++) {
87 if (!remove.contains(i)) {
88 if (!first) {
89 sb.append(" ");
90 } else {
91 first = false;
92 }
93 sb.append(formatTransformedValue(valueList.get(i)));
94 }
95 }
96 return sb.toString();
97 }
98
99 private void transformRow(String line, Map<String, List<Double>> taxonHash, Map<String, Integer> taxonCounts, List<Integer> remove) {
100 StringTokenizer token = new StringTokenizer(line);
101 token.nextToken();
102 token.nextToken();
103 String name = token.nextToken();
104 int a1 = Integer.parseInt(token.nextToken());
105 int a2 = Integer.parseInt(token.nextToken());
106 token.nextToken();
107 int count1 = Integer.parseInt(token.nextToken());
108 int total = Integer.parseInt(token.nextToken());
109 int count2 = total - count1;
110 // if (a1 > a2) {
111 // int tmp = count1;
112 // count1 = count2;
113 // count2 = tmp;
114 // }
115 double value = transform(count1, count2);
116 if (Double.isNaN(value)) {
117 StringBuffer sb = new StringBuffer();
118 sb.append("PLINK line: " + line + " generates invalid frequency estimate;");
119 if (removeMissingLoci) {
120 sb.append(" marking loci for removal from analysis");
121 List<Double> valueList = taxonHash.get(name);
122 remove.add(valueList.size());
123 // System.err.println("Marking loci #" + valueList.size());
124 } else {
125 sb.append(" filling in with default value");
126 value = defaultMissingValue();
127 }
128 Logger.getLogger("dr.evomodel.continuous").warning(sb.toString());
129 }
130 List<Double> valueList = taxonHash.get(name);
131 if (valueList == null) {
132 valueList = new ArrayList<Double>();
133 taxonHash.put(name, valueList);
134 taxonCounts.put(name, 1);
135 } else {
136 // sb.append(" ");
137 taxonCounts.put(name, taxonCounts.get(name) + 1);
138 }
139 valueList.add(value);
140 // sb.append(formatTransformedValue(value));
141 }
142
143 public String toStatisticsString() {
144 StringBuffer sb = new StringBuffer();
145 sb.append("PLINK importer read ");
146 sb.append(taxonHash.keySet().size()).append(" taxa with entry counts:\n");
147 for (String taxon : taxonHash.keySet()) {
148 sb.append("\t");
149 sb.append(taxonCounts.get(taxon));
150 sb.append(" = ").append(taxon).append(taxonHash.get(taxon).size()).append("\n");
151 }
152 sb.append("\tPlease cite:\n");
153 sb.append(Citable.Utils.getCitationString(this));
154 return sb.toString();
155 }
156
157 public String toString() {
158 return toTaxonBlockString();
159 }
160
161 public void parse(Reader source) throws IOException {
162 BufferedReader reader = new BufferedReader(source);
163
164 String line = reader.readLine();
165 if (line == null) {
166 throw new IllegalArgumentException("Empty file");
167 }
168
169 line = reader.readLine();
170 while (line != null) {
171 transformRow(line, taxonHash, taxonCounts, remove);
172 line = reader.readLine();
173 }
174
175 if (remove.size() > 0) {
176 Logger.getLogger("dr.evomodel.continuous").warning("Removing " + remove.size() + " loci from analysis...");
177 // for (int i : remove) {
178 // for (String taxon : taxonHash.keySet()) {
179 // List<Double> valueList = taxonHash.get(taxon);
180 // valueList.remove(i);
181 // }
182 // }
183 }
184 }
185
186 public void addTaxonAttribute(TaxonList inTaxonList, String traitName) {
187
188 taxonList = new Taxa();
189 for (Taxon taxon : inTaxonList) {
190 List<Double> valueList = taxonHash.get(taxon.getId());
191
192 if (valueList == null) {
193 Logger.getLogger("dr.evolution").warning("Taxon " + taxon.getId() + " not found in PLINK data");
194 } else {
195 String string = makeStringAttribute(valueList);
196 ((Taxa)taxonList).addTaxon(taxon);
197 taxon.setAttribute(traitName, string);
198 }
199 if (DEBUG) {
200 System.err.println("Added trait for " + taxon.getId());
201 }
202 }
203 }
204
205 public String toTaxonBlockString() {
206 StringBuffer sb = new StringBuffer();
207 if (taxonList != null) {
208 for (Taxon taxon : taxonList) {
209 sb.append("<taxon id=\"").append(taxon.getId()).append("\">\n");
210 Iterator<String> attributeIterator = taxon.getAttributeNames();
211 while (attributeIterator.hasNext()) {
212 String attribute = attributeIterator.next();
213 sb.append("\t<attribute name=\"").append(attribute).append("\"> ");
214 sb.append(taxon.getAttribute(attribute));
215 sb.append(" </attribute>\n");
216 }
217 sb.append("</taxon>\n\n");
218 }
219 }
220 return sb.toString();
221 }
222
223 private double innerTransform(double p) {
224 return Math.log(p / (1.0 - p));
225 }
226
227 private double defaultMissingValue() {
228 return 0.0;
229 }
230
231 // private double innerTransform(double p) {
232 // return Math.asin(Math.sqrt(p));
233 // }
234 //
235 // private double defaultMissingValue() {
236 // return Math.asin(Math.sqrt(0.5));
237 // }
238
239 private double transform(int count1, int count2) {
240 int total = count1 + count2;
241 double halfFreq = 0.5 / total;
242 double obsFreq;
243 if (count1 == 0) {
244 obsFreq = halfFreq;
245 } else if (count2 == 0) {
246 obsFreq = 1.0 - halfFreq;
247 } else {
248 obsFreq = ((double) count1) / ((double) total);
249 }
250 return innerTransform(obsFreq);
251 }
252
253 // **************************************************************
254 // XMLObjectParser
255 // **************************************************************
256
257 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
258
259 public static final String PLINK_IMPORT = "plinkImport";
260
261 public final static String INPUT_FILE_NAME = FileHelpers.FILE_NAME;
262 public static final String TRAIT_NAME = "traitName";
263
264 public String getParserName() {
265 return PLINK_IMPORT;
266 }
267
268 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
269
270 FileReader fileReader = XMLParser.getFileReader(xo, INPUT_FILE_NAME);
271 Logger.getLogger("dr.evomodel.continuous").info("Attempting to read PLINK file...\n");
272 PlinkImporter importer;
273 try {
274 importer = new PlinkImporter(fileReader);
275 Logger.getLogger("dr.evomodel.continuous").info(importer.toStatisticsString());
276 } catch (IOException e) {
277 throw new XMLParseException("Unable to read plink data from file, " + fileReader.getEncoding());
278 }
279
280
281 Taxa taxonList = new Taxa();
282
283 for (int i = 0; i < xo.getChildCount(); i++) {
284 Object child = xo.getChild(i);
285 if (child instanceof Taxon) {
286 Taxon taxon = (Taxon) child;
287 taxonList.addTaxon(taxon);
288 } else if (child instanceof TaxonList) {
289 TaxonList taxonList1 = (TaxonList) child;
290 for (int j = 0; j < taxonList1.getTaxonCount(); j++) {
291 taxonList.addTaxon(taxonList1.getTaxon(j));
292 }
293 } else {
294 throwUnrecognizedElement(xo);
295 }
296 }
297
298 importer.addTaxonAttribute(taxonList, xo.getAttribute(TRAIT_NAME, "null"));
299 return importer;
300 }
301
302 //************************************************************************
303 // AbstractXMLObjectParser implementation
304 //************************************************************************
305
306 public String getParserDescription() {
307 return "Provides the likelihood of pairwise distance given vectors of coordinates" +
308 "for points according to the multidimensional scaling scheme of XXX & Rafferty (xxxx).";
309 }
310
311 public XMLSyntaxRule[] getSyntaxRules() {
312 return rules;
313 }
314
315 private final XMLSyntaxRule[] rules = {
316 AttributeRule.newStringRule(INPUT_FILE_NAME, false, "The name of the file containing the plink table"),
317 new OrRule(
318 new ElementRule(Taxa.class, 1, Integer.MAX_VALUE),
319 new ElementRule(Taxon.class, 1, Integer.MAX_VALUE)
320 ),
321 AttributeRule.newStringRule(TRAIT_NAME),
322 };
323
324 public Class getReturnType() {
325 return PlinkImporter.class;
326 }
327 };
328
329
330 private static final boolean DEBUG = false;
331 private boolean removeMissingLoci = true;
332
333
334 }