Debian Codegraph @

src/dr/app/beauti/util/BEAUTiImporter.java

raw symbols SCIP
1 /*
2 * BEAUTiImporter.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.beauti.util;
27
28 import dr.app.beauti.BeautiFrame;
29 import dr.app.beauti.mcmcpanel.MCMCPanel;
30 import dr.app.beauti.options.*;
31 import dr.app.util.Utils;
32 import dr.evolution.alignment.Alignment;
33 import dr.evolution.alignment.Patterns;
34 import dr.evolution.alignment.SimpleAlignment;
35 import dr.evolution.datatype.DataType;
36 import dr.evolution.datatype.Microsatellite;
37 import dr.evolution.datatype.Nucleotides;
38 import dr.evolution.io.FastaImporter;
39 import dr.evolution.io.Importer.ImportException;
40 import dr.evolution.io.MicroSatImporter;
41 import dr.evolution.io.NexusImporter;
42 import dr.evolution.io.NexusImporter.MissingBlockException;
43 import dr.evolution.io.NexusImporter.NexusBlock;
44 import dr.evolution.tree.Tree;
45 import dr.evolution.util.Taxa;
46 import dr.evolution.util.Taxon;
47 import dr.evolution.util.TaxonList;
48 import dr.evolution.util.Units;
49 import dr.util.DataTable;
50 import org.jdom.JDOMException;
51
52 import javax.swing.*;
53 import java.awt.*;
54 import java.io.*;
55 import java.util.*;
56 import java.util.List;
57
58
59 /**
60 * @author Andrew Rambaut
61 * @author Walter Xie
62 * @version $Id$
63 */
64 public class BEAUTiImporter {
65
66 private final String DEFAULT_NAME = "default";
67
68 private final BeautiOptions options;
69 private final BeautiFrame frame;
70
71 private PartitionNameDialog partitionNameDialog = null;
72
73 public BEAUTiImporter(BeautiFrame frame, BeautiOptions options) {
74 this.frame = frame;
75 this.options = options;
76 }
77
78 public void importFromFile(File file) throws IOException, ImportException, JDOMException {
79 try {
80 Reader reader = new FileReader(file);
81
82 BufferedReader bufferedReader = new BufferedReader(reader);
83 String line = bufferedReader.readLine();
84 while (line != null && line.length() == 0) {
85 line = bufferedReader.readLine();
86 }
87
88 if ((line != null && line.toUpperCase().contains("#NEXUS"))) {
89 // is a NEXUS file
90 importNexusFile(file);
91 } else if ((line != null && line.trim().startsWith("" + FastaImporter.FASTA_FIRST_CHAR))) {
92 // is a FASTA file
93 importFastaFile(file);
94 } else if ((line != null && (line.toUpperCase().contains("<?XML") || line.toUpperCase().contains("<BEAST")))) {
95 // assume it is a BEAST XML file and see if that works...
96 importBEASTFile(file);
97 // } else {
98 // // assume it is a tab-delimited traits file and see if that works...
99 // importTraits(file);
100 } else if ((line != null && line.toUpperCase().contains("#MICROSAT"))) {
101 // MicroSatellite
102 importMicroSatFile(file);
103 } else {
104 throw new ImportException("Unrecognized format for imported file.");
105 }
106
107 bufferedReader.close();
108 } catch (IOException e) {
109 throw new IOException(e.getMessage());
110 }
111 }
112
113 // micro-sat
114 private void importMicroSatFile(File file) throws IOException, ImportException {
115 try {
116 Reader reader = new FileReader(file);
117 BufferedReader bufferedReader = new BufferedReader(reader);
118
119 MicroSatImporter importer = new MicroSatImporter(bufferedReader);
120
121 List<Patterns> microsatPatList = importer.importPatterns();
122 Taxa unionSetTaxonList = importer.getUnionSetTaxonList();
123 Microsatellite microsatellite = importer.getMicrosatellite();
124 // options.allowDifferentTaxa = importer.isHasDifferentTaxon();
125
126 bufferedReader.close();
127
128 PartitionSubstitutionModel substModel = new PartitionSubstitutionModel(options, microsatPatList.get(0).getId());
129 substModel.setMicrosatellite(microsatellite);
130
131 for (Patterns patterns : microsatPatList) {
132 setData(file.getName(), unionSetTaxonList, patterns, substModel, null);
133 }
134 // has to call after data is imported
135 options.microsatelliteOptions.initModelParametersAndOpererators();
136
137 } catch (ImportException e) {
138 throw new ImportException(e.getMessage());
139 } catch (IOException e) {
140 throw new IOException(e.getMessage());
141 }
142 }
143
144 // xml
145 private void importBEASTFile(File file) throws IOException, ImportException, JDOMException {
146 try {
147 FileReader reader = new FileReader(file);
148
149 BeastImporter importer = new BeastImporter(reader);
150
151 List<TaxonList> taxonLists = new ArrayList<TaxonList>();
152 List<Alignment> alignments = new ArrayList<Alignment>();
153
154 importer.importBEAST(taxonLists, alignments);
155
156 TaxonList taxa = taxonLists.get(0);
157
158 int count = 1;
159 for (Alignment alignment : alignments) {
160 String name = file.getName();
161 if (alignment.getId() != null && alignment.getId().length() > 0) {
162 name = alignment.getId();
163 } else {
164 if (alignments.size() > 1) {
165 name += count;
166 }
167 }
168 setData(name, taxa, alignment, null, null, null, null, null);
169
170 count++;
171 }
172
173 // assume that any additional taxon lists are taxon sets...
174 for (int i = 1; i < taxonLists.size(); i++) {
175 Taxa taxonSet = (Taxa) taxonLists.get(i);
176
177 options.taxonSets.add(taxonSet);
178 options.taxonSetsMono.put(taxonSet, false);
179 options.taxonSetsIncludeStem.put(taxonSet, false);
180 options.taxonSetsTreeModel.put(taxonSet, options.getPartitionTreeModels().get(0));
181 options.updateTMRCAStatistic(taxonSet); // force the creation of a tmrca statistic
182 }
183 Collections.sort(options.taxonSets);
184
185 reader.close();
186 } catch (JDOMException e) {
187 throw new JDOMException(e.getMessage());
188 } catch (ImportException e) {
189 throw new ImportException(e.getMessage());
190 } catch (IOException e) {
191 throw new IOException(e.getMessage());
192 }
193
194 }
195
196 // nexus
197 private void importNexusFile(File file) throws IOException, ImportException {
198 TaxonList taxa = null;
199 SimpleAlignment alignment = null;
200 List<Tree> trees = new ArrayList<Tree>();
201 PartitionSubstitutionModel model = null;
202 List<NexusApplicationImporter.CharSet> charSets = new ArrayList<NexusApplicationImporter.CharSet>();
203 List<NexusApplicationImporter.TaxSet> taxSets = new ArrayList<NexusApplicationImporter.TaxSet>();
204
205 try {
206 FileReader reader = new FileReader(file);
207
208 NexusApplicationImporter importer = new NexusApplicationImporter(reader);
209
210 boolean done = false;
211
212 while (!done) {
213 try {
214
215 NexusBlock block = importer.findNextBlock();
216
217 if (block == NexusImporter.TAXA_BLOCK) {
218
219 if (taxa != null) {
220 throw new MissingBlockException("TAXA block already defined");
221 }
222
223 taxa = importer.parseTaxaBlock();
224
225 } else if (block == NexusImporter.CALIBRATION_BLOCK) {
226 if (taxa == null) {
227 throw new MissingBlockException("TAXA or DATA block must be defined before a CALIBRATION block");
228 }
229
230 importer.parseCalibrationBlock(taxa);
231
232 } else if (block == NexusImporter.CHARACTERS_BLOCK) {
233
234 if (taxa == null) {
235 throw new MissingBlockException("TAXA block must be defined before a CHARACTERS block");
236 }
237
238 if (alignment != null) {
239 throw new MissingBlockException("CHARACTERS or DATA block already defined");
240 }
241
242 alignment = (SimpleAlignment) importer.parseCharactersBlock(taxa);
243
244 } else if (block == NexusImporter.DATA_BLOCK) {
245
246 if (alignment != null) {
247 throw new MissingBlockException("CHARACTERS or DATA block already defined");
248 }
249
250 // A data block doesn't need a taxon block before it
251 // but if one exists then it will use it.
252 alignment = (SimpleAlignment) importer.parseDataBlock(taxa);
253 if (taxa == null) {
254 taxa = alignment;
255 }
256
257 } else if (block == NexusImporter.TREES_BLOCK) {
258
259 // I guess there is no reason not to allow multiple trees blocks
260 // if (trees.size() > 0) {
261 // throw new MissingBlockException("TREES block already defined");
262 // }
263
264 Tree[] treeArray = importer.parseTreesBlock(taxa);
265 trees.addAll(Arrays.asList(treeArray));
266
267 if (taxa == null && trees.size() > 0) {
268 taxa = trees.get(0);
269 }
270
271
272 } else if (block == NexusApplicationImporter.PAUP_BLOCK) {
273
274 model = importer.parsePAUPBlock(options, charSets);
275
276 } else if (block == NexusApplicationImporter.MRBAYES_BLOCK) {
277
278 model = importer.parseMrBayesBlock(options, charSets);
279
280 } else if (block == NexusApplicationImporter.ASSUMPTIONS_BLOCK || block == NexusApplicationImporter.SETS_BLOCK) {
281
282 importer.parseAssumptionsBlock(charSets, taxSets);
283
284 } else {
285 // Ignore the block..
286 }
287
288 } catch (EOFException ex) {
289 done = true;
290 }
291 }
292
293 reader.close();
294
295 // Allow the user to load taxa only (perhaps from a tree file) so that they can sample from a prior...
296 if (alignment == null && taxa == null) {
297 throw new MissingBlockException("TAXON, DATA or CHARACTERS block is missing");
298 }
299
300 } catch (IOException e) {
301 throw new IOException(e.getMessage());
302 } catch (ImportException e) {
303 throw new ImportException(e.getMessage());
304 // } catch (Exception e) {
305 // throw new Exception(e.getMessage());
306 }
307
308 setData(file.getName(), taxa, alignment, charSets, taxSets, model, null, trees);
309 }
310
311 // FASTA
312
313 private void importFastaFile(File file) throws IOException, ImportException {
314 try {
315 FileReader reader = new FileReader(file);
316
317 FastaImporter importer = new FastaImporter(reader, Nucleotides.INSTANCE);
318
319 Alignment alignment = importer.importAlignment();
320
321 reader.close();
322
323 setData(file.getName(), alignment, alignment, null, null, null, null, null);
324 } catch (ImportException e) {
325 throw new ImportException(e.getMessage());
326 } catch (IOException e) {
327 throw new IOException(e.getMessage());
328 }
329 }
330
331 private boolean isMissingValue(String value) {
332 return (value.equals("?") || value.equals("NA") || value.length() == 0);
333 }
334
335 public void importTraits(final File file) throws Exception {
336 List<TraitData> importedTraits = new ArrayList<TraitData>();
337 Taxa taxa = options.taxonList;
338
339 DataTable<String[]> dataTable = DataTable.Text.parse(new FileReader(file));
340
341 String[] traitNames = dataTable.getColumnLabels();
342 String[] taxonNames = dataTable.getRowLabels();
343
344 for (int i = 0; i < dataTable.getColumnCount(); i++) {
345 boolean warningGiven = false;
346
347 String traitName = traitNames[i];
348
349 String[] values = dataTable.getColumn(i);
350 Class c = null;
351 if (!isMissingValue(values[0])) {
352 c = Utils.detectType(values[0]);
353 }
354 for (int j = 1; j < values.length; j++) {
355 if (!isMissingValue(values[j])) {
356 if (c == null) {
357 c = Utils.detectType(values[j]);
358 } else {
359 Class c1 = Utils.detectType(values[j]);
360 if (c == Integer.class && c1 == Double.class) {
361 // change the type to double
362 c = Double.class;
363 }
364
365 if (c1 != c &&
366 !(c == Double.class && c1 == Integer.class) &&
367 !warningGiven ) {
368 JOptionPane.showMessageDialog(frame, "Not all values of same type for trait" + traitName,
369 "Incompatible values", JOptionPane.WARNING_MESSAGE);
370 warningGiven = true;
371 }
372 }
373 }
374 }
375
376 TraitData.TraitType t = (c == Boolean.class || c == String.class || c == null) ? TraitData.TraitType.DISCRETE :
377 (c == Integer.class) ? TraitData.TraitType.INTEGER : TraitData.TraitType.CONTINUOUS;
378 TraitData newTrait = new TraitData(options, traitName, file.getName(), t);
379
380 if (validateTraitName(traitName)) {
381 importedTraits.add(newTrait);
382 }
383
384 int j = 0;
385 for (final String taxonName : taxonNames) {
386
387 final int index = taxa.getTaxonIndex(taxonName);
388 Taxon taxon;
389 if (index >= 0) {
390 taxon = taxa.getTaxon(index);
391 } else {
392 taxon = new Taxon(taxonName);
393 taxa.addTaxon(taxon);
394 }
395 if (!isMissingValue(values[j])) {
396 taxon.setAttribute(traitName, Utils.constructFromString(c, values[j]));
397 } else {
398 // AR - merge rather than replace existing trait values
399 if (taxon.getAttribute(traitName) == null) {
400 taxon.setAttribute(traitName, "?");
401 }
402 }
403 j++;
404 }
405 }
406 setData(file.getName(), taxa, null, null, null, null, importedTraits, null);
407 }
408
409 public boolean importPredictors(final File file, final TraitData trait) throws Exception {
410 List<Predictor> importedPredictors = new ArrayList<Predictor>();
411 // Taxa taxa = options.taxonList;
412
413 // This is the order that states will be in...
414 Set<String> states = trait.getStatesOfTrait();
415
416 String fileName = file.getName();
417 String extension = "";
418 if (fileName.lastIndexOf(".") != -1) {
419 extension = fileName.substring(fileName.lastIndexOf(".") + 1);
420 fileName = fileName.substring(0, fileName.lastIndexOf("."));
421 }
422 boolean isCSV = extension.toUpperCase().equals("CSV");
423
424 DataTable<String[]> dataTable = DataTable.Text.parse(new FileReader(file), isCSV);
425
426 String[] stateNamesCol = dataTable.getColumnLabels();
427 String[] stateNamesRow = dataTable.getRowLabels();
428
429 if (dataTable.getRowCount() != states.size()) {
430 JOptionPane.showMessageDialog(frame, "Predictor data does not have the same number of rows as trait states",
431 "Mismatched states", JOptionPane.ERROR_MESSAGE);
432 return false;
433 }
434
435 for (String name : stateNamesRow) {
436 if (!states.contains(name)) {
437 JOptionPane.showMessageDialog(frame, "Predictor row label contains unrecognized state '" + name + "'",
438 "Unrecognized state", JOptionPane.ERROR_MESSAGE);
439 return false;
440 }
441 }
442
443 boolean isMatrix = false;
444
445 if (dataTable.getColumnCount() == states.size()) {
446 // likely this is a matrix
447 int matches = states.size();
448 for (String name : stateNamesCol) {
449 if (!states.contains(name)) {
450 matches -= 1;
451 }
452 }
453 if (((double)matches) / states.size() > 0.5) { // arbitrary cut off but if 50% matching then presumably they all should
454 for (String name : stateNamesCol) {
455 if (!states.contains(name)) {
456 JOptionPane.showMessageDialog(frame, "Predictor row label contains unrecognized state '" + name + "'",
457 "Unrecognized state", JOptionPane.ERROR_MESSAGE);
458 return false;
459 }
460 }
461
462 isMatrix = true;
463 }
464 }
465
466 if (isMatrix) {
467 double[][] data = new double[dataTable.getRowCount()][dataTable.getRowCount()];
468
469 String name = stateNamesCol[0];
470 for (int i = 0; i < dataTable.getRowCount(); i++) {
471 String[] row = dataTable.getRow(i);
472 for (int j = 0; j < row.length; j++) {
473 try {
474 data[i][j] = Double.parseDouble(row[j]);
475 } catch (NumberFormatException nfe) {
476 JOptionPane.showMessageDialog(frame, "Predictor '" + name + "' has a bad value at row " + (i+1),
477 "Missing value", JOptionPane.ERROR_MESSAGE);
478 }
479 }
480
481
482 }
483 Predictor predictor = new Predictor(options, fileName, trait, stateNamesRow, data, Predictor.Type.MATRIX);
484 importedPredictors.add(predictor);
485
486 } else {
487 // a series of vectors
488 for (int i = 0; i < dataTable.getColumnCount(); i++) {
489 String name = stateNamesCol[i];
490
491 double[][] data = new double[dataTable.getRowCount()][1];
492
493 String[] values = dataTable.getColumn(i);
494 for (int j = 0; j < values.length; j++) {
495 try {
496 data[j][0] = Double.parseDouble(values[j]);
497 } catch (NumberFormatException nfe) {
498 JOptionPane.showMessageDialog(frame, "Predictor '" + name + "' has a bad value at position " + (j+1),
499 "Missing value", JOptionPane.ERROR_MESSAGE);
500 }
501 }
502
503 Predictor predictor = new Predictor(options, name, trait, stateNamesRow, data, Predictor.Type.BOTH_VECTOR);
504 importedPredictors.add(predictor);
505 }
506 }
507
508 for (Predictor predictor : importedPredictors) {
509 trait.addPredictor(predictor);
510 }
511
512 return true;
513 }
514
515 private boolean validateTraitName(String traitName) {
516 // check that the name is valid
517 if (traitName.trim().length() == 0) {
518 Toolkit.getDefaultToolkit().beep();
519 return false;
520 }
521
522 // disallow a trait called 'date'
523 if (traitName.equalsIgnoreCase("date")) {
524 JOptionPane.showMessageDialog(frame,
525 "This trait name has a special meaning. Use the 'Tip Date' panel\n" +
526 " to set dates for taxa.",
527 "Reserved trait name",
528 JOptionPane.WARNING_MESSAGE);
529
530 return false;
531 }
532
533 // check that the trait name doesn't exist
534 if (options.traitExists(traitName)) {
535 int option = JOptionPane.showConfirmDialog(frame,
536 "A trait of this name already exists. Do you wish to replace\n" +
537 "it with this new trait? This may result in the loss or change\n" +
538 "in trait values for the taxa.",
539 "Overwrite trait?",
540 JOptionPane.YES_NO_OPTION,
541 JOptionPane.WARNING_MESSAGE);
542
543 if (option == JOptionPane.NO_OPTION) {
544 return false;
545 }
546 }
547
548 return true;
549 }
550
551 // for Alignment
552 private void setData(String fileName, TaxonList taxonList, Alignment alignment,
553 List<NexusApplicationImporter.CharSet> charSets,
554 List<NexusApplicationImporter.TaxSet> taxSets,
555 PartitionSubstitutionModel model,
556 List<TraitData> traits, List<Tree> trees) throws ImportException, IllegalArgumentException {
557 String fileNameStem = Utils.trimExtensions(fileName,
558 new String[]{"NEX", "NEXUS", "FA", "FAS", "FASTA", "TRE", "TREE", "XML", "TXT"});
559 if (options.fileNameStem == null || options.fileNameStem.equals(MCMCPanel.DEFAULT_FILE_NAME_STEM)) {
560 options.fileNameStem = fileNameStem;
561 }
562
563 addTaxonList(taxonList);
564
565 addAlignment(alignment, charSets, model, fileName, fileNameStem);
566
567 addTaxonSets(taxonList, taxSets);
568
569 addTraits(traits);
570
571 addTrees(trees);
572 }
573
574 // for Patterns
575 private void setData(String fileName, Taxa taxonList, Patterns patterns,
576 PartitionSubstitutionModel model, List<TraitData> traits
577 ) throws ImportException, IllegalArgumentException {
578 String fileNameStem = Utils.trimExtensions(fileName,
579 new String[]{"NEX", "NEXUS", "FA", "FAS", "FASTA", "TRE", "TREE", "XML", "TXT"});
580 if (options.fileNameStem == null || options.fileNameStem.equals(MCMCPanel.DEFAULT_FILE_NAME_STEM)) {
581 options.fileNameStem = fileNameStem;
582 }
583
584 addTaxonList(taxonList);
585
586 addPatterns(patterns, model, fileName);
587
588 addTraits(traits);
589 }
590
591 private void addTaxonList(TaxonList taxonList) throws ImportException {
592 checkTaxonList(taxonList);
593 if (options.taxonList == null) {
594 // This is the first partition to be loaded...
595 options.taxonList = new Taxa(taxonList);
596 } else {
597 // otherwise just add the new ones...
598 for (Taxon taxon : taxonList) {
599 if (!options.taxonList.contains(taxon)) {
600 options.taxonList.addTaxon(taxon);
601 }
602 }
603 }
604 }
605
606 private void checkTaxonList(TaxonList taxonList) throws ImportException {
607
608 // check the taxon names for invalid characters
609 boolean foundAmp = false;
610 for (Taxon taxon : taxonList) {
611 String name = taxon.getId();
612 if (name.indexOf('&') >= 0) {
613 foundAmp = true;
614 }
615 }
616 if (foundAmp) {
617 throw new ImportException("One or more taxon names include an illegal character ('&').\n" +
618 "These characters will prevent BEAST from reading the resulting XML file.\n\n" +
619 "Please edit the taxon name(s) before reloading the data file.");
620 }
621
622 // make sure they all have dates...
623 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
624 if (taxonList.getTaxonAttribute(i, "date") == null) {
625 Date origin = new Date(0);
626
627 dr.evolution.util.Date date = dr.evolution.util.Date.createTimeSinceOrigin(0.0, Units.Type.YEARS, origin);
628 taxonList.getTaxon(i).setAttribute("date", date);
629 }
630 }
631 }
632
633 private void addTaxonSets(TaxonList taxonList, List<NexusApplicationImporter.TaxSet> taxSets) throws ImportException {
634 if (taxSets != null) {
635 for (NexusApplicationImporter.TaxSet taxSet : taxSets) {
636 Taxa taxa = new Taxa(taxSet.getName());
637 for (NexusApplicationImporter.CharSetBlock block : taxSet.getBlocks()) {
638 for (int i = block.getFromSite(); i <= block.getToSite(); i++) {
639 taxa.addTaxon(taxonList.getTaxon(i - 1));
640 }
641 }
642 options.taxonSets.add(taxa);
643 options.taxonSetsTreeModel.put(taxa, options.getPartitionTreeModels().get(0));
644 options.taxonSetsMono.put(taxa, false);
645 options.taxonSetsIncludeStem.put(taxa, false);
646 options.taxonSetsHeights.put(taxa, 0.0);
647 }
648 }
649 }
650
651 private void addAlignment(Alignment alignment,
652 List<NexusApplicationImporter.CharSet> charSets,
653 PartitionSubstitutionModel model,
654 String fileName, String fileNameStem) {
655 if (alignment != null) {
656 List<AbstractPartitionData> partitions = new ArrayList<AbstractPartitionData>();
657 if (charSets != null && charSets.size() > 0) {
658 for (NexusApplicationImporter.CharSet charSet : charSets) {
659 partitions.add(new PartitionData(options, charSet.name, fileName,
660 charSet.constructCharSetAlignment(alignment)));
661 }
662 } else {
663 partitions.add(new PartitionData(options, fileNameStem, fileName, alignment));
664 }
665 createPartitionFramework(model, partitions);
666 }
667 }
668
669 private void addPatterns(Patterns patterns, PartitionSubstitutionModel model, String fileName) {
670 if (patterns != null) {
671 List<AbstractPartitionData> partitions = new ArrayList<AbstractPartitionData>();
672 partitions.add(new PartitionPattern(options, patterns.getId(), fileName, patterns));
673
674 createPartitionFramework(model, partitions);
675 }
676 }
677
678 private void createPartitionFramework(PartitionSubstitutionModel model, List<AbstractPartitionData> partitions) {
679 for (AbstractPartitionData partition : partitions) {
680 String name = partition.getName();
681
682 while (name.length() == 0 || options.hasPartitionData(name)) {
683 String text;
684 if (options.hasPartitionData(name)) {
685 text = "<html>" +
686 "A partition named, " + name + ", already exists.<br>" +
687 "Please provide a unique name for this partition." +
688 "</html>";
689 } else {
690 text = "<html>" +
691 "Invalid partition name. Please provide a unique<br>" +
692 "name for this partition." +
693 "</html>";
694 }
695 if (partitionNameDialog == null) {
696 partitionNameDialog = new PartitionNameDialog(frame);
697 }
698
699 partitionNameDialog.setDescription(text);
700
701 int result = partitionNameDialog.showDialog();
702
703 if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
704 return;
705 }
706
707 name = partitionNameDialog.getName();
708 }
709 partition.setName(name);
710
711 options.dataPartitions.add(partition);
712
713 if (model != null) {
714 setSubstModel(partition, model);
715
716 setClockAndTree(partition);//TODO Cannot load Clock Model and Tree Model from BEAST file yet
717
718 } else {// only this works
719 if (options.getPartitionSubstitutionModels(partition.getDataType()).size() < 1) {// use same substitution model in beginning
720 // PartitionSubstitutionModel based on PartitionData
721 PartitionSubstitutionModel psm = new PartitionSubstitutionModel(options, DEFAULT_NAME, partition);
722 partition.setPartitionSubstitutionModel(psm);
723 } else { //if (options.getPartitionSubstitutionModels() != null) {
724 // && options.getPartitionSubstitutionModels().size() == 1) {
725 PartitionSubstitutionModel psm = options.getPartitionSubstitutionModels(partition.getDataType()).get(0);
726 setSubstModel(partition, psm);
727 }
728
729 setClockAndTree(partition);
730 }
731 }
732
733 // options.updatePartitionAllLinks();
734 // options.clockModelOptions.initClockModelGroup();
735 }
736
737 private void setClockAndTree(AbstractPartitionData partition) {
738
739 PartitionTreeModel treeModel;
740
741 // use same tree model and same tree prior in beginning
742 if (options.getPartitionTreeModels().size() < 1) {
743 // PartitionTreeModel based on PartitionData
744 treeModel = new PartitionTreeModel(options, DEFAULT_NAME);
745 partition.setPartitionTreeModel(treeModel);
746
747 // PartitionTreePrior always based on PartitionTreeModel
748 PartitionTreePrior ptp = new PartitionTreePrior(options, treeModel);
749 treeModel.setPartitionTreePrior(ptp);
750 } else { //if (options.getPartitionTreeModels() != null) {
751 // && options.getPartitionTreeModels().size() == 1) {
752 if (partition.getDataType().getType() == DataType.MICRO_SAT) {
753 treeModel = new PartitionTreeModel(options, partition.getName()); // different tree model,
754 PartitionTreePrior ptp = options.getPartitionTreePriors().get(0); // but same tree prior
755 treeModel.setPartitionTreePrior(ptp);
756 } else {
757 treeModel = options.getPartitionTreeModels().get(0); // same tree model,
758 }
759 partition.setPartitionTreeModel(treeModel); // if same tree model, therefore same prior
760 }
761
762 // use same clock model in beginning, have to create after partition.setPartitionTreeModel(ptm);
763 if (options.getPartitionClockModels(partition.getDataType()).size() < 1) {
764 // PartitionClockModel based on PartitionData
765 PartitionClockModel pcm = new PartitionClockModel(options, DEFAULT_NAME, partition, treeModel);
766 partition.setPartitionClockModel(pcm);
767 } else { //if (options.getPartitionClockModels() != null) {
768 // && options.getPartitionClockModels().size() == 1) {
769 PartitionClockModel pcm;
770 if (partition.getDataType().getType() == DataType.MICRO_SAT) {
771 pcm = new PartitionClockModel(options, partition.getName(), partition, treeModel);
772 } else {
773 // make sure in the same data type
774 pcm = options.getPartitionClockModels(partition.getDataType()).get(0);
775 }
776 partition.setPartitionClockModel(pcm);
777 }
778 }
779
780 private void setSubstModel(AbstractPartitionData partition, PartitionSubstitutionModel psm) {
781 partition.setPartitionSubstitutionModel(psm);
782
783 if (psm.getDataType().getType() != partition.getDataType().getType())
784 throw new IllegalArgumentException("Partition " + partition.getName()
785 + "\ncannot assign to Substitution Model\n" + psm.getName()
786 + "\nwith different data type.");
787 }
788
789 private void addTraits(List<TraitData> traits) {
790 if (traits != null) {
791 for (TraitData trait : traits) {
792 options.addTrait(trait);
793 }
794
795 // options.updatePartitionAllLinks();
796 }
797 }
798
799 private void addTrees(List<Tree> trees) {
800 if (trees != null && trees.size() > 0) {
801 for (Tree tree : trees) {
802 String id = tree.getId();
803 if (id == null || id.trim().length() == 0) {
804 tree.setId("tree_" + (options.userTrees.size() + 1));
805 } else {
806 String newId = id;
807 int count = 1;
808 for (Tree tree1 : options.userTrees) {
809 if (tree1.getId().equals(newId)) {
810 newId = id + "_" + count;
811 count++;
812 }
813 }
814 tree.setId(newId);
815 }
816 options.userTrees.add(tree);
817 }
818 }
819 }
820
821 }