Debian Codegraph @

src/dr/app/beastgen/DataModelImporter.java

raw symbols SCIP
1 /*
2 * DataModelImporter.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.app.beastgen;
27
28 import dr.app.beauti.options.*;
29 import dr.app.util.Utils;
30 import dr.evolution.alignment.Alignment;
31 import dr.evolution.alignment.SimpleAlignment;
32 import dr.evolution.datatype.Nucleotides;
33 import dr.evolution.io.FastaImporter;
34 import dr.evolution.io.Importer;
35 import dr.evolution.io.Importer.ImportException;
36 import dr.evolution.io.NewickImporter;
37 import dr.evolution.io.NexusImporter;
38 import dr.evolution.io.NexusImporter.MissingBlockException;
39 import dr.evolution.io.NexusImporter.NexusBlock;
40 import dr.evolution.sequence.Sequence;
41 import dr.evolution.tree.Tree;
42 import dr.evolution.tree.TreeUtils;
43 import dr.evolution.util.Taxon;
44 import dr.evolution.util.TaxonList;
45 import dr.evolution.util.Units;
46 import org.jdom.JDOMException;
47
48 import java.io.*;
49 import java.util.*;
50 import java.util.List;
51
52
53 /**
54 * @author Andrew Rambaut
55 * @version $Id$
56 */
57 public class DataModelImporter {
58
59 private final DateGuesser guesser;
60
61 public DataModelImporter() {
62 this.guesser = null;
63 }
64
65 public DataModelImporter(DateGuesser guesser) {
66 this.guesser = guesser;
67 }
68
69 public HashMap importFromFile(File file) throws IOException, Importer.ImportException {
70 HashMap dataModel = new HashMap();
71 try {
72 Reader reader = new FileReader(file);
73
74 BufferedReader bufferedReader = new BufferedReader(reader);
75 String line = bufferedReader.readLine();
76 while (line != null && line.length() == 0) {
77 line = bufferedReader.readLine();
78 }
79
80 if ((line != null && line.toUpperCase().contains("#NEXUS"))) {
81 // is a NEXUS file
82 importNexusFile(file, guesser, dataModel);
83 } else if ((line != null && line.trim().startsWith("" + FastaImporter.FASTA_FIRST_CHAR))) {
84 // is a FASTA file
85 importFastaFile(file, guesser, dataModel);
86 } else if ((line != null && (line.toUpperCase().contains("<?XML") || line.toUpperCase().contains("<BEAST")))) {
87 // assume it is a BEAST XML file and see if that works...
88 importBEASTFile(file, guesser, dataModel);
89 // } else {
90 // // assume it is a tab-delimited traits file and see if that works...
91 // importTraits(file);
92 } else {
93 throw new ImportException("Unrecognized format for imported file.");
94 }
95
96 bufferedReader.close();
97 } catch (IOException e) {
98 throw new IOException(e.getMessage());
99 }
100
101 return dataModel;
102
103 }
104
105 // xml
106 private void importBEASTFile(File file, DateGuesser guesser, Map dataModel) throws IOException, ImportException {
107 try {
108 FileReader reader = new FileReader(file);
109
110 BeastImporter importer = new BeastImporter(reader);
111
112 List<TaxonList> taxonLists = new ArrayList<TaxonList>();
113 List<Alignment> alignments = new ArrayList<Alignment>();
114
115 importer.importBEAST(taxonLists, alignments);
116
117 TaxonList taxa = taxonLists.get(0);
118
119 int count = 1;
120 for (Alignment alignment : alignments) {
121 String name = file.getName();
122 if (alignment.getId() != null && alignment.getId().length() > 0) {
123 name = alignment.getId();
124 } else {
125 if (alignments.size() > 1) {
126 name += count;
127 }
128 }
129 setData(dataModel, guesser, name, taxa, taxonLists, alignment, null, null, null);
130
131 count++;
132 }
133
134 reader.close();
135 } catch (JDOMException e) {
136 throw new ImportException(e.getMessage());
137 } catch (ImportException e) {
138 throw new ImportException(e.getMessage());
139 } catch (IOException e) {
140 throw new IOException(e.getMessage());
141 }
142
143 }
144
145 // nexus
146 private void importNexusFile(File file, DateGuesser guesser, Map dataModel) throws IOException, ImportException {
147 TaxonList taxa = null;
148 SimpleAlignment alignment = null;
149 List<Tree> trees = new ArrayList<Tree>();
150 List<NexusApplicationImporter.CharSet> charSets = new ArrayList<NexusApplicationImporter.CharSet>();
151
152 try {
153 FileReader reader = new FileReader(file);
154
155 NexusApplicationImporter importer = new NexusApplicationImporter(reader);
156
157 boolean done = false;
158
159 while (!done) {
160 try {
161
162 NexusBlock block = importer.findNextBlock();
163
164 if (block == NexusImporter.TAXA_BLOCK) {
165
166 if (taxa != null) {
167 throw new MissingBlockException("TAXA block already defined");
168 }
169
170 taxa = importer.parseTaxaBlock();
171
172 dataModel.put("taxa", createTaxonList(taxa));
173
174 } else if (block == NexusImporter.CALIBRATION_BLOCK) {
175 if (taxa == null) {
176 throw new MissingBlockException("TAXA or DATA block must be defined before a CALIBRATION block");
177 }
178
179 importer.parseCalibrationBlock(taxa);
180
181 } else if (block == NexusImporter.CHARACTERS_BLOCK) {
182
183 if (taxa == null) {
184 throw new MissingBlockException("TAXA block must be defined before a CHARACTERS block");
185 }
186
187 if (alignment != null) {
188 throw new MissingBlockException("CHARACTERS or DATA block already defined");
189 }
190
191 alignment = (SimpleAlignment) importer.parseCharactersBlock(taxa);
192
193 } else if (block == NexusImporter.DATA_BLOCK) {
194
195 if (alignment != null) {
196 throw new MissingBlockException("CHARACTERS or DATA block already defined");
197 }
198
199 // A data block doesn't need a taxon block before it
200 // but if one exists then it will use it.
201 alignment = (SimpleAlignment) importer.parseDataBlock(taxa);
202 if (taxa == null) {
203 taxa = alignment;
204 }
205
206 } else if (block == NexusImporter.TREES_BLOCK) {
207
208 // I guess there is no reason not to allow multiple trees blocks
209 // if (trees.size() > 0) {
210 // throw new MissingBlockException("TREES block already defined");
211 // }
212
213 Tree[] treeArray = importer.parseTreesBlock(taxa);
214 trees.addAll(Arrays.asList(treeArray));
215
216 if (taxa == null && trees.size() > 0) {
217 taxa = trees.get(0);
218 }
219
220
221 } else if (block == NexusApplicationImporter.ASSUMPTIONS_BLOCK) {
222
223 importer.parseAssumptionsBlock(charSets);
224
225 } else {
226 // Ignore the block..
227 }
228
229 } catch (EOFException ex) {
230 done = true;
231 }
232 }
233
234 reader.close();
235
236 // Allow the user to load taxa only (perhaps from a tree file) so that they can sample from a prior...
237 if (alignment == null && taxa == null) {
238 throw new MissingBlockException("TAXON, DATA or CHARACTERS block is missing");
239 }
240
241 } catch (IOException e) {
242 throw new IOException(e.getMessage());
243 } catch (ImportException e) {
244 throw new ImportException(e.getMessage());
245 // } catch (Exception e) {
246 // throw new Exception(e.getMessage());
247 }
248
249 setData(dataModel, guesser, file.getName(), taxa, null, alignment, charSets, null, trees);
250 }
251
252 // FASTA
253
254 private void importFastaFile(File file, DateGuesser guesser, Map dataModel) throws IOException, ImportException {
255 try {
256 FileReader reader = new FileReader(file);
257
258 FastaImporter importer = new FastaImporter(reader, Nucleotides.INSTANCE);
259
260 Alignment alignment = importer.importAlignment();
261
262 reader.close();
263
264 setData(dataModel, guesser, file.getName(), alignment, null, alignment, null, null, null);
265 } catch (ImportException e) {
266 throw new ImportException(e.getMessage());
267 } catch (IOException e) {
268 throw new IOException(e.getMessage());
269 }
270 }
271
272 public Map importFromTreeFile(String fileName, Map dataModel) throws IOException, Importer.ImportException {
273 Tree tree = null;
274 try {
275 Reader reader = new FileReader(fileName);
276
277 BufferedReader bufferedReader = new BufferedReader(reader);
278 String line = bufferedReader.readLine();
279 while (line != null && line.length() == 0) {
280 line = bufferedReader.readLine();
281 }
282
283 reader = new FileReader(fileName);
284
285 if ((line != null && line.toUpperCase().contains("#NEXUS"))) {
286 // is a NEXUS file
287 NexusImporter importer = new NexusImporter(reader);
288 tree = importer.importNextTree();
289
290 } else {
291 NewickImporter importer = new NewickImporter(reader);
292 tree = importer.importNextTree();
293 }
294
295 bufferedReader.close();
296 } catch (IOException e) {
297 throw new IOException(e.getMessage());
298 }
299
300 if (tree != null) {
301 dataModel.put("tree", TreeUtils.newick(tree));
302 }
303
304 return dataModel;
305
306 }
307
308
309 private boolean isMissingValue(String value) {
310 return (value.equals("?") || value.equals("NA") || value.length() == 0);
311 }
312
313 // public void importTraits(final File file, Map dataModel) throws Exception {
314 // List<TraitData> importedTraits = new ArrayList<TraitData>();
315 // Taxa taxa = options.taxonList;
316 //
317 // DataTable<String[]> dataTable = DataTable.Text.parse(new FileReader(file));
318 //
319 // String[] traitNames = dataTable.getColumnLabels();
320 // String[] taxonNames = dataTable.getRowLabels();
321 //
322 // for (int i = 0; i < dataTable.getColumnCount(); i++) {
323 // boolean warningGiven = false;
324 //
325 // String traitName = traitNames[i];
326 //
327 // String[] values = dataTable.getColumn(i);
328 // Class c = null;
329 // if (!isMissingValue(values[0])) {
330 // c = Utils.detectType(values[0]);
331 // }
332 // for (int j = 1; j < values.length; j++) {
333 // if (!isMissingValue(values[j])) {
334 // if (c == null) {
335 // c = Utils.detectType(values[j]);
336 // } else {
337 // Class c1 = Utils.detectType(values[j]);
338 // if (c == Integer.class && c1 == Double.class) {
339 // // change the type to double
340 // c = Double.class;
341 // }
342 //
343 // if (c1 != c &&
344 // !(c == Double.class && c1 == Integer.class) &&
345 // !warningGiven ) {
346 // System.err.println("Not all values of same type for trait" + traitName);
347 // warningGiven = true;
348 // }
349 // }
350 // }
351 // }
352 //
353 // TraitData.TraitType t = (c == Boolean.class || c == String.class || c == null) ? TraitData.TraitType.DISCRETE :
354 // (c == Integer.class) ? TraitData.TraitType.INTEGER : TraitData.TraitType.CONTINUOUS;
355 // TraitData newTrait = new TraitData(options, traitName, file.getName(), t);
356 //
357 // importedTraits.add(newTrait);
358 //
359 // int j = 0;
360 // for (final String taxonName : taxonNames) {
361 //
362 // final int index = taxa.getTaxonIndex(taxonName);
363 // Taxon taxon;
364 // if (index >= 0) {
365 // taxon = taxa.getTaxon(index);
366 // } else {
367 // taxon = new Taxon(taxonName);
368 // taxa.addTaxon(taxon);
369 // }
370 // if (!isMissingValue(values[j])) {
371 // taxon.setAttribute(traitName, Utils.constructFromString(c, values[j]));
372 // } else {
373 // // AR - merge rather than replace existing trait values
374 // if (taxon.getAttribute(traitName) == null) {
375 // taxon.setAttribute(traitName, "?");
376 // }
377 // }
378 // j++;
379 // }
380 // }
381 // setData(dataModel, file.getName(), taxa, null, null, null, importedTraits, null);
382 // }
383
384 // for Alignment
385 private void setData(Map dataModel, DateGuesser guesser, String fileName, TaxonList taxonList, List<TaxonList> taxonLists, Alignment alignment,
386 List<NexusApplicationImporter.CharSet> charSets,
387 List<TraitData> traits, List<Tree> trees) throws ImportException, IllegalArgumentException {
388 String fileNameStem = Utils.trimExtensions(fileName,
389 new String[]{"NEX", "NEXUS", "FA", "FAS", "FASTA", "TRE", "TREE", "XML", "TXT"});
390
391 checkTaxonList(taxonList, guesser);
392 dataModel.put("taxa", createTaxonList(taxonList));
393 dataModel.put("taxon_count", Integer.toString(taxonList.getTaxonCount()));
394 dataModel.put("taxon_count_minus_one", Integer.toString(taxonList.getTaxonCount()-1));
395
396 if (taxonLists != null) {
397 List<Map> tss = new ArrayList<Map>();
398
399 for (TaxonList tl : taxonLists) {
400 Map ts = new HashMap();
401 ts.put("id", tl.getId());
402 ts.put("taxa", createTaxonList(taxonList));
403
404 tss.add(ts);
405 }
406 dataModel.put("taxonSets", tss);
407 }
408
409 dataModel.put("alignment", createAlignment(alignment));
410 dataModel.put("site_count", Integer.toString(alignment.getSiteCount()));
411
412 dataModel.put("filename", fileName);
413 dataModel.put("filename_stem", fileNameStem);
414 }
415
416 private void checkTaxonList(TaxonList taxonList, DateGuesser guesser) throws ImportException {
417
418 // check the taxon names for invalid characters
419 boolean foundAmp = false;
420 for (Taxon taxon : taxonList) {
421 String name = taxon.getId();
422 if (name.indexOf('&') >= 0) {
423 foundAmp = true;
424 }
425 }
426 if (foundAmp) {
427 throw new ImportException("One or more taxon names include an illegal character ('&').\n" +
428 "These characters will prevent BEAST from reading the resulting XML file.\n\n" +
429 "Please edit the taxon name(s) before reloading the data file.");
430 }
431
432 if (guesser != null) {
433 guesser.guessDates(taxonList);
434 } else {
435 // make sure they all have dates...
436 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
437 if (taxonList.getTaxonAttribute(i, "date") == null) {
438 Date origin = new Date(0);
439
440 dr.evolution.util.Date date = dr.evolution.util.Date.createTimeSinceOrigin(0.0, Units.Type.YEARS, origin);
441 taxonList.getTaxon(i).setAttribute("date", date);
442 }
443 }
444 }
445 }
446
447 private List<Map> createTaxonList(TaxonList taxa) {
448
449 List<Map> tl = new ArrayList<Map>();
450 for (Taxon taxon : taxa) {
451 tl.add(createTaxon(taxon));
452 }
453
454 return tl;
455 }
456
457 private Map createTaxon(Taxon taxon) {
458 Map t = new HashMap();
459 t.put("id", taxon.getId());
460 if (taxon.getDate() != null) {
461 t.put("date", Double.toString(taxon.getDate().getTimeValue()));
462 }
463 return t;
464 }
465
466 private Map createAlignment(Alignment alignment) {
467
468 Map a = new HashMap();
469 a.put("id", (alignment.getId() != null ? alignment.getId() : "alignment"));
470
471 List<Map> ss = new ArrayList<Map>();
472 for (int i = 0; i < alignment.getSequenceCount(); i++) {
473 Sequence sequence = alignment.getSequence(i);
474 ss.add(createSequence(sequence));
475 }
476
477 a.put("sequences", ss);
478 return a;
479 }
480
481 private Map createSequence(Sequence sequence) {
482 Map s = new HashMap();
483 s.put("taxon", createTaxon(sequence.getTaxon()));
484 s.put("data", sequence.getSequenceString());
485 return s;
486 }
487 }