Search in sources :

Example 11 with RootedTree

use of jebl.evolution.trees.RootedTree in project beast-mcmc by beast-dev.

the class DiscreteTreeToKML method main.

public static void main(String[] args) throws Arguments.ArgumentException {
    String inputFileName = null;
    String outputFileName = null;
    RootedTree tree = null;
    String[][] locations = null;
    String stateAnnotation = "state";
    //in case trees are scaled in other time units
    double timeScaler = 1;
    // the width of branches will be stateProbability*branchWidthMultiplier+branchWidthConstant
    double branchWidthConstant = 2.0;
    double branchWidthMultiplier = 5.0;
    // this is to chop up the branches of the surface tree in 'divider' segments
    double divider = 100;
    // use state probabilities for branch width
    boolean useStateProbability = true;
    // branch width if posterior probabilities are not used
    double branchWidth = 10.0;
    // use posterior probabilities to color branch
    boolean usePosterior = false;
    // use heights (time) to color branches
    boolean useHeights = true;
    //red: 0000FF green: 00FF00 magenta: FF00FF white: FFFFFF yellow: 00FFFF cyan: FFFF00
    String startBranchColor = "FF00FF";
    String endBranchColor = "FFFF00";
    // branch color if color range based on rates is not used
    String branchColor = "ffffff";
    // branches are arcs with heights proportional to the distance between locations
    boolean arcBranches = true;
    // the height of the arcs is proportional to the time the branch spans, by default arch-heights are proportional to the distance between locations
    boolean arcTimeHeight = false;
    // this is the factor with which to multiply the time of the branch to get the altitude for that branch in the surface Tree
    double altitudeFactor = 100;
    boolean temporary = false;
    // required to convert heights to calendar dates
    double mostRecentDate = 2010;
    //circles
    int numberOfIntervals = 100;
    //boolean autoRadius = false;
    double radius = 0;
    String circleOpacity = "8F";
    //extra coordinates for some taxa
    boolean coordinatesForTaxa = false;
    String[][] taxaCoordinates = null;
    //tree slices for google maps, requires treeHeight in exporterString: e.g., exporterString.writeTreeToKML(0.025);
    //TODO: have this outputed to a different file (what happens now)?
    boolean makeTreeSlices = false;
    double[] sliceTimes = null;
    double treeSliceBranchWidth = 3;
    // shows complete branch for slice if time is more recent than the branch's midpoint
    boolean showBranchAtMidPoint = false;
    Arguments arguments = new Arguments(new Arguments.Option[] { new Arguments.StringOption(COORDINATES, "coordinate file", "specifies a tab-delimited file with coordinates for the locations"), new Arguments.StringOption(ANNOTATION, "location state annotation string", "specifies the string used for location state annotation [default=state]"), new Arguments.RealOption(TIMESCALER, "specifies the scaling factor by which to rescale time [default=1]"), new Arguments.RealOption(MRSD, "specifies the most recent sampling data in fractional years to rescale time [default=2010]"), new Arguments.RealOption(BWC, "specifies the branch width constant [default=2]"), new Arguments.RealOption(BWM, "specifies the branch width multiplier [default=5]"), new Arguments.StringOption(USP, falseTrue, false, "use state probabilities for branch width [default = true]"), new Arguments.StringOption(BCUSE, use, false, "use heights or posterior probabilities for branch colors [default = heights]"), new Arguments.RealOption(BW, "specifies the branch width if posterior probabilities are not used [default=10]"), new Arguments.IntegerOption(DIVIDER, "specifies in how many segments at branch should be chopped up [default=50]"), new Arguments.StringOption(BSTARTCOLOR, "branch start color", "specifies a starting color for the branches [default=FF00FF]"), new Arguments.StringOption(BENDCOLOR, "branch end color", "specifies an end color for the branches [default=FFFF00]"), new Arguments.StringOption(BCOLOR, "branch color", "specifies a branch color if color range based on rates is not used [default=ffffff]"), new Arguments.StringOption(ARCHBRANCH, falseTrue, false, "use arcs for the branches [default = true], by default arc-heights are proportional to the distance between locations"), new Arguments.StringOption(ARCHHEIGHT, arch, false, "use time or distance for arch heights [default = no arcs]"), new Arguments.RealOption(ALTITUDE, "specifies the altitudefactor for the branches [default=1000]"), new Arguments.StringOption(TEMP, falseTrue, false, "display branches only temporary [default=false"), new Arguments.IntegerOption(CIRCLESEGMENTS, "specifies the number of segments to construct circles [default=100]"), new Arguments.IntegerOption(RADIUS, "specifies the radiusfactor for the circles [default='autoradius']"), new Arguments.StringOption(CIRCLEOP, "circle opacity", "sets the opacity of the circles [default=8F]"), new Arguments.Option(HELP, "option to print this message"), new Arguments.StringOption(COORDSFORTAXA, "file with taxa coords", "specifies a file with additional coordinates for particular taxa"), new Arguments.RealOption(SLICEBW, "specifies the branch width for tree slices [default=3]"), new Arguments.StringOption(SLICES, "time", "specifies a slice time-list [default=none]"), new Arguments.StringOption(SLICEMIDPOINT, falseTrue, false, "shows complete branch for sliced tree if time is more recent than the branch's midpoint [default=false") });
    try {
        arguments.parseArguments(args);
    } catch (Arguments.ArgumentException ae) {
        progressStream.println(ae);
        printUsage(arguments);
        System.exit(1);
    }
    if (args.length == 0 || arguments.hasOption(HELP)) {
        printUsage(arguments);
        System.exit(0);
    }
    try {
        String coordinatesFileString = arguments.getStringOption(COORDINATES);
        //System.out.println(coordinatesFileString);
        if (coordinatesFileString != null) {
            // count lines in locations file and tokens per line
            int[] counts = countLinesAndTokens(coordinatesFileString);
            //System.out.println(counts[0]+"\t"+counts[1]);
            //read in locations
            locations = new String[counts[0]][counts[1]];
            readLocationsCoordinates(coordinatesFileString, locations);
        } else {
            progressStream.println("no coordinates for taxa??");
            System.exit(1);
        }
        if (arguments.hasOption(MRSD)) {
            mostRecentDate = arguments.getRealOption(MRSD);
        }
        if (arguments.hasOption(TIMESCALER)) {
            timeScaler = arguments.getRealOption(TIMESCALER);
        }
        if (arguments.hasOption(DIVIDER)) {
            divider = arguments.getRealOption(DIVIDER);
        }
        if (arguments.hasOption(ALTITUDE)) {
            altitudeFactor = arguments.getRealOption(ALTITUDE);
        }
        String stateAnnotationString = arguments.getStringOption(ANNOTATION);
        if (stateAnnotationString != null) {
            stateAnnotation = stateAnnotationString;
        }
        String useStateProbString = arguments.getStringOption(USP);
        if (useStateProbString != null && useStateProbString.compareToIgnoreCase("posteriors") != 0)
            useStateProbability = false;
        String useColorString = arguments.getStringOption(BCUSE);
        if (useColorString != null && useColorString.compareToIgnoreCase("posteriors") == 0) {
            usePosterior = true;
            useHeights = false;
        }
        if (useColorString != null && useColorString.compareToIgnoreCase("heights") == 0) {
            useHeights = true;
            usePosterior = false;
        }
        if (arguments.hasOption(BWC)) {
            branchWidthConstant = arguments.getRealOption(BWC);
        }
        if (arguments.hasOption(BWM)) {
            branchWidthMultiplier = arguments.getRealOption(BWM);
        }
        if (arguments.hasOption(BW)) {
            branchWidth = arguments.getRealOption(BW);
        }
        String color1String = arguments.getStringOption(BSTARTCOLOR);
        if (color1String != null) {
            startBranchColor = color1String;
        }
        String color2String = arguments.getStringOption(BENDCOLOR);
        if (color2String != null) {
            endBranchColor = color2String;
        }
        String colorString = arguments.getStringOption(BCOLOR);
        if (colorString != null) {
            branchColor = colorString;
        }
        String archString = arguments.getStringOption(ARCHBRANCH);
        if (archString != null && archString.compareToIgnoreCase("false") == 0)
            arcBranches = false;
        String archHeightString = arguments.getStringOption(ARCHHEIGHT);
        if (archHeightString != null && archHeightString.compareToIgnoreCase("time") == 0) {
            arcTimeHeight = true;
        }
        String tempString = arguments.getStringOption(TEMP);
        if (tempString != null && tempString.compareToIgnoreCase("true") == 0)
            temporary = true;
        if (arguments.hasOption(CIRCLESEGMENTS)) {
            numberOfIntervals = arguments.getIntegerOption(CIRCLESEGMENTS);
        }
        if (arguments.hasOption(RADIUS)) {
            radius = arguments.getIntegerOption(RADIUS);
        }
        String circleOpacityString = arguments.getStringOption(CIRCLEOP);
        if (circleOpacityString != null) {
            circleOpacity = circleOpacityString;
        }
        //read in extra taxon locations
        String taxaCoordinatesFileString = arguments.getStringOption(COORDSFORTAXA);
        if (taxaCoordinatesFileString != null) {
            coordinatesForTaxa = true;
            progressStream.println("\radditional taxa locations:");
            // count lines in locations file and tokens per line
            int[] counts = countLinesAndTokens(taxaCoordinatesFileString);
            //read in locations
            taxaCoordinates = new String[counts[0]][counts[1]];
            readLocationsCoordinates(taxaCoordinatesFileString, taxaCoordinates);
        }
        String sliceString = arguments.getStringOption(SLICES);
        if (sliceString != null) {
            makeTreeSlices = true;
            sliceTimes = parseVariableLengthDoubleArray(sliceString);
        }
        if (arguments.hasOption(SLICEBW)) {
            treeSliceBranchWidth = arguments.getRealOption(SLICEBW);
        }
        String midpointString = arguments.getStringOption(SLICEMIDPOINT);
        if (midpointString != null && midpointString.compareToIgnoreCase("true") == 0)
            showBranchAtMidPoint = true;
    } catch (Arguments.ArgumentException e) {
        progressStream.println(e);
        printUsage(arguments);
        System.exit(-1);
    }
    final String[] args2 = arguments.getLeftoverArguments();
    outputFileName = args2[0] + ".kml";
    switch(args2.length) {
        case 0:
            printUsage(arguments);
            System.exit(1);
        case 2:
            outputFileName = args2[1];
        // fall to
        case 1:
            inputFileName = args2[0];
            tree = readTree(inputFileName);
            break;
        default:
            {
                System.err.println("Unknown option: " + args2[2]);
                System.err.println();
                printUsage(arguments);
                System.exit(1);
            }
    }
    DiscreteKMLString exporterString = new DiscreteKMLString(tree, stateAnnotation, locations, inputFileName, mostRecentDate, timeScaler, divider, branchWidthConstant, branchWidthMultiplier, useStateProbability, branchWidth, startBranchColor, endBranchColor, branchColor, useHeights, usePosterior, arcBranches, arcTimeHeight, altitudeFactor, temporary, numberOfIntervals, radius, circleOpacity, coordinatesForTaxa, taxaCoordinates, makeTreeSlices);
    try {
        BufferedWriter out1 = new BufferedWriter(new FileWriter(outputFileName));
        StringBuffer buffer = new StringBuffer();
        if (makeTreeSlices) {
            for (int i = 0; i < sliceTimes.length; i++) exporterString.writeTreeToKML(sliceTimes[i], treeSliceBranchWidth, showBranchAtMidPoint);
        } else {
            exporterString.writeTreeToKML();
            exporterString.writeLineagesToCircles();
        }
        exporterString.writeLocationsKML();
        exporterString.compileBuffer(buffer);
        out1.write(buffer.toString());
        out1.close();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}
Also used : FileWriter(java.io.FileWriter) Arguments(dr.app.util.Arguments) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) RootedTree(jebl.evolution.trees.RootedTree)

Example 12 with RootedTree

use of jebl.evolution.trees.RootedTree in project beast-mcmc by beast-dev.

the class LineageCountThroughTime method getLTT.

public static Variate[] getLTT(String treeFile, double minTime, double maxTime, int binCount, // number of trees to skip
int skip) throws IOException, ImportException {
    double delta = (maxTime - minTime) / (binCount - 1);
    BufferedReader reader = new BufferedReader(new FileReader(treeFile));
    String line = reader.readLine();
    TreeImporter importer;
    if (line.toUpperCase().startsWith("#NEXUS")) {
        importer = new NexusImporter(reader);
    } else {
        importer = new NewickImporter(reader, false);
    }
    int state = 0;
    while (importer.hasTree() && state < skip) {
        importer.importNextTree();
        state += 1;
    }
    // the age of the end of this group
    List<double[]> branchingTimes = new ArrayList<double[]>();
    state = 0;
    while (importer.hasTree()) {
        RootedTree tree = (RootedTree) importer.importNextTree();
        double[] bt = new double[tree.getInternalNodes().size()];
        int i = 0;
        for (Node node : tree.getInternalNodes()) {
            bt[i] = tree.getHeight(node);
            i++;
        }
        Arrays.sort(bt);
        branchingTimes.add(bt);
        state += 1;
    }
    Variate[] bins = new Variate[binCount];
    double height = 0;
    double n = branchingTimes.get(0).length;
    for (int k = 0; k < binCount; k++) {
        bins[k] = new Variate.D();
        if (height >= 0.0 && height <= maxTime) {
            for (state = 0; state < branchingTimes.size(); state++) {
                int index = 0;
                while (index < branchingTimes.get(state).length && branchingTimes.get(state)[index] < height) {
                    index += 1;
                }
                double lineageCount = 1;
                if (index < branchingTimes.get(state).length) {
                    lineageCount = n - index + 1;
                }
                bins[k].add(lineageCount);
            }
        }
        height += delta;
    }
    Variate xData = new Variate.D();
    Variate yDataMean = new Variate.D();
    Variate yDataMedian = new Variate.D();
    Variate yDataUpper = new Variate.D();
    Variate yDataLower = new Variate.D();
    double t = minTime;
    for (Variate bin : bins) {
        xData.add(t);
        if (bin.getCount() > 0) {
            yDataMean.add(bin.getMean());
            yDataMedian.add(bin.getQuantile(0.5));
            yDataLower.add(bin.getQuantile(0.025));
            yDataUpper.add(bin.getQuantile(0.975));
        } else {
            yDataMean.add(Double.NaN);
            yDataMedian.add(Double.NaN);
            yDataLower.add(Double.NaN);
            yDataUpper.add(Double.NaN);
        }
        t += delta;
    }
    return new Variate[] { xData, yDataMean };
}
Also used : NexusImporter(jebl.evolution.io.NexusImporter) Variate(dr.stats.Variate) Node(jebl.evolution.graphs.Node) ArrayList(java.util.ArrayList) RootedTree(jebl.evolution.trees.RootedTree) NewickImporter(jebl.evolution.io.NewickImporter) BufferedReader(java.io.BufferedReader) TreeImporter(jebl.evolution.io.TreeImporter) FileReader(java.io.FileReader)

Aggregations

RootedTree (jebl.evolution.trees.RootedTree)12 NexusImporter (jebl.evolution.io.NexusImporter)8 ImportException (jebl.evolution.io.ImportException)6 TreeImporter (jebl.evolution.io.TreeImporter)6 Variate (dr.stats.Variate)3 FileReader (java.io.FileReader)3 IOException (java.io.IOException)3 Node (jebl.evolution.graphs.Node)3 Arguments (dr.app.util.Arguments)2 Regression (dr.stats.Regression)2 NumberFormatter (dr.util.NumberFormatter)2 BufferedWriter (java.io.BufferedWriter)2 FileWriter (java.io.FileWriter)2 Taxon (jebl.evolution.taxa.Taxon)2 LogFileTraces (dr.inference.trace.LogFileTraces)1 java.io (java.io)1 BufferedReader (java.io.BufferedReader)1 ArrayList (java.util.ArrayList)1 EmpiricalDemographicFunction (jebl.evolution.coalescent.EmpiricalDemographicFunction)1 NewickExporter (jebl.evolution.io.NewickExporter)1