use of dr.evolution.alignment.Alignment in project beast-mcmc by beast-dev.
the class AscertainedSitePatternsParser method parseXMLObject.
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Alignment alignment = (Alignment) xo.getChild(Alignment.class);
XMLObject xoc;
TaxonList taxa = null;
int from = -1;
int to = -1;
int every = xo.getAttribute(EVERY, 1);
if (every <= 0)
throw new XMLParseException("illegal 'every' attribute in patterns element");
int startInclude = -1;
int stopInclude = -1;
int startExclude = -1;
int stopExclude = -1;
if (xo.hasAttribute(FROM)) {
from = xo.getIntegerAttribute(FROM) - 1;
if (from < 0)
throw new XMLParseException("illegal 'from' attribute in patterns element");
}
if (xo.hasAttribute(TO)) {
to = xo.getIntegerAttribute(TO) - 1;
if (to < 0 || to < from)
throw new XMLParseException("illegal 'to' attribute in patterns element");
}
if (xo.hasChildNamed(TAXON_LIST)) {
taxa = (TaxonList) xo.getElementFirstChild(TAXON_LIST);
}
if (from > alignment.getSiteCount())
throw new XMLParseException("illegal 'from' attribute in patterns element");
if (to > alignment.getSiteCount())
throw new XMLParseException("illegal 'to' attribute in patterns element");
if (from < 0)
from = 0;
if (to < 0)
to = alignment.getSiteCount() - 1;
// if (xo.hasAttribute(XMLParser.ID)) {
Logger.getLogger("dr.evoxml").info("Creating ascertained site patterns '" + xo.getId() + "' from positions " + Integer.toString(from + 1) + "-" + Integer.toString(to + 1) + " of alignment '" + alignment.getId() + "'");
if (every > 1) {
Logger.getLogger("dr.evoxml").info(" only using every " + every + " site");
}
if (xo.hasChildNamed(INCLUDE)) {
xoc = xo.getChild(INCLUDE);
if (xoc.hasAttribute(FROM) && xoc.hasAttribute(TO)) {
startInclude = xoc.getIntegerAttribute(FROM) - 1;
stopInclude = xoc.getIntegerAttribute(TO);
} else {
throw new XMLParseException("both from and to attributes are required for includePatterns");
}
if (startInclude < 0 || stopInclude < startInclude) {
throw new XMLParseException("invalid 'from' and 'to' attributes in includePatterns");
}
Logger.getLogger("dr.evoxml").info("\tAscertainment: Patterns in columns " + (startInclude + 1) + " to " + (stopInclude) + " are only possible. ");
}
if (xo.hasChildNamed(EXCLUDE)) {
xoc = xo.getChild(EXCLUDE);
if (xoc.hasAttribute(FROM) && xoc.hasAttribute(TO)) {
startExclude = xoc.getIntegerAttribute(FROM) - 1;
stopExclude = xoc.getIntegerAttribute(TO);
} else {
throw new XMLParseException("both from and to attributes are required for excludePatterns");
}
if (startExclude < 0 || stopExclude < startExclude) {
throw new XMLParseException("invalid 'from' and 'to' attributes in includePatterns");
}
Logger.getLogger("dr.evoxml").info("\tAscertainment: Patterns in columns " + (startExclude + 1) + " to " + (stopExclude) + " are not possible. ");
}
AscertainedSitePatterns patterns = new AscertainedSitePatterns(alignment, taxa, from, to, every, startInclude, stopInclude, startExclude, stopExclude);
Logger.getLogger("dr.evoxml").info("\tThere are " + patterns.getPatternCount() + " patterns in total.");
Logger.getLogger("dr.evoxml").info("\tPlease cite:\n" + Citable.Utils.getCitationString(patterns));
return patterns;
}
use of dr.evolution.alignment.Alignment in project beast-mcmc by beast-dev.
the class BeagleTreeLikelihood method main.
public static void main(String[] args) {
try {
MathUtils.setSeed(666);
System.out.println("Test case 1: simulateOnePartition");
int sequenceLength = 1000;
ArrayList<Partition> partitionsList = new ArrayList<Partition>();
// create tree
NewickImporter importer = new NewickImporter("(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
Tree tree = importer.importTree(null);
TreeModel treeModel = new TreeModel(tree);
// create Frequency Model
Parameter freqs = new Parameter.Default(new double[] { 0.25, 0.25, 0.25, 0.25 });
FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
// create branch model
Parameter kappa1 = new Parameter.Default(1, 1);
Parameter kappa2 = new Parameter.Default(1, 1);
HKY hky1 = new HKY(kappa1, freqModel);
HKY hky2 = new HKY(kappa2, freqModel);
HomogeneousBranchModel homogenousBranchSubstitutionModel = new HomogeneousBranchModel(hky1);
List<SubstitutionModel> substitutionModels = new ArrayList<SubstitutionModel>();
substitutionModels.add(hky1);
substitutionModels.add(hky2);
List<FrequencyModel> freqModels = new ArrayList<FrequencyModel>();
freqModels.add(freqModel);
Parameter epochTimes = new Parameter.Default(1, 20);
// create branch rate model
Parameter rate = new Parameter.Default(1, 0.001);
BranchRateModel branchRateModel = new StrictClockBranchRates(rate);
// create site model
GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
BranchModel homogeneousBranchModel = new HomogeneousBranchModel(hky1);
BranchModel epochBranchModel = new EpochBranchModel(treeModel, substitutionModels, epochTimes);
// create partition
Partition partition1 = new //
Partition(//
treeModel, //
homogenousBranchSubstitutionModel, //
siteRateModel, //
branchRateModel, //
freqModel, // from
0, // to
sequenceLength - 1, // every
1);
partitionsList.add(partition1);
// feed to sequence simulator and generate data
BeagleSequenceSimulator simulator = new BeagleSequenceSimulator(partitionsList);
Alignment alignment = simulator.simulate(false, false);
BeagleTreeLikelihood nbtl = new BeagleTreeLikelihood(alignment, treeModel, homogeneousBranchModel, siteRateModel, branchRateModel, null, false, PartialsRescalingScheme.DEFAULT, false);
System.out.println("nBTL(homogeneous) = " + nbtl.getLogLikelihood());
nbtl = new BeagleTreeLikelihood(alignment, treeModel, epochBranchModel, siteRateModel, branchRateModel, null, false, PartialsRescalingScheme.DEFAULT, false);
System.out.println("nBTL(epoch) = " + nbtl.getLogLikelihood());
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
// END: try-catch block
}
use of dr.evolution.alignment.Alignment in project beast-mcmc by beast-dev.
the class AlignmentGenerator method writeAlignments.
/**
* Write all Alignments
* @param writer XMLWriter
*/
public void writeAlignments(List<Alignment> alignments, XMLWriter writer) {
int index = 1;
for (Alignment alignment : alignments) {
if (alignments.size() > 1) {
//if (!options.allowDifferentTaxa) {
alignment.setId(AlignmentParser.ALIGNMENT + index);
//} else { // e.g. alignment_gene1
// alignment.setId("alignment_" + mulitTaxaTagName + index);
//}
} else {
alignment.setId(AlignmentParser.ALIGNMENT);
}
writeAlignment(alignment, writer);
index += 1;
writer.writeText("");
}
}
use of dr.evolution.alignment.Alignment in project beast-mcmc by beast-dev.
the class BeastGenerator method generateXML.
/**
* Generate a beast xml file from these beast options
*
* @param file File
* @throws java.io.IOException IOException
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
public void generateXML(File file) throws GeneratorException, IOException, Arguments.ArgumentException {
XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(file)));
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString(), " by Alexei J. Drummond, Andrew Rambaut and Marc A. Suchard", " Department of Computer Science, University of Auckland and", " Institute of Evolutionary Biology, University of Edinburgh", " David Geffen School of Medicine, University of California, Los Angeles", " http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
if (options.originDate != null) {
// Create a dummy taxon whose job is to specify the origin date
Taxon originTaxon = new Taxon("originTaxon");
options.originDate.setUnits(options.units);
originTaxon.setDate(options.originDate);
writeTaxon(originTaxon, true, false, writer);
}
//++++++++++++++++ Taxon List ++++++++++++++++++
try {
// write complete taxon list
writeTaxa(options.taxonList, writer);
writer.writeText("");
if (!options.hasIdenticalTaxa()) {
// write all taxa in each gene tree regarding each data partition,
for (AbstractPartitionData partition : options.dataPartitions) {
if (partition.getTaxonList() != null) {
writeDifferentTaxa(partition, writer);
}
}
} else {
// microsat
for (PartitionPattern partitionPattern : options.getPartitionPattern()) {
if (partitionPattern.getTaxonList() != null && partitionPattern.getPatterns().hasMask()) {
writeDifferentTaxa(partitionPattern, writer);
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
throw new GeneratorException("Taxon list generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
List<Taxa> taxonSets = options.taxonSets;
try {
if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) {
tmrcaStatisticsGenerator.writeTaxonSets(writer, taxonSets);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Taxon sets generation has failed:\n" + e.getMessage());
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
//++++++++++++++++ Alignments ++++++++++++++++++
List<Alignment> alignments = new ArrayList<Alignment>();
try {
for (AbstractPartitionData partition : options.dataPartitions) {
Alignment alignment = null;
if (partition instanceof PartitionData) {
// microsat has no alignment
alignment = ((PartitionData) partition).getAlignment();
}
if (alignment != null && !alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (alignments.size() > 0) {
alignmentGenerator.writeAlignments(alignments, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Alignments generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Pattern Lists ++++++++++++++++++
try {
if (!options.samplePriorOnly) {
List<Microsatellite> microsatList = new ArrayList<Microsatellite>();
for (AbstractPartitionData partition : options.dataPartitions) {
// Each PD has one TreeLikelihood
if (partition.getTaxonList() != null) {
switch(partition.getDataType().getType()) {
case DataType.NUCLEOTIDES:
case DataType.AMINO_ACIDS:
case DataType.CODONS:
case DataType.COVARION:
case DataType.TWO_STATES:
patternListGenerator.writePatternList((PartitionData) partition, writer);
break;
case DataType.GENERAL:
case DataType.CONTINUOUS:
// attribute patterns which is generated next bit of this method.
break;
case DataType.MICRO_SAT:
// microsat does not have alignment
patternListGenerator.writePatternList((PartitionPattern) partition, microsatList, writer);
break;
default:
throw new IllegalArgumentException("Unsupported data type");
}
writer.writeText("");
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Pattern lists generation has failed:\n" + e.getMessage());
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
try {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree prior model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Starting Tree ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Starting tree generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Tree Model +++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Statistics ++++++++++++++++++
try {
if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) {
tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("TMRCA statistics generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
treePriorGenerator.writePriorLikelihood(model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeMultiLociTreePriors(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree prior likelihood generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
try {
for (PartitionClockModel model : options.getPartitionClockModels()) {
clockModelGenerator.writeBranchRatesModel(model, writer);
writer.writeText("");
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Branch rates model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Substitution Model & Site Model ++++++++++++++++++
try {
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionSiteModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Substitution model or site model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ AllMus parameter ++++++++++++++++++
try {
for (PartitionClockModel model : options.getPartitionClockModels()) {
clockModelGenerator.writeAllMus(model, writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Clock model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Site Model ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// substitutionModelGenerator.writeSiteModel(model, writer); // site model
// substitutionModelGenerator.writeAllMus(model, writer); // allMus
// writer.writeText("");
// }
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
try {
AncestralStatesComponentOptions ancestralStatesOptions = (AncestralStatesComponentOptions) options.getComponentOptions(AncestralStatesComponentOptions.class);
Map<Pair<PartitionTreeModel, DataType>, List<PartitionData>> partitionLists = new HashMap<Pair<PartitionTreeModel, DataType>, List<PartitionData>>();
List<AbstractPartitionData> otherPartitions = new ArrayList<AbstractPartitionData>();
for (AbstractPartitionData partition : options.dataPartitions) {
// generate tree likelihoods for alignment data partitions
if (partition.getTaxonList() != null) {
if (partition.getDataType().getType() == DataType.NUCLEOTIDES || partition.getDataType().getType() != DataType.AMINO_ACIDS) {
// all sequence partitions of the same type as the first into the list for use in a
// MultipartitionTreeDataLikelihood. Must also share the same tree and not be doing
// ancestral reconstruction or counting
Pair<PartitionTreeModel, DataType> key = new Pair(partition.getPartitionTreeModel(), partition.getDataType());
List<PartitionData> partitions = partitionLists.get(key);
if (partitions == null) {
partitions = new ArrayList<PartitionData>();
}
partitions.add((PartitionData) partition);
partitionLists.put(key, partitions);
} else {
otherPartitions.add(partition);
}
}
}
for (List<PartitionData> partitions : partitionLists.values()) {
treeLikelihoodGenerator.writeTreeDataLikelihood(partitions, writer);
writer.writeText("");
}
for (AbstractPartitionData partition : otherPartitions) {
// generate tree likelihoods for the other data partitions
if (partition.getTaxonList() != null) {
if (partition instanceof PartitionData) {
treeLikelihoodGenerator.writeTreeLikelihood((PartitionData) partition, writer);
writer.writeText("");
} else if (partition instanceof PartitionPattern) {
// microsat
treeLikelihoodGenerator.writeTreeLikelihood((PartitionPattern) partition, writer);
writer.writeText("");
} else {
throw new GeneratorException("Find unrecognized partition:\n" + partition.getName());
}
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree likelihood generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ *BEAST ++++++++++++++++++
if (options.useStarBEAST) {
//++++++++++++++++ species ++++++++++++++++++
try {
starBeastGenerator.writeSpecies(writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST species section generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Species Sets ++++++++++++++++++
List<Taxa> speciesSets = options.speciesSets;
try {
if (speciesSets != null && speciesSets.size() > 0) {
tmrcaStatisticsGenerator.writeTaxonSets(writer, speciesSets);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Species sets generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ trees ++++++++++++++++++
try {
if (speciesSets != null && speciesSets.size() > 0) {
starBeastGenerator.writeStartingTreeForCalibration(writer);
}
starBeastGenerator.writeSpeciesTree(writer, speciesSets != null && speciesSets.size() > 0);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST trees generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Statistics ++++++++++++++++++
try {
if (speciesSets != null && speciesSets.size() > 0) {
tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST TMRCA statistics generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ prior and likelihood ++++++++++++++++++
try {
starBeastGenerator.writeSTARBEAST(writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST trees section generation has failed:\n" + e.getMessage());
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
//++++++++++++++++ Operators ++++++++++++++++++
try {
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_OPERATORS, writer);
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Operators generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ MCMC ++++++++++++++++++
try {
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("MCMC or log generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ ++++++++++++++++++
try {
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("The last part of XML generation has failed:\n" + e.getMessage());
}
writer.writeCloseTag("beast");
writer.flush();
writer.close();
}
use of dr.evolution.alignment.Alignment in project beast-mcmc by beast-dev.
the class DataPanel method showAlignment.
private void showAlignment() {
int[] selRows = dataTable.getSelectedRows();
for (int row : selRows) {
AbstractPartitionData partition = options.dataPartitions.get(row);
Alignment alignment = null;
if (partition instanceof PartitionData)
alignment = ((PartitionData) partition).getAlignment();
// alignment == null if partition is trait or microsat http://code.google.com/p/beast-mcmc/issues/detail?id=343
if (alignment == null) {
JOptionPane.showMessageDialog(this, "Cannot display traits or microsatellite data currently.\nUse the traits panel to view and edit traits.", "Illegal Argument Exception", JOptionPane.ERROR_MESSAGE);
return;
}
JFrame frame = new JFrame();
frame.setSize(800, 600);
AlignmentViewer viewer = new AlignmentViewer();
if (alignment.getDataType().getType() == DataType.NUCLEOTIDES) {
viewer.setCellDecorator(new StateCellDecorator(new NucleotideDecorator(), false));
} else if (alignment.getDataType().getType() == DataType.AMINO_ACIDS) {
viewer.setCellDecorator(new StateCellDecorator(new AminoAcidDecorator(), false));
} else {
// no colouring
}
viewer.setAlignmentBuffer(new BeautiAlignmentBuffer(alignment));
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
panel.add(viewer, BorderLayout.CENTER);
JPanel infoPanel = new JPanel(new BorderLayout());
infoPanel.setOpaque(false);
panel.add(infoPanel, BorderLayout.SOUTH);
frame.setContentPane(panel);
frame.setVisible(true);
}
}
Aggregations