| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.evoxml; |
| 27 |
|
| 28 |
import dr.evolution.util.Taxa; |
| 29 |
import dr.evolution.util.Taxon; |
| 30 |
import dr.evolution.util.TaxonList; |
| 31 |
import dr.math.MathUtils; |
| 32 |
import dr.xml.*; |
| 33 |
|
| 34 |
import java.util.List; |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
public class RandomSubsetTaxaParser extends AbstractXMLObjectParser { |
| 41 |
|
| 42 |
public static final String RANDOM_SUBSET_TAXA = "randomSubsetTaxa"; |
| 43 |
public static final String COUNT = "total"; |
| 44 |
public static final String WITH_REPLACEMENT = "withReplacement"; |
| 45 |
|
| 46 |
public String getParserName() { return RANDOM_SUBSET_TAXA; } |
| 47 |
|
| 48 |
|
| 49 |
public Object parseXMLObject(XMLObject xo) throws XMLParseException { |
| 50 |
|
| 51 |
Taxa originalTaxa = new Taxa(); |
| 52 |
|
| 53 |
for (int i = 0; i < xo.getChildCount(); i++) { |
| 54 |
Object child = xo.getChild(i); |
| 55 |
if (child instanceof Taxon) { |
| 56 |
Taxon taxon = (Taxon)child; |
| 57 |
originalTaxa.addTaxon(taxon); |
| 58 |
} else if (child instanceof TaxonList) { |
| 59 |
TaxonList taxonList1 = (TaxonList)child; |
| 60 |
for (int j = 0; j < taxonList1.getTaxonCount(); j++) { |
| 61 |
originalTaxa.addTaxon(taxonList1.getTaxon(j)); |
| 62 |
} |
| 63 |
} else { |
| 64 |
throwUnrecognizedElement(xo); |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
List<Taxon> originalTaxonList = originalTaxa.asList(); |
| 69 |
|
| 70 |
int sampleTotal = xo.getAttribute(COUNT, originalTaxonList.size()); |
| 71 |
if (sampleTotal < 2) { |
| 72 |
throw new XMLParseException("Must sample atleast two taxa"); |
| 73 |
} |
| 74 |
|
| 75 |
boolean withReplacement = xo.getAttribute(WITH_REPLACEMENT, false); |
| 76 |
|
| 77 |
Taxa sampledTaxa = new Taxa(); |
| 78 |
for (int i = 0; i < sampleTotal; i++) { |
| 79 |
int choice = MathUtils.nextInt(originalTaxonList.size()); |
| 80 |
Taxon taxonToAdd = originalTaxonList.get(choice); |
| 81 |
sampledTaxa.addTaxon(taxonToAdd); |
| 82 |
|
| 83 |
if (!withReplacement) { |
| 84 |
originalTaxonList.remove(choice); |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
return sampledTaxa; |
| 89 |
} |
| 90 |
|
| 91 |
public XMLSyntaxRule[] getSyntaxRules() { return rules; } |
| 92 |
|
| 93 |
private final XMLSyntaxRule[] rules = { |
| 94 |
new OrRule( |
| 95 |
new ElementRule(Taxa.class, 1, Integer.MAX_VALUE), |
| 96 |
new ElementRule(Taxon.class, 1, Integer.MAX_VALUE) |
| 97 |
), |
| 98 |
AttributeRule.newIntegerRule(COUNT), |
| 99 |
AttributeRule.newBooleanRule(WITH_REPLACEMENT), |
| 100 |
}; |
| 101 |
|
| 102 |
public String getParserDescription() { |
| 103 |
return "Defines a set of taxon objects."; |
| 104 |
} |
| 105 |
|
| 106 |
public Class getReturnType() { return Taxa.class; } |
| 107 |
} |