public static void main(String[] arg) throws IOException, Importer.ImportException {
    Tree tree = (new NewickImporter("((A:1,B:1):1,(C:1, D:1):1);")).importNextTree();

    BetaTreeDiversityStatistic statistic =
        (BetaTreeDiversityStatistic) BetaTreeDiversityStatistic.FACTORY.createStatistic();

    Taxa taxa = new Taxa();
    taxa.addTaxon(new Taxon("A"));
    taxa.addTaxon(new Taxon("C"));

    statistic.setTaxonList(taxa);

    System.out.println(statistic.getSummaryStatistic(tree)[0]);
  }
  public static void main(String[] arg) throws IOException {

    // READ DEMOGRAPHIC FUNCTION

    String filename = arg[0];
    BufferedReader reader = new BufferedReader(new FileReader(filename));

    double popSizeScale = 1.0;
    double generationTime = 1.0;
    if (arg.length > 2) {
      popSizeScale = Double.parseDouble(arg[2]);
    }
    if (arg.length > 3) {
      generationTime = Double.parseDouble(arg[3]);
    }

    PrintWriter populationFuncLogger = null;
    if (arg.length > 5) {
      String logFileName = arg[5];
      if (logFileName.equals("-")) {
        populationFuncLogger = new PrintWriter(System.out);
      } else {
        populationFuncLogger = new PrintWriter(new FileWriter(logFileName));
      }
    }

    List<Double> times = new ArrayList<Double>();

    String line = reader.readLine();
    String[] tokens = line.trim().split("[\t ]+");
    if (tokens.length < 2) throw new RuntimeException();

    ArrayList<ArrayList> popSizes = new ArrayList<ArrayList>();
    while (line != null) {
      double time = Double.parseDouble(tokens[0]) / generationTime;
      times.add(time);

      for (int i = 1; i < tokens.length; i++) {
        popSizes.add(new ArrayList<Double>());
        popSizes.get(i - 1).add(Double.parseDouble(tokens[i]));
      }
      line = reader.readLine();
      if (line != null) {
        tokens = line.trim().split("[\t ]+");
        if (tokens.length != popSizes.size() + 1) throw new RuntimeException();
      }
    }

    reader.close();

    // READ SAMPLE TIMES

    String samplesFilename = arg[1];

    reader = new BufferedReader(new FileReader(samplesFilename));

    line = reader.readLine();
    Taxa taxa = new Taxa();
    int id = 0;
    while (line != null) {

      if (!line.startsWith("#")) {

        tokens = line.split("[\t ]+");

        if (tokens.length == 4) {

          double t0 = Double.parseDouble(tokens[0]);
          double t1 = Double.parseDouble(tokens[1]);
          double dt = Double.parseDouble(tokens[2]);
          int k = Integer.parseInt(tokens[3]);
          for (double time = t0; time <= t1; time += dt) {

            double sampleTime = time / generationTime;
            for (int i = 0; i < k; i++) {
              Taxon taxon = new Taxon("t" + id);
              taxon.setAttribute(
                  dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
              taxa.addTaxon(taxon);
              id += 1;
            }
          }

        } else {

          // sample times are in the same units as simulation
          double sampleTime = Double.parseDouble(tokens[0]) / generationTime;
          int count = Integer.parseInt(tokens[1]);

          for (int i = 0; i < count; i++) {
            Taxon taxon = new Taxon(id + "");
            taxon.setAttribute(
                dr.evolution.util.Date.DATE, new Date(sampleTime, Units.Type.GENERATIONS, true));
            taxa.addTaxon(taxon);
            id += 1;
          }
        }
      }
      line = reader.readLine();
    }

    double minTheta = Double.MAX_VALUE;
    double maxTheta = 0.0;

    PrintWriter out;
    if (arg.length > 4) {
      out = new PrintWriter(new FileWriter(arg[4]));
    } else {
      out = new PrintWriter(System.out);
    }

    int pp = 0;
    for (List<Double> popSize : popSizes) {
      double[] thetas = new double[popSize.size()];
      double[] intervals = new double[times.size() - 1];

      if (populationFuncLogger != null) {
        populationFuncLogger.println("# " + pp);
        ++pp;
      }

      // must reverse the direction of the model
      for (int j = intervals.length; j > 0; j--) {
        intervals[intervals.length - j] = times.get(j) - times.get(j - 1);

        final double theta = popSize.get(j) * popSizeScale;
        thetas[intervals.length - j] = theta;
        if (theta < minTheta) {
          minTheta = theta;
        }
        if (theta > maxTheta) {
          maxTheta = theta;
        }

        final double t = times.get(intervals.length) - times.get(j);
        if (populationFuncLogger != null) {
          populationFuncLogger.println(t + "\t" + theta);
        }
      }

      if (debug != null) {
        debug.println("min theta = " + minTheta);
        debug.println("max theta = " + maxTheta);
      }

      PiecewiseLinearPopulation demo =
          new PiecewiseLinearPopulation(intervals, thetas, Units.Type.GENERATIONS);

      CoalescentSimulator simulator = new CoalescentSimulator();
      Tree tree = simulator.simulateTree(taxa, demo);

      out.println(Tree.Utils.newick(tree));
      if (debug != null) {
        debug.println(Tree.Utils.newick(tree));
      }
    }

    if (populationFuncLogger != null) {
      populationFuncLogger.flush();
      populationFuncLogger.close();
    }

    out.flush();
    out.close();
  }
Beispiel #3
0
  /**
   * write log to file
   *
   * @param writer XMLWriter
   * @param treePriorGenerator TreePriorGenerator
   * @param branchRatesModelGenerator BranchRatesModelGenerator
   * @param substitutionModelGenerator SubstitutionModelGenerator
   * @param treeLikelihoodGenerator TreeLikelihoodGenerator
   * @param generalTraitGenerator
   */
  public void writeLogToFile(
      XMLWriter writer,
      TreePriorGenerator treePriorGenerator,
      BranchRatesModelGenerator branchRatesModelGenerator,
      SubstitutionModelGenerator substitutionModelGenerator,
      TreeLikelihoodGenerator treeLikelihoodGenerator,
      GeneralTraitGenerator generalTraitGenerator) {
    writer.writeComment("write log to file");

    if (options.logFileName == null) {
      options.logFileName = options.fileNameStem + ".log";
    }
    writer.writeOpenTag(
        LoggerParser.LOG,
        new Attribute[] {
          new Attribute.Default<String>(XMLParser.ID, "fileLog"),
          new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
          new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName),
          new Attribute.Default<Boolean>(
              LoggerParser.ALLOW_OVERWRITE_LOG, options.allowOverwriteLog)
        });

    if (options.hasData()) {
      writer.writeIDref(CompoundLikelihoodParser.POSTERIOR, "posterior");
    }
    writer.writeIDref(CompoundLikelihoodParser.PRIOR, "prior");
    if (options.hasData()) {
      writer.writeIDref(CompoundLikelihoodParser.LIKELIHOOD, "likelihood");
    }

    if (options.useStarBEAST) { // species
      // coalescent prior
      writer.writeIDref(
          MultiSpeciesCoalescentParser.SPECIES_COALESCENT,
          TraitData.TRAIT_SPECIES + "." + COALESCENT);
      // prior on population sizes
      //            if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
      writer.writeIDref(MixedDistributionLikelihoodParser.DISTRIBUTION_LIKELIHOOD, SPOPS);
      //            } else {
      //                writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
      //            }
      // prior on species tree
      writer.writeIDref(SpeciationLikelihoodParser.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);

      writer.writeIDref(
          ParameterParser.PARAMETER,
          TraitData.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
      writer.writeIDref(
          ParameterParser.PARAMETER, SpeciesTreeModelParser.SPECIES_TREE + "." + SPLIT_POPS);

      if (options.getPartitionTreePriors().get(0).getNodeHeightPrior()
          == TreePriorType.SPECIES_BIRTH_DEATH) {
        writer.writeIDref(
            ParameterParser.PARAMETER,
            TraitData.TRAIT_SPECIES + "." + BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME);
        writer.writeIDref(
            ParameterParser.PARAMETER,
            TraitData.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
      } else if (options.getPartitionTreePriors().get(0).getNodeHeightPrior()
          == TreePriorType.SPECIES_YULE) {
        writer.writeIDref(
            ParameterParser.PARAMETER,
            TraitData.TRAIT_SPECIES
                + "."
                + YuleModelParser.YULE
                + "."
                + YuleModelParser.BIRTH_RATE);
      } else {
        throw new IllegalArgumentException(
            "Get wrong species tree prior using *BEAST : "
                + options.getPartitionTreePriors().get(0).getNodeHeightPrior().toString());
      }

      // Species Tree: tmrcaStatistic
      writer.writeIDref(
          TMRCAStatisticParser.TMRCA_STATISTIC,
          SpeciesTreeModelParser.SPECIES_TREE + "." + TreeModelParser.ROOT_HEIGHT);
    }

    for (PartitionTreeModel model : options.getPartitionTreeModels()) {
      writer.writeIDref(
          ParameterParser.PARAMETER,
          model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
    }

    for (Taxa taxa : options.taxonSets) {
      // make tmrca(tree.name) eay to read in log for Tracer
      writer.writeIDref(
          TMRCAStatisticParser.TMRCA_STATISTIC,
          "tmrca(" + taxa.getTreeModel().getPrefix() + taxa.getId() + ")");
    }

    //        if ( options.shareSameTreePrior ) { // Share Same Tree Prior
    //	        treePriorGenerator.setModelPrefix("");
    //        	treePriorGenerator.writeParameterLog(options.activedSameTreePrior, writer);
    //        } else { // no species
    for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
      //	        	treePriorGenerator.setModelPrefix(prior.getPrefix()); // priorName.treeModel
      treePriorGenerator.writeParameterLog(prior, writer);
    }
    //	    }

    for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
      substitutionModelGenerator.writeLog(writer, model);
      if (model.hasCodon()) {
        writer.writeIDref(CompoundParameterParser.COMPOUND_PARAMETER, model.getPrefix() + "allMus");
      }
    }

    if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
      writer.writeIDref(ParameterParser.PARAMETER, "allClockRates");
      for (PartitionClockModel model : options.getPartitionClockModels()) {
        if (model.getClockType() == ClockType.UNCORRELATED_LOGNORMAL)
          writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
      }
    } else {
      for (PartitionClockModel model : options.getPartitionClockModels()) {
        branchRatesModelGenerator.writeLog(model, writer);
      }
    }

    for (PartitionClockModel model : options.getPartitionClockModels()) {
      branchRatesModelGenerator.writeLogStatistic(model, writer);
    }

    generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);

    if (options.hasData()) {
      treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
    }

    generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);

    // coalescentLikelihood
    for (PartitionTreeModel model : options.getPartitionTreeModels()) {
      PartitionTreePrior prior = model.getPartitionTreePrior();
      treePriorGenerator.writePriorLikelihoodReferenceLog(prior, model, writer);
      writer.writeText("");
    }

    for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
      if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE)
        writer.writeIDref(
            CoalescentLikelihoodParser.COALESCENT_LIKELIHOOD,
            prior.getPrefix() + COALESCENT); // only 1 coalescent
    }

    if (options.hasDiscreteIntegerTraitsExcludeSpecies()) {
      generalTraitGenerator.writeAncestralTreeLikelihoodReferences(writer);
    }

    writer.writeCloseTag(LoggerParser.LOG);

    generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
  }