Debian Codegraph @

src/dr/app/bss/Utils.java

raw symbols SCIP
1 /*
2 * Utils.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.bss;
27
28 import java.awt.Desktop;
29 import java.awt.Frame;
30 import java.io.BufferedInputStream;
31 import java.io.BufferedReader;
32 import java.io.File;
33 import java.io.FileInputStream;
34 import java.io.FileReader;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.net.URL;
39 import java.nio.charset.Charset;
40 import java.text.NumberFormat;
41 import java.util.ArrayList;
42 import java.util.Iterator;
43 import java.util.LinkedHashMap;
44 import java.util.List;
45 import java.util.Locale;
46 import java.util.Map;
47 import java.util.Map.Entry;
48 import java.util.concurrent.ConcurrentHashMap;
49
50 import javax.swing.ImageIcon;
51 import javax.swing.JOptionPane;
52 import javax.swing.JTabbedPane;
53 import javax.swing.SwingUtilities;
54
55 import dr.evolution.datatype.HiddenDataType;
56 import dr.evolution.tree.TreeUtils;
57 import org.apache.commons.math.random.MersenneTwister;
58
59 import dr.app.bss.test.AncestralSequenceTrait;
60 import dr.evolution.datatype.Codons;
61 import dr.evolution.datatype.DataType;
62 import dr.evolution.io.Importer.ImportException;
63 import dr.evolution.io.NewickImporter;
64 import dr.evolution.io.NexusImporter;
65 import dr.evolution.sequence.Sequence;
66 import dr.evolution.tree.NodeRef;
67 import dr.evolution.tree.Tree;
68 import dr.evolution.tree.TreeTraitProvider;
69 import dr.evolution.util.MutableTaxonList;
70 import dr.evolution.util.Taxa;
71 import dr.evolution.util.Taxon;
72 import dr.evomodel.tree.TreeModel;
73 import dr.inference.model.Parameter;
74 import dr.math.MathUtils;
75
76 /**
77 * @author Filip Bielejec
78 * @version $Id$
79 */
80 public class Utils {
81
82 // ////////////////////
83 // ---THREAD UTILS---//
84 // ////////////////////
85
86 public static void sleep(int seconds) {
87 try {
88
89 Thread.sleep(seconds * 1000);
90 } catch (InterruptedException e) {
91 e.printStackTrace();
92 }
93 }// END: sleep
94
95 // ////////////////////////////////
96 // ---RANDOM NUMB3R GENERATION---//
97 // ////////////////////////////////
98
99 private static MersenneTwister random = new MersenneTwister(
100 MathUtils.nextLong());
101
102 public static double rLogNormal(double stdev, double mean) {
103
104 double rNorm = random.nextGaussian() * stdev + mean;
105 double rLognormal = Math.exp(rNorm);
106
107 return rLognormal;
108 }// END: drawRandom
109
110 public static int rMultinom(double[] probabilities) {
111
112 int range = probabilities.length + 1;
113 double[] distribution = new double[range];
114 double sumProb = 0;
115
116 for (double value : probabilities) {
117 sumProb += value;
118 }// END: probabilities loop
119
120 distribution[0] = 0;
121 for (int i = 1; i < range; ++i) {
122
123 distribution[i] = distribution[i - 1]
124 + (probabilities[i - 1] / sumProb);
125
126 }// END: i loop
127
128 distribution[range - 1] = 1.0;
129
130 double key = random.nextDouble();
131
132 int mindex = 1;
133 int maxdex = range - 1;
134 int midpoint = mindex + (maxdex - mindex) / 2;
135 while (mindex <= maxdex) {
136
137 if (key < distribution[midpoint - 1]) {
138
139 maxdex = midpoint - 1;
140
141 } else if (key > distribution[midpoint]) {
142
143 mindex = midpoint + 1;
144
145 } else {
146
147 return midpoint - 1;
148
149 }
150
151 midpoint = mindex + (int) Math.ceil((maxdex - mindex) / 2);
152
153 }//END: mindex loop
154
155 System.out.println("Error in rMultinom!");
156
157 return range - 1;
158 }//END: rMultinom
159
160 // ////////////
161 // ---MATH---//
162 // ////////////
163
164 public static int sample(double[] probabilities) {
165
166 int samplePos = -Integer.MAX_VALUE;
167 double cumProb = 0.0;
168 double u = random.nextDouble();
169
170 for (int i = 0; i < probabilities.length; i++) {
171
172 cumProb += probabilities[i];
173
174 if (u <= cumProb) {
175 samplePos = i;
176 break;
177 }
178 }
179
180 return samplePos;
181 }// END: randomChoicePDF
182
183 public static void rescale(double[] logX) {
184 double max = max(logX);
185 for (int i = 0; i < logX.length; i++) {
186 logX[i] -= max;
187 }
188 }// END: rescale
189
190 public double getParameterVariance(Parameter param) {
191
192 int n = param.getSize();
193 double mean = getParameterMean(param);
194 double var = 0;
195
196 for (int i = 0; i < n; i++) {
197
198 var+= Math.pow( (param.getValue(i) - mean), 2);
199
200 }
201
202 var/= (n-1);
203
204 return var;
205 }// END: getParameterVariance
206
207 public double getParameterMean(Parameter param) {
208 double mean = 0;
209 int n = param.getSize();
210 for (int i = 0; i < n; i++) {
211 mean += param.getValue(i);
212 }
213 mean /= n;
214
215 return mean;
216 }// END: getParameterMean
217
218 public static double getNorm(double[] vector) {
219 double norm = 0;
220 for (int i = 0; i < vector.length; i++) {
221 norm += Math.pow(vector[i], 2);
222 }
223
224 return Math.sqrt(norm);
225 }// END: getNorm
226
227 public static void normalize(double[] vector) {
228
229 double norm = getNorm(vector);
230 for (int i = 0; i < vector.length; i++) {
231 vector[i] = vector[i] / norm;
232 }
233
234 }// END: normalize
235
236 // ////////////////////
237 // ---ARRAYS UTILS---//
238 // ////////////////////
239
240 public static void exponentiate(double[] array) {
241 for (int i = 0; i < array.length; i++) {
242 array[i] = Math.exp(array[i]);
243 }
244 }// END: exponentiate
245
246 public static int max(int[] array) {
247
248 int max = -Integer.MAX_VALUE;
249
250 for (int i = 0; i < array.length; i++) {
251
252 if (array[i] > max) {
253
254 max = (int)array[i];
255
256 }// END: if check
257
258 }// END: i loop
259
260 return max;
261 }// END: findMaximum
262
263 public static int max(double[] array) {
264
265 int max = -Integer.MAX_VALUE;
266
267 for (int i=0; i< array.length;i++) {
268
269 if (array[i] > max) {
270
271 max = (int)array[i];
272
273 }// END: if check
274
275 }// END: i loop
276
277 return max;
278 }// END: findMaximum
279
280 public static int max(ArrayList<Integer> array) {
281
282 int max = -Integer.MAX_VALUE;
283
284 for (Integer element : array) {
285
286 if (element > max) {
287
288 max = element;
289
290 }// END: if check
291
292 }// END: i loop
293
294 return max;
295 }// END: findMaximum
296
297 public static double sumArray(int[] array) {
298
299 double sum = 0.0;
300 for (int i = 0; i < array.length; i++) {
301
302 sum += array[i];
303
304 }
305
306 return sum;
307 }// END: sumArray
308
309 public static double sumArray(double[] array) {
310
311 double sum = 0.0;
312 for (int i = 0; i < array.length; i++) {
313
314 sum += array[i];
315
316 }
317
318 return sum;
319 }// END: sumArray
320
321 // /////////////////
322 // ---CONSTANTS---//
323 // /////////////////
324
325 // public static final int TREE_MODEL_ELEMENT = 0;
326 public static final int BRANCH_MODEL_ELEMENT = 1;
327 public static final int SITE_RATE_MODEL_ELEMENT = 2;
328 public static final int BRANCH_RATE_MODEL_ELEMENT = 3;
329 public static final int FREQUENCY_MODEL_ELEMENT = 4;
330 public static final int DEMOGRAPHIC_MODEL_ELEMENT = 5;
331
332 public static final String TOPOLOGY = "topology";
333 public static final String ABSOLUTE_HEIGHT = "absoluteHeight";
334 public static final String TREE_FILENAME = "treeFilename";
335 public static final String SUBSTITUTION_MODEL = "substitutionModel";
336 public static final String DEMOGRAPHIC_MODEL = "demographicModel";
337 public static final String FREQUENCY_MODEL = "frequencyModel";
338 public static final String CODON_UNIVERSAL = "codon-universal";
339 public static final String CHOOSE_FILE = "Choose file...";
340 public static final String EDIT_TAXA_SET = "Edit taxa set...";
341 public static final String ANCESTRAL_SEQUENCE = "ancestralSequence";
342
343 public static final String BSS_ICON = "icons/bss.png";
344 public static final String CHECK_ICON = "icons/check.png";
345 public static final String ERROR_ICON = "icons/error.png";
346 public static final String HAMMER_ICON = "icons/hammer.png";
347 public static final String CLOSE_ICON = "icons/close.png";
348 public static final String BIOHAZARD_ICON = "icons/biohazard.png";
349 public static final String BUBBLE_BLUE_ICON = "icons/bubble-blue.png";
350 public static final String SAVE_ICON = "icons/save.png";
351 public static final String TEXT_FILE_ICON = "icons/file.png";
352
353 public static final double[] UNIFORM_CODON_FREQUENCIES = new double[] {
354 0.0163936, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
355 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
356 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
357 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
358 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
359 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
360 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
361 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
362 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
363 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
364 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
365 0.01639344, 0.01639344, 0.01639344, 0.01639344, 0.01639344,
366 0.01639344 };
367
368 public static final String STOP_CODONS[] = new String[] { "TAA", "TAG", "TGA" };
369
370 // ///////////////////////////////
371 // ---GENERAL UTILITY METHODS---//
372 // ///////////////////////////////
373
374 public static double logfactor(int n) {
375
376 double logfactor = 0.0;
377 for (int i = 1; i <= n; i++) {
378 logfactor += Math.log(i);
379 }
380
381 return logfactor;
382 }
383
384 public static double map(double value, double low1, double high1,
385 double low2, double high2) {
386 /**
387 * maps a single value from its range into another interval
388 *
389 * @param low1
390 * , high1 - range of value; low2, high2 - interval
391 * @return the mapped value
392 */
393 return (value - low1) / (high1 - low1) * (high2 - low2) + low2;
394 }// END: map
395
396 public static String[] loadStrings(String filename) throws IOException {
397
398 int linesCount = countLines(filename);
399 String[] lines = new String[linesCount];
400
401 FileInputStream inputStream;
402 BufferedReader reader;
403 String line;
404
405 inputStream = new FileInputStream(filename);
406 reader = new BufferedReader(new InputStreamReader(inputStream,
407 Charset.forName("UTF-8")));
408 int i = 0;
409 while ((line = reader.readLine()) != null) {
410 lines[i] = line;
411 i++;
412 }
413
414 // Clean up
415 reader.close();
416 reader = null;
417 inputStream = null;
418
419 return lines;
420 }// END: loadStrings
421
422 public static int countLines(String filename) throws IOException {
423
424 InputStream is = new BufferedInputStream(new FileInputStream(filename));
425
426 byte[] c = new byte[1024];
427 int count = 0;
428 int readChars = 0;
429 boolean empty = true;
430 while ((readChars = is.read(c)) != -1) {
431 empty = false;
432 for (int i = 0; i < readChars; ++i) {
433 if (c[i] == '\n') {
434 ++count;
435 }
436 }
437 }
438
439 is.close();
440
441 return (count == 0 && !empty) ? 1 : count;
442
443 }// END: countLines
444
445 public static Taxa importTaxaFromFile(File file) throws IOException {
446
447 Taxa taxa = new Taxa();
448 Taxon taxon;
449 String[] lines = Utils.loadStrings(file.getAbsolutePath());
450
451 for (int i = 0; i < lines.length; i++) {
452
453 String[] line = lines[i].split("\\s+");
454
455 taxon = new Taxon(line[TaxaEditorTableModel.NAME_INDEX]);
456 taxon.setAttribute(Utils.ABSOLUTE_HEIGHT,
457 Double.valueOf(line[TaxaEditorTableModel.HEIGHT_INDEX]));
458
459 taxa.addTaxon(taxon);
460
461 }// END: i loop
462
463 return taxa;
464 }// END: importTaxaFromFile
465
466 public static Tree importTreeFromFile(File file) throws IOException,
467 ImportException {
468
469 Tree tree = null;
470
471 BufferedReader reader = new BufferedReader(new FileReader(file));
472 String line = reader.readLine();
473
474 if (line.toUpperCase().startsWith("#NEXUS")) {
475
476 NexusImporter importer = new NexusImporter(reader);
477 tree = importer.importTree(null);
478
479 } else {
480
481 NewickImporter importer = new NewickImporter(reader);
482 tree = importer.importTree(null);
483
484 }
485
486 reader.close();
487
488 return tree;
489 }// END: importTreeFromFile
490
491 public static void removeTaxaWithAttributeValue(PartitionDataList dataList,
492 String attribute, String value) {
493
494 for (int i = 0; i < dataList.allTaxa.getTaxonCount(); i++) {
495
496 Taxon taxon = dataList.allTaxa.getTaxon(i);
497 if (taxon.getAttribute(attribute).toString()
498 .equalsIgnoreCase(value)) {
499
500 dataList.allTaxa.removeTaxon(taxon);
501 i--;
502
503 }
504 }
505
506 }// END: removeTaxaWithAttributeValue
507
508 public static void centreLine(String line, int pageWidth) {
509 int n = pageWidth - line.length();
510 int n1 = n / 2;
511 for (int i = 0; i < n1; i++) {
512 System.out.print(" ");
513 }
514 System.out.println(line);
515 }
516
517 public static int getSiteCount(PartitionDataList dataList) {
518
519 int siteCount = 0;
520 int to = 0;
521 for (PartitionData data : dataList) {
522 // siteCount += data.createPartitionSiteCount();
523 to = data.to;
524 if (to > siteCount) {
525 siteCount = to;
526 }
527
528 }
529
530 return siteCount;// + 1;
531 }// END: getSiteCount
532
533 public static int arrayIndex(String[] array, String element) {
534
535 List<String> vector = new ArrayList<String>();
536 for (int i = 0; i < array.length; i++) {
537 vector.add(array[i]);
538 }
539
540 return vector.indexOf(element);
541 }// END: arrayIndex
542
543 public static ArrayList<TreeModel> treesToList(PartitionDataList dataList) {
544
545 ArrayList<TreeModel> treeModelsList = new ArrayList<TreeModel>();
546 for (PartitionData data : dataList) {
547 treeModelsList.add(data.createTreeModel());
548 }
549
550 return treeModelsList;
551 }// END: treesToList
552
553 public static boolean taxonExists(Taxon taxon, MutableTaxonList taxonList) {
554
555 boolean exists = false;
556 for (Taxon taxon2 : taxonList) {
557
558 if (taxon.equals(taxon2)
559 // &&
560 // taxon.getAttribute(Utils.TREE_FILENAME).toString().equalsIgnoreCase(taxon2.getAttribute(Utils.TREE_FILENAME).toString())
561 ) {
562 exists = true;
563 break;
564 }
565
566 }
567
568 return exists;
569 }// END: taxonExists
570
571 // private boolean isFileInList(File file) {
572 // boolean exists = false;
573 //
574 // for (File file2 : dataList.treesList) {
575 //
576 // if (file.getName().equalsIgnoreCase(file2.getName())) {
577 // exists = true;
578 // break;
579 // }
580 //
581 // }
582 //
583 // return exists;
584 // }// END: isFileInList
585
586 public static double getAbsoluteTaxonHeight(Taxon taxon, Tree tree) {
587
588 double height = 0.0;
589 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
590
591 NodeRef externalNode = tree.getExternalNode(i);
592 Taxon externalNodeTaxon = tree.getNodeTaxon(externalNode);
593
594 if (externalNodeTaxon.equals(taxon)) {
595 height = tree.getNodeHeight(externalNode);
596 }
597 }// END: external node loop
598
599 return height;
600 }// END: getAbsoluteTaxonHeight
601
602 public static boolean isRecordInList(TreesTableRecord record,
603 ArrayList<TreesTableRecord> recordsList) {
604
605 boolean exists = false;
606
607 for (TreesTableRecord record2 : recordsList) {
608
609 if (record.getName().equalsIgnoreCase(record2.getName())) {
610 exists = true;
611 break;
612 }
613
614 }
615
616 return exists;
617 }// END: isRecordInList
618
619 public static boolean isTaxaInList(Taxa taxa, ArrayList<Taxa> taxaList) {
620
621 boolean exists = false;
622
623 for (Taxa taxa2 : taxaList) {
624
625 if (taxaToString(taxa, true).equalsIgnoreCase(
626 taxaToString(taxa2, true))) {
627 exists = true;
628 break;
629 }
630
631 }
632
633 return exists;
634 }// END: isTaxaInList
635
636 public static int taxaIsIdenticalWith(Taxa taxa, ArrayList<Taxa> taxaList) {
637
638 int index = -Integer.MAX_VALUE;
639
640 for (Taxa taxa2 : taxaList) {
641
642 if (taxaToString(taxa, true).equalsIgnoreCase(
643 taxaToString(taxa2, true))) {
644 index = taxaList.indexOf(taxa2);
645 break;
646 }
647
648 }
649
650 return index;
651 }// END: treeModelIsIdenticalWith
652
653 public static boolean isTreeModelInList(TreeModel treeModel,
654 ArrayList<TreeModel> treeModelList) {
655
656 boolean exists = false;
657
658 for (TreeModel treeModel2 : treeModelList) {
659
660 if (treeModel.getNewick().equalsIgnoreCase(treeModel2.getNewick())) {
661 exists = true;
662 break;
663 }
664
665 }
666
667 return exists;
668 }// END: isTreeModelInList
669
670 public static int treeModelIsIdenticalWith(TreeModel treeModel,
671 ArrayList<TreeModel> treeModelList) {
672
673 int index = -Integer.MAX_VALUE;
674
675 for (TreeModel treeModel2 : treeModelList) {
676
677 if (treeModel.getNewick().equalsIgnoreCase(treeModel2.getNewick())) {
678 index = treeModelList.indexOf(treeModel2);
679 break;
680 }
681
682 }
683
684 return index;
685 }// END: treeModelIsIdenticalWith
686
687 public static boolean isElementInList(PartitionData data,
688 ArrayList<PartitionData> partitionList, int elementIndex) {
689
690 boolean exists = false;
691
692 switch (elementIndex) {
693
694 case DEMOGRAPHIC_MODEL_ELEMENT:
695
696 for (PartitionData data2 : partitionList) {
697 if (demographicModelToString(data).equalsIgnoreCase(
698 demographicModelToString(data2))) {
699 exists = true;
700 break;
701 }
702 }
703
704 break;
705
706 case BRANCH_RATE_MODEL_ELEMENT:
707
708 for (PartitionData data2 : partitionList) {
709 if (clockRateModelToString(data).equalsIgnoreCase(
710 clockRateModelToString(data2))) {
711 exists = true;
712 break;
713 }
714 }
715
716 break;
717
718 case FREQUENCY_MODEL_ELEMENT:
719
720 for (PartitionData data2 : partitionList) {
721 if (frequencyModelToString(data).equalsIgnoreCase(
722 frequencyModelToString(data2))) {
723 exists = true;
724 break;
725 }
726 }
727
728 break;
729
730 case BRANCH_MODEL_ELEMENT:
731
732 for (PartitionData data2 : partitionList) {
733 if (branchSubstitutionModelToString(data).equalsIgnoreCase(
734 branchSubstitutionModelToString(data2))) {
735 exists = true;
736 break;
737 }
738 }
739
740 break;
741
742 case SITE_RATE_MODEL_ELEMENT:
743
744 for (PartitionData data2 : partitionList) {
745 if (siteRateModelToString(data).equalsIgnoreCase(
746 siteRateModelToString(data2))) {
747 exists = true;
748 break;
749 }
750 }
751
752 break;
753
754 default:
755
756 throw new RuntimeException("Unknown element");
757
758 }// END: switch
759
760 return exists;
761 }// END: isModelInList
762
763 public static int isIdenticalWith(PartitionData data,
764 ArrayList<PartitionData> partitionList, int elementIndex) {
765
766 int index = -Integer.MAX_VALUE;
767
768 switch (elementIndex) {
769
770 case DEMOGRAPHIC_MODEL_ELEMENT:
771
772 for (PartitionData data2 : partitionList) {
773 if (demographicModelToString(data).equalsIgnoreCase(
774 demographicModelToString(data2))) {
775 index = partitionList.indexOf(data2);
776 break;
777 }
778 }
779
780 break;
781
782 case BRANCH_RATE_MODEL_ELEMENT:
783
784 for (PartitionData data2 : partitionList) {
785 if (clockRateModelToString(data).equalsIgnoreCase(
786 clockRateModelToString(data2))) {
787 index = partitionList.indexOf(data2);
788 break;
789 }
790 }
791
792 break;
793
794 case FREQUENCY_MODEL_ELEMENT:
795
796 for (PartitionData data2 : partitionList) {
797 if (frequencyModelToString(data).equalsIgnoreCase(
798 frequencyModelToString(data2))) {
799 index = partitionList.indexOf(data2);
800 break;
801 }
802 }
803
804 break;
805
806 case BRANCH_MODEL_ELEMENT:
807
808 for (PartitionData data2 : partitionList) {
809 if (branchSubstitutionModelToString(data).equalsIgnoreCase(
810 branchSubstitutionModelToString(data2))) {
811 index = partitionList.indexOf(data2);
812 break;
813 }
814 }
815
816 break;
817
818 case SITE_RATE_MODEL_ELEMENT:
819
820 for (PartitionData data2 : partitionList) {
821 if (siteRateModelToString(data).equalsIgnoreCase(
822 siteRateModelToString(data2))) {
823 index = partitionList.indexOf(data2);
824 break;
825 }
826 }
827
828 break;
829
830 default:
831
832 throw new RuntimeException("Unknown element");
833
834 }// END: switch
835
836 return index;
837 }// END: isIdenticalWith
838
839 // /////////////////
840 // ---GUI UTILS---//
841 // /////////////////
842
843 public static ImageIcon createImageIcon(String path) {
844
845 ImageIcon icon = null;
846
847 URL imgURL = BeagleSequenceSimulatorApp.class.getResource(path);
848
849 if (imgURL != null) {
850 icon = new ImageIcon(imgURL);
851 } else {
852 System.err.println("Couldn't find file: " + path + "\n");
853 }
854
855 return icon;
856 }// END: CreateImageIcon
857
858 public static boolean isBrowsingSupported() {
859 if (!Desktop.isDesktopSupported()) {
860 return false;
861 }
862 boolean result = false;
863 Desktop desktop = java.awt.Desktop.getDesktop();
864 if (desktop.isSupported(Desktop.Action.BROWSE)) {
865 result = true;
866 }
867 return result;
868
869 }// END: isBrowsingSupported
870
871 public static int getTabbedPaneComponentIndex(JTabbedPane tabbedPane,
872 String title) {
873
874 int index = -Integer.MAX_VALUE;
875
876 int count = tabbedPane.getTabCount();
877 for (int i = 0; i < count; i++) {
878 if (tabbedPane.getTitleAt(i).toString().equalsIgnoreCase(title)) {
879 index = i;
880 break;
881 }// END: title check
882
883 }// END: i loop
884
885 return index;
886 }// END: getComponentIndex
887
888 public static Frame getActiveFrame() {
889 Frame result = null;
890 Frame[] frames = Frame.getFrames();
891 for (int i = 0; i < frames.length; i++) {
892 Frame frame = frames[i];
893 if (frame.isVisible()) {
894 result = frame;
895 break;
896 }
897 }
898 return result;
899 }
900
901 public static String getMultipleWritePath(File outFile,
902 String defaultExtension, int i) {
903
904 String path = outFile.getParent();
905 String[] nameArray = outFile.getName().split("\\.", 2);
906 String name = ((i == 0) ? nameArray[0] : nameArray[0] + i);
907
908 String extension = (nameArray.length == 1) ? (defaultExtension)
909 : (nameArray[1]);
910 String fullPath = path + System.getProperty("file.separator") + name
911 + "." + extension;
912
913 return fullPath;
914 }// END: getMultipleWritePath
915
916 public static String getWritePath(File outFile, String defaultExtension) {
917
918 String path = outFile.getParent();
919 String[] nameArray = outFile.getName().split("\\.", 2);
920 String name = nameArray[0];
921
922 String extension = (nameArray.length == 1) ? (defaultExtension)
923 : (nameArray[1]);
924 String fullPath = path + System.getProperty("file.separator") + name
925 + "." + extension;
926
927 return fullPath;
928 }// END: getWritePath
929
930 public static void showDialog(final String message) {
931
932 if (SwingUtilities.isEventDispatchThread()) {
933
934 JOptionPane.showMessageDialog(getActiveFrame(), message, "Message",
935 JOptionPane.ERROR_MESSAGE,
936 Utils.createImageIcon(Utils.BUBBLE_BLUE_ICON));
937
938 } else {
939 SwingUtilities.invokeLater(new Runnable() {
940 public void run() {
941
942 JOptionPane.showMessageDialog(getActiveFrame(), message,
943 "Message", JOptionPane.ERROR_MESSAGE,
944 Utils.createImageIcon(Utils.BUBBLE_BLUE_ICON));
945
946 }
947 });
948 }// END: edt check
949 }// END: showDialog
950
951 // ////////////////////////////////
952 // ---EXCEPTION HANDLING UTILS---//
953 // ////////////////////////////////
954
955 public static void handleException(final Throwable e, final String message) {
956
957 final Thread t = Thread.currentThread();
958
959 if (SwingUtilities.isEventDispatchThread()) {
960 showExceptionDialog(t, e, message);
961 } else {
962 SwingUtilities.invokeLater(new Runnable() {
963 public void run() {
964 showExceptionDialog(t, e, message);
965 }
966 });
967 }// END: edt check
968 }// END: uncaughtException
969
970 public static void handleException(final Throwable e) {
971
972 final Thread t = Thread.currentThread();
973
974 if (SwingUtilities.isEventDispatchThread()) {
975 showExceptionDialog(t, e);
976 } else {
977 SwingUtilities.invokeLater(new Runnable() {
978 public void run() {
979 showExceptionDialog(t, e);
980 }
981 });
982 }// END: edt check
983 }// END: handleException
984
985 private static void showExceptionDialog(Thread t, Throwable e) {
986
987 String msg = String.format("Unexpected problem on thread %s: %s",
988 t.getName(), e.getMessage());
989
990 logException(t, e);
991
992 JOptionPane.showMessageDialog(Utils.getActiveFrame(), //
993 msg, //
994 "Error", //
995 JOptionPane.ERROR_MESSAGE, //
996 Utils.createImageIcon(Utils.ERROR_ICON));
997 }// END: showExceptionDialog
998
999 private static void showExceptionDialog(Thread t, Throwable e,
1000 String message) {
1001
1002 String msg = String.format("Unexpected problem on thread %s: %s" + "\n"
1003 + message, t.getName(), e.getMessage());
1004
1005 logException(t, e);
1006
1007 JOptionPane.showMessageDialog(Utils.getActiveFrame(), //
1008 msg, //
1009 "Error", //
1010 JOptionPane.ERROR_MESSAGE, //
1011 Utils.createImageIcon(Utils.ERROR_ICON));
1012 }// END: showExceptionDialog
1013
1014 private static void logException(Thread t, Throwable e) {
1015 e.printStackTrace();
1016 }// END: logException
1017
1018 // ///////////////////
1019 // ---PRINT UTILS---//
1020 // ///////////////////
1021
1022 public static void printMap(Map<?, ?> mp) {
1023
1024 Iterator<?> it = mp.entrySet().iterator();
1025 while (it.hasNext()) {
1026
1027 Entry<?, ?> pairs = (Entry<?, ?>) it.next();
1028 Object obj = pairs.getValue();
1029
1030 if (obj instanceof int[]) {
1031
1032 int[] seq = (int[]) obj;
1033 System.out.print(pairs.getKey() + " =");
1034
1035 for (int i = 0; i < seq.length; ++i) {
1036 System.out.print(" " + seq[i]);
1037 }
1038 System.out.println();
1039
1040 } else if (obj instanceof double[]) {
1041
1042 double[] seq = (double[]) obj;
1043 System.out.print(pairs.getKey() + " =");
1044
1045 for (int i = 0; i < seq.length; ++i) {
1046 System.out.print(" " + seq[i]);
1047 }
1048 System.out.println();
1049
1050 } else {
1051 System.out.println(pairs.getKey() + " = " + pairs.getValue());
1052 }// END: obj class check
1053
1054 }
1055 }// END: printMap
1056
1057 public static void printHashMap(ConcurrentHashMap<?, ?> hashMap) {
1058
1059 Iterator<?> iterator = hashMap.entrySet().iterator();
1060 while (iterator.hasNext()) {
1061
1062 Entry<?, ?> pairs = (Entry<?, ?>) iterator.next();
1063
1064 Taxon taxon = (Taxon) pairs.getKey();
1065 int[] sequence = (int[]) pairs.getValue();
1066
1067 System.out.println(taxon.toString());
1068 Utils.printArray(sequence);
1069
1070 }// END: while has next
1071
1072 }// END: printHashMap
1073
1074 public static void printArray(Object[] x) {
1075 for (int i = 0; i < x.length; i++) {
1076 System.out.print(x[i] + " ");
1077 }
1078 System.out.println();
1079 }// END: printArray
1080
1081 public static void printArray(int[] x) {
1082 for (int i = 0; i < x.length; i++) {
1083 System.out.print(x[i] + " ");
1084 }
1085 System.out.println();
1086 }// END: printArray
1087
1088 public static void printArray(double[] x) {
1089 for (int i = 0; i < x.length; i++) {
1090 System.out.print(x[i] + " ");
1091 }
1092 System.out.println();
1093 }// END: printArray
1094
1095 public static void printArray(boolean[] x) {
1096 for (int i = 0; i < x.length; i++) {
1097 System.out.print(x[i] + " ");
1098 }
1099 System.out.println();
1100
1101 }
1102
1103 public static void printArray(String[] x) {
1104 for (int i = 0; i < x.length; i++) {
1105 System.out.println(x[i]);
1106 }
1107 }// END: printArray
1108
1109 public static void print2DArray(double[][] array) {
1110 for (int row = 0; row < array.length; row++) {
1111 for (int col = 0; col < array[row].length; col++) {
1112 System.out.print(array[row][col] + " ");
1113 }
1114 System.out.print("\n");
1115 }
1116 }// END: print2DArray
1117
1118 public static void print2DArray(int[][] array) {
1119 for (int row = 0; row < array.length; row++) {
1120 for (int col = 0; col < array[row].length; col++) {
1121 System.out.print(array[row][col] + " ");
1122 }
1123 System.out.print("\n");
1124 }
1125 }// END: print2DArray
1126
1127 public static void print2Arrays(int[] array1, double[] array2, int nrow) {
1128 for (int row = 0; row < nrow; row++) {
1129 System.out.print(array1[row] + " " + array2[row] + " ");
1130 System.out.print("\n");
1131 }
1132 }// END: print2DArray
1133
1134 public static void print2DArray(double[][] array, int formatEvery) {
1135
1136 int i = 0;
1137 for (int row = 0; row < array.length; row++) {
1138 for (int col = 0; col < array[row].length; col++) {
1139
1140 if (i == formatEvery) {
1141 System.out.print("\n");
1142 i = 0;
1143 }
1144
1145 System.out.print(array[row][col] + " ");
1146 i++;
1147 }
1148 System.out.print("\n");
1149 }
1150 }// END: print2DArray
1151
1152 public static void printBranchSubstitutionModel(PartitionData data) {
1153 System.out.print("\tBranch Substitution model: ");
1154 System.out.print(branchSubstitutionModelToString(data));
1155 System.out.print("\n");
1156 }// END: printBranchSubstitutionModel
1157
1158 public static void printClockRateModel(PartitionData data) {
1159 System.out.print("\tClock rate model: ");
1160 System.out.print(clockRateModelToString(data));
1161 System.out.print("\n");
1162 }// END: printClockRateModel
1163
1164 public static void printFrequencyModel(PartitionData data) {
1165 System.out.print("\tFrequency model: ");
1166 System.out.print(frequencyModelToString(data));
1167 System.out.print("\n");
1168 }// END: printFrequencyModel
1169
1170 public static void printSiteRateModel(PartitionData data) {
1171 System.out.print("\tSite rate model: ");
1172 System.out.print(siteRateModelToString(data));
1173 System.out.print("\n");
1174 }// END: printFrequencyModel
1175
1176 public static void printDemographicModel(PartitionData data) {
1177 System.out.print("\tDemographic model: ");
1178 System.out.print(demographicModelToString(data));
1179 System.out.print("\n");
1180 }// END: printFrequencyModel
1181
1182 private static void printDataType(PartitionData data) {
1183 System.out.print("\tData type: ");
1184 System.out.print(dataTypeToString(data));
1185 System.out.print("\n");
1186 }// END: printDataType
1187
1188 public static void printTaxaSet(Taxa taxa) {
1189 for (int i = 0; i < taxa.getTaxonCount(); i++) {
1190 Taxon taxon = taxa.getTaxon(i);
1191 System.out.print("\t\t " + taxonToString(taxon, false) + ("\n"));
1192 }
1193 }// END: printTaxaSet
1194
1195 public static void printTree(TreesTableRecord record) {
1196 System.out.print(record.getTree().toString());
1197 System.out.print("\n");
1198 }// END: printTree
1199
1200 public static void printRecord(TreesTableRecord record) {
1201
1202 if (record == null) {
1203
1204 System.out.println("\tRecord: NOT SET");
1205
1206 } else if (record.isTreeSet()) {
1207
1208 System.out.print("\t" + record.getName() + ": ");
1209 printTree(record);
1210
1211 } else if (record.isTaxaSet()) {
1212
1213 System.out.println("\t" + record.getName() + ":");
1214 printTaxaSet(record.getTaxa());
1215
1216 } else {
1217 //
1218 }
1219 }// END: printRecord
1220
1221 public static void printRecords(PartitionDataList dataList) {
1222 for (TreesTableRecord record : dataList.recordsList) {
1223 printRecord(record);
1224 }// END: record loop
1225 }// END: printRecords
1226
1227 public static void printPartitionData(PartitionData data) {
1228 printRecord(data.record);
1229 printDataType(data);
1230 printDemographicModel(data);
1231 System.out.println("\tFrom: " + data.from);
1232 System.out.println("\tTo: " + data.to);
1233 System.out.println("\tEvery: " + data.every);
1234 printBranchSubstitutionModel(data);
1235 printSiteRateModel(data);
1236 printClockRateModel(data);
1237 printFrequencyModel(data);
1238 }// END: printPartitionData
1239
1240 public static void printPartitionDataList(PartitionDataList dataList) {
1241
1242 // System.out.println(dataList.get(0).from + " " +
1243 // dataList.get(1).from);
1244
1245 if (BeagleSequenceSimulatorApp.DEBUG) {
1246 System.out.println("Possible records: ");
1247 printRecords(dataList);
1248 }
1249
1250 System.out.println("\tSite count: " + getSiteCount(dataList));
1251 System.out.println("\tOutput type: " + dataList.outputFormat);
1252
1253 if (dataList.setSeed) {
1254 System.out.println("\tStarting seed: " + dataList.startingSeed);
1255 }
1256
1257 int row = 1;
1258 for (PartitionData data : dataList) {
1259
1260 System.out.println("Partition: " + row);
1261 printPartitionData(data);
1262 row++;
1263
1264 }// END: data list loop
1265
1266 }// END: printDataList
1267
1268 public static void printTaxonList(PartitionDataList dataList) {
1269 System.out.println(taxaToString(dataList.allTaxa, true));
1270 }// END: printTaxonList
1271
1272 public static Sequence intArray2Sequence(Taxon taxon, int[] seq,
1273 int gapFlag, DataType dataType) {
1274
1275 StringBuilder sSeq = new StringBuilder();
1276 int partitionSiteCount = seq.length;
1277
1278 if (dataType instanceof Codons) {
1279
1280 for (int i = 0; i < partitionSiteCount; i++) {
1281
1282 int state = seq[i];
1283
1284 if (state == gapFlag) {
1285 sSeq.append(dataType.getTriplet(dataType.getGapState()));
1286 } else {
1287 sSeq.append(dataType.getTriplet(seq[i]));
1288 }// END: gap check
1289
1290 }// END: replications loop
1291
1292 } else {
1293
1294 for (int i = 0; i < partitionSiteCount; i++) {
1295
1296 int state = seq[i];
1297
1298 if (state == gapFlag) {
1299 sSeq.append(dataType.getCode(dataType.getGapState()));
1300 } else {
1301 if(dataType instanceof HiddenDataType){
1302 sSeq.append(dataType.getCode(seq[i] %
1303 (dataType.getStateCount()/((HiddenDataType) dataType).getHiddenClassCount())));
1304 }else{
1305 sSeq.append(dataType.getCode(seq[i]));
1306 }
1307 }// END: gap check
1308
1309 }// END: replications loop
1310
1311 }// END: dataType check
1312
1313 return new Sequence(taxon, sSeq.toString());
1314 }// END: intArray2Sequence
1315
1316 // //////////////////////
1317 // ---TOSTRING UTILS---//
1318 // //////////////////////
1319
1320 public static String taxonToString(Taxon taxon, boolean printNames) {
1321
1322 String string = null;
1323
1324 if (printNames) {
1325 string = taxon.getId() + " ("
1326 + taxon.getAttribute(Utils.ABSOLUTE_HEIGHT) + ","
1327 + taxon.getAttribute(Utils.TREE_FILENAME) + ")";
1328
1329 } else {
1330 string = taxon.getId() + " ("
1331 + taxon.getAttribute(Utils.ABSOLUTE_HEIGHT) + ")";
1332 }
1333
1334 return string;
1335 }// END: taxonToString
1336
1337 public static String taxaToString(Taxa taxa, boolean printNames) {
1338
1339 String string = "";
1340
1341 for (int i = 0; i < taxa.getTaxonCount(); i++) {
1342
1343 Taxon taxon = taxa.getTaxon(i);
1344 string += taxonToString(taxon, printNames) + ("\n");
1345
1346 }
1347
1348 return string;
1349 }// END: taxaToString
1350
1351 public static String partitionDataToString(PartitionData data,
1352 TreeModel simulatedTreeModel
1353 // , LinkedHashMap<NodeRef, int[]> sequencesMap
1354 ) {
1355
1356 String string = "";
1357
1358 // if (data.record.isTreeSet()) {
1359 //
1360 // string += ("Tree: " + data.record.getTree().toString())+ ("\n");
1361 //
1362 // } else if (data.record.isTaxaSet()) {
1363 //
1364 // string += ("Taxa Set: \n" + taxaToString(data.record.getTaxa(),
1365 // false));//+ ("\n");
1366 //
1367 // } else {
1368 // //
1369 // }
1370
1371 string += ("Tree model: " + simulatedTreeModel.toString()) + ("\n");
1372 // string += ("Tree model: "
1373 // +annotatedTreeModelToString(simulatedTreeModel, sequencesMap,
1374 // data.createDataType()) ) + ("\n");
1375 string += ("From: " + data.from) + ("\n");
1376 string += ("To: " + data.to) + ("\n");
1377 string += ("Every: " + data.every) + ("\n");
1378 string += ("Data type: ") + dataTypeToString(data) + ("\n");
1379 string += ("Demographic model: ") + demographicModelToString(data)
1380 + ("\n");
1381 string += ("Branch Substitution model: ")
1382 + branchSubstitutionModelToString(data) + ("\n");
1383 string += ("Frequency model: ") + frequencyModelToString(data) + ("\n");
1384 string += ("Site Rate model: ") + siteRateModelToString(data) + ("\n");
1385 string += ("Clock Rate model: ") + clockRateModelToString(data)
1386 + ("\n");
1387
1388 return string;
1389 }// END: partitionDataToString
1390
1391 public static String partitionDataListToString(PartitionDataList dataList, //
1392 ArrayList<TreeModel> simulatedTreeModelList
1393 // ,LinkedHashMap<Integer,LinkedHashMap<NodeRef, int[]>>
1394 // partitionSequencesMap
1395 ) {
1396
1397 String string = "";
1398 TreeModel simulatedTreeModel;
1399 // LinkedHashMap<NodeRef, int[]> sequencesMap;
1400
1401 string += ("Site count: " + getSiteCount(dataList)) + ("\n");
1402 if (dataList.setSeed) {
1403 string += ("Starting seed: " + dataList.startingSeed) + ("\n");
1404 }
1405
1406 int row = 0;
1407 for (PartitionData data : dataList) {
1408
1409 simulatedTreeModel = simulatedTreeModelList.get(row);
1410 // sequencesMap = partitionSequencesMap.get(row);
1411
1412 string += ("Partition: " + (row + 1)) + ("\n");
1413 string += partitionDataToString(data, simulatedTreeModel
1414 // , sequencesMap
1415 );
1416 string += ("\n");
1417 row++;
1418
1419 }// END: data list loop
1420
1421 return string;
1422 }// END: partitionDataListToString
1423
1424 // TODO: doesn't work
1425 public static String annotatedTreeModelToString(TreeModel treeModel,
1426 LinkedHashMap<NodeRef, int[]> sequencesMap, DataType dataType) {
1427
1428 StringBuffer buffer = new StringBuffer();
1429 NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
1430 boolean useTipLabels = true;
1431
1432 AncestralSequenceTrait ancestralSequence = new AncestralSequenceTrait(
1433 sequencesMap, dataType);
1434 TreeTraitProvider[] treeTraitProviders = new TreeTraitProvider[] { ancestralSequence };
1435
1436 TreeUtils.newick(treeModel, //
1437 treeModel.getRoot(), //
1438 useTipLabels, //
1439 TreeUtils.BranchLengthType.LENGTHS_AS_TIME, //
1440 format, //
1441 null, //
1442 treeTraitProviders, //
1443 null, buffer);
1444
1445 return buffer.toString();
1446 }
1447
1448 private static String dataTypeToString(PartitionData data) {
1449 String string = PartitionData.dataTypes[data.dataTypeIndex];
1450 return string;
1451 }
1452
1453 public static String demographicModelToString(PartitionData data) {
1454
1455 String string = PartitionData.demographicModels[data.demographicModelIndex];
1456
1457 string += (" ( ");
1458 for (int i = 0; i < PartitionData.demographicParameterIndices[data.demographicModelIndex].length; i++) {
1459 string += data.demographicParameterValues[PartitionData.demographicParameterIndices[data.demographicModelIndex][i]];
1460 string += " ";
1461 }// END: indices loop
1462 string += ")";
1463
1464 return string;
1465 }
1466
1467 public static String clockRateModelToString(PartitionData data) {
1468
1469 String string = PartitionData.clockModels[data.clockModelIndex];
1470
1471 string += (" ( ");
1472 for (int i = 0; i < PartitionData.clockParameterIndices[data.clockModelIndex].length; i++) {
1473 string += data.clockParameterValues[PartitionData.clockParameterIndices[data.clockModelIndex][i]];
1474 string += " ";
1475 }// END: indices loop
1476 string += ")";
1477
1478 if(data.clockModelIndex == data.LRC_INDEX) {
1479
1480 String space = (data.lrcParametersInRealSpace == true ? "real" : "log");
1481 string += " ( " + "Parameters in " + space + " space )";
1482
1483 }
1484
1485 return string;
1486 }
1487
1488 public static String frequencyModelToString(PartitionData data) {
1489
1490 String string = PartitionData.frequencyModels[data.frequencyModelIndex];
1491
1492 string += (" ( ");
1493 for (int i = 0; i < data.frequencyParameterIndices[data.frequencyModelIndex].length; i++) {
1494 string += data.frequencyParameterValues[data.frequencyParameterIndices[data.frequencyModelIndex][i]];
1495 string += " ";
1496 }// END: indices loop
1497 string += ")";
1498
1499 return string;
1500 }
1501
1502 public static String branchSubstitutionModelToString(PartitionData data) {
1503
1504 String string = PartitionData.substitutionModels[data.substitutionModelIndex];
1505
1506 string += (" ( ");
1507 for (int i = 0; i < PartitionData.substitutionParameterIndices[data.substitutionModelIndex].length; i++) {
1508 string += data.substitutionParameterValues[PartitionData.substitutionParameterIndices[data.substitutionModelIndex][i]];
1509 string += " ";
1510 }// END: indices loop
1511 string += ")";
1512
1513 return string;
1514 }
1515
1516 public static String siteRateModelToString(PartitionData data) {
1517
1518 String string = PartitionData.siteRateModels[data.siteRateModelIndex];
1519
1520 string += (" ( ");
1521 for (int i = 0; i < PartitionData.siteRateModelParameterIndices[data.siteRateModelIndex].length; i++) {
1522 string += data.siteRateModelParameterValues[PartitionData.siteRateModelParameterIndices[data.siteRateModelIndex][i]];
1523 string += " ";
1524 }// END: indices loop
1525 string += ")";
1526
1527 return string;
1528 }
1529
1530 public static String demographyModelToString(PartitionData data) {
1531
1532 String string = PartitionData.demographicModels[data.demographicModelIndex];
1533
1534 string += (" ( ");
1535 for (int i = 0; i < PartitionData.demographicParameterIndices[data.demographicModelIndex].length; i++) {
1536 string += data.demographicParameterValues[PartitionData.demographicParameterIndices[data.demographicModelIndex][i]];
1537 string += " ";
1538 }// END: indices loop
1539 string += ")";
1540
1541 return string;
1542 }
1543
1544
1545 }// END: class