Search in sources :

Example 76 with Tree

use of dr.evolution.tree.Tree in project beast-mcmc by beast-dev.

the class BeagleSeqSimTest method ancestralSequenceTree.

//END: simulateRandomBranchAssignment
static void ancestralSequenceTree() {
    try {
        LinkedHashMap<NodeRef, int[]> sequenceMap = new LinkedHashMap<NodeRef, int[]>();
        DataType dataType = Nucleotides.INSTANCE;
        // 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);
        for (NodeRef node : treeModel.getNodes()) {
            if (treeModel.isExternal(node)) {
                int[] seq = new int[] { 1, 1, 1 };
                sequenceMap.put(node, seq);
            } else {
                int[] seq = new int[] { 2, 2, 2 };
                sequenceMap.put(node, seq);
            }
        }
        // END: nodes loop
        AncestralSequenceTrait ancestralSequence = new AncestralSequenceTrait(sequenceMap, dataType);
        TreeTraitProvider[] treeTraitProviders = new TreeTraitProvider[] { ancestralSequence };
        StringBuffer buffer = new StringBuffer();
        NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
        boolean useTipLabels = true;
        //
        TreeUtils.newick(//
        treeModel, //
        treeModel.getRoot(), //
        useTipLabels, //
        TreeUtils.BranchLengthType.LENGTHS_AS_TIME, //
        format, //
        null, //
        treeTraitProviders, null, buffer);
        System.out.println(buffer);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ImportException e) {
        e.printStackTrace();
    }
// END: try-catch
}
Also used : TreeTraitProvider(dr.evolution.tree.TreeTraitProvider) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ImportException(dr.evolution.io.Importer.ImportException) NodeRef(dr.evolution.tree.NodeRef) TreeModel(dr.evomodel.tree.TreeModel) NewickImporter(dr.evolution.io.NewickImporter) DataType(dr.evolution.datatype.DataType) Tree(dr.evolution.tree.Tree) NumberFormat(java.text.NumberFormat)

Example 77 with Tree

use of dr.evolution.tree.Tree in project beast-mcmc by beast-dev.

the class BeagleSeqSimTest method simulateTopology.

// END: annotateTree
static void simulateTopology() {
    try {
        System.out.println("Test case 1: simulateTopology");
        MathUtils.setSeed(666);
        int sequenceLength = 10;
        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);
        // set demographic function
        ExponentialGrowth exponentialGrowth = new ExponentialGrowth(Units.Type.YEARS);
        exponentialGrowth.setN0(10);
        exponentialGrowth.setGrowthRate(0.5);
        Taxa taxa = new Taxa();
        for (Taxon taxon : tree.asList()) {
            double absoluteHeight = Utils.getAbsoluteTaxonHeight(taxon, tree);
            taxon.setAttribute(Utils.ABSOLUTE_HEIGHT, absoluteHeight);
            // taxon.setAttribute("date", new Date(absoluteHeight,
            // Units.Type.YEARS, true));
            taxa.addTaxon(taxon);
        }
        // END: taxon loop
        CoalescentSimulator topologySimulator = new CoalescentSimulator();
        TreeModel treeModel = new TreeModel(topologySimulator.simulateTree(taxa, exponentialGrowth));
        System.out.println(treeModel.toString());
        Parameter freqs = new Parameter.Default(new double[] { 0.25, 0.25, 0.25, 0.25 });
        FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
        // create substitution model
        Parameter kappa = new Parameter.Default(1, 10);
        HKY hky = new HKY(kappa, freqModel);
        HomogeneousBranchModel substitutionModel = new HomogeneousBranchModel(hky);
        // create site model
        GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
        // create branch rate model
        BranchRateModel branchRateModel = new DefaultBranchRateModel();
        // create partition
        Partition partition1 = new //
        Partition(//
        treeModel, //
        substitutionModel, //
        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);
        System.out.println(simulator.simulate(simulateInPar, false).toString());
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
// END: try-catch block
}
Also used : FrequencyModel(dr.evomodel.substmodel.FrequencyModel) Partition(dr.app.beagle.tools.Partition) ExponentialGrowth(dr.evolution.coalescent.ExponentialGrowth) Taxon(dr.evolution.util.Taxon) ArrayList(java.util.ArrayList) HomogeneousBranchModel(dr.evomodel.branchmodel.HomogeneousBranchModel) GammaSiteRateModel(dr.evomodel.siteratemodel.GammaSiteRateModel) CoalescentSimulator(dr.evolution.coalescent.CoalescentSimulator) BeagleSequenceSimulator(dr.app.beagle.tools.BeagleSequenceSimulator) ImportException(dr.evolution.io.Importer.ImportException) IOException(java.io.IOException) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) Taxa(dr.evolution.util.Taxa) TreeModel(dr.evomodel.tree.TreeModel) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) BranchRateModel(dr.evomodel.branchratemodel.BranchRateModel) NewickImporter(dr.evolution.io.NewickImporter) HKY(dr.evomodel.substmodel.nucleotide.HKY) Tree(dr.evolution.tree.Tree) Parameter(dr.inference.model.Parameter)

Example 78 with Tree

use of dr.evolution.tree.Tree in project beast-mcmc by beast-dev.

the class BeagleSeqSimTest method simulateOnePartition.

// END: simulate topology
static void simulateOnePartition() {
    try {
        MathUtils.setSeed(666);
        System.out.println("Test case 2: simulateOnePartition");
        int sequenceLength = 10;
        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 substitution model
        Parameter kappa = new Parameter.Default(1, 10);
        HKY hky = new HKY(kappa, freqModel);
        HomogeneousBranchModel substitutionModel = new HomogeneousBranchModel(hky);
        // create site model
        GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
        // create branch rate model
        BranchRateModel branchRateModel = new DefaultBranchRateModel();
        // create partition
        Partition partition1 = new //
        Partition(//
        treeModel, //
        substitutionModel, //
        siteRateModel, //
        branchRateModel, //
        freqModel, // from
        0, // to
        sequenceLength - 1, // every
        1);
        Sequence ancestralSequence = new Sequence();
        ancestralSequence.appendSequenceString("TCAAGTGAGG");
        partition1.setRootSequence(ancestralSequence);
        partitionsList.add(partition1);
        // feed to sequence simulator and generate data
        BeagleSequenceSimulator simulator = new BeagleSequenceSimulator(partitionsList);
        SimpleAlignment alignment = simulator.simulate(simulateInPar, false);
        // alignment.setOutputType(SimpleAlignment.OutputType.NEXUS);
        alignment.setOutputType(SimpleAlignment.OutputType.XML);
        System.out.println(alignment.toString());
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
// END: try-catch block
}
Also used : FrequencyModel(dr.evomodel.substmodel.FrequencyModel) Partition(dr.app.beagle.tools.Partition) ArrayList(java.util.ArrayList) HomogeneousBranchModel(dr.evomodel.branchmodel.HomogeneousBranchModel) GammaSiteRateModel(dr.evomodel.siteratemodel.GammaSiteRateModel) Sequence(dr.evolution.sequence.Sequence) BeagleSequenceSimulator(dr.app.beagle.tools.BeagleSequenceSimulator) ImportException(dr.evolution.io.Importer.ImportException) IOException(java.io.IOException) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) TreeModel(dr.evomodel.tree.TreeModel) SimpleAlignment(dr.evolution.alignment.SimpleAlignment) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) BranchRateModel(dr.evomodel.branchratemodel.BranchRateModel) NewickImporter(dr.evolution.io.NewickImporter) HKY(dr.evomodel.substmodel.nucleotide.HKY) Tree(dr.evolution.tree.Tree) Parameter(dr.inference.model.Parameter)

Example 79 with Tree

use of dr.evolution.tree.Tree in project beast-mcmc by beast-dev.

the class DebugTreeImporter method main.

//args[0]: saved dump file
//args[1]: new XML file
//args[2]: new tree (Newick format)
//args[3]: output file
//e.g.: dump.trump.160 worobey-con-sc-resume-162-taxa.xml newtree.nwk restart.dump
public static void main(String[] args) {
    if (args.length != 4) {
        throw new RuntimeException("Incorrect number of arguments.");
    }
    try {
        FileReader fileIn = new FileReader(args[2]);
        BufferedReader in = new BufferedReader(fileIn);
        String fullTree = in.readLine();
        NewickImporter importer = new NewickImporter(fullTree);
        Tree tree = importer.importNextTree();
        //assume rootHeight in dumpfile is ALWAYS followed by all the nodeHeights
        System.out.println("root height: " + tree.getNodeHeight(tree.getRoot()));
        FileReader dumpFileIn = new FileReader(args[0]);
        BufferedReader dumpIn = new BufferedReader(dumpFileIn);
        FileWriter dumpFileOut = new FileWriter(args[3]);
        BufferedWriter dumpOut = new BufferedWriter(dumpFileOut);
        String original = dumpIn.readLine();
        String[] fields = original.split("\t");
        //write new rootHeight to new output dump file
        while (!fields[0].equals("treeModel.rootHeight")) {
            if (DEBUG) {
                System.out.println(original);
            }
            dumpOut.write(original + "\n");
            original = dumpIn.readLine();
            fields = original.split("\t");
        }
        fields[2] = Double.toString(tree.getNodeHeight(tree.getRoot()));
        for (int i = 0; i < fields.length; i++) {
            dumpOut.write(fields[i] + "\t");
        }
        dumpOut.write("\n");
        //write all new node heights to new output dump file
        int nodeCount = tree.getNodeCount();
        if (DEBUG) {
            System.out.println(nodeCount + " nodes found in tree.");
        }
        for (int i = 0; i < (nodeCount - 1); i++) {
            if (DEBUG) {
                System.out.println(tree.getNode(i).getNumber() + "\t" + tree.getNodeHeight(tree.getNode(i)));
            }
            dumpOut.write(tree.getNode(i).getNumber() + "\t1\t" + tree.getNodeHeight(tree.getNode(i)) + "\n");
        }
        //skip all the node heights in the original dump file
        //no clue as to how many there are ...
        //best I can tell only node heights have integers as parameter names
        original = dumpIn.readLine();
        if (DEBUG) {
            System.out.println(original);
        }
        fields = original.split("\t");
        while (isInteger(fields[0])) {
            original = dumpIn.readLine();
            fields = original.split("\t");
        }
        while (!fields[0].equals("treeModel")) {
            dumpOut.write(original + "\n");
            original = dumpIn.readLine();
            if (DEBUG) {
                System.out.println(original);
            }
            fields = original.split("\t");
        }
        dumpOut.write(fields[0] + "\t" + fullTree);
        dumpOut.flush();
        dumpOut.close();
    } catch (FileNotFoundException fnfe) {
        throw new RuntimeException("Tree file not found.");
    } catch (IOException ioe) {
        throw new RuntimeException("Unable to read file: " + ioe.getMessage());
    } catch (Importer.ImportException ie) {
        throw new RuntimeException("Unable to import tree: " + ie.getMessage());
    }
}
Also used : NewickImporter(dr.evolution.io.NewickImporter) Tree(dr.evolution.tree.Tree) Importer(dr.evolution.io.Importer) NewickImporter(dr.evolution.io.NewickImporter)

Example 80 with Tree

use of dr.evolution.tree.Tree in project beast-mcmc by beast-dev.

the class IstvanOperator method doOperation.

public double doOperation() {
    Tree tree = likelihood.getTreeModel();
    alignment = likelihood.getAlignment();
    //System.out.println("Incoming alignment");
    //System.out.println(alignment);
    //System.out.println();
    SubstitutionModel substModel = likelihood.getSiteModel().getSubstitutionModel();
    // initialize the iParent and iTau arrays based on the given tree.
    initTree(tree, likelihood.getSiteModel().getMu());
    int[] treeIndex = new int[tree.getTaxonCount()];
    for (int i = 0; i < treeIndex.length; i++) {
        treeIndex[i] = tree.getTaxonIndex(alignment.getTaxonId(i));
    }
    // initialize the iAlignment array from the given alignment.
    initAlignment(alignment, treeIndex);
    // initialize the iProbs array from the substitution model -- must be called after populating tree!
    initSubstitutionModel(substModel);
    DataType dataType = substModel.getDataType();
    proposal.setGapSymbol(dataType.getGapState());
    int[][] returnedAlignment = new int[iAlignment.length][];
    //System.out.println("Initialization done, starting proposal proper...");
    double logq = proposal.propose(iAlignment, iProbs, iBaseFreqs, iParent, iTau, returnedAlignment, tuning, exponent, gapPenalty);
    //System.out.println("Proposal finished, logq=" + logq);
    //create new alignment object
    SimpleAlignment newAlignment = new SimpleAlignment();
    for (int i = 0; i < alignment.getTaxonCount(); i++) {
        StringBuffer seqBuffer = new StringBuffer();
        for (int j = 0; j < returnedAlignment[i].length; j++) {
            seqBuffer.append(dataType.getChar(returnedAlignment[treeIndex[i]][j]));
        }
        // add sequences in order of tree
        String seqString = seqBuffer.toString();
        Sequence sequence = new Sequence(alignment.getTaxon(i), seqString);
        newAlignment.addSequence(sequence);
        String oldunaligned = alignment.getUnalignedSequenceString(i);
        String unaligned = newAlignment.getUnalignedSequenceString(i);
        if (!unaligned.equals(oldunaligned)) {
            System.err.println("Sequence changed from:");
            System.err.println("old:'" + oldunaligned + "'");
            System.err.println("new:'" + unaligned + "'");
            throw new RuntimeException();
        }
    }
    //System.out.println("Outgoing alignment");
    //System.out.println(newAlignment);
    //System.out.println();
    likelihood.setAlignment(newAlignment);
    return logq;
}
Also used : SimpleAlignment(dr.evolution.alignment.SimpleAlignment) Tree(dr.evolution.tree.Tree) DataType(dr.evolution.datatype.DataType) Sequence(dr.evolution.sequence.Sequence) SubstitutionModel(dr.oldevomodel.substmodel.SubstitutionModel)

Aggregations

Tree (dr.evolution.tree.Tree)128 NewickImporter (dr.evolution.io.NewickImporter)32 ArrayList (java.util.ArrayList)31 TreeModel (dr.evomodel.tree.TreeModel)26 Parameter (dr.inference.model.Parameter)26 NexusImporter (dr.evolution.io.NexusImporter)18 TaxonList (dr.evolution.util.TaxonList)18 Taxa (dr.evolution.util.Taxa)17 FlexibleTree (dr.evolution.tree.FlexibleTree)16 Taxon (dr.evolution.util.Taxon)15 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)15 NodeRef (dr.evolution.tree.NodeRef)14 SimpleTree (dr.evolution.tree.SimpleTree)13 ImportException (dr.evolution.io.Importer.ImportException)12 Importer (dr.evolution.io.Importer)11 DefaultBranchRateModel (dr.evomodel.branchratemodel.DefaultBranchRateModel)11 BeagleSequenceSimulator (dr.app.beagle.tools.BeagleSequenceSimulator)10 Partition (dr.app.beagle.tools.Partition)10 GammaSiteRateModel (dr.evomodel.siteratemodel.GammaSiteRateModel)10 FrequencyModel (dr.evomodel.substmodel.FrequencyModel)9