use of jebl.evolution.graphs.Node in project beast-mcmc by beast-dev.
the class TreeUtils method convertToJebl.
private static Node convertToJebl(Tree tree, NodeRef node, SimpleRootedTree jtree) {
if (tree.isExternal(node)) {
String taxonId = tree.getTaxonId(node.getNumber());
Node externalNode = jtree.createExternalNode(jebl.evolution.taxa.Taxon.getTaxon(taxonId));
jtree.setHeight(externalNode, tree.getNodeHeight(node));
return externalNode;
}
List<Node> jchildren = new ArrayList<Node>();
for (int nc = 0; nc < tree.getChildCount(node); ++nc) {
NodeRef child = tree.getChild(node, nc);
Node node1 = convertToJebl(tree, child, jtree);
jtree.setHeight(node1, tree.getNodeHeight(child));
jchildren.add(node1);
}
return jtree.createInternalNode(jchildren);
}
use of jebl.evolution.graphs.Node in project beast-mcmc by beast-dev.
the class PathogenPanel method treeSelectionChanged.
private void treeSelectionChanged() {
Set<Node> selectedTips = treePanel.getTreeViewer().getSelectedTips();
frame.getCopyAction().setEnabled(selectedTips != null && selectedTips.size() > 0);
selectedPoints = new HashSet<Integer>();
for (Node node : selectedTips) {
selectedPoints.add(pointMap.get(node));
}
if (rootToTipPlot != null) {
rootToTipPlot.setSelectedPoints(selectedPoints);
}
if (residualPlot != null) {
residualPlot.setSelectedPoints(selectedPoints);
}
if (SHOW_NODE_DENSITY && nodeDensityPlot != null) {
nodeDensityPlot.setSelectedPoints(selectedPoints);
}
selectMRCA();
}
use of jebl.evolution.graphs.Node in project beast-mcmc by beast-dev.
the class PathogenPanel method setupPanel.
public void setupPanel() {
StringBuilder sb = new StringBuilder();
NumberFormatter nf = new NumberFormatter(6);
if (tree != null) {
temporalRooting = new TemporalRooting(tree);
currentTree = this.tree;
if (bestFittingRoot && bestFittingRootTree != null) {
currentTree = bestFittingRootTree;
sb.append("Best-fitting root");
} else {
sb.append("User root");
}
if (temporalRooting.isContemporaneous()) {
if (tabbedPane.getSelectedIndex() == 2) {
tabbedPane.setSelectedIndex(1);
}
tabbedPane.setEnabledAt(2, false);
} else {
tabbedPane.setEnabledAt(2, true);
}
RootedTree jtree = dr.evolution.tree.TreeUtils.asJeblTree(currentTree);
List<Color> colours = new ArrayList<Color>();
for (Node tip : jtree.getExternalNodes()) {
Taxon taxon = jtree.getTaxon(tip);
colours.add((Color) taxon.getAttribute("!color"));
}
if (temporalRooting.isContemporaneous()) {
double[] dv = temporalRooting.getRootToTipDistances(currentTree);
List<Double> values = new ArrayList<Double>();
for (double d : dv) {
values.add(d);
}
rootToTipChart.removeAllPlots();
NumericalDensityPlot dp = new NumericalDensityPlot(values, 20, null);
dp.setLineColor(new Color(9, 70, 15));
double yOffset = (Double) dp.getYData().getMax() / 2;
List<Double> dummyValues = new ArrayList<Double>();
for (int i = 0; i < values.size(); i++) {
// add a random y offset to give some visual spread
double y = MathUtils.nextGaussian() * ((Double) dp.getYData().getMax() * 0.05);
dummyValues.add(yOffset + y);
}
rootToTipPlot = new ScatterPlot(values, dummyValues);
rootToTipPlot.setColours(colours);
rootToTipPlot.setMarkStyle(Plot.CIRCLE_MARK, 8, new BasicStroke(0.0F), new Color(44, 44, 44), new Color(129, 149, 149));
rootToTipPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
rootToTipPlot.addListener(new Plot.Adaptor() {
@Override
public void markClicked(int index, double x, double y, boolean isShiftDown) {
rootToTipPlot.selectPoint(index, isShiftDown);
}
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
rootToTipChart.addPlot(rootToTipPlot);
rootToTipChart.addPlot(dp);
rootToTipPanel.setXAxisTitle("root-to-tip divergence");
rootToTipPanel.setYAxisTitle("proportion");
residualChart.removeAllPlots();
sb.append(", contemporaneous tips");
sb.append(", mean root-tip distance: " + nf.format(DiscreteStatistics.mean(dv)));
sb.append(", coefficient of variation: " + nf.format(DiscreteStatistics.stdev(dv) / DiscreteStatistics.mean(dv)));
sb.append(", stdev: " + nf.format(DiscreteStatistics.stdev(dv)));
sb.append(", variance: " + nf.format(DiscreteStatistics.variance(dv)));
showMRCACheck.setVisible(false);
} else {
Regression r = temporalRooting.getRootToTipRegression(currentTree);
double[] residuals = temporalRooting.getRootToTipResiduals(currentTree, r);
pointMap.clear();
for (int i = 0; i < currentTree.getExternalNodeCount(); i++) {
NodeRef tip = currentTree.getExternalNode(i);
Node node = jtree.getNode(Taxon.getTaxon(currentTree.getNodeTaxon(tip).getId()));
node.setAttribute("residual", residuals[i]);
pointMap.put(node, i);
}
rootToTipChart.removeAllPlots();
if (showMRCACheck.isSelected()) {
double[] dv = temporalRooting.getParentRootToTipDistances(currentTree);
List<Double> parentDistances = new ArrayList<Double>();
for (int i = 0; i < dv.length; i++) {
parentDistances.add(i, dv[i]);
}
List<Double> parentTimes = new ArrayList<Double>();
for (int i = 0; i < parentDistances.size(); i++) {
parentTimes.add(i, r.getX(parentDistances.get(i)));
}
mrcaPlot = new ParentPlot(r.getXData(), r.getYData(), parentTimes, parentDistances);
mrcaPlot.setLineColor(new Color(105, 202, 105));
mrcaPlot.setLineStroke(new BasicStroke(0.5F));
rootToTipChart.addPlot(mrcaPlot);
}
if (true) {
double[] datePrecisions = temporalRooting.getTipDatePrecisions(currentTree);
Variate.D ed = new Variate.D();
for (int i = 0; i < datePrecisions.length; i++) {
ed.add(datePrecisions[i]);
}
errorBarPlot = new ErrorBarPlot(ErrorBarPlot.Orientation.HORIZONTAL, r.getXData(), r.getYData(), ed);
errorBarPlot.setLineColor(new Color(44, 44, 44));
errorBarPlot.setLineStroke(new BasicStroke(1.0F));
rootToTipChart.addPlot(errorBarPlot);
}
rootToTipPlot = new ScatterPlot(r.getXData(), r.getYData());
rootToTipPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
rootToTipPlot.setColours(colours);
rootToTipPlot.setMarkStyle(Plot.CIRCLE_MARK, 8, new BasicStroke(0.0F), new Color(44, 44, 44), new Color(129, 149, 149));
rootToTipPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
rootToTipChart.addPlot(rootToTipPlot);
rootToTipChart.addPlot(new RegressionPlot(r));
rootToTipChart.getXAxis().addRange(r.getXIntercept(), (Double) r.getXData().getMax());
rootToTipPanel.setXAxisTitle("time");
rootToTipPanel.setYAxisTitle("root-to-tip divergence");
residualChart.removeAllPlots();
Variate.D values = (Variate.D) r.getYResidualData();
NumericalDensityPlot dp = new NumericalDensityPlot(values, 20);
dp.setLineColor(new Color(103, 128, 144));
double yOffset = (Double) dp.getYData().getMax() / 2;
Double[] dummyValues = new Double[values.getCount()];
for (int i = 0; i < dummyValues.length; i++) {
// add a random y offset to give some visual spread
double y = MathUtils.nextGaussian() * ((Double) dp.getYData().getMax() * 0.05);
dummyValues[i] = yOffset + y;
}
Variate.D yOffsetValues = new Variate.D(dummyValues);
residualPlot = new ScatterPlot(values, yOffsetValues);
residualPlot.addListener(new Plot.Adaptor() {
@Override
public void markClicked(int index, double x, double y, boolean isShiftDown) {
rootToTipPlot.selectPoint(index, isShiftDown);
}
@Override
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
residualPlot.setColours(colours);
residualPlot.setMarkStyle(Plot.CIRCLE_MARK, 8, new BasicStroke(0.0F), new Color(44, 44, 44), new Color(129, 149, 149));
residualPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
residualChart.addPlot(residualPlot);
residualChart.addPlot(dp);
residualPanel.setXAxisTitle("residual");
residualPanel.setYAxisTitle("proportion");
if (SHOW_NODE_DENSITY) {
Regression r2 = temporalRooting.getNodeDensityRegression(currentTree);
nodeDensityChart.removeAllPlots();
nodeDensityPlot = new ScatterPlot(r2.getXData(), r2.getYData());
nodeDensityPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
nodeDensityPlot.setColours(colours);
nodeDensityPlot.setMarkStyle(Plot.CIRCLE_MARK, 8, new BasicStroke(0.0F), new Color(44, 44, 44), new Color(129, 149, 149));
nodeDensityPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
nodeDensityChart.addPlot(nodeDensityPlot);
nodeDensityChart.addPlot(new RegressionPlot(r2));
nodeDensityChart.getXAxis().addRange(r2.getXIntercept(), (Double) r2.getXData().getMax());
nodeDensityPanel.setXAxisTitle("time");
nodeDensityPanel.setYAxisTitle("node density");
}
sb.append(", dated tips");
sb.append(", date range: " + nf.format(temporalRooting.getDateRange()));
sb.append(", slope (rate): " + nf.format(r.getGradient()));
sb.append(", x-intercept (TMRCA): " + nf.format(r.getXIntercept()));
sb.append(", corr. coeff: " + nf.format(r.getCorrelationCoefficient()));
sb.append(", R^2: " + nf.format(r.getRSquared()));
showMRCACheck.setVisible(true);
}
treePanel.setTree(jtree);
treePanel.setColourBy("residual");
} else {
treePanel.setTree(null);
rootToTipChart.removeAllPlots();
sb.append("No trees loaded");
}
textArea.setText(sb.toString());
statisticsModel.fireTableStructureChanged();
repaint();
}
use of jebl.evolution.graphs.Node in project beast-mcmc by beast-dev.
the class DiscreteKMLString method writeTreeToKML.
public void writeTreeToKML() {
int nodeNumber = 0;
posteriorMinAndMax[1] = 1;
posteriorMinAndMax[0] = getPosteriorMin(treeToExport);
heightMinAndMax[0] = 0;
heightMinAndMax[1] = treeToExport.getHeight(treeToExport.getRootNode());
for (Node node : treeToExport.getNodes()) {
nodeNumber++;
String state = ((((String) node.getAttribute(annotation)).replaceAll("\"", "")).replaceAll(" ", "")).trim();
//in case the location state is a concatenation of other states (occurs when they get the same posterior prob)
if (state.contains("+")) {
state = state.substring(0, state.indexOf("+"));
}
if (!treeToExport.isRoot(node)) {
Node parentNode = treeToExport.getParent(node);
// test to see node has the attribute
Object testAttribute = parentNode.getAttribute(annotation);
if (testAttribute == null) {
System.err.print("An internal node has no state attribute; make sure to set the posterior probability limit to 0 when annotating an MCC tree in TreeAnnotator!");
}
String parentState = ((((String) parentNode.getAttribute(annotation)).replaceAll("\"", "")).replaceAll(" ", "")).trim();
if (parentState.contains("+")) {
parentState = parentState.substring(0, parentState.indexOf('+'));
}
boolean considerTaxonCoordinateForThisNode = false;
if (coordinatesForTaxa) {
if (treeToExport.isExternal(node)) {
if (taxonHasSeparateCoordinate(treeToExport.getTaxon(node), taxaNames)) {
considerTaxonCoordinateForThisNode = true;
}
}
}
if (!(state.toLowerCase()).equals(parentState.toLowerCase()) || considerTaxonCoordinateForThisNode) {
double stateProbability = (Double) node.getAttribute(annotation + ".prob");
double latitude = getCoordinate(state, stateNames, stateCoordinates, 0);
double longitude = getCoordinate(state, stateNames, stateCoordinates, 1);
double posteriorProb = 1;
if (!treeToExport.isExternal(node)) {
posteriorProb = (Double) node.getAttribute("posterior");
} else {
if (considerTaxonCoordinateForThisNode) {
latitude = getTaxaCoordinate(treeToExport.getTaxon(node), taxaNames, taxaCoordinates, 0);
longitude = getTaxaCoordinate(treeToExport.getTaxon(node), taxaNames, taxaCoordinates, 1);
}
}
if ((latitude == 0) && (longitude == 0)) {
System.err.println(state + " has no coordinate??");
}
double parentStateProbability = (Double) parentNode.getAttribute(annotation + ".prob");
double parentLatitude = getCoordinate(parentState, stateNames, stateCoordinates, 0);
double parentLongitude = getCoordinate(parentState, stateNames, stateCoordinates, 1);
//System.out.println(latitude+"\t"+parentLatitude+"\t"+longitude+"\t"+parentLongitude);
// distance used for chopping up and altitude
double distance = (3958 * Math.PI * Math.sqrt((parentLatitude - latitude) * (parentLatitude - latitude) + Math.cos(parentLatitude / 57.29578) * Math.cos(latitude / 57.29578) * (parentLongitude - longitude) * (parentLongitude - longitude)) / 180);
double maxAltitude;
if (arcTimeHeight) {
maxAltitude = (treeToExport.getHeight(parentNode) - treeToExport.getHeight(node)) * altitudeFactor;
} else {
maxAltitude = distance * altitudeFactor;
}
// check if we have to go through the 180
boolean longitudeBreak = longitudeBreak(longitude, parentLongitude);
double latitudeDifference = parentLatitude - latitude;
double longitudeDifference;
if (!longitudeBreak) {
longitudeDifference = parentLongitude - longitude;
} else {
if (parentLongitude < 0) {
longitudeDifference = (180 + parentLongitude) + (180 - longitude);
} else {
longitudeDifference = (180 - parentLongitude) + (180 + longitude);
}
}
branchesBuffer.append("\t<Folder>\r");
branchesBuffer.append("\t\t\t<name>branch" + nodeNumber + "</name>\r");
//System.out.println("branch "+nodeNumber+"\t+state+"+"\t"+latitude+"\t"+longitude+"\t"+parentLatitude+"\t"+parentLongitude);
//divider dependent on distance
//divider = (2*(int)(distance/25));
double currentLongitude1 = 0;
double currentLongitude2 = 0;
for (int a = 0; a < divider; a++) {
branchesBuffer.append("\t\t<Placemark>\r");
branchesBuffer.append("\t\t\t<name>branch" + nodeNumber + "_part" + (a + 1) + "</name>\r");
branchesBuffer.append("\t\t\t<TimeSpan>\r");
//convert height of the branch segment to a real date (based on th date for the most recent sample)
double date = mostRecentDate - ((treeToExport.getHeight(node) * timeScaler) + (a + 1) * (((treeToExport.getHeight(parentNode) * timeScaler) - ((treeToExport.getHeight(node)) * timeScaler)) / divider));
//used to make branches dissapear over time
double endDate = mostRecentDate - ((treeToExport.getHeight(node) * timeScaler) - (divider - (a + 1)) * (((treeToExport.getHeight(parentNode) * timeScaler) - ((treeToExport.getHeight(node)) * timeScaler)) / divider));
if (endDate > mostRecentDate) {
endDate = mostRecentDate;
}
String[] yearMonthDay = convertToYearMonthDay(date);
String[] endYearMonthDay = convertToYearMonthDay(endDate);
//System.out.println(yearMonthDay[0]+"\t"+date+"\t"+mostRecentDate+"\t"+(treeToExport.getHeight(node) + (a + 1) * ((treeToExport.getHeight(parentNode) - (treeToExport.getHeight(node)))/divider))+"\t"+date);
if (ancient) {
branchesBuffer.append("\t\t\t\t<begin>" + Math.round(date) + "</begin>\r");
} else {
branchesBuffer.append("\t\t\t\t<begin>" + yearMonthDay[0] + "-" + yearMonthDay[1] + "-" + yearMonthDay[2] + "</begin>\r");
}
if (temporary) {
if (ancient) {
branchesBuffer.append("\t\t\t\t<end>" + Math.round(endDate) + "</end>\r");
} else {
branchesBuffer.append("\t\t\t\t<end>" + endYearMonthDay[0] + "-" + endYearMonthDay[1] + "-" + endYearMonthDay[2] + "</end>\r");
}
}
branchesBuffer.append("\t\t\t</TimeSpan>\r");
branchesBuffer.append("\t\t\t<styleUrl>#branch" + nodeNumber + "_part" + (a + 1) + "_style</styleUrl>\r");
// branchesBuffer.append("\t\t\t<styleUrl>#surfaceTreeBranch"+nodeNumber+"_style</styleUrl>\r");
branchesBuffer.append("\t\t\t<LineString>\r");
if (arcBranches) {
branchesBuffer.append("\t\t\t\t<altitudeMode>absolute</altitudeMode>\r");
branchesBuffer.append("\t\t\t\t<tessellate>1</tessellate>\r");
} else {
branchesBuffer.append("\t\t\t\t<altitudeMode>clampToGround</altitudeMode>\r");
}
branchesBuffer.append("\t\t\t\t<coordinates>\r");
if (longitudeBreak) {
if (longitude > 0) {
currentLongitude1 = longitude + a * (longitudeDifference / divider);
if (currentLongitude1 < 180) {
branchesBuffer.append("\t\t\t\t\t" + currentLongitude1 + ",");
//System.out.println("1 currentLongitude1 < 180\t"+currentLongitude1+"\t"+longitude);
} else {
branchesBuffer.append("\t\t\t\t\t" + (-180 - (180 - currentLongitude1)) + ",");
//System.out.println("2 currentLongitude1 > 180\t"+currentLongitude1+"\t"+(-180-(180-currentLongitude1))+"\t"+longitude);
}
} else {
currentLongitude1 = longitude - a * (longitudeDifference / divider);
if (currentLongitude1 > (-180)) {
branchesBuffer.append("\t\t\t\t\t" + currentLongitude1 + ",");
//System.out.println("currentLongitude1 > -180\t"+currentLongitude1+"\t"+longitude);
} else {
branchesBuffer.append("\t\t\t\t\t" + (180 + (currentLongitude1 + 180)) + ",");
//System.out.println("currentLongitude1 > -180\t"+(180+(currentLongitude1+180))+"\t"+longitude);
}
}
} else {
branchesBuffer.append("\t\t\t\t\t" + (longitude + a * (longitudeDifference / divider)) + ",");
}
branchesBuffer.append((latitude + a * (latitudeDifference / divider)) + ",");
branchesBuffer.append((maxAltitude * Math.sin(Math.acos(1 - a * (1.0 / (divider / 2.0))))) + "\r");
if (longitudeBreak) {
if (longitude > 0) {
currentLongitude2 = longitude + (a + 1) * (longitudeDifference / divider);
if (currentLongitude2 < 180) {
branchesBuffer.append("\t\t\t\t\t" + (currentLongitude2) + ",");
} else {
branchesBuffer.append("\t\t\t\t\t" + (-180 - (180 - currentLongitude2)) + ",");
}
} else {
currentLongitude2 = longitude - (a + 1) * (longitudeDifference / divider);
if (currentLongitude2 > (-180)) {
branchesBuffer.append("\t\t\t\t\t" + currentLongitude2 + ",");
} else {
branchesBuffer.append("\t\t\t\t\t" + (180 + (currentLongitude2 + 180)) + ",");
}
}
} else {
branchesBuffer.append("\t\t\t\t\t" + (longitude + (a + 1) * (longitudeDifference / divider)) + ",");
}
branchesBuffer.append((latitude + (a + 1) * (latitudeDifference / divider)) + ",");
branchesBuffer.append((maxAltitude * Math.sin(Math.acos(1 - (a + 1) * (1.0 / (divider / 2.0))))) + "\r");
branchesBuffer.append("\t\t\t\t</coordinates>\r");
branchesBuffer.append("\t\t\t</LineString>\r");
branchesBuffer.append("\t\t</Placemark>\r");
styleBuffer.append("\t<Style id=\"branch" + nodeNumber + "_part" + (a + 1) + "_style\">\r");
styleBuffer.append("\t\t<LineStyle>\r");
if (useStateProbability) {
double stateprobabilityDifference = (stateProbability - parentStateProbability) / divider;
styleBuffer.append("\t\t\t<width>" + (branchWidthConstant + (parentStateProbability + ((a + 1) * stateprobabilityDifference)) * branchWidthMultiplier) + "</width>\r");
} else {
styleBuffer.append("\t\t\t<width>" + branchWidth + "</width>\r");
}
if (useHeights) {
styleBuffer.append("\t\t\t<color>" + "FF" + ContinuousKML.getKMLColor((treeToExport.getHeight(node) + (a + 1) * ((treeToExport.getHeight(parentNode) - (treeToExport.getHeight(node))) / divider)), heightMinAndMax, startBranchColor, endBranchColor) + "</color>\r");
} else if (usePosterior) {
styleBuffer.append("\t\t\t<color>" + "FF" + ContinuousKML.getKMLColor(posteriorProb, posteriorMinAndMax, startBranchColor, endBranchColor) + "</color>\r");
} else {
styleBuffer.append("\t\t\t<color>" + "FF" + branchColor + "</color>\r");
}
styleBuffer.append("\t\t</LineStyle>\r");
styleBuffer.append("\t</Style>\r");
}
branchesBuffer.append("\t</Folder>\r");
}
}
}
}
use of jebl.evolution.graphs.Node in project beast-mcmc by beast-dev.
the class ContinuousKML method getRateMinMaxMedian.
private double[] getRateMinMaxMedian(RootedTree tree, boolean log) {
double[] minMaxMedian = new double[3];
double[] rates = new double[(tree.getNodes().size() - 1)];
int counter = 0;
int i = 0;
for (Node node : tree.getNodes()) {
if (!tree.isRoot(node)) {
if (log) {
rates[counter] = Math.log((Double) node.getAttribute("rate"));
} else {
rates[counter] = (Double) node.getAttribute("rate");
}
counter++;
}
i++;
}
double median = DiscreteStatistics.quantile(0.5, rates);
double max = 0.0;
double min = Double.MAX_VALUE;
for (int j = 0; j < rates.length; j++) {
if (rates[j] > max) {
max = rates[j];
}
if (rates[j] < min) {
min = rates[j];
}
}
minMaxMedian[0] = min;
minMaxMedian[1] = max;
minMaxMedian[2] = median;
return minMaxMedian;
}
Aggregations