@Override
 public List<Integer> getLeaves() {
   int externalNodeCount = tree.getExternalNodeCount();
   List<Integer> leaves = new ArrayList<Integer>(externalNodeCount);
   for (int i = 0; i < externalNodeCount; ++i) leaves.add(tree.getExternalNode(i).getNumber());
   return leaves;
 }
  /**
   * @param tree
   * @param node
   * @return and array of the total amount of time spent in each of the discrete states along the
   *     branch above the given node.
   */
  private double[] getProcessValues(final Tree tree, final NodeRef node) {

    double[] processValues = null;
    double branchTime = tree.getBranchLength(node);

    if (mode == Mode.MARKOV_JUMP_PROCESS) {
      processValues = (double[]) trait.getTrait(tree, node);
    } else if (mode == Mode.PARSIMONY) {
      // an approximation to dwell times using parsimony, assuming
      // the state changes midpoint on the tree. Does a weighted
      // average of the equally parsimonious state reconstructions
      // at the top and bottom of each branch.

      if (treeChanged) {
        fitchParsimony.initialize(tree);
        // Debugging test to count work
        //                treeInitializeCounter += 1;
        //                if (treeInitializeCounter % 10 == 0) {
        //                    System.err.println("Cnt: "+treeInitializeCounter);
        //                }
        treeChanged = false;
      }
      int[] states = fitchParsimony.getStates(tree, node);
      int[] parentStates = fitchParsimony.getStates(tree, tree.getParent(node));

      processValues = new double[fitchParsimony.getPatterns().getStateCount()];

      for (int state : states) {
        processValues[state] += branchTime / 2;
      }
      for (int state : parentStates) {
        processValues[state] += branchTime / 2;
      }

      for (int i = 0; i < processValues.length; i++) {
        // normalize by the number of equally parsimonious states at each end of the branch
        // processValues should add up to the total branch length
        processValues[i] /= (states.length + parentStates.length) / 2;
      }
    } else if (mode == Mode.NODE_STATES) {
      processValues = new double[dataType.getStateCount()];
      //            if (indicatorParameter != null) {
      //                // this array should be size #states NOT #rates
      //                processValues = new double[indicatorParameter.getDimension()];
      //            } else {
      //                // this array should be size #states NOT #rates
      //                processValues = new double[rateParameter.getDimension()];
      //            }

      // if the states are being sampled - then there is only one possible state at each
      // end of the branch.
      int state = ((int[]) trait.getTrait(tree, node))[traitIndex];
      processValues[state] += branchTime / 2;
      int parentState = ((int[]) trait.getTrait(tree, tree.getParent(node)))[traitIndex];
      processValues[parentState] += branchTime / 2;
    }

    return processValues;
  }
 @Override
 public List<Integer> getChildren(int i) {
   NodeRef n = tree.getNode(i);
   int childCount = tree.getChildCount(n);
   List<Integer> children = new ArrayList<Integer>(childCount);
   for (int j = 0; j < childCount; ++j) children.add(tree.getChild(n, j).getNumber());
   return children;
 }
 @Override
 public List<Integer> getAncestors(int i, boolean b) {
   List<Integer> ancestors = new ArrayList<Integer>();
   if (b) ancestors.add(i);
   for (NodeRef n = tree.getParent(tree.getNode(i)); n != null; n = tree.getParent(n))
     ancestors.add(n.getNumber());
   return ancestors;
 }
 @Override
 public int getSibling(int i) {
   NodeRef n = tree.getNode(i);
   if (tree.isRoot(n)) return RootedTree.NULL;
   NodeRef p = tree.getParent(n);
   int c1 = tree.getChild(p, 0).getNumber();
   int c2 = tree.getChild(p, 1).getNumber();
   return n.getNumber() == c2 ? c1 : c2;
 }
  public double[] getSummaryStatistic(Tree tree) {
    if (taxonList == null) {
      return new double[] {1.0};
    }

    double TL = Tree.Utils.getTreeLength(tree, tree.getRoot());

    double betaDiversity = (TL - getUniqueBranches(tree, tree.getRoot())) / TL;

    return new double[] {betaDiversity};
  }
  public void getTransitionProbabilities(
      Tree tree, NodeRef node, int rateCategory, double[] matrix) {

    NodeRef parent = tree.getParent(node);

    final double branchRate = branchModel.getBranchRate(tree, node);

    // Get the operational time of the branch
    final double startTime = tree.getNodeHeight(parent);
    final double endTime = tree.getNodeHeight(node);
    final double branchTime = branchRate * (startTime - endTime);

    if (branchTime < 0.0) {
      throw new RuntimeException("Negative branch length: " + branchTime);
    }

    double distance = siteModel.getRateForCategory(rateCategory) * branchTime;

    int matrixCount = 0;
    boolean oneMatrix = (getEpochWeights(startTime, endTime, weight) == 1);
    for (int m = 0; m < numberModels; m++) {
      if (weight[m] > 0) {
        SubstitutionModel model = modelList.get(m);
        if (matrixCount == 0) {
          if (oneMatrix) {
            model.getTransitionProbabilities(distance, matrix);
            break;
          } else model.getTransitionProbabilities(distance * weight[m], resultMatrix);
          matrixCount++;
        } else {
          model.getTransitionProbabilities(distance * weight[m], stepMatrix);
          // Sum over unobserved state
          int index = 0;
          for (int i = 0; i < stateCount; i++) {
            for (int j = 0; j < stateCount; j++) {
              productMatrix[index] = 0;
              for (int k = 0; k < stateCount; k++) {
                productMatrix[index] +=
                    resultMatrix[i * stateCount + k] * stepMatrix[k * stateCount + j];
              }
              index++;
            }
          }
          // Swap pointers
          double[] tmpMatrix = resultMatrix;
          resultMatrix = productMatrix;
          productMatrix = tmpMatrix;
        }
      }
    }
    if (!oneMatrix) System.arraycopy(resultMatrix, 0, matrix, 0, stateCount * stateCount);
  }
 @Override
 public List<Integer> getDescendants(int i, boolean b) {
   List<Integer> descendants = new ArrayList<Integer>();
   getDescendants(tree.getNode(i), descendants);
   if (b) descendants.remove(0);
   return descendants;
 }
Exemplo n.º 9
0
  private void setStatusMessage() {
    Tree tree = treesPanel.getTree();
    if (tree != null) {
      String message = "";
      message += "Tree loaded, " + tree.getTaxonCount() + " taxa";

      TemporalRooting tr = treesPanel.getTemporalRooting();
      if (tr.isContemporaneous()) {
        message += ", contemporaneous tips";
      } else {
        NumberFormatter nf = new NumberFormatter(3);
        message += ", dated tips with range " + nf.format(tr.getDateRange());
      }
      statusLabel.setText(message);
    }
  }
 @Override
 public List<Integer> getDescendantLeaves(int i, boolean b) {
   List<Integer> descendants = new ArrayList<Integer>();
   if (!b) descendants.add(i);
   for (NodeRef n : Tree.Utils.getExternalNodes(tree, tree.getNode(i)))
     descendants.add(n.getNumber());
   return descendants;
 }
  private double getUniqueBranches(Tree tree, NodeRef node) {

    if (tree.isExternal(node)) {
      return tree.getBranchLength(node);
    } else {
      double length = 0;
      if (isUnique(taxonList, tree, node)) {
        length = tree.getBranchLength(node);
        // System.out.println("length = " + length);
      }
      for (int i = 0; i < tree.getChildCount(node); i++) {
        length += getUniqueBranches(tree, tree.getChild(node, i));
      }
      // System.out.println("length of node " + node + " = " + length);
      return length;
    }
  }
Exemplo n.º 12
0
  public Map<String, Integer> writeNexusHeader(Tree tree) {
    int taxonCount = tree.getTaxonCount();
    List<String> names = new ArrayList<String>();

    for (int i = 0; i < tree.getTaxonCount(); i++) {
      names.add(tree.getTaxonId(i));
    }

    if (sorted) Collections.sort(names);

    out.println("#NEXUS");
    out.println();
    out.println("Begin taxa;");
    out.println("\tDimensions ntax=" + taxonCount + ";");
    out.println("\tTaxlabels");
    for (String name : names) {
      if (name.matches(SPECIAL_CHARACTERS_REGEX)) {
        name = "'" + name + "'";
      }
      out.println("\t\t" + name);
    }
    out.println("\t\t;");
    out.println("End;");
    out.println("");
    out.println("Begin trees;");

    // This is needed if the trees use numerical taxon labels
    out.println("\tTranslate");
    Map<String, Integer> idMap = new HashMap<String, Integer>();

    int k = 1;
    for (String name : names) {
      idMap.put(name, k);
      if (name.matches(SPECIAL_CHARACTERS_REGEX)) {
        name = "'" + name + "'";
      }
      if (k < names.size()) {
        out.println("\t\t" + k + " " + name + ",");
      } else {
        out.println("\t\t" + k + " " + name);
      }
      k += 1;
    }
    return idMap;
  }
Exemplo n.º 13
0
  /** Calculates the actual rates corresponding to the category indices. */
  protected void setupRates() {

    // System.out.println("BRRRTTZZZ " + distributionIndexParameter.getValue(0));
    for (int i = 0; i < tree.getNodeCount(); i++) {
      // rates[i] = distributionModel.quantile(rateCategoryQuantiles.getNodeValue(
      // rateCategoryQuantiles.getTreeModel(), rateCategoryQuantiles.getTreeModel().getNode(i) ));
      if (!tree.isRoot(tree.getNode(i))) {

        if (useQuantilesForRates) {
            /* Using quantiles to represent rates */
          rates[tree.getNode(i).getNumber()] =
              distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))].quantile(
                  rateCategoryQuantiles.getNodeValue(tree, tree.getNode(i)));
        } else {
            /* Not using quantiles to represent rates. This is practically useless for anything else other than simulation */
          rates[tree.getNode(i).getNumber()] =
              rateCategoryQuantiles.getNodeValue(tree, tree.getNode(i));
        }
      }
    }
    /*System.out.print(distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))].getClass().getName() + "\t" + (int) Math.round(distributionIndexParameter.getValue(0)) + "\t" + rates[1] + "\t" + rateCategoryQuantiles.getNodeValue(tree, tree.getNode(1)));// + "\t" + distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))].);
    if(distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))].getClass().getName().equals("dr.inference.distribution.LogNormalDistributionModel")) {
        LogNormalDistributionModel lndm = (LogNormalDistributionModel) distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))];
        System.out.println("\t" + lndm.getS());
    }
    else if (distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))].getClass().getName().equals("dr.inference.distribution.InverseGaussianDistributionModel")) {
        InverseGaussianDistributionModel lndm = (InverseGaussianDistributionModel) distributionModels[(int) Math.round(distributionIndexParameter.getValue(0))];
        System.out.println("\t" + lndm.getS());
    }*/
    if (normalize) computeFactor();
  }
  double calculateNorm(Tree tree) {

    double time = 0.0;
    double rateTime = 0.0;
    for (int i = 0; i < tree.getNodeCount(); i++) {

      NodeRef node = tree.getNode(i);

      if (!tree.isRoot(node)) {

        double branchTime = tree.getBranchLength(node);

        rateTime += getRawBranchRate(tree, node) * branchTime;
        time += branchTime;
      }
    }
    return rateTime / time;
  }
Exemplo n.º 15
0
 public Double getTrait(Tree tree, NodeRef node) {
   if (!weightsKnown) {
     expectedIBD();
     weightsKnown = true;
   }
   if (tree.isExternal(node)) {
     return getIBDWeight(tree, node);
   }
   return null;
 }
Exemplo n.º 16
0
 private double getIBDWeight(Tree tree, NodeRef node) {
   if (!weightsKnown) {
     expectedIBD();
     weightsKnown = true;
   }
   if (tree.isExternal(node)) {
     int nodeNum = node.getNumber();
     return ibdweights[nodeNum] + 1;
   }
   return 0;
 }
Exemplo n.º 17
0
  private static int mauCanonicalSub(
      Tree tree, NodeRef node, int loc, NodeRef[] order, boolean[] wasSwaped) {
    if (tree.isExternal(node)) {
      order[loc] = node;
      assert (loc & 0x1) == 0;
      return loc + 1;
    }

    final boolean swap = MathUtils.nextBoolean();
    // wasSwaped[(loc-1)/2] = swap;

    int l = mauCanonicalSub(tree, tree.getChild(node, swap ? 1 : 0), loc, order, wasSwaped);

    order[l] = node;
    assert (l & 0x1) == 1;
    wasSwaped[(l - 1) / 2] = swap;

    l = mauCanonicalSub(tree, tree.getChild(node, swap ? 0 : 1), l + 1, order, wasSwaped);
    return l;
  }
Exemplo n.º 18
0
  public void writeNexusTree(Tree tree, String s, boolean attributes, Map<String, Integer> idMap) {
    // PAUP marks rooted trees thou
    String treeAttributes = "[&R] ";

    // Place tree level attributes in tree comment
    StringBuilder treeComment = null;
    {
      Iterator<String> iter = tree.getAttributeNames();
      if (iter != null) {
        while (iter.hasNext()) {
          final String name = iter.next();
          final String value = tree.getAttribute(name).toString();

          if (name.equals("weight")) {
            treeAttributes = treeAttributes + "[&W " + value + " ] ";
          } else {
            if (treeComment == null) {
              treeComment = new StringBuilder(" [&");
            } else if (treeComment.length() > 2) {
              treeComment.append(", ");
            }

            treeComment.append(name).append("=").append(value);
          }
        }
        if (treeComment != null) {
          treeComment.append("]");
        }
      }
    }

    out.print(
        "tree "
            + s
            + ((treeComment != null) ? treeComment.toString() : "")
            + " = "
            + treeAttributes);

    writeNode(tree, tree.getRoot(), attributes, idMap);
    out.println(";");
  }
  /**
   * Calculates the probability of a given tree.
   *
   * @param tree - the tree to be analyzed
   * @return estimated posterior probability in log
   */
  public double getTreeProbability(Tree tree, HashMap<String, Integer> taxonMap) {
    double prob = 0.0;

    List<Clade> clades = new ArrayList<Clade>();
    List<Clade> parentClades = new ArrayList<Clade>();
    // get clades contained in the tree
    getNonComplementaryClades(tree, tree.getRoot(), parentClades, clades, taxonMap);

    int size = clades.size();
    // for every clade multiply its conditional clade probability to the
    // tree probability
    for (int i = 0; i < size; i++) {
      Clade c = clades.get(i);

      // get the bits of the clade
      Clade parent = parentClades.get(i);

      // set the occurrences to epsilon
      double tmp = EPSILON;
      double parentOccurrences = 0.0;
      BitSet parentBits = parent.getBits();
      if (cladeProbabilities.containsKey(parentBits)) {
        // if we observed this clade in the trace, add the
        // occurrences
        // to epsilon
        parentOccurrences += cladeProbabilities.get(parentBits).getSampleCount();
      }

      if (cladeCoProbabilities.containsKey(parentBits)) {
        // if we observed the parent clade
        HashMap<BitSet, Clade> conditionalProbs = cladeCoProbabilities.get(parentBits);

        BitSet bits = c.getBits();
        if (conditionalProbs.containsKey(bits)) {
          // if we observed this conditional clade in the trace,
          // add
          // the occurrences to epsilon
          tmp += conditionalProbs.get(bits).getSampleCount();
        }
      }
      // add epsilon for each clade
      final double splits = Math.pow(2, parent.getSize() - 1) - 1;
      parentOccurrences += EPSILON * splits;

      // multiply the conditional clade probability to the tree
      // probability
      prob += Math.log(tmp / parentOccurrences);
    }

    return prob;
  }
Exemplo n.º 20
0
  public SubstitutionModelDelegate(Tree tree, BranchModel branchModel, int bufferPoolSize) {

    if (MEASURE_RUN_TIME) {
      updateTime = 0;
      convolveTime = 0;
    }

    this.tree = tree;

    this.substitutionModelList = branchModel.getSubstitutionModels();

    this.branchModel = branchModel;

    eigenCount = substitutionModelList.size();
    nodeCount = tree.getNodeCount();

    // two eigen buffers for each decomposition for store and restore.
    eigenBufferHelper = new BufferIndexHelper(eigenCount, 0);

    // two matrices for each node less the root
    matrixBufferHelper = new BufferIndexHelper(nodeCount, 0);

    this.extraBufferCount =
        branchModel.requiresMatrixConvolution()
            ? (bufferPoolSize > 0 ? bufferPoolSize : BUFFER_POOL_SIZE_DEFAULT)
            : 0;

    if (branchModel.requiresMatrixConvolution() && this.extraBufferCount < eigenCount) {
      throw new RuntimeException(
          "SubstitutionModelDelegate requires at least "
              + eigenCount
              + " extra buffers to convolve matrices");
    }

    for (int i = 0; i < extraBufferCount; i++) {
      pushAvailableBuffer(i + matrixBufferHelper.getBufferCount());
    }

    // one extra created as a reserve
    // which is used to free up buffers when the avail stack is empty.
    reserveBufferIndex = matrixBufferHelper.getBufferCount() + extraBufferCount;

    if (DEBUG) {
      System.out.println("Creating reserve buffer with index: " + reserveBufferIndex);
    }
  } // END: Constructor
Exemplo n.º 21
0
  public double[] getSummaryStatistic(Tree tree) {

    double externalLength = 0.0;
    double internalLength = 0.0;

    int externalNodeCount = tree.getExternalNodeCount();
    for (int i = 0; i < externalNodeCount; i++) {
      NodeRef node = tree.getExternalNode(i);
      externalLength += tree.getBranchLength(node);
    }

    int internalNodeCount = tree.getInternalNodeCount();
    for (int i = 0; i < internalNodeCount; i++) {
      NodeRef node = tree.getInternalNode(i);
      if (!tree.isRoot(node)) {
        internalLength += tree.getBranchLength(node);
      }
    }
    return new double[] {internalLength + externalLength};
  }
 @Override
 public int getNoOfVertices() {
   return tree.getNodeCount();
 }
 @Override
 public int getLCA(int i, int j) {
   return Tree.Utils.getCommonAncestor(tree, tree.getNode(i), tree.getNode(j)).getNumber();
 }
 private void getDescendants(NodeRef n, List<Integer> descendants) {
   descendants.add(n.getNumber());
   if (tree.isExternal(n)) return;
   for (int i = 0; i < tree.getChildCount(n); ++i)
     getDescendants(tree.getChild(n, i), descendants);
 }
 @Override
 public int getHeight() {
   return getHeight(tree.getRoot().getNumber());
 }
 @Override
 public boolean isRoot(int i) {
   return tree.isRoot(tree.getNode(i));
 }
 public JPrIMERBTreeWrapperForBEASTTree(Tree tree) {
   super(tree.getId(), 1);
   this.tree = tree;
   root = getRoot();
 }
 @Override
 public String getName() {
   return tree.getId();
 }
 @Override
 public int getLeftChild(int i) {
   return tree.getChild(tree.getNode(i), 0).getNumber();
 }
 @Override
 public int getRightChild(int i) {
   return tree.getChild(tree.getNode(i), 1).getNumber();
 }